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
f414dc64818afe4380450f321d1f7a5872268a2c
TypeScript
ricozacharias/ng-pokemon-trainer
/src/app/models/pokemon.model.ts
2.5625
3
export interface Pokemon { name: string; url: string; id: string; selected: boolean; } export interface PokemonRequest { count: number; next: string; previous: string; results: Pokemon[]; }
b1035f033f65ab5980553d768de58d9adc17d024
TypeScript
TRIPTYK/nfw-cli
/src/test/05_AddEndpointCommand.test.ts
2.625
3
import { expect } from "chai"; import { join } from "path"; import { execInProject as exec , testInput } from "./global" describe("AddEndpointCommand", function() { this.timeout("10s"); let command = null; const method = "PUT"; it("Adds an endpoint", () => { command = exec(`nfw add-endpoint ${testInput} ${testInput} ${method}`); expect(command).to.exit.with.code(0) .and.stdout.to.contain(`Endpoint ${method} on /${join(testInput, testInput)} created !`); }); it("Tries to add an already existing endpoint", () => { command = exec(`nfw add-endpoint ${testInput} ${testInput} ${method}`); expect(command).to.exit.with.code(1) .and.stdout.to.contain(`This method already exists.`); }); it("Tries to add an endpoint but with an non-valid method", () => { const faultyValue = "BANANA"; command = exec(`nfw add-endpoint ${testInput} ${testInput} ${faultyValue}`); expect(command).to.exit.with.code(1) .and.stdout.to.contain(`${faultyValue} doesn't exist or isn't compatible yet.`); }); });
9b52b491c907cf8ac34f7f3e110420cb47aba981
TypeScript
jquense/docpocalypse
/packages/code-live/src/transform/index.ts
2.609375
3
/* eslint-disable no-restricted-syntax */ import { Parser } from 'acorn'; import acornJsx from 'acorn-jsx'; import MagicString from 'magic-string'; import { Node, NormalVisitor, Plugin, VisitorMap } from './types'; const parser = Parser.extend(acornJsx()); type NormalVisitorMap = Record<string, NormalVisitor[]>; const isNode = (n: any): n is Node => n !== null && typeof n.type === 'string'; function walk( ctx: MagicString, visitors: NormalVisitorMap, node?: Node, parent?: Node, ) { if (!node) return; const visitor = visitors[node.type]; visitor?.forEach(v => v.enter?.call(ctx, node, parent)); // eslint-disable-next-line guard-for-in for (const key in node) { const value = node[key]; if (isNode(value)) { walk(ctx, visitors, value, node); } if (Array.isArray(value)) { for (const item of value) { if (isNode(item)) { walk(ctx, visitors, item, node); } } } } visitor?.forEach(v => v.leave?.call(ctx, node, parent)); } const mergeVisitors = (visitors: VisitorMap[]) => { const rootVisitor: Record<string, NormalVisitor[]> = {}; for (const visitor of visitors) { for (const key of Object.keys(visitor)) { const value = visitor[key]; for (const type of key.split('|')) { const normalized = typeof value === 'function' ? { enter: value } : value; rootVisitor[type] = rootVisitor[type] || []; rootVisitor[type].push(normalized); } } } return rootVisitor; }; export interface Options { plugins: Plugin[]; file?: string; source?: string; includeContent?: boolean; } export function transform(source: string, options: Options = { plugins: [] }) { const { plugins } = options; const code = new MagicString(source); const ast = parser.parse(source, { ecmaVersion: 10, preserveParens: true, sourceType: 'module', allowAwaitOutsideFunction: true, allowReturnOutsideFunction: true, allowHashBang: true, onComment: (...args) => { plugins.forEach(p => p.onComment?.(...args)); }, }); walk(code, mergeVisitors(plugins.map(p => p.visitor!).filter(Boolean)), ast); return { ast, code: code.toString(), map: code.generateMap({ file: options.file, source: options.source, includeContent: options.includeContent !== false, }), }; }
2c3ba85c012aa203313c21c6193299cceb0ca7ee
TypeScript
jstarmx/sunflower-lab
/packages/greenhouse/src/lib/types/components/Input.d.ts
2.84375
3
import { SvelteComponentTyped } from 'svelte'; export interface InputProps { /** * Content for the <label> element that wraps the input element */ label: string; /** * Placeholder for the input element */ placeholder: string; /** * Bound value of the input element */ value: string; /** * Type of input element * @default "text" */ type?: 'text' | 'number' | 'email' | 'password'; /** * An optional error message to display */ error?: string; } export default class Input extends SvelteComponentTyped<InputProps> {}
5606b1fb70fcffbaadb4f11eef8e9eb55db2be0a
TypeScript
hardrese7/rectangles-map
/src/models/rectangle/RectangleGeoJSON.ts
2.53125
3
import ShapeGeoJSON from 'src/models/shape/ShapeGeoJSON'; import { calculateRectangleCoordinates, getRotatedRectangle, } from 'src/utils/geometry'; import Rectangle from './Rectangle'; export default class RectangleGeoJSON extends ShapeGeoJSON { constructor({ center_lng, center_lat, length, width, yaw_angle, color, }: Rectangle) { const data = getRotatedRectangle( calculateRectangleCoordinates(center_lat, center_lng, length, width), center_lng, center_lat, yaw_angle, ); data.properties = { color }; super(data); } }
67e2dcfa810c4a0e759b067f012d4ee6ec024dd0
TypeScript
N1cc3/war-game
/src/game/Game.test.ts
2.984375
3
import Hex from '../hexgrid/Hex' import Game, { Player, Unit, UnitType } from './Game' describe('Game', () => { test('lastTickTime updates on simulate', () => { const startTime = new Date('2020-01-01T00:00:00.000Z') const game = new Game(startTime, 15 * 60 * 1000) game.simulate() expect(game.lastTickTime().toISOString()).toBe('2020-01-01T00:15:00.000Z') game.simulate() expect(game.lastTickTime().toISOString()).toBe('2020-01-01T00:30:00.000Z') }) describe('Combat', () => { test('units should fight', () => { const player1: Player = { name: 'player1' } const player2: Player = { name: 'player2' } const soldier: UnitType = { name: 'Soldier', damage: 1, maxHp: 5, speed: 1 } const unit1: Unit = { hp: 5, position: new Hex(0, 0), owner: player1, type: soldier } const unit2: Unit = { hp: 3, position: new Hex(0, 0), owner: player2, type: soldier } const game = new Game(new Date('2020-01-01'), 1, [unit1, unit2]) game.simulate() expect(unit1.hp).toBe(4) expect(unit2.hp).toBe(2) }) }) })
b2e93a7540f4c4ada2091c12bea93559bcfab209
TypeScript
maxfontani/moji-warz
/packages/client/src/game/sprites/effects.ts
3
3
import { DisplayObject, Sprite } from 'pixi.js'; const FLASH_DURATION = 200; const BLINK_DURATION = 300; const BLINK_COUNT = 5; export const flash = (sprite: Sprite, tintColor: number, baseColor: number) => { sprite.tint = tintColor; setTimeout(() => { sprite.tint = baseColor; }, FLASH_DURATION); }; export const blink = (object: DisplayObject) => { let count = 0; const interval = setInterval(() => { object.visible = !object.visible; count++; if (count >= BLINK_COUNT) { object.visible = true; clearInterval(interval); } }, BLINK_DURATION); }; export const hide = (object: DisplayObject, duration: number) => { object.alpha = 0 setTimeout(() => { object.alpha = 1 }, duration) };
8c72337de4228c643c8a6022e7e84ac75f3552cd
TypeScript
kidstech/word-river
/client/src/testing/user-service-mock.ts
2.609375
3
/* eslint-disable max-len */ import { HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { map } from 'rxjs/operators'; import { Learner } from 'src/app/datatypes/learner'; import { User } from 'src/app/datatypes/user'; @Injectable() export class UserServiceMock { learners: Learner[] = [ { _id: '123', name: 'George', icon: 'image.jpg', learnerPacks: ['meow', 'fungi'] }, { _id: '345', name: 'Steve', icon: 'image.jpg', learnerPacks: ['football', 'soccer'] }, { _id: '678', name: 'Peter', icon: 'image.jpg', learnerPacks: ['bananas', 'apples'] } ]; users: User[] = [ { _id: 'test', authId: '12345', name: 'John Doe', icon: 'image.png', learners: this.learners, contextPacks: ['meow', 'woof', 'moo'] }, { _id: 'test1', authId: '123', name: 'Danny Doe', icon: 'image.png', learners: this.learners, contextPacks: ['moo', 'woof'] }, { _id: 'test2', authId: '42021', name: 'Matt Doe', icon: 'image.png', learners: [], contextPacks: ['bark', 'woof'] }, ]; constructor() { } getUser(authId: string): Observable<User> { return of(this.users.find(user => user.authId === authId)); } createUser(newUser: User): Observable<string> { this.users.push(newUser); return of('1234'); } createLearner(authId: string, newLearner: Learner): Observable<string> { this.learners.push(newLearner); return new Observable(sub => { if (newLearner.name !== null) { sub.next('err'); } else { sub.error(authId); } }); } getLearners(authId: string): Observable<Learner[]> { return of(this.learners); } getLearner(authId: string, learnerId: string): Observable<Learner> { return of(this.learners.find(l => l._id === learnerId)); } editLearner(authId: string, learnerId: string, editedLearner: Learner): Observable<Learner> { this.learners = this.learners.map(learner => learner._id === learnerId ? editedLearner : learner); return of(editedLearner); } removeLearner(authId: string, learnerId: string): Observable<string> { console.log(this.users); this.users = this.users.map(user => user.authId === authId ? user.learners.filter(learner => learner._id !== learnerId) : user) as User[]; return of(learnerId); } // removePackFromLearner(authId: string, learnerId: string, packId: string): Observable<string> { // this.learners = this.learners.map(learner => learner._id === learnerId ? learner.learnerPacks.filter( // l => l !== packId // ) : learner) as Learner[]; // return of(packId); // } // addPackToLearner(authId: string, learnerId: string, packId: string): Observable<string> { // // this.learners = this.learners.map(learner => learner._id === learnerId ? // // learner.learnerPacks.concat : learner) as Learner[]; // return of(packId); // } }
216107bf9d35ae0ca83964086751b5c2d7f91d14
TypeScript
HaidelBert/haidelbert
/register-of-assets/src/entity/asset.ts
2.515625
3
import {BaseEntity, Column, Entity, JoinColumn, OneToMany, PrimaryColumn, PrimaryGeneratedColumn} from "typeorm"; import {AssetDepreciation} from "./assetDepreciation"; import {bigint, date} from "../helpers/dbHelpers"; @Entity({ name: "assets" }) export class Asset{ @PrimaryColumn("bigint", { transformer: [bigint] }) @PrimaryGeneratedColumn() id?: number; @Column() name: string = ""; @Column( "date", {name: "purchase_date", transformer: [date]}) purchaseDate: Date = new Date(); @Column("bigint", {name: "gross_amount", transformer: [bigint]}) grossAmount: number = 0; @Column("bigint", {name: "net_amount", transformer: [bigint]}) netAmount: number = 0; @Column({name: "depreciation_duration"}) depreciationDuration: number = 3; @Column("bigint",{name: "net_remaining_block_value", transformer: [bigint]}) netRemainingBlockValue: number = 0; @Column({name: "user_id"}) userId: string = ""; @Column({name: "active"}) active: boolean = false; @OneToMany(() => AssetDepreciation, assetDepreciation => assetDepreciation.asset, { eager: true, cascade: true, onDelete: 'CASCADE' }) depreciations?: AssetDepreciation[]; }
f074cb958b0a25dd5cd7650b3bae203b31a99197
TypeScript
holomekc/ioBroker.bshb
/src/log-level.ts
2.921875
3
/** * This enum defines all log levels with an ordinal ordered by lower is finer log level. * This helps to decide if a log should be present * * @author Christopher Holomek * @since 01.12.2019 */ export enum LogLevel { silly, debug, info, warn, error }
d95fe222a47299f4312ec25fc2c821f34265e6ff
TypeScript
imckl/ts-leetcode
/src/202012/202012151454-longest-increasing-subsequence.ts
3.453125
3
export function lengthOfLIS(nums: number[]): number { if (nums.length === 0) { return 0; } if (nums.length === 1) { return 1; } let longestSeq = []; for (let i = 0; i < nums.length; i++) { let max = nums[i]; const seq = [nums[i]]; for (let j = i + 1; j < nums.length; j++) { if (nums[j] > max) { seq.push(nums[j]); max = nums[j]; } } if (seq.length > longestSeq.length) { longestSeq = seq; } } return longestSeq.length; }
b206a8010d8b30d2718f6ccafcfcdee5a18bd15d
TypeScript
josiah-dunham/npm-ts-boilerplate
/src/main.ts
3.140625
3
import { logr } from './helpers/utils' logr("it works!") const myFn = (optional?: string) => { logr('optional') logr(optional) const things = ["one", "two"] if(!optional) { logr('doing something with things because no optional') } else { logr('doing nothing') } } myFn()
bc628eea0bac41abedd62026aafd4847deddfec6
TypeScript
decentraland/agora
/src/Translation/Translation.router.ts
2.640625
3
import { server } from 'decentraland-server' import * as express from 'express' import { Translation, TranslationData } from './Translation' import { Router } from '../lib' export class TranslationRouter extends Router { mount() { /** * Returns the translations for a given locale * @param {string} locale - locale name * @return {array<Translation>} */ this.app.get( '/translations/:locale', server.handleRequest(this.getTranslations) ) } async getTranslations(req: express.Request): Promise<TranslationData> { let locale = server.extractFromReq(req, 'locale') locale = locale.slice(0, 2) // We support base locales for now, like en, it, etc return new Translation().fetch(locale) } }
7fc789c5a97ee5484ac9aafd377ed105359e2ebd
TypeScript
devrsi0n/typescript-algorithms
/packages/algs4/src/StdRandom/StdRandom.test.ts
3.078125
3
import StdRandom from './index'; test('random method return range [0, 1)', () => { expect(typeof StdRandom.random()).toBe('number'); expect(StdRandom.random()).toBeGreaterThanOrEqual(0); expect(StdRandom.random()).toBeLessThan(1); }); test('setSeed method', () => { StdRandom.setSeed(1); expect(StdRandom.random()).toBe(0.2694488477791326); }); test('uniform method', () => { expect(typeof StdRandom.uniform()).toBe('number'); expect(StdRandom.uniform()).toBeGreaterThanOrEqual(0); expect(StdRandom.uniform()).toBeLessThan(1); expect(StdRandom.uniform(10)).toBeGreaterThanOrEqual(0); expect(StdRandom.uniform(10)).toBeLessThan(10); expect(StdRandom.uniform(-1.5, 12)).toBeGreaterThanOrEqual(-1.5); expect(StdRandom.uniform(-1.5, 12)).toBeLessThan(12); }); test('bernoulli method', () => { expect(typeof StdRandom.bernoulli(0.1)).toBe('boolean'); expect(StdRandom.bernoulli(1)).toBe(true); }); test('gaussian method', () => { expect(typeof StdRandom.gaussian()).toBe('number'); expect(StdRandom.gaussian()).toBeGreaterThanOrEqual(0); expect(StdRandom.gaussian()).toBeLessThan(1); }); test('discrete method', () => { expect(typeof StdRandom.discrete([0, 0.1, 0.9])).toBe('number'); expect(() => StdRandom.discrete([-1])).toThrowError(); }); test('shuffle method', () => { const arr = [0, 1, 2, 3]; StdRandom.shuffle(arr); expect(Array.isArray(arr)).toBe(true); });
54ba69cb1dd711b5582823031c0ace3893f4effa
TypeScript
LTMezzari/MockableNodeAPI
/src/application/handler/DefaultHandler.ts
2.5625
3
import IRouteAuthenticator from '../authenticator/IRouteAuthenticator'; import IRoute from '../../domain/model/route/IRoute'; import IRouteRepository from '../../domain/repository/IRouteRepository'; import IRouteHandler from './IRouteHandler'; import Configuration from '../../configurator/Configuration'; import IRouteValidator from '../validator/IRouteValidator'; export default class DefaultHandler implements IRouteHandler { registerRoutes(server: any, routes: IRoute[], configuration: Configuration) { for (const route of routes) { this.registerRoute(server, route, configuration); } } registerRoute(server: any, route: IRoute, configuration: Configuration) { if (server.match(route.method, route.path)) { return; } const repository = configuration.repository; const authenticator = configuration.authenticator; const validator = configuration.validator; server.route({ method: route.method, path: route.path, handler: async (request: any, reply: any) => { try { const options = configuration.factory.createOptions(request); const current = repository.getRoutes(options).find((r: IRoute) => r.path === route.path && r.method === route.method ); if (!current) { return reply.response({ statusCode: 404, error: 'Not Found', message: 'The requested method was not found' }).code(404); } await this.handleTimeOut(current); return this.handleRequest(request, reply, current, authenticator, validator); } catch (error: any) { console.log(error); return reply.response({ statusCode: 400, error: 'Bad Request', message: error.message }).code(400); } } }) } handleTimeOut(route: IRoute): Promise<any> { return new Promise((resolve: any) => { if (!route?.timeOut) { return resolve(); } setTimeout(resolve, route.timeOut); }) } handleRequest(request: any, reply: any, route: IRoute, authenticator?: IRouteAuthenticator, validator?: IRouteValidator) { try { if (!(authenticator?.isRouteAuthenticated(request, route) ?? true)) { const response = { statusCode: 401, error: 'Unathorized', message: 'You are not authorized to use this method' }; this.addLog(route, 'REQUEST RECEIVED', this.createLog(request, route.response, 401)); return reply.response(response).code(401); } if (!(validator?.isRouteValid(request, route) ?? true)) { throw Error('The request did not pass the validations'); } this.addLog(route, 'REQUEST RECEIVED', this.createLog(request, route.response, route.status)); return reply.response(route.response).code(route.status); } catch (error: any) { console.log(error); const response = { statusCode: 400, error: 'Bad Request', message: error.message }; this.addLog(route, 'BAD REQUEST RECEIVED', this.createLog(request, response, 400)) return reply.response(response).code(400); } } addLog(route: IRoute, message: string, data: any) { route.logs.push({ time: new Date(), message, data, }) } createLog(request: any, response: any, status: number) { return { headers: request.headers, body: request.payload, params: request.params, query: request.query, response, status, } } }
607a2f209b338a41a2326db22b7f8393484700a8
TypeScript
Th3CracKed/PillTracker-DashBoard
/src/v1/models/order.model.ts
2.515625
3
import * as mongoose from 'mongoose'; import { Schema } from 'jsonschema'; import { ObjectId } from 'mongodb'; const ProductOrderSchema = new mongoose.Schema( { quantity: { type: Number, required: true, default: 1 }, product: { type: ObjectId, ref: 'Product' } } ); interface ProductOrder { quantity: Number; product: ObjectId | string; } export interface Order { orderDate: string; deliveryDate: string; productOrder: ProductOrder[]; userId?: string; } const OrderSchema = new mongoose.Schema( { orderDate: { type: Date, required: true }, deliveryDate: { type: Date, required: true }, productOrder: [{ type: ProductOrderSchema, required: true }] }, { timestamps: true, useNestedStrict: true } ); export let productOrderJsonSchema: Schema = { id: '/ProductOrderJsonSchema', type: 'object', properties: { quantity: { type: 'number' }, product: { type: 'string' } }, required: ['quantity', 'product'], additionalProperties: false }; export let orderJsonSchema: Schema = { id: '/OrderJsonSchema', type: 'object', properties: { orderDate: { type: 'date-time' }, deliveryDate: { type: 'date-time' }, productOrder: { type: 'array', items: { '$ref': '/ProductOrderJsonSchema' }, minItems: 1 }, userId: { type: 'string' } }, required: ['orderDate', 'deliveryDate', 'productOrder'], additionalProperties: false }; export default mongoose.model('Order', OrderSchema);
6617913ee7697c60f98368e23647a73f23f18065
TypeScript
mattduggan/boggle
/scripts/packDictionary.ts
2.53125
3
import { createReadStream, writeFileSync } from 'fs'; import { resolve } from 'path'; import { createInterface } from 'readline'; const { Trie } = require('dawg-lookup'); var trie = new Trie(); // TODO add 16 and 17 letter words, sorted // TODO filter Q words where Q is not followed by U createInterface({ input: createReadStream(resolve(__dirname, '../lib', 'Collins Scrabble Words (2019).txt'), 'utf-8') }).on('line', (line: string) => { if (line.length >= 3 && line.length <= 17) { trie.insert(line.toLowerCase()); } }).on('close', () => { writeFileSync(resolve(__dirname, '../lib', 'packed-dictionary.txt'), trie.pack(), 'utf-8'); console.timeEnd('pack'); });
c0aff29d930c6e7b4bae27534a4c038ea205e00b
TypeScript
cnickert-umich/lambda-eats
/serverless-backend/src/food/FoodDao.ts
2.609375
3
'use strict'; import { DynamoDB } from 'aws-sdk' import * as uuid from 'uuid' import { FOOD_TABLE_NAME } from '../Constants'; import { FoodDO } from './_types/FoodDO'; import { NewFood } from './_types/NewFood'; import { UpdateFood } from './_types/UpdateFood'; const dynamoDb = new DynamoDB.DocumentClient() export default class FoodDao { static async create(newFood: NewFood): Promise<FoodDO> { const timestamp = new Date().getTime(); const toSave: FoodDO = { id: uuid.v1(), shopId: newFood.shopId, title: newFood.title, description: newFood.description, cost: newFood.cost, createdAt: timestamp, updatedAt: timestamp } const params: DynamoDB.DocumentClient.PutItemInput = { TableName: FOOD_TABLE_NAME, Item: toSave } const result = await dynamoDb.put(params).promise(); console.log("Success."); return toSave; } static async findAllByShopId(shopId: string): Promise<FoodDO[]> { const params: DynamoDB.DocumentClient.QueryInput = { TableName: FOOD_TABLE_NAME, IndexName: "ShopIdIndex", KeyConditionExpression: "shopId = :shopId", ExpressionAttributeValues: { ":shopId": shopId } }; // fetch shop from the database const result = await dynamoDb.query(params).promise(); console.log("Success."); return result.Items as FoodDO[]; } static async findByShopIdAndFoodId(shopId: string, foodId: string,): Promise<FoodDO> { const params: DynamoDB.DocumentClient.GetItemInput = { TableName: FOOD_TABLE_NAME, Key: { id: foodId, shopId: shopId } }; // fetch shop from the database const result = await dynamoDb.get(params).promise(); console.log("Success."); return result.Item as FoodDO; } static async findAllByShopIdAndFoodIds(shopId: string, foodIds: string[],): Promise<FoodDO[]> { if (foodIds.length == 0) { return []; } const params = { RequestItems: {} }; params.RequestItems[FOOD_TABLE_NAME] = { Keys: [] }; foodIds.forEach((foodId) => { params.RequestItems[FOOD_TABLE_NAME].Keys.push({ id: foodId, shopId: shopId }); }); console.log(`Batch gets request: ${JSON.stringify(params)}`); // fetch shop from the database const result = await dynamoDb.batchGet(params).promise(); console.log("Success."); return result.Responses[FOOD_TABLE_NAME] as FoodDO[]; } static async update(updateFood: UpdateFood): Promise<FoodDO> { const timestamp = new Date().getTime(); const params: DynamoDB.DocumentClient.UpdateItemInput = { TableName: FOOD_TABLE_NAME, Key: { id: updateFood.id, shopId: updateFood.shopId }, ExpressionAttributeValues: { ':title': updateFood.title, ':description': updateFood.description, ':cost': updateFood.cost, ':updatedAt': timestamp }, UpdateExpression: 'SET title = :title, description = :description, cost = :cost, updatedAt = :updatedAt', ReturnValues: 'ALL_NEW', }; const result = await dynamoDb.update(params).promise(); console.log("Success."); return await this.findByShopIdAndFoodId(updateFood.shopId, updateFood.id); } }
54004837684cf7fd0dc9f455238b6569ccedf493
TypeScript
harshadakunde/TrainingManagement
/Angular/src/app/technology/technology.ts
2.96875
3
export class Technology { constructor(public technology_id: number, public technology_name: string,public active: number ) { } toString(): string { console.log("in tostring"); return `${this.technology_id} ${this.technology_name} ${this.active} `; } }
58b9390331d73d4817cc8b3d6968005e7f3ea049
TypeScript
richardcrng/included-m
/src/lib/why-what-error/WhyWhatError.ts
3.34375
3
interface WhyWhat { /** * **What** operation/update failed */ what: string; /** * **Why** the operation/update failed */ why: string; } class WhyWhatError extends Error { message: string; /** * **What** operation/update failed */ what: string; /** * **Why** the operation/update failed */ why?: string; /** * * @param param0.what - What operation failed * @param param0.why - Why the operation failed */ constructor( { what = "Operation failed", why }: Partial<WhyWhat>, errorName?: string ) { const message = why ? [what, why].join(". ") : what; super(message); this.message = message; this.name = errorName || "WhyWhatError"; this.what = what; this.why = why; } static from(err: Error, details: Partial<WhyWhat>) { const why = err instanceof WhyWhatError ? err.why : err.message; return new WhyWhatError({ why, ...details }); } } export default WhyWhatError;
8ad61d0c13db882ab51f27475e485e22819b225c
TypeScript
louischan-oursky/skygear-next-SDK-JS
/packages/skygear-core/src/container.ts
2.5625
3
import { JSONObject, User, Identity, AuthResponse, SSOLoginOptions, } from "./types"; import { ContainerStorage } from "./storage"; import { BaseAPIClient } from "./client"; import { encodeUser, encodeIdentity, decodeUser, decodeIdentity, } from "./encoding"; function keyAccessToken(name: string): string { return `${name}_accessToken`; } function keyUser(name: string): string { return `${name}_user`; } function keyIdentity(name: string): string { return `${name}_identity`; } /** * @public */ export class AuthContainer<T extends BaseAPIClient> { parent: Container<T>; currentUser: User | null; currentIdentity: Identity | null; constructor(parent: Container<T>) { this.parent = parent; this.currentUser = null; this.currentIdentity = null; } // @ts-ignore get accessToken(): string | null { return this.parent.apiClient.accessToken; } async persistResponse(response: AuthResponse): Promise<void> { const { user, identity, accessToken } = response; const userJSON = encodeUser(user); await this.parent.storage.safeSetJSON(keyUser(this.parent.name), userJSON); if (identity) { const identityJSON = encodeIdentity(identity); await this.parent.storage.safeSetJSON( keyIdentity(this.parent.name), identityJSON ); } if (accessToken) { await this.parent.storage.safeSet( keyAccessToken(this.parent.name), accessToken ); } this.currentUser = user; if (identity) { this.currentIdentity = identity; } if (accessToken) { this.parent.apiClient.accessToken = accessToken; } } async signup( loginIDs: { [key: string]: string }[] | { [key: string]: string }, password: string, options?: { realm?: string; metadata?: JSONObject; } ): Promise<User> { const response = await this.parent.apiClient.signup( loginIDs, password, options ); await this.persistResponse(response); return response.user; } /** * signupWithEmail is a shorthand of {@link AuthContainer.signup | the signup() method}. */ async signupWithEmail( email: string, password: string, options?: { realm?: string; metadata?: JSONObject; } ): Promise<User> { return this.signup( { email, }, password, options ); } /** * signupWithUsername is a shorthand of {@link AuthContainer.signup | the signup() method}. */ async signupWithUsername( username: string, password: string, options?: { realm?: string; metadata?: JSONObject; } ): Promise<User> { return this.signup( { username, }, password, options ); } async login( loginID: string, password: string, options?: { loginIDKey?: string; realm?: string } ): Promise<User> { const response = await this.parent.apiClient.login( loginID, password, options ); await this.persistResponse(response); return response.user; } async logout(): Promise<void> { await this.parent.apiClient.logout(); await this.parent.storage.safeDel(keyAccessToken(this.parent.name)); await this.parent.storage.safeDel(keyIdentity(this.parent.name)); await this.parent.storage.safeDel(keyUser(this.parent.name)); this.currentUser = null; this.currentIdentity = null; this.parent.apiClient.accessToken = null; } async me(): Promise<User> { const response = await this.parent.apiClient.me(); await this.persistResponse(response); return response.user; } async changePassword( newPassword: string, oldPassword: string ): Promise<User> { const response = await this.parent.apiClient.changePassword( newPassword, oldPassword ); await this.persistResponse(response); return response.user; } async updateMetadata(metadata: JSONObject): Promise<User> { const response = await this.parent.apiClient.updateMetadata(metadata); await this.persistResponse(response); return response.user; } async requestForgotPasswordEmail(email: string): Promise<void> { return this.parent.apiClient.requestForgotPasswordEmail(email); } async resetPassword(form: { userID: string; code: string; expireAt: number; newPassword: string; }): Promise<void> { return this.parent.apiClient.resetPassword(form); } async requestEmailVerification(email: string): Promise<void> { return this.parent.apiClient.requestEmailVerification(email); } async verifyWithCode(code: string): Promise<void> { return this.parent.apiClient.verifyWithCode(code); } async loginWithCustomToken( token: string, options?: SSOLoginOptions ): Promise<User> { const response = await this.parent.apiClient.loginWithCustomToken( token, options ); await this.persistResponse(response); return response.user; } async deleteOAuthProvider(providerID: string): Promise<void> { return this.parent.apiClient.deleteOAuthProvider(providerID); } async loginOAuthProviderWithAccessToken( providerID: string, accessToken: string, options?: SSOLoginOptions ): Promise<User> { const response = await this.parent.apiClient.loginOAuthProviderWithAccessToken( providerID, accessToken, options ); await this.persistResponse(response); return response.user; } async linkOAuthProviderWithAccessToken( providerID: string, accessToken: string ): Promise<User> { const response = await this.parent.apiClient.linkOAuthProviderWithAccessToken( providerID, accessToken ); await this.persistResponse(response); return response.user; } } /** * @public */ export class Container<T extends BaseAPIClient> { name: string; apiClient: T; storage: ContainerStorage; auth: AuthContainer<T>; constructor(name: string, apiClient: T, storage: ContainerStorage) { this.name = name; this.apiClient = apiClient; this.storage = storage; this.auth = new AuthContainer(this); } async configure(options: { apiKey: string; endpoint: string; }): Promise<void> { this.apiClient.apiKey = options.apiKey; this.apiClient.endpoint = options.endpoint; const accessToken = await this.storage.safeGet(keyAccessToken(this.name)); this.apiClient.accessToken = accessToken; const userJSON = await this.storage.safeGetJSON(keyUser(this.name)); if (userJSON) { const user = decodeUser(userJSON); this.auth.currentUser = user; } else { this.auth.currentUser = null; } const identityJSON = await this.storage.safeGetJSON(keyIdentity(this.name)); if (identityJSON) { const identity = decodeIdentity(identityJSON); this.auth.currentIdentity = identity; } else { this.auth.currentIdentity = null; } } }
162f7bad2502d6fc3211fae0b2f4b899d8f7d9a6
TypeScript
rabobank-blockchain/ula-vc-data-management
/test/unit/model/address-model.test.ts
2.671875
3
/* * Copyright 2020 Coöperatieve Rabobank U.A. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { assert } from 'chai' import { Address, IAddress } from '../../../src' const testAddr: IAddress = { address: '0x3f8C962eb167aD2f80C72b5F933511CcDF0719D4', accountId: 101, keyId: 532, predicate: 'givenName' } describe('Address constructor', function () { it('should not accept empty address', () => { const createSut = () => { return new Address({ address: '', accountId: testAddr.accountId, keyId: testAddr.keyId, predicate: testAddr.predicate }) } assert.throws(createSut, ReferenceError, 'Address and/or predicate is empty') }) it('should not accept empty predicate', () => { const createSut = () => { return new Address({ address: testAddr.address, accountId: testAddr.accountId, keyId: testAddr.keyId, predicate: '' }) } assert.throws(createSut, ReferenceError, 'Address and/or predicate is empty') }) it('should not throw on valid inputs', () => { const createSut = () => { return new Address(testAddr) } assert.doesNotThrow(createSut) }) it('should convert a JSON object to a Address class', () => { const sut1 = new Address(testAddr) const jsonObj = JSON.parse(JSON.stringify(sut1)) const sut2 = new Address(jsonObj) assert.deepEqual(sut1, sut2) }) it('should return a stringified object', () => { const sut = new Address(testAddr) assert.deepEqual(JSON.stringify(sut), `{"address":"${testAddr.address}","accountId":${testAddr.accountId},"keyId":${testAddr.keyId},"predicate":"${testAddr.predicate}"}`) }) })
80e6fa3051e73796098e1227c3a8e9afdc25bf9e
TypeScript
nais/deploy-frontend
/packages/frontend/src/ui/userInfoReducer.ts
2.890625
3
import { USERINFO_REQUEST_SUCCESS, USERINFO_REQUEST_FAILED } from '../config/actionTypes' const userInfoReducer = ( state = { userName: '', }, action ) => { switch (action.type) { case USERINFO_REQUEST_SUCCESS: return { ...state, userName: `${action.value.givenName} ${action.value.surname}`, } case USERINFO_REQUEST_FAILED: return { ...state, userName: '', } default: return state } } export default userInfoReducer
01843e360bc110eb1e5ca29a6371b6f56d29682f
TypeScript
labs42io/itiriri-async
/test/iterators/intersect.test.ts
2.75
3
import { expect } from 'chai'; import { intersect } from '../../lib/iterators/intersect'; import { toArray } from '../helpers/toArray'; import { fromArray } from '../helpers/asyncGenerators'; describe('iterators/intersect', () => { describe('When called on empty sources', () => { it('Should return empty source', async () => { const source = []; const others = []; const iterator = intersect(fromArray(source), others, x => x); expect(await toArray(iterator)).to.be.deep.equal([]); }); }); describe('When called on some sources', () => { it('Should return all 3 elements', async () => { const source = [3, 4, 5]; const others = [3, 4, 5]; const iterator = intersect(fromArray(source), others, x => x); expect(await toArray(iterator)).to.be.deep.equal([3, 4, 5]); }); it('Should return all 4 elements', async () => { const source = [3, 44, 5, 1]; const others = [3, 1, 5, 44]; const iterator = intersect(fromArray(source), others, x => x); expect(await toArray(iterator)).to.be.deep.equal([3, 44, 5, 1]); }); it('Should return 2 elements', async () => { const source = [3, 44, 5, 1]; const others = [3, 7, 6, 44]; const iterator = intersect(fromArray(source), others, x => x); expect(await toArray(iterator)).to.be.deep.equal([3, 44]); }); it('Should return 1 element', async () => { const source = [3, 44, 5, 1, 20]; const others = [1, 1, 51, 444, 2]; const iterator = intersect(fromArray(source), others, x => x); expect(await toArray(iterator)).to.be.deep.equal([1]); }); it('Should return empty source', async () => { const source = [3, 44, 5, 1]; const others = [11, 11, 51, 414]; const iterator = intersect(fromArray(source), others, x => x); expect(await toArray(iterator)).to.be.deep.equal([]); }); it('Should return empty source', async () => { const source = [{ x: 1, y: 'aasdf' }, { x: 2, y: 'fdasd' }]; const others = [{ x: 2, y: 'asdf' }, { x: 3, y: 'asdf' }]; const iterator = intersect(fromArray(source), others, x => x.x); expect(await toArray(iterator)).to.be.deep.equal([{ x: 2, y: 'fdasd' }]); }); }); describe('When calling on some Promises', () => { it('Should return rejected Promise', async () => { // hitting all tests (coverage) const source = [ Promise.resolve(1).finally(), Promise.reject(1).finally(), Promise.resolve(1), ]; const q = intersect(fromArray(source), [], x => x); expect(toArray(q)).to.eventually.be.rejected; }); }); });
a75a30916e1335a624ec6473dc9a098ab3d02890
TypeScript
4ian/GDevelop
/Extensions/DraggableBehavior/draggableruntimebehavior.ts
2.828125
3
/* GDevelop - Draggable Behavior Extension Copyright (c) 2013-2021 Florian Rival (Florian.Rival@gmail.com) */ namespace gdjs { /** * The DraggableRuntimeBehavior represents a behavior allowing objects to be * moved using the mouse. */ export class DraggableRuntimeBehavior extends gdjs.RuntimeBehavior { /** * The manager that currently handles the dragging of the owner if any. * When the owner is being dragged, no other manager can start dragging it. */ _draggedByDraggableManager: DraggableManager | null = null; _checkCollisionMask: boolean; _justDropped = false; constructor( instanceContainer: gdjs.RuntimeInstanceContainer, behaviorData, owner ) { super(instanceContainer, behaviorData, owner); this._checkCollisionMask = behaviorData.checkCollisionMask ? true : false; } updateFromBehaviorData(oldBehaviorData, newBehaviorData): boolean { // Nothing to update. return true; } onDeActivate() { this._endDrag(); } onDestroy() { this.onDeActivate(); } _endDrag() { if (this._draggedByDraggableManager) { this._draggedByDraggableManager.endDrag(); this._justDropped = true; } this._draggedByDraggableManager = null; } _dismissDrag() { this._draggedByDraggableManager = null; } _tryBeginDrag(instanceContainer: gdjs.RuntimeInstanceContainer) { if (this._draggedByDraggableManager) { return false; } const inputManager = instanceContainer.getGame().getInputManager(); const touchIds = inputManager.getStartedTouchIdentifiers(); for (let i = 0; i < touchIds.length; ++i) { const touchDraggableManager = DraggableManager.getTouchManager( instanceContainer, touchIds[i] ); if (touchDraggableManager.isDragging(this)) { continue; } if (touchDraggableManager.tryAndTakeDragging(instanceContainer, this)) { this._draggedByDraggableManager = touchDraggableManager; return true; } } return false; } _shouldEndDrag(instanceContainer: gdjs.RuntimeInstanceContainer) { if (!this._draggedByDraggableManager) { return false; } return this._draggedByDraggableManager.shouldEndDrag( instanceContainer, this ); } _updateObjectPosition(instanceContainer: gdjs.RuntimeInstanceContainer) { if (!this._draggedByDraggableManager) { return false; } this._draggedByDraggableManager.updateObjectPosition( instanceContainer, this ); return true; } doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) { this._tryBeginDrag(instanceContainer); if (this._shouldEndDrag(instanceContainer)) { this._endDrag(); } this._updateObjectPosition(instanceContainer); } doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) { this._justDropped = false; } isDragged(): boolean { return !!this._draggedByDraggableManager; } wasJustDropped(): boolean { return this._justDropped; } } /** * Handle the dragging */ class DraggableManager { private _touchId: integer; /** * The object has left its original position. * When true, the search for the best object to drag has ended. */ protected _draggingSomething = false; /** * The behavior of the object that is being dragged and that is the best one (i.e: highest Z order) found. */ protected _draggableBehavior: gdjs.DraggableRuntimeBehavior | null = null; protected _xOffset: number = 0; protected _yOffset: number = 0; constructor( instanceContainer: gdjs.RuntimeInstanceContainer, touchId: integer ) { this._touchId = touchId; } /** * Get the platforms manager of an instance container. */ static getTouchManager( instanceContainer: gdjs.RuntimeInstanceContainer, touchId: integer ): DraggableManager { // @ts-ignore if (!instanceContainer.touchDraggableManagers) { //Create the shared manager if necessary. // @ts-ignore instanceContainer.touchDraggableManagers = []; } // @ts-ignore if (!instanceContainer.touchDraggableManagers[touchId]) { //Create the shared manager if necessary. // @ts-ignore instanceContainer.touchDraggableManagers[ touchId ] = new DraggableManager(instanceContainer, touchId); } // @ts-ignore return instanceContainer.touchDraggableManagers[touchId]; } tryAndTakeDragging( instanceContainer: gdjs.RuntimeInstanceContainer, draggableRuntimeBehavior: DraggableRuntimeBehavior ) { if ( this._draggableBehavior && draggableRuntimeBehavior.owner.getZOrder() <= this._draggableBehavior.owner.getZOrder() ) { return false; } const position = this.getPosition( instanceContainer, draggableRuntimeBehavior ); if ( !draggableRuntimeBehavior.owner.insideObject(position[0], position[1]) ) { return false; } else if ( draggableRuntimeBehavior._checkCollisionMask && !draggableRuntimeBehavior.owner.isCollidingWithPoint( position[0], position[1] ) ) { return false; } if (this._draggableBehavior) { // The previous best object to drag will not be dragged. this._draggableBehavior._dismissDrag(); } this._draggableBehavior = draggableRuntimeBehavior; this._xOffset = position[0] - draggableRuntimeBehavior.owner.getX(); this._yOffset = position[1] - draggableRuntimeBehavior.owner.getY(); return true; } updateObjectPosition( instanceContainer: gdjs.RuntimeInstanceContainer, draggableRuntimeBehavior: DraggableRuntimeBehavior ) { const position = this.getPosition( instanceContainer, draggableRuntimeBehavior ); if ( draggableRuntimeBehavior.owner.getX() != position[0] - this._xOffset || draggableRuntimeBehavior.owner.getY() != position[1] - this._yOffset ) { draggableRuntimeBehavior.owner.setX(position[0] - this._xOffset); draggableRuntimeBehavior.owner.setY(position[1] - this._yOffset); this._draggingSomething = true; } } endDrag() { this._draggingSomething = false; this._draggableBehavior = null; } isDragging(draggableRuntimeBehavior: DraggableRuntimeBehavior): boolean { return this._draggingSomething; } getPosition( instanceContainer: gdjs.RuntimeInstanceContainer, draggableRuntimeBehavior: DraggableRuntimeBehavior ): FloatPoint { const workingPoint: FloatPoint = gdjs.staticArray( DraggableManager.prototype.getPosition ) as FloatPoint; const inputManager = instanceContainer.getGame().getInputManager(); return instanceContainer .getLayer(draggableRuntimeBehavior.owner.getLayer()) .convertCoords( inputManager.getTouchX(this._touchId), inputManager.getTouchY(this._touchId), 0, workingPoint ); } shouldEndDrag( instanceContainer: gdjs.RuntimeInstanceContainer, draggableRuntimeBehavior: DraggableRuntimeBehavior ): boolean { const inputManager = instanceContainer.getGame().getInputManager(); return inputManager.hasTouchEnded(this._touchId); } } gdjs.registerBehavior( 'DraggableBehavior::Draggable', gdjs.DraggableRuntimeBehavior ); }
8e898fb61017b28ef818c6b073460ecc2be4c871
TypeScript
si-saude/saude-app
/src/app/model/avaliacao-fisica-atividade-fisica.ts
2.546875
3
import { AvaliacaoFisica } from './avaliacao-fisica'; import { AtividadeFisica } from './atividade-fisica'; export class AvaliacaoFisicaAtividadeFisica { private id: number; private avaliacaoFisica: AvaliacaoFisica; private atividadeFisica: AtividadeFisica; private domingo: boolean; private segunda: boolean; private terca: boolean; private quarta: boolean; private quinta: boolean; private sexta: boolean; private sabado: boolean; private tipo: string; private minuto: number; private totalMinuto: number; private classificacao: string; private observacao: string; private index: number; private version: number; getIndex() { return this.index; } setIndex(index: number) { this.index = index; } public getAvaliacaoFisica() { return this.avaliacaoFisica; } public setAvaliacaoFisica(avaliacaoFisica) { this.avaliacaoFisica = avaliacaoFisica; } public getAtividadeFisica() { return this.atividadeFisica; } public setAtividadeFisica(atividadeFisica) { this.atividadeFisica = atividadeFisica; } public getDomingo() { return this.domingo; } public setDomingo(domingo) { this.domingo = domingo; } public getSegunda() { return this.segunda; } public setSegunda(segunda) { this.segunda = segunda; } public getTerca() { return this.terca; } public setTerca(terca) { this.terca = terca; } public getQuarta() { return this.quarta; } public setQuarta(quarta) { this.quarta = quarta; } public getQuinta() { return this.quinta; } public setQuinta(quinta) { this.quinta = quinta; } public getSexta() { return this.sexta; } public setSexta(sexta) { this.sexta = sexta; } public getSabado() { return this.sabado; } public setSabado(sabado) { this.sabado = sabado; } public getTipo() { return this.tipo; } public setTipo(tipo) { this.tipo = tipo; } public getMinuto() { return this.minuto; } public setMinuto(minuto) { this.minuto = minuto; } public getTotalMinuto() { return this.totalMinuto; } public setTotalMinuto(totalMinuto) { this.totalMinuto = totalMinuto; } public getClassificacao() { return this.classificacao; } public setClassificacao(classificacao) { this.classificacao = classificacao; } public getObservacao() { return this.observacao; } public setObservacao(observacao) { this.observacao = observacao; } public getId() { return this.id; } public setId(id) { this.id = id; } public getVersion() { return this.version; } public setVersion(version) { this.version = version; } }
90f0142fe45447749b36c622d6e6688ce892baae
TypeScript
mateusdeitos/rocketseat-ignite-autenticacao-next
/services/api.ts
2.65625
3
import axios, { AxiosError } from "axios"; import { parseCookies, setCookie } from 'nookies'; import { signOut } from "../contexts/AuthContext"; import { AuthTokenError } from "../errors/AuthTokenError"; let isRefreshing = false; let failedRequestsQueue = []; // Ao fazer dessa forma, funciona client side e server side, pois serverSide irá passar o context export const setupApiClient = (ctx = undefined) => { let cookies = parseCookies(ctx); const api = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_URL, headers: { Authorization: `Bearer ${cookies['nextauth.token']}` } }); api.interceptors.response.use( response => response, (error: AxiosError) => { if (error.response.status === 401) { if (error.response.data?.code === 'token.expired') { // renovar o token cookies = parseCookies(ctx); // Objeto armazena dados do request original const originalRequest = error.config; if (!isRefreshing) { // Garante que somente uma chamada para refresh será feita ao expirar o token isRefreshing = true; console.log('is-refreshing') api.post('/refresh', { refreshToken: cookies['nextauth.refreshToken'] }).then(response => { const { token, refreshToken } = response.data; setCookie(ctx, 'nextauth.token', token, { maxAge: 60 * 60 * 24 * 30, path: '/' }) setCookie(ctx, 'nextauth.refreshToken', refreshToken, { maxAge: 60 * 60 * 24 * 30, path: '/' }) api.defaults.headers['Authorization'] = `Bearer ${token}`; // Executa todos requests dentro da fila failedRequestsQueue.forEach(request => request.onSuccess(token)); failedRequestsQueue = []; }).catch(err => { // Retorna falha em todos requests da fila failedRequestsQueue.forEach(request => request.onFailure(err)); failedRequestsQueue = []; if (process.browser) { signOut(); } }).finally(() => { isRefreshing = false; }) } // o Axios não suporta que a funcao onError seja async, então é necessário retornar uma promise // Adiciona o request que falhou em uma fila para executar após o refresh ser feito return new Promise((resolve, reject) => { failedRequestsQueue.push({ // Quando o token foi atualizado com sucesso onSuccess: (token: string) => { originalRequest.headers['Authorization'] = `Bearer ${token}`; // É feito dessa forma pra o axios aguardar isso ser feito resolve(api(originalRequest)); }, // Quando o token não for atualizado onFailure: (err: AxiosError) => { reject(err); } }) }) } else { if (process.browser) { signOut(); } else { return Promise.reject(new AuthTokenError()); } } } return Promise.reject(error); }) return api; }
242d65f936ae27f88be908b5a5c256ec8559f988
TypeScript
Ambial/AngularTodo
/src/app/services/task.service.ts
2.515625
3
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from "@angular/common/http"; import { Observable } from "rxjs"; import { Task } from "../Task"; const httpOptions = { headers: new HttpHeaders({ 'Content-Type':'application/json' }) } @Injectable({ providedIn: 'root' }) export class TaskService { private apiURL = 'http://localhost:5000/tasks' constructor(private http:HttpClient) { } getTasks(): Observable<Task[]> { return this.http.get<Task[]>(this.apiURL) } deleteTask(task:Task):Observable<Task>{ const url = `${this.apiURL}/${task.id}` return this.http.delete<Task>(url); } toggleReminder(alteredTask:Task):Observable<Task>{ const url = `${this.apiURL}/${alteredTask.id}` return this.http.patch<Task>(url, { "reminder":alteredTask.reminder }, httpOptions); } addTask(newTask:Task):Observable<Task>{ const rand = Math.floor(Math.random() * 10000); newTask.id = rand; const url = this.apiURL return this.http.post<Task>(url, newTask, httpOptions); } }
25886ccc09b0d45a684eeb765d8ddac59aab6b73
TypeScript
gabs-work/random-users-from-country
/src/server.ts
2.5625
3
import axios from 'axios' import { Request, Response, Application } from 'express' import { AsyncAttempt } from 'attempt-ts' import config from './config.json' import sameCountryService from './same-country' import nationalizeService from './nationalize' import randomUserService from './random-user' import express = require('express') // Express server const server: Application = express() const port = config.port const nClient = axios.create({ baseURL: config.nationalizeClientURL, timeout: 1000, }) const rClient = axios.create({ baseURL: config.randomUserClientURL, timeout: 1000, }) // Pulled from the randomUser API since it can only generate users from these locations const validLocations = config.validLocations // SameCountryService with all clients injected const service = sameCountryService( nationalizeService(nClient), randomUserService(rClient, validLocations) ) server.get('/same_country/:name', async (req: Request, res: Response) => { const name = req.params.name ?? '' try { const result = await AsyncAttempt(service.getUsersFromSameCountryAsName(name)) res.json(result) } catch (err) { res.status(err.status || 500).json(err) } }) server.listen(port, () => { console.log(`Ready and listening on port ${port}`) })
03ce2acd446957f0ba39faaea89b31fe3bf71135
TypeScript
wailorman/ball-fixtures
/src/utils.ts
2.984375
3
import { pad } from 'lodash'; import { Fixtures } from './types'; export function generateUUID(...args: (string | number)[]): string { // 5095072f-5308-40a5-b994-e9b05230a4dd // 8| 13| 18| 23| 36| const ONE_GROUP_LENGTH = 8; const TWO_GROUPS_LENGTH = 13; const THREE_GROUPS_LENGTH = 18; const FOUR_GROUPS_LENGTH = 23; const FIVE_GROUPS_LENGTH = 36; const FULL_UUID_LENGTH = 36; const res: string[] = []; const pushStrToRes = (str: string) => { `${str}` .replace(/[^0-9a-f]/g, '0') .split('') .forEach(char => { if (res.length >= FULL_UUID_LENGTH) { return; } if ( res.length === ONE_GROUP_LENGTH || res.length === TWO_GROUPS_LENGTH || res.length === THREE_GROUPS_LENGTH || res.length === FOUR_GROUPS_LENGTH ) { res.push('-'); } res.push(char); }); return res.join(''); }; const makeNextGroup = () => { if (res.length < ONE_GROUP_LENGTH) { const len = ONE_GROUP_LENGTH - res.length; pushStrToRes(pad('0', len, '0')); } else if (res.length < TWO_GROUPS_LENGTH) { const len = TWO_GROUPS_LENGTH - res.length; pushStrToRes(pad('0', len, '0')); } else if (res.length < THREE_GROUPS_LENGTH) { const len = THREE_GROUPS_LENGTH - res.length; pushStrToRes(pad('0', len, '0')); } else if (res.length < FOUR_GROUPS_LENGTH) { const len = FOUR_GROUPS_LENGTH - res.length; pushStrToRes(pad('0', len, '0')); } else if (res.length < FIVE_GROUPS_LENGTH) { const len = FIVE_GROUPS_LENGTH - res.length; pushStrToRes(pad('0', len, '0')); } }; [args[0], args[1], args[2], args[3], args[4]].forEach(arg => { if (arg) { pushStrToRes(`${arg}f`); } else { pushStrToRes('f'); } makeNextGroup(); }); return res.join(''); } export function mergeFixtures(array: Fixtures[]): Fixtures { return array.reduce((curFixturesSet, resFixtures) => { Object.keys(curFixturesSet).forEach(modelName => { resFixtures[modelName] = [ ...(resFixtures[modelName] || []), ...(curFixturesSet[modelName] || []), ]; }); return resFixtures; }, {}); } export interface ArrayToMapOpts { /** if element in array is object */ key?: string | ((arrayElem: any) => string); } export function arrayToMap(array: any[], opts?: ArrayToMapOpts) { const { key = null } = opts || {}; return array.reduce((prev, cur: any | object) => { if (typeof cur === 'object' && key) { if (typeof key === 'function') { prev[key(cur)] = cur; } else { prev[cur[key]] = cur; } } else { prev[cur] = true; } return prev; }, {}); }
49636a8c3308b1b2569b8889dbddbaa19b669736
TypeScript
angular-empowerment-club/webinar-folgen
/apps/folge-4/src/app/stock-risk-filter/stock-risk-filter.component.ts
2.53125
3
import { Component, EventEmitter, Output, OnInit } from '@angular/core'; import { StockQuoteRisk } from '../models'; @Component({ selector: 'aec-stock-risk-filter', templateUrl: './stock-risk-filter.component.html', styleUrls: ['./stock-risk-filter.component.css'] }) export class StockRiskFilterComponent implements OnInit { risks = StockQuoteRisk; riskKeys = Object.keys(this.risks).filter(r => !isNaN(+r)); /** * Represents the initial State of the filter * where all known risks are selected. */ activeRisks = [...this.riskKeys]; @Output() update = new EventEmitter<string[]>(); ngOnInit(): void { this.update.emit(this.activeRisks); } updateActiveRisks(key: string) { this.isRiskActive(key) ? (this.activeRisks = this.activeRisks.filter(k => k !== key)) : (this.activeRisks = [...this.activeRisks, key]); this.update.emit(this.activeRisks); } isRiskActive(key: string) { return this.activeRisks.includes(key); } }
4cb12843b4c775e0c83767633c9ec25a7d4fb541
TypeScript
Diaa-Ghonim/article-app-server
/src/infrastructure/db/entities/user/index.ts
2.734375
3
import { Entity, ObjectIdColumn, Column, ObjectID, OneToMany } from 'typeorm'; import User from '../../../../core/domain/entities/User'; /** * here we can name Entity inside it between paranthese * and also can add constructor to Entity class * */ @Entity() export class EntityUser { @ObjectIdColumn() id: ObjectID; @Column({ type: 'string' }) username: string; @Column({ type: 'string' }) name: string; @Column({ type: 'string' }) email: string; @Column({ type: 'string' }) password: string; @Column({ type: 'string' }) profImage: string; @Column({ type: 'string', name: 'bio', nullable: true }) bio?: string | undefined; @Column({ nullable: true }) dateOfBirth: object; @Column({ type: 'number', name: 'age', nullable: true }) age: number | undefined; @Column({ type: 'number' }) rate: number; @Column({ type: 'array' }) followers: User[]; @Column({ type: 'array' }) following: User[]; }
8ff2c94c88c70c4046e8ba59c77ac0a7e3d610dc
TypeScript
Svaly/angularTraining
/src/app/shared-controls/status-flow-radio-button/radio-button-allowed-values-transitions-graph.spec.ts
2.71875
3
import { RadioButtonAllowedValuesTransitionsGraph } from './radio-button-allowed-values-transitions-graph'; describe('RadioButtonAllowedValuesTransitionsGraph', () => { it('should create an instance', () => { expect(new RadioButtonAllowedValuesTransitionsGraph()).toBeTruthy(); }); it('should create an instance with allowed transitions', () => { const instance = new RadioButtonAllowedValuesTransitionsGraph([{from: 'a', to: 'b'}, {from: 'a', to: 'c'}, ]); expect(instance.getAllowedTransitions('a')).toContain('a'); expect(instance.getAllowedTransitions('a')).toContain('b'); expect(instance.getAllowedTransitions('a')).toContain('c'); expect(instance.getAllowedTransitions('b')).toEqual(['b']); expect(instance.getAllowedTransitions('c')).toEqual(['c']); expect(instance.getAllowedTransitions('d')).toEqual([]); }); it('should add allowed transition', () => { const instance = new RadioButtonAllowedValuesTransitionsGraph(); instance.addAllowedValueTransition('a', 'b'); expect(instance.getAllowedTransitions('a')).toContain('a'); expect(instance.getAllowedTransitions('a')).toContain('b'); expect(instance.getAllowedTransitions('b')).toEqual(['b']); }); it('should add transition only once', () => { const instance = new RadioButtonAllowedValuesTransitionsGraph(); instance.addAllowedValueTransition('a', 'b'); instance.addAllowedValueTransition('a', 'b'); expect(instance.getAllowedTransitions('a').length).toBe(2); expect(instance.getAllowedTransitions('b').length).toBe(1); }); });
93e9b7b88ba409e822cff2c6aa24317e3b03e0ef
TypeScript
devyonghee/mybloglab
/front/src/features/root-actions.ts
2.578125
3
import { Action } from 'redux'; type TypeConstant = string; export interface AppAction<T extends TypeConstant, P> extends Action<T> { type: T; payload: P; }
4c8263db028c3a2000d3b1cfe22bd96ddf7b6c4e
TypeScript
neko-gg/gfl-combat-simulator
/src/app/model/EquipStats.ts
2.875
3
export class EquipStat { min: number; max: number; upgrade: number; } export default class EquipStats { damage: EquipStat | undefined; rof: EquipStat | undefined; accuracy: EquipStat | undefined; evasion: EquipStat | undefined; armor: EquipStat | undefined; movementSpeed: EquipStat | undefined; armorPenetration: EquipStat | undefined; criticalRate: EquipStat | undefined; criticalDamage: EquipStat | undefined; rounds: EquipStat | undefined; nightVision: EquipStat | undefined; skillEffectModifier: number | undefined; } export class CurrentEquipStats { damage = 0; rof = 0; accuracy = 0; evasion = 0; armor = 0; movementSpeed = 0; armorPenetration = 0; criticalRate = 0; criticalDamage = 0; rounds = 0; nightVision = 0; skillEffectModifier = 0; sum(other: CurrentEquipStats): CurrentEquipStats { const sum = new CurrentEquipStats(); Object.keys(this) .forEach((key: keyof CurrentEquipStats) => (sum[key] as number) = (this[key] as number || 0) + (other[key] as number || 0)); return sum; } } export function getFormattedStatName(stat: keyof CurrentEquipStats): string { if ('rof' === stat) return 'RoF'; const unCamelCase = stat.split(/(?=[A-Z])/) .join(' '); return unCamelCase.charAt(0).toUpperCase() + unCamelCase.slice(1); } export function getFormattedStatValue(stat: keyof CurrentEquipStats, value: number): string { const positivePrefix = `${value > 0 ? '+' : ''}`; if (['criticalRate', 'criticalDamage', 'nightVision'].includes(stat)) return `${positivePrefix}${value}﹪`; return `${positivePrefix}${value}`; }
2730675b1d2f9d1c9948cb11489833f7075fdcec
TypeScript
Happy-Ferret/nesemu
/src/nes/apu.ts
2.75
3
// APU: Audio Processing Unit import {Address, Byte} from './types' export enum PadBit { A = 0, B = 1, SELECT = 2, START = 3, U = 4, D = 5, L = 6, R = 7, } export enum PadValue { A = 1 << PadBit.A, B = 1 << PadBit.B, SELECT = 1 << PadBit.SELECT, START = 1 << PadBit.START, U = 1 << PadBit.U, D = 1 << PadBit.D, L = 1 << PadBit.L, R = 1 << PadBit.R, } const BASE = 0x4000 const STATUS_REG = 0x15 const PAD1_REG = 0x16 const PAD2_REG = 0x17 const FRAME_COUNTER = 0x17 const IRQ_INHIBIT = 1 << 6 const SEQUENCER_MODE = 1 << 7 const CONSTANT_VOLUME = 0x10 const LENGTH_COUNTER_HALT = 0x20 const CH_PULSE1 = 0 const CH_PULSE2 = 1 const CH_TRIANGLE = 2 const CH_NOISE = 3 const kLengthTable = [ 0x0a, 0xfe, 0x14, 0x02, 0x28, 0x04, 0x50, 0x06, 0xa0, 0x08, 0x3c, 0x0a, 0x0e, 0x0c, 0x1a, 0x0e, 0x0c, 0x10, 0x18, 0x12, 0x30, 0x14, 0x60, 0x16, 0xc0, 0x18, 0x48, 0x1a, 0x10, 0x1c, 0x20, 0x1e, ] const kNoiseFrequencies = ( [4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068] .map(v => v * 1)) const VBLANK_START = 241 // ================================================================ // GamePad class GamePad { private status = new Array<Byte>(2) private tmp = new Array<Byte>(2) public setStatus(no: number, status: Byte): void { this.status[no] = status } public latch(): void { this.tmp[0] = this.status[0] this.tmp[1] = this.status[1] } public shift(no: number): number { const result = this.tmp[no] this.tmp[no] = result >> 1 return result & 1 } } // ================================================================ // Sound channel class Channel { protected regs = new Uint8Array(4) public reset() { this.regs.fill(0) } public write(reg: number, value: Byte) { this.regs[reg] = value } public getVolume(): number { return 0 } public getFrequency(): number { return 0 } public stop() {} public update() {} public isPlaying(): boolean { return false } } class PulseChannel extends Channel { private stopped = false private lengthCounter = 0 private sweepCounter = 0 public reset() { super.reset() this.stopped = true this.sweepCounter = 0 } public stop() { this.stopped = true } public write(reg: number, value: Byte) { super.write(reg, value) switch (reg) { case 1: this.sweepCounter = value >> 4 break case 3: // Set length. const length = kLengthTable[value >> 3] this.lengthCounter = length this.stopped = false break default: break } } public isPlaying(): boolean { return !this.stop } public getVolume(): number { if (this.stopped) return 0 let v = this.regs[0] if ((v & CONSTANT_VOLUME) !== 0) return (v & 15) / 15.0 return 1 } public getFrequency(): number { const value = this.regs[2] + ((this.regs[3] & 7) << 8) return ((1790000 / 16) / (value + 1)) | 0 } public update() { if (this.stopped) return 0 this.updateVolumes() this.sweep() } private updateVolumes(): void { let l = this.lengthCounter let v = this.regs[0] if ((v & LENGTH_COUNTER_HALT) === 0) { this.lengthCounter = l -= 2 * 4 if (l <= 0) { this.regs[0] = v = (v & 0xf0) // Set volume = 0 this.lengthCounter = 0 this.stopped = true } } } // APU Sweep: http://wiki.nesdev.com/w/index.php/APU_Sweep private sweep(): void { const sweep = this.regs[1] if ((sweep & 0x80) === 0) // Not enabled. return let c = this.sweepCounter c += 2 // 2 sequences per frame. const count = (sweep >> 4) & 7 if (c >= count) { c -= count let freq = this.regs[2] + ((this.regs[3] & 7) << 8) const shift = sweep & 7 if (shift > 0) { const add = freq >> shift if ((sweep & 0x08) === 0) { freq += add if (freq > 0x07ff) this.stopped = true } else { freq -= add if (freq < 8) this.stopped = true } this.regs[2] = freq & 0xff this.regs[3] = (this.regs[3] & ~7) | ((freq & 0x0700) >> 8) } c -= 2 // 2 sequences per frame if (c <= 0) { this.sweepCounter = ((sweep >> 4) & 7) + c } } this.sweepCounter = c } } class TriangleChannel extends Channel { private stopped = false private lengthCounter = 0 public reset() { super.reset() this.stopped = true } public stop() { this.stopped = true } public write(reg: number, value: Byte) { super.write(reg, value) switch (reg) { case 3: // Set length. const length = kLengthTable[value >> 3] this.lengthCounter = length this.stopped = false break default: break } } public isPlaying(): boolean { return !this.stop } public getVolume(): number { if (this.stopped) return 0 return 1 } public getFrequency(): number { const value = this.regs[2] + ((this.regs[3] & 7) << 8) return ((1790000 / 32) / (value + 1)) | 0 } public update() { if (this.stopped) return this.updateVolumes() } private updateVolumes(): void { let l = this.lengthCounter let v = this.regs[0] if ((v & LENGTH_COUNTER_HALT) === 0) { this.lengthCounter = l -= 2 * 4 if (l <= 0) { this.regs[0] = v = (v & 0xf0) // Set volume = 0 this.lengthCounter = 0 this.stopped = true } } } } class NoiseChannel extends Channel { private stopped = false private lengthCounter = 0 public reset() { super.reset() this.stopped = true } public stop() { this.stopped = true } public write(reg: number, value: Byte) { super.write(reg, value) switch (reg) { case 3: // Set length. const length = kLengthTable[value >> 3] this.lengthCounter = length this.stopped = false break default: break } } public isPlaying(): boolean { return !this.stop } public getVolume(): number { if (this.stopped) return 0 let v = this.regs[0] if ((v & CONSTANT_VOLUME) !== 0) return (v & 15) / 15.0 return 1 } public getFrequency(): number { const period = this.regs[2] & 15 return kNoiseFrequencies[period] } public update() { if (this.stopped) return this.updateVolumes() } private updateVolumes(): void { let l = this.lengthCounter let v = this.regs[0] if ((v & LENGTH_COUNTER_HALT) === 0) { this.lengthCounter = l -= 2 * 4 if (l <= 0) { this.regs[0] = v = (v & 0xf0) // Set volume = 0 this.lengthCounter = 0 this.stopped = true } } } } // ================================================================ // Apu export class Apu { public static CHANNEL = 4 private regs = new Uint8Array(0x20) private channels = new Array<Channel>(Apu.CHANNEL) private frameInterrupt = 0 // 0=not occurred, 0x40=occurred private dmcInterrupt = 0x80 // 0=not occurred, 0x80=occurred private gamePad = new GamePad() constructor(private triggerIrq: () => void) { this.channels[CH_PULSE1] = new PulseChannel() this.channels[CH_PULSE2] = new PulseChannel() this.channels[CH_TRIANGLE] = new TriangleChannel() this.channels[CH_NOISE] = new NoiseChannel() } public reset() { this.regs.fill(0) this.regs[FRAME_COUNTER] = IRQ_INHIBIT this.frameInterrupt = 0 this.dmcInterrupt = 0x80 // TODO: Implement this.channels.forEach(channel => { channel.reset() }) } public read(adr: Address): Byte { const reg = adr - BASE switch (reg) { case STATUS_REG: { // TODO: Implement. let result = this.dmcInterrupt | this.frameInterrupt for (let ch = 0; ch < Apu.CHANNEL; ++ch) { if (this.channels[ch].isPlaying()) result |= 1 << ch } // Reading this register clears the frame interrupt flag (but not the DMC interrupt flag). this.frameInterrupt = 0 return result } case PAD1_REG: case PAD2_REG: return this.gamePad.shift(reg - PAD1_REG) default: return 0 } } public write(adr: Address, value: Byte): void { const reg = adr - BASE if (reg >= 0x20) return this.regs[reg] = value if (reg < 0x10) { // Sound const ch = reg >> 2 const r = reg & 3 this.channels[ch].write(r, value) } switch (reg) { case STATUS_REG: this.dmcInterrupt = 0 // Writing to this register clears the DMC interrupt flag. for (let ch = 0; ch < Apu.CHANNEL; ++ch) { if ((this.regs[STATUS_REG] & (1 << ch)) === 0) this.channels[ch].stop() } break case PAD1_REG: // Pad status. bit0 = Controller shift register strobe if ((value & 1) === 0) { this.gamePad.latch() } break default: break } } public getVolume(ch: number): number { return this.channels[ch].getVolume() } public getFrequency(ch: number): number { return this.channels[ch].getFrequency() } public setPadStatus(no: number, status: Byte): void { this.gamePad.setStatus(no, status) } public onHblank(hcount: number): void { switch (hcount) { case VBLANK_START: this.channels.forEach(channel => { channel.update() }) if (this.isIrqEnabled()) { this.frameInterrupt = 0x40 this.triggerIrq() } break default: break } } private isIrqEnabled(): boolean { // http://wiki.nesdev.com/w/index.php/IRQ // Enable: $4017 write with bits 7-6 = 00 return (this.regs[FRAME_COUNTER] & (IRQ_INHIBIT | SEQUENCER_MODE)) === 0 } }
fd929a988742b605f9b65ad1f8de84ed1bc45169
TypeScript
combinatorist/grist-core
/app/client/models/SearchModel.ts
2.546875
3
// tslint:disable:no-console // TODO: Add documentation and clean up log statements. import {GristDoc} from 'app/client/components/GristDoc'; import {ViewFieldRec, ViewSectionRec} from 'app/client/models/DocModel'; import {delay} from 'app/common/delay'; import {waitObs} from 'app/common/gutil'; import {TableData} from 'app/common/TableData'; import {BaseFormatter, createFormatter} from 'app/common/ValueFormatter'; import {Disposable, Observable} from 'grainjs'; import debounce = require('lodash/debounce'); /** * SearchModel used to maintain the state of the search UI. */ export interface SearchModel { value: Observable<string>; // string in the search input isOpen: Observable<boolean>; // indicates whether the search bar is expanded to show the input noMatch: Observable<boolean>; // indicates if there are no search matches isRunning: Observable<boolean>; // indicates that matching is in progress findNext(): Promise<void>; // find next match findPrev(): Promise<void>; // find previous match } interface SearchPosition { tabIndex: number; sectionIndex: number; rowIndex: number; fieldIndex: number; } class Stepper<T> { public array: ReadonlyArray<T> = []; public index: number = 0; public inRange() { return this.index >= 0 && this.index < this.array.length; } // Doing await at every step adds a ton of overhead; we can optimize by returning and waiting on // Promises only when needed. public next(step: number, nextArrayFunc: () => Promise<void>|void): Promise<void>|void { this.index += step; if (!this.inRange()) { // If index reached the end of the array, take a step at a higher level to get a new array. // For efficiency, only wait asynchronously if the callback returned a promise. const p = nextArrayFunc(); if (p) { return p.then(() => this.setStart(step)); } else { this.setStart(step); } } } public setStart(step: number) { this.index = step > 0 ? 0 : this.array.length - 1; } public get value(): T { return this.array[this.index]; } } /** * Implementation of SearchModel used to construct the search UI. */ export class SearchModelImpl extends Disposable implements SearchModel { public readonly value = Observable.create(this, ''); public readonly isOpen = Observable.create(this, false); public readonly isRunning = Observable.create(this, false); public readonly noMatch = Observable.create(this, true); private _searchRegexp: RegExp; private _tabStepper = new Stepper<any>(); private _sectionStepper = new Stepper<ViewSectionRec>(); private _sectionTableData: TableData; private _rowStepper = new Stepper<number>(); private _fieldStepper = new Stepper<ViewFieldRec>(); private _fieldFormatters: BaseFormatter[]; private _startPosition: SearchPosition; private _tabsSwitched: number = 0; constructor(private _gristDoc: GristDoc) { super(); // Listen to input value changes (debounced) to activate searching. const findFirst = debounce((_value: string) => this._findFirst(_value), 100); this.autoDispose(this.value.addListener(v => { void findFirst(v); })); } public async findNext() { if (this.noMatch.get()) { return; } this._startPosition = this._getCurrentPosition(); await this._nextField(1); return this._matchNext(1); } public async findPrev() { if (this.noMatch.get()) { return; } this._startPosition = this._getCurrentPosition(); await this._nextField(-1); return this._matchNext(-1); } private _findFirst(value: string) { if (!value) { this.noMatch.set(true); return; } this._searchRegexp = makeRegexp(value); const tabs: any[] = this._gristDoc.docModel.allDocPages.peek(); this._tabStepper.array = tabs; this._tabStepper.index = tabs.findIndex(t => t.viewRef() === this._gristDoc.activeViewId.get()); if (this._tabStepper.index < 0) { this.noMatch.set(true); return; } const view = this._tabStepper.value.view.peek(); const sections: any[] = view.viewSections().peek(); this._sectionStepper.array = sections; this._sectionStepper.index = sections.findIndex(s => s.getRowId() === view.activeSectionId()); if (this._sectionStepper.index < 0) { this.noMatch.set(true); return; } this._initNewSectionShown(); // Find the current cursor position in the current section. const viewInstance = this._sectionStepper.value.viewInstance.peek()!; const pos = viewInstance.cursor.getCursorPos(); this._rowStepper.index = pos.rowIndex!; this._fieldStepper.index = pos.fieldIndex!; this._startPosition = this._getCurrentPosition(); return this._matchNext(1); } private async _matchNext(step: number): Promise<void> { const indicatorTimer = setTimeout(() => this.isRunning.set(true), 300); try { const searchRegexp = this._searchRegexp; let count = 0; let lastBreak = Date.now(); this._tabsSwitched = 0; while (!this._matches() || ((await this._loadSection(step)) && !this._matches())) { // To avoid hogging the CPU for too long, check time periodically, and if we've been running // for long enough, take a brief break. We choose a 5ms break every 20ms; and only check // time every 100 iterations, to avoid excessive overhead purely due to time checks. if ((++count) % 100 === 0 && Date.now() >= lastBreak + 20) { await delay(5); lastBreak = Date.now(); // After other code had a chance to run, it's possible that we are now searching for // something else, in which case abort this task. if (this._searchRegexp !== searchRegexp) { console.log("SearchBar: aborting search since a new one was started"); return; } } const p = this._nextField(step); if (p) { await p; } // Detect when we get back to the start position; this is where we break on no match. if (this._isCurrentPosition(this._startPosition)) { console.log("SearchBar: reached start position without finding anything"); this.noMatch.set(true); return; } // A fail-safe to prevent certain bugs from causing infinite loops; break also if we scan // through tabs too many times. // TODO: test it by disabling the check above. if (this._tabsSwitched > this._tabStepper.array.length) { console.log("SearchBar: aborting search due to too many tab switches"); this.noMatch.set(true); return; } } console.log("SearchBar: found a match at %s", JSON.stringify(this._getCurrentPosition())); this.noMatch.set(false); await this._highlight(); } finally { clearTimeout(indicatorTimer); this.isRunning.set(false); } } private _getCurrentPosition(): SearchPosition { // It's important to call _getCurrentPosition() in the visible tab, since other tabs will not // use the currently visible version of the data (with the same sort and filter). return { tabIndex: this._tabStepper.index, sectionIndex: this._sectionStepper.index, rowIndex: this._rowStepper.index, fieldIndex: this._fieldStepper.index, }; } private _isCurrentPosition(pos: SearchPosition): boolean { return ( this._tabStepper.index === pos.tabIndex && this._sectionStepper.index === pos.sectionIndex && this._rowStepper.index === pos.rowIndex && this._fieldStepper.index === pos.fieldIndex ); } private _nextField(step: number): Promise<void>|void { return this._fieldStepper.next(step, () => this._nextRow(step)); // console.log("nextField", this._fieldStepper.index); } private _nextRow(step: number) { return this._rowStepper.next(step, () => this._nextSection(step)); // console.log("nextRow", this._rowStepper.index); } private async _nextSection(step: number) { // Switching sections is rare enough that we don't worry about optimizing away `await` calls. await this._sectionStepper.next(step, () => this._nextTab(step)); // console.log("nextSection", this._sectionStepper.index); await this._initNewSectionAny(); } // TODO There are issues with filtering. A section may have filters applied, and it may be // auto-filtered (linked sections). If a tab is shown, we have the filtered list of rowIds; if // the tab is not shown, it takes work to apply explicit filters. For linked sections, the // sensible behavior seems to scan through ALL values, then once a match is found, set the // cursor that determines the linking to include the matched row. And even that may not always // be possible. So this is an open question. private _initNewSectionCommon() { const section = this._sectionStepper.value; const tableModel = this._gristDoc.getTableModel(section.table.peek().tableId.peek()); this._sectionTableData = tableModel.tableData; this._fieldStepper.array = section.viewFields().peek(); this._fieldFormatters = this._fieldStepper.array.map( f => createFormatter(f.displayColModel().type(), f.widgetOptionsJson())); return tableModel; } private _initNewSectionShown() { this._initNewSectionCommon(); const viewInstance = this._sectionStepper.value.viewInstance.peek()!; this._rowStepper.array = viewInstance.sortedRows.getKoArray().peek() as number[]; } private async _initNewSectionAny() { const tableModel = this._initNewSectionCommon(); const viewInstance = this._sectionStepper.value.viewInstance.peek(); if (viewInstance) { this._rowStepper.array = viewInstance.sortedRows.getKoArray().peek() as number[]; } else { // If we are searching through another tab (not currently loaded), we will NOT have a // viewInstance, but we use the unsorted unfiltered row list, and if we find a match, the // _loadSection() method will load the tab and we'll repeat the search with a viewInstance. await tableModel.fetch(); this._rowStepper.array = this._sectionTableData.getRowIds(); } } private async _nextTab(step: number) { await this._tabStepper.next(step, () => undefined); this._tabsSwitched++; // console.log("nextTab", this._tabStepper.index); const view = this._tabStepper.value.view.peek(); this._sectionStepper.array = view.viewSections().peek(); } private _matches(): boolean { if (this._tabStepper.index < 0 || this._sectionStepper.index < 0 || this._rowStepper.index < 0 || this._fieldStepper.index < 0) { console.warn("match outside"); return false; } const field = this._fieldStepper.value; const formatter = this._fieldFormatters[this._fieldStepper.index]; const rowId = this._rowStepper.value; const displayCol = field.displayColModel.peek(); const value = this._sectionTableData.getValue(rowId, displayCol.colId.peek()); // TODO: Note that formatting dates is now the bulk of the performance cost. const text = formatter.format(value); return this._searchRegexp.test(text); } private async _loadSection(step: number): Promise<boolean> { // If we found a match in a section for which we don't have a valid BaseView instance, we need // to load the BaseView and start searching the section again, since the match we found does // not take into account sort or filters. So we switch to the right tab, wait for the // viewInstance to be created, reset the section info, and return true to continue searching. const section = this._sectionStepper.value; if (!section.viewInstance.peek()) { const view = this._tabStepper.value.view.peek(); await this._gristDoc.openDocPage(view.getRowId()); console.log("SearchBar: loading view %s section %s", view.getRowId(), section.getRowId()); const viewInstance: any = await waitObs(section.viewInstance); await viewInstance.getLoadingDonePromise(); this._initNewSectionShown(); this._rowStepper.setStart(step); this._fieldStepper.setStart(step); console.log("SearchBar: loaded view %s section %s", view.getRowId(), section.getRowId()); return true; } return false; } // Highlights the cell at the current position. private async _highlight() { const view = this._tabStepper.value.view.peek(); await this._gristDoc.openDocPage(view.getRowId()); const section = this._sectionStepper.value; view.activeSectionId(section.getRowId()); // We may need to wait for the BaseView instance to load. const viewInstance = await waitObs<any>(section.viewInstance); await viewInstance.getLoadingDonePromise(); viewInstance.setCursorPos({ rowIndex: this._rowStepper.index, fieldIndex: this._fieldStepper.index, }); // Highlight the selected cursor, after giving it a chance to update. We find the cursor in // this ad-hoc way rather than use observables, to avoid the overhead of *every* cell // depending on an additional observable. await delay(0); const cursor = viewInstance.viewPane.querySelector('.selected_cursor'); if (cursor) { cursor.classList.add('search-match'); setTimeout(() => cursor.classList.remove('search-match'), 20); } } } function makeRegexp(value: string) { // From https://stackoverflow.com/a/3561711/328565 const escaped = value.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); return new RegExp(escaped, 'i'); }
a7770b51f16fc1506616f3048631f160dd60f665
TypeScript
shrestharosy/nest-official-course
/src/common/dto/pagination-query.dto.ts
2.59375
3
import { Type } from 'class-transformer'; import { IsOptional, IsPositive } from 'class-validator'; export class PaginationQueryDto { // tranform query param of type string to number // alternative is to add transformOptions: enableImplicitConversion: true,} in global validation pipe options @Type(() => Number) @IsOptional() @IsPositive() limit: number; @Type(() => Number) @IsOptional() @IsPositive() offset: number; }
8c6989cc07881248dd70d4e488b4195e3f4e8e2f
TypeScript
TiliaKS/TypeScript
/src/app.ts
2.765625
3
import {Category} from './enums'; import {Book, Logger} from './intefaces'; import {logSearchResults} from './functions'; showHello('greeting', 'TypeScript'); function showHello(divName: string, name: string) { const elt = document.getElementById(divName); elt.innerText = `Hello from ${name}`; } //=================================================================== //Task 01.02 // logFirstAvailable(getAllBooks()); // const titles = getBookTitleByCategory(Category.JavaScript); // logBookTitles(titles); // const result = getBookAuthorByIndex(1); // console.log(result); // console.log(calcTotalPages()); //=================================================================== //Task 03.01 // const titles = getBookTitleByCategory(Category.JavaScript); // titles.forEach(title => console.log(title)); // const book = getBookById(10); // console.log(book) //Task 03.02 // const myId = createCustomerId('Ann', 10); // console.log(myId); // let idGenerator: (name: string, id: number) => string = (name: string, id: number) => `${id} - ${name}`; // idGenerator = createCustomerId; // console.log(idGenerator('boris', 20)); //Task 03.03 // createCustomer('Boris', 35); // createCustomer('Tilia', 35, 'kiev'); // console.log(getBookTitleByCategory()); // logFirstAvailable(); // const myBooks = checkoutBooks('Ann', 1, 2, 3); // console.log(myBooks); //Task 03.04 // const checkedOutBooks = getTitles('1'); // console.log(checkedOutBooks); //Task 03.05 // console.log(bookTitleTransform((getAllBooks()[0] as any).title)); // console.log(bookTitleTransform(123) //=================================================================== //Task 04.01 // const myBook: Book = { // id: 5, // title: 'Colors, Backgrounds, and Gradients', // author: 'Eric A. Meyer', // available: true, // category: Category.CSS, // // year: 2015, // // copies: 3 // pages: 200, // markedDamaged: (reason: string) => { // console.log(`Damaged ${reason}`) // } // }; // printBook(myBook); // myBook.markedDamaged('missing back cover') // myBook.markedDamaged('missing back cover'); //Task 04.02 const logDamage: Logger = (reason) => { console.log(`Damaged ${reason}`) }; logDamage('missing back cover'); //Task 04.03 // const favoriteAuthor: Author = { // name: 'Anna', // email: 'anna@gmail.com', // numBookPublished: 10 // }; // const favoriteLibrarian: Librarian = { // name: 'Boris', // email: 'boris@email.com', // department: 'Classic Literature', // assistCustomer: null // } // Task 04.04 // const offer: any ={ // book: { // title: 'Essential TypeScript' // } // }; // console.log(offer?.magazine); //Task 04.05 // console.log(getBookProp(getAllBooks()[0], 'title')); // console.log(getBookProp(getAllBooks()[0], 'markedDamaged')); // console.log(getBookProp(getAllBooks()[0], 'isbn')); //=================================================================== // Task 05.01 // const ref = new ReferenceItem('my title', 2020); // console.log(ref); // ref.printItem(); // ref.publisher = 'My pablisher'; // console.log(ref.publisher); // Task 05.02 // const refBook = new refBook('Title', 2020, 10); // console.log(refBook); // refBook.printItem(); // refBook.publisher = 'abc'; // console.log(refBook.publisher); // Task 05.03 // const refBook = new Encyclopedia('Title', 2020, 10); // refBook.printCitation(); // console.log(refBook); // Taks 05.04 // const favoriteLibrarian: Librarian = new UniversityLibrarian(); // favoriteLibrarian.name = "Tilia"; // favoriteLibrarian.assistCustomer('Pasha'); // console.log(favoriteLibrarian); // Task 05.05 // const personBook: PersonBook = { // name: 'Sergey', // email: 'test@mail.com', // id: 5, // title: 'My title', // available: true, // category: Category.CSS, // author: 'Anton Pelex' // }; // // console.log(personBook); // Task 06.05 // import ('./classes').then(module => { // const reader = new module.Reader(); // console.log(reader); // reader.name = 'Anna'; // reader.}); //=================================================================== // Task 07.01 const inventory: Book[] = [ { id: 10, title: 'The C Programming Language', author: 'K & R', available: true, category: Category.Software }, { id: 11, title: 'Code Complete', author: 'Steve McConnell', available: true, category: Category.Software }, { id: 12, title: '8-Bit Graphics with Cobol', author: 'A. B.', available: true, category: Category.Software }, { id: 13, title: 'Cool autoexec.bat Scripts!', author: 'C. D.', available: true, category: Category.Software } ]; // console.log(purge(inventory)); // console.log(purge([1, 2, 3])); // Task 07.02 // const bookshelf: Shelf<Book> = new Shelf<Book>(); // inventory.forEach(book => bookshelf.add(book)); // const firstBook = bookshelf.getFirst(); // console.log(firstBook); // // const mazazines: Mazazine[] = [ // { title: 'Programming Language Monthly', publisher: 'Code Mags' }, // { title: 'Literary Fiction Quarterly', publisher: 'College Press' }, // { title: 'Five Points', publisher: 'GSU' } // ]; // const magazineShelf = new Shelf<Mazazine>(); // mazazines.forEach(mag => magazineShelf.add(mag)); // const firstMag = magazineShelf.getFirst(); // console.log(firstMag); // Task 07.03 // magazineShelf.printTitles(); // const result = magazineShelf.find('Five Points'); // console.log(result); // Task 07.04 // const book: BookRequiredFields = { // id:1, // title: '', // author: 'Unknown', // available: false, // category: Category.TypeScript, // markedDamaged: null, // pages: 300 // }; // // const updatedBook: UpdatedBook = { // id: 1, // title: 'Refactoring JavaScript' // }; // // const params: Parameters<CreateCustomerFunctionType> = ['Anna']; // createCustomer(...params); //=================================================================== // Task 08.01 // const o = new UniversityLibrarian(); // console.log(o); // Task 08.02 // o.name = 'Sergey'; // (o as any).printLibrarian(); //=================================================================== // Task 08.03 // const o = new UniversityLibrarian(); // o.assistFaculty = null; // o.teachCommunity = null; // Task 08.04 // const refBook = new RefBook('Title', 2020, 10); // Encyclopedia.printItem(); // Task 08.05 // const o = new UniversityLibrarian(); // o.name = 'Anna'; // o.assistCustomer('Boris'); // Task 08.06 // const o = new UniversityLibrarian(); // o.name = 'Anna'; // o.assistCustomer('Boris'); // console.log(o.name); // Task 08.07 // const refBook = new RefBook('Title', 2020, 10); // refBook.copies = 10; //=================================================================== // Task 09.01 // console.log('Begin'); // getBooksByCategory(Category.JavaScript, logCategorySearch); // getBooksByCategory(Category.Software, logCategorySearch); // console.log('End'); // Task 09.02 // console.log('Begin'); // getBooksByCategoryPromise(Category.JavaScript).then(titles => {console.log(titles); // return titles.length}); // getBooksByCategoryPromise(Category.Software).catch(err => {console.log(err)}); // console.log('End'); // Task 09.03 console.log('Begin'); logSearchResults(Category.JavaScript).catch(err => console.log(err)); console.log('End');
6eb12ba156bfa57413d89b168e793a517d1c9fdc
TypeScript
nickagrawal/fiservassignment
/src/services/parserService_v1.ts
2.796875
3
import { Respose } from "./../model/response"; export class ParserService { static parse(req: any): any { if(req && typeof req === 'string' && req.length > 18){ const res = new Respose(); res.firstName =req.substring(0,8); res.lastName =req.substring(8,18); res.clientId =req.substring(18); return res; }else{ throw new Error("Invalid Input String"); } } }
07626708637c41f7c83cbbaf93cde16582e862bf
TypeScript
DimiDeKerf/typescript-course
/exercises/04_walker/exercise/src/walker.ts
3.625
4
class Walker { name; numberOfLegs; color; // TODO: convert to constructor assignment constructor( name, numberOfLegs, color?, // Color can either by gray or black. ) { this.name = name; this.numberOfLegs = numberOfLegs; this.color = color || 'gray'; } getInfo() { return `The ${this.name} has ${this.numberOfLegs} legs`; } } // TODO; Define Manufacturer interface and have the kuat object below comply to it interface Manufacturer { } const kuat = { name: 'Kuat Drive Yards', owner: 'Kuat of Kuat', active: true, buildWalker: function (name, numberOfLegs) { return new Walker(name, numberOfLegs); } // TODO convert to arrow function } const walker = kuat.buildWalker('AT-AT', 4); console.log(walker.getInfo());
f57f2550943b253f6873a4c089f12e37f36d4ede
TypeScript
x-way/cal-heatmap
/src/DataFetcher.ts
2.859375
3
import { json, csv, dsv, text, } from 'd3-fetch'; import type { DataOptions, DataRecord } from './options/Options'; import type { Timestamp } from './index'; import type CalHeatmap from './CalHeatmap'; export default class DataFetcher { calendar: CalHeatmap; constructor(calendar: CalHeatmap) { this.calendar = calendar; } /** * Fetch and interpret data from the datasource * * @param {string|object} source * @param {number} startTimestamp * @param {number} endTimestamp * * @return {Promize} A promise, that will return the final data when resolved */ async getDatas( source: DataOptions['source'], startTimestamp: Timestamp, endTimestamp: Timestamp, ): Promise<unknown> { if (typeof source === 'string' && source.length > 0) { return this.#fetch(source, startTimestamp, endTimestamp); } let d: DataRecord[] = []; if (Array.isArray(source)) { d = source; } return new Promise((resolve) => { resolve(d); }); } parseURI( str: string, startTimestamp: Timestamp, endTimestamp: Timestamp, ): string { let newUri = str.replace(/\{\{start=(.*)\}\}/g, (_, format) => // eslint-disable-next-line implicit-arrow-linebreak this.calendar.dateHelper.date(startTimestamp).format(format)); newUri = newUri.replace(/\{\{end=(.*)\}\}/g, (_, format) => // eslint-disable-next-line implicit-arrow-linebreak this.calendar.dateHelper.date(endTimestamp).format(format)); return newUri; } #fetch( source: DataOptions['source'], startTimestamp: Timestamp, endTimestamp: Timestamp, ): Promise<unknown> { const { type, requestInit } = this.calendar.options.options.data; const url = this.parseURI(source as string, startTimestamp, endTimestamp); switch (type) { case 'json': return json(url, requestInit); case 'csv': return csv(url, requestInit); case 'tsv': return dsv('\t', url, requestInit); case 'txt': return text(url, requestInit); default: return new Promise((resolve) => { resolve([]); }); } } }
231e785a97587fccf9a11cdb50559d98679b0a91
TypeScript
DenisDenis2015/library
/ui-library-angular/library/src/app/store/reducer/booksReducer.ts
2.71875
3
import {createFeatureSelector, createSelector} from '@ngrx/store'; import {BooksState} from '../../model/AppState'; import * as fromActions from '../action/booksAction'; import {BookModel, IBookModel} from '../../model/book-model'; import {GenreModel, IGenreModel} from '../../model/genre-model'; export const initialState: BooksState = {books: [], genres: []}; export function reducer(state = initialState, action: fromActions.All): BooksState { switch (action.type) { case fromActions.LOAD_BOOKS_BY_GENRE: { const newBook: IBookModel[] = action.payload.books; return { books: state.books.concat(action.payload.books), genres: state.genres }; } case fromActions.LOAD_BOOKS: { const newBook: IBookModel[] = action.payload.books; return { books: state.books.concat(newBook), genres: state.genres }; } case fromActions.LOAD_GENRES: { const newGenres: IGenreModel[] = action.payload.genres; return { books: state.books, genres: state.genres.concat(newGenres), }; } case fromActions.CLEAR_BOOK_STORE: { return { books: [], genres: state.genres, }; } case fromActions.ADD_NEW_BOOK_STORE: { let book: IBookModel = new BookModel(null, "", "", "", new GenreModel("", ""), ""); return { books: state.books.concat(book), genres: state.genres } } default: { return state; } } } export const getBooksState = createFeatureSelector<BooksState>('bookState'); export const getBooks = createSelector( getBooksState, (state: BooksState) => state.books ); export const getGenres = createSelector( getBooksState, (state: BooksState) => state.genres );
a5640aa402a83f269fbca08007d20d60bb98340e
TypeScript
Dennisschu/Screeps
/src/creeps/base.ts
2.921875
3
export default class { private body_: BodyPartConstant[]; private name_: string; private role_: string; private memory_: CreepMemory; public constructor(Name: string, Role: string, Body: BodyPartConstant[], Memory: CreepMemory) { this.name_ = Name; this.role_ = Role; this.body_ = Body; this.memory_ = Memory; } public get name(): string { return this.name_; } public set name(NewName: string) { this.name_ = NewName; } public get role(): string { return this.role_; } public set role(NewRole: string) { this.role_ = NewRole; } public get body(): BodyPartConstant[] { return this.body_; } public set body(NewBody: BodyPartConstant[]) { this.body_ = NewBody; } public get memory(): CreepMemory { return this.memory_; } public set memory(Memory: CreepMemory) { this.memory_ = Memory; } public static run(creep: Creep): void { this.CheckEnergy(creep); if (!creep.memory.working) { const target = creep.room.find(FIND_STRUCTURES, { filter: structure => { return structure.structureType === STRUCTURE_STORAGE && structure.store[RESOURCE_ENERGY] > 100; } }); // const target = creep.pos.findClosestByPath; if (target) { this.NotWorking(creep, target[0]); } } else { this.Work(creep); } } protected static CheckEnergy(creep: Creep): void { if (creep.memory.working && creep.store[RESOURCE_ENERGY] === 0) { creep.memory.working = false; } if (!creep.memory.working && creep.store.getFreeCapacity() === 0) { creep.memory.working = true; } } protected static GetSources(creep: Creep): Source | null { return creep.pos.findClosestByRange(FIND_SOURCES); } protected static NotWorking(creep: Creep, target: AnyStructure): void { if (creep.withdraw(target, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) { creep.moveTo(target); } } protected static Work(creep: Creep): void { return; } }
ecb4d5e46d8b79614fed3428b632c278eb73e101
TypeScript
postor/hearthstone-gameserver
/src/Game.ts
2.953125
3
import { EventEmitter } from 'events' import Player from './Player' import DeadQueueItem from './utils/DeadQueueItem' import gameStart from './acts/gameStart' import { getWaitPromise } from './utils/getWaitPromise' const defaultConfig = { players: [ { hero: 'Mage', cards: [ 'ArcaneExplosion', 'ArcaneExplosion', 'ArcaneIntellect', 'ArcaneIntellect', 'FrostBolt', 'FrostBolt', 'BloodmageThalnos', 'BloodmageThalnos', 'ArcaneMissiles', 'ArcaneMissiles', 'Polymorph', 'Polymorph', 'FireBall', 'FireBall', 'MirrorImage', 'MirrorImage', 'FrostNova', 'FrostNova', ], }, { hero: 'Mage', cards: [ 'ArcaneExplosion', 'ArcaneExplosion', 'ArcaneIntellect', 'ArcaneIntellect', 'FrostBolt', 'FrostBolt', 'BloodmageThalnos', 'BloodmageThalnos', 'ArcaneMissiles', 'ArcaneMissiles', 'Polymorph', 'Polymorph', 'FireBall', 'FireBall', 'MirrorImage', 'MirrorImage', 'FrostNova', 'FrostNova', ], } ] } /** * 一局游戏 * * @export * @class Game * @extends {EventEmitter} */ export class Game extends EventEmitter { /** * 玩家列表 * * @type {Player[]} * @memberof Game */ players: Player[] = [] /** * 当前回合 * * @type {number} * @memberof Game */ turn: number = 0 /** * 阵亡的随从 * * @type {DeadQueueItem[]} * @memberof Game */ deadQueue: DeadQueueItem[] = [] /** * 排队要做的事情 * * @type {Function[]} * @memberof Game */ todoQueue: Function[] = [] /** * 当前 * * @type {Player} * @memberof Game */ currentPlayer: Player /** * 游戏结束 * * @type {boolean} * @memberof Game */ gameover: boolean = false _curID: number = 10 _toClean: any = () => { } setToClean(x: any) { this._toClean = x } clean() { this._toClean() this.removeAllListeners() } newID() { return this._curID++ } /** * Creates an instance of Game. * @param {Object} [config=defaultConfig] * @memberof Game */ constructor(config: { players: Object[] } = defaultConfig) { super() this.setMaxListeners(30) this.players = config.players.map((x: { hero: string, cards: string[] }, i) => { return new Player(this, x.hero, x.cards, i) }) this.players.forEach((x) => x.game = this) } async start() { gameStart(this) while (!this.gameover) { await this.tick() } } async tick() { //没有事做了等一下再试 if (!this.todoQueue.length) { await getWaitPromise(100) return } //处理 const fn = this.todoQueue.shift() const result = fn() if (result instanceof Promise) { //异步 return result } else { //同步 return Promise.resolve() } } }
5f3049185abf14dd95f5ca45c2937ce4a6eeb5b9
TypeScript
SudoDotDog/Sudoo-Time
/src/duration.ts
3.25
3
/** * @author WMXPY * @namespace Time * @description Duration */ import { TIME_CHANGE } from "@sudoo/magic"; const floorIfNeeded = (value: number, floor?: boolean): number => { if (typeof floor !== 'boolean') { return value; } if (floor) { return Math.floor(value); } return value; }; const getAssertNumber = (value?: number): number => { if (typeof value === 'number') { return value; } return 0; }; export type DurationConfig = { readonly days?: number; readonly hours?: number; readonly minutes?: number; readonly seconds?: number; readonly milliseconds?: number; }; export class Duration { public static of(config: DurationConfig): Duration { return new Duration(config); } public static fromDays(days: number): Duration { return new Duration({ days }); } public static fromHours(hours: number): Duration { return new Duration({ hours }); } public static fromMinutes(minutes: number): Duration { return new Duration({ minutes }); } public static fromSeconds(seconds: number): Duration { return new Duration({ seconds }); } public static fromMilliseconds(milliseconds: number): Duration { return new Duration({ milliseconds }); } private readonly _milliseconds: number; private constructor(config: DurationConfig) { this._milliseconds = this._parseMilliseconds(config); } public toMilliseconds(): number { return this._milliseconds; } public toSeconds(floor?: boolean): number { return floorIfNeeded( this.toMilliseconds() / 1000, floor, ); } public toMinutes(floor?: boolean): number { return floorIfNeeded( this.toSeconds() / TIME_CHANGE.SECOND_TO_MINUTE, floor, ); } public toHours(floor?: boolean): number { return floorIfNeeded( this.toMinutes() / TIME_CHANGE.MINUTE_TO_HOUR, floor, ); } public toDays(floor?: boolean): number { return floorIfNeeded( this.toHours() / TIME_CHANGE.HOUR_TO_DAY, floor, ); } private _parseMilliseconds(config: DurationConfig): number { let milliseconds: number = 0; milliseconds += getAssertNumber(config.milliseconds); milliseconds += getAssertNumber(config.seconds) * 1000; milliseconds += getAssertNumber(config.minutes) * 1000 * TIME_CHANGE.SECOND_TO_MINUTE; milliseconds += getAssertNumber(config.hours) * 1000 * TIME_CHANGE.SECOND_TO_MINUTE * TIME_CHANGE.MINUTE_TO_HOUR; milliseconds += getAssertNumber(config.days) * 1000 * TIME_CHANGE.SECOND_TO_MINUTE * TIME_CHANGE.MINUTE_TO_HOUR * TIME_CHANGE.HOUR_TO_DAY; return milliseconds; } }
85f8270b88b1e1eb395f5167d6c440a388f7ac28
TypeScript
ejnkns/gdocs-database
/utils/contentTypes.ts
3.046875
3
export enum ContentTypes { Title, Para, Link, Image, Video, Pdf, Html, Break } export class ContentObject { contentType: ContentTypes; // denotes a 'type' for the content data; needed for strings data: string | Link | Para; constructor(contentType: ContentTypes, data: string | Link | Para) { this.contentType = contentType; this.data = data; } } export class Para { content: (string|Link)[] constructor(content: (string|Link)[]) { this.content = content; } } export class Link { url: string; text: string; constructor(url: string, text: string) { this.url = url; this.text = text; } } export type jsonType = ({ contentType: number; data: { content: (string | { url: string; text: string; })[]; }; } | { contentType: number; data: string; })[]; export class Page { name?: string; path: string; docsUrl: string; constructor(name: string = "", path: string, docsUrl: string) { this.name = name; this.path = path; this.docsUrl = docsUrl; } }
e205d5da54dbf61993f562173ab750dfcc22f484
TypeScript
jedrzejowski/spbd-project
/src/gui/lib/geometryToString.ts
2.953125
3
import GeoJSON from "geojson"; export default function (geometry: GeoJSON.Geometry): string { switch (geometry.type) { case "Point": { const [lng, lat] = geometry.coordinates; return `Punkt[${lat > 0 ? "N" : "S"}${lat} ${lng > 0 ? "E" : "W"}${lng}]` } default: return "[unsupported geometry]" } }
00a2bc2d3a8b18571c8790eec55f7ec876969b67
TypeScript
no-stack-dub-sack/apexdox-vs-code
/src/common/models/EnumModel.ts
2.59375
3
import ApexDox from '../../engine/ApexDox'; import { ModelType, TopLevelModel } from './TopLevelModel'; import { Option } from '../..'; class EnumModel extends TopLevelModel { private _values: string[] = []; public constructor(comments: string[], nameLine: string, lineNum: number, sourceUrl: Option<string>, relativeFilePath: string) { super(comments, ModelType.ENUM, sourceUrl, relativeFilePath); this.setNameLine(nameLine, lineNum); this.setValues(nameLine); } public get groupName(): string { return this._groupName; } public get name(): string { let nameLine = this.nameLine; let i = nameLine.indexOf(ApexDox.ENUM); return nameLine.slice(i + ApexDox.ENUM.length).trim(); } public get values(): string[] { return this._values; } protected setNameLine(nameLine: string, lineNum: number): void { if (nameLine) { // remove any trailing stuff after enum name let i = nameLine.indexOf('{'); if (i > 0) { nameLine = nameLine.substring(0, i); } } super.setNameLine(nameLine.trim(), lineNum); } private setValues(line: string): void { line = line.substring(line.indexOf('{') + 1, line.indexOf('}')); line.trim() .split(',') .forEach(value => value.trim() && this.values.push(value.trim())); } } export { EnumModel };
ca14ef1475838c97b774cc77bc9ffc4f80d073bf
TypeScript
CSID-DGU/2019-1-OSSP2-infiniteDevelopment-6
/plass-ide-frontend/src/app/console/tab/tab.component.ts
2.734375
3
import { Component, Input, } from '@angular/core'; import { File } from 'src/app/types'; @Component({ selector: 'tab-component', templateUrl: './tab.component.html', styleUrls: ['./tab.component.scss'], }) export class TabComponent { @Input() upload = (file: File, data: string, isTemp: boolean, cb, errcb) => {}; @Input() compile = () => {}; public files:Array<File> = []; public selectFile:File = null; public isFileChange: boolean = false; public text:string = ""; public newCount:number = 0; pushFile(file:File) { if(this.files.findIndex((value)=>(file === value)) !== -1) { this.selectFile = file; return; } // if files aready exsist this.files.push(file); if(this.files.length === 1) { this.clickFile(file) }; // if the pushed file is first } clickFile(file: File) { this.selectFile = file; this.text = file.data; console.log(file); this.isFileChange = true; } changeEditor($event) { if(this.isFileChange) {this.isFileChange = false; return;} if(this.selectFile) { // TODO: bug fix: a file change to modify state when change file this.selectFile.data = this.text; this.selectFile.modify = true; } else { const tempFile: File = { name: "undefined", isDirectory: false, path: "", data: this.text, isTemp: true, modify: true } this.files.push(tempFile) this.selectFile = tempFile; } } createNewFile($event) { const tempFile: File = { name: "undefined " + (this.newCount++), isDirectory: false, path: "", data: "", isTemp: true, modify: true } this.files.push(tempFile) this.clickFile(tempFile); } uploadFile($event) { console.log(this.upload); if(this.selectFile.isTemp) { this.selectFile.isTemp = false; this.upload(this.selectFile, this.text, true, ()=>{}, ()=>{}); } else { this.upload(this.selectFile, this.text, false, ()=>{}, ()=>{}); } } compileProject(event) { this.compile(); } }
1e7492f2f5d7f00af28efc2523275c66b00f4646
TypeScript
rgrannell1/inkling
/test/fd.ts
2.828125
3
import tap from 'tap' import * as fd from '../src/fd.js' const testStderr = async () => { const stream = fd.stubStderr() stream.write('test') const text = await new Promise(resolve => { stream.on('data', (data:string) => { resolve(data) }) }) tap.equal(text, 'test') } const testStdin = async () => { const stream = fd.stubStdin() stream.write('test') const text = await new Promise(resolve => { stream.on('data', (data:string) => { resolve(data) }) }) tap.equal(text, 'test') } const testStdout = async () => { const stream = fd.stubStdout({ columns: 100, rows: 20 }) stream.write('test') const text = await new Promise(resolve => { stream.on('data', (data:string) => { resolve(data) }) }) tap.equal(text, 'test') tap.equals(stream.columns, 100) tap.equals(stream.rows, 20) } const testTtyIn = async () => { const stream = fd.stubTtyIn() stream.press('a') const char = await new Promise(resolve => { stream.on('keypress', (char:string) => { resolve(char) }) }) tap.equal(char, 'a') } testStderr() testStdin() testStdout() testTtyIn()
59f2981d5e7cd01673559ef3aa89815cb3c6453e
TypeScript
LienardEdwin/livementor_test
/store/index.ts
2.5625
3
import { vuexfireMutations } from 'vuexfire' import { INotification } from '~/models/notification' export interface IState { locale: string notification?: INotification locales: Array<string> conversations?: Map<string, any> users?: Map<string, any> authUser?: string } export const state = ():IState => ({ locales: ['en', 'fr'], locale: 'fr', notification: undefined, authUser: undefined, }) export const getters = { getNotification (state: IState) { return state.notification }, } export const mutations = { ...vuexfireMutations, SET_NOTIFICATION: (state: IState, payload?: INotification) => { state.notification = payload }, SET_AUTH_USER (state: IState, id: string) { state.authUser = id }, } export const actions = { showNotification (store: any, payload: any) { store.commit('SET_NOTIFICATION', payload) }, hideNotification (store: any) { store.commit('SET_NOTIFICATION', undefined) }, setAuthUser (store: any, id: string) { store.commit('SET_AUTH_USER', id, { root: true }) }, }
68734156da98d1e4ae76c6bf5c3dae95e0049691
TypeScript
jhlagado/hilo
/src/evaluate.ts
3.046875
3
import { grammar } from './grammar'; import { semantics } from './semantics'; import { Expression, Lambda, Definition, Application, Identifier } from './elements'; export type EvalExpression = Expression | Closure | undefined; class Closure { name?: string; lambda: Lambda; context: any; constructor(lambda: Lambda, context: any) { this.lambda = lambda; this.context = context; } toString() { return `${this.name ? this.name : this.lambda}` } } export function evaluate(expr: Expression, context: any): EvalExpression { if (Array.isArray(expr)) { return expr.reduce((_acc, item) => evaluate(item, context), null); } else if (expr instanceof Lambda) { return new Closure(expr, context); } else if (expr instanceof Definition) { const value = evaluate(expr.definition, context); if (value instanceof Closure) value.name = expr.name.value; context[expr.name.value] = value; return undefined; //void } else if (expr instanceof Application) { const closure = evaluate(expr.funcExpr, context); if (!(closure instanceof Closure)) { throw `expected function in left arg: ${ expr} received: ${closure}`; } else { const argValue = evaluate(expr.argExpr, context); const argName: Identifier = closure.lambda.argName; const bodyExpr = closure.lambda.bodyExpr; const newContext = { ...closure.context, [argName.value]: argValue }; return evaluate(bodyExpr, newContext); } } else if (expr instanceof Identifier) { if (context != null && expr.value in context) { return context[expr.value]; } else { throw `Unknown identifier ${ expr.value}`; } } else { return expr; } } export function parseEval(text: string, context: {}):EvalExpression { const matchResult = grammar.match(text); if (matchResult.failed()) { console.log(matchResult.message); } else { const adapter = semantics(matchResult); const expression = adapter.parse(); try { return evaluate(expression, context); } catch (e) { console.error(`${text} error:${e}`); } } return undefined; }
16f8af63564a47db42e28076df12fd3fb78d9770
TypeScript
tanianegrete/proyecto2
/CodenotchTemas/proyectosTipeScript/vector.ts
3.234375
3
class Vector{ //Declaracion de atributos: private elements:Number[]; public n:number;//longitud de vector public k:number;//maximo valor de elementos vector //Implementacion de Metodo constructor: constructor(elements:Number[],n:number,k:number){ this.n=n; this.k=k; } public Vectores(){ for(let i=0;i<this.n;i++){ this.elements[i]=Math.floor(Math.random() * (this.n- 1 + 1) + 1); } return this.elements; } }
a54a4373cfcce80dafebffea2057b17de2bc52ba
TypeScript
ketavchotaliya/stack-operations
/src/components/stack-operations/operators/Pop.ts
2.828125
3
import { Stack } from '../stack'; class Pop { /** * Validate stack length. * @return true/false in Boolean value. */ public validateInput() { const stack = Stack.getStack(); if (!stack.length) { return false; } return true; } /** * Remove top element of stack. * @return true in Boolean value. */ public stackOperation() { Stack.pop(); return true; } } export default new Pop();
52da8641f837f0d804c85ee79971ecde72b6acfe
TypeScript
zamotany/logkitty
/src/ios/IosParser.ts
2.8125
3
import DayJS from 'dayjs'; import { IParser, Entry } from '../types'; import { Priority, PriorityNames } from './constants'; export default class IosParser implements IParser { static timeRegex: RegExp = /\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.[\d+]+/m; static headerRegex: RegExp = /^\s+[a-z0-9]+\s+(\w+)\s+[a-z0-9]+\s+(\d+)\s+\d+\s+([^:]+):/; splitMessages(raw: string): string[] { const messages: string[] = []; let data = raw.toString(); let match = data.match(IosParser.timeRegex); while (match) { const timeMatch = match[0]; data = data.slice((match.index || 0) + timeMatch.length); const nextMatch = data.match(IosParser.timeRegex); const body = nextMatch ? data.slice(0, nextMatch.index) : data; messages.push(`${timeMatch} ${body}`); match = nextMatch; } return messages; } parseMessages(messages: string[]): Entry[] { return messages .map( (rawMessage: string): Entry => { const timeMatch = rawMessage.match(IosParser.timeRegex); if (!timeMatch) { throw new Error( `Time regex was not matched in message: ${rawMessage}` ); } const headerMatch = rawMessage .slice(timeMatch[0].length) .match(IosParser.headerRegex) || ['', 'Default', '-1', 'unknown']; const [, priority, pid, tag] = headerMatch; return { platform: 'ios', date: DayJS(timeMatch[0]).set('millisecond', 0), pid: parseInt(pid.trim(), 10) || 0, priority: Priority.fromName(priority as PriorityNames), tag, messages: [ rawMessage .slice(timeMatch[0].length + headerMatch[0].length) .trim(), ], }; } ) .reduce((acc: Entry[], entry: Entry) => { if ( acc.length > 0 && acc[acc.length - 1].date.isSame(entry.date) && acc[acc.length - 1].appId === entry.appId && acc[acc.length - 1].pid === entry.pid && acc[acc.length - 1].priority === entry.priority ) { acc[acc.length - 1].messages.push(...entry.messages); return acc; } return [...acc, entry]; }, []); } }
9cbdb8008dc07768d1a99d41fb6e3b035bb85c5f
TypeScript
ma125120/code
/clock.ts
3
3
import { ANGLE, ANGLE1, sin, cos, angle } from "./math"; import { BaseCanvas } from "./canvas"; type AngleItem = { angle: number; text: number | string; level: number; isReverse: boolean; sin: number; cos: number; }; const secondScales: AngleItem[] = new Array(60).fill(0).map((v, i) => { const num = i + 1; const angleNum = (i + 1) * (360 / 60); const obj = { isReverse: num >= 15, angle: angle(angleNum), sin: sin(angleNum), cos: cos(angleNum), level: 1 }; if (num % 5 === 0) { let text = num / 5; if (text % 3 === 0) { return { ...obj, level: 3, text }; } return { ...obj, level: 2, text }; } return { ...obj, text: "" }; }); export class Clock extends BaseCanvas { x = 20; y = 20; radius = 100; strokeStyle: any = "#000"; constructor(ctx: CanvasRenderingContext2D) { super(ctx); } paint() { const { radius, x, y, context } = this; this.draw(() => { context.beginPath(); context.translate(x + radius, y + radius); context.arc(0, 0, radius, 0, ANGLE, false); context.strokeStyle = this.strokeStyle; context.stroke(); }); this.draw(() => { context.beginPath(); context.translate(x + radius, y + radius); context.arc(0, 0, 6, 0, ANGLE, false); context.fillStyle = this.strokeStyle; context.fill(); }); this.drawSeconds(); } drawSeconds() { const { radius, x, y, context } = this; secondScales.map((v: AngleItem) => { this.draw(() => { context.beginPath(); context.translate( x + radius + radius * v.sin, y + radius + radius * v.cos ); context.rotate(v.angle); context.fillStyle = this.strokeStyle; context.fillRect(-1, 0, 2, 4 * v.level); }); this.draw(() => { context.beginPath(); context.translate( x + radius + (radius - 4 * v.level - 10) * v.sin, y + radius + (radius - 4 * v.level - 10) * v.cos ); context.textAlign = "center"; context.textBaseline = "middle"; context.fillText(v.text + "", 0, 0); }); }); } }
82bdb8cf3e87f316c4fc8616f814a4cab1a7ce23
TypeScript
wpflying/05_utils
/src/utils/object/extractProperty.ts
3.125
3
/** * 函数生成器:生成获取对象的属性值的函数 * @param propertyName 需要获取的属性名 */ export default function extract<T extends object, P extends keyof T>(propertyName: P) { return (obj: T) => obj[propertyName]; }
7a88d4a4e032dc57afb017863bc454dacdfa116d
TypeScript
puleri/euchre-webapp
/src/mockstate.ts
2.6875
3
import { dealCards, EmptyTripleStack, EmptyStack, sortCards, EmptyDoubleStack, } from "./interfaces/cards"; import { PlayPhaseState, PlayPhaseTag, JoinPhaseState, PassPhaseState, ScorePhaseState, JoinPhaseTag, PassPhaseTag, ScorePhaseTag, DealPhaseState, DealPhaseTag, } from "./interfaces/game/state/state"; import { PlayerPosition } from "./interfaces/game/player/position"; import { PendingPlayer, PassPhasePlayer, PlayPhasePlayer, ScorePhasePlayer, DealPhasePlayer, } from "./interfaces/game/playerstate"; import { PlayerProfile, PlayerIndex } from "./interfaces/game/player/player"; const cardsDealt = dealCards(); const makePlayerProfile = (i: PlayerIndex): PlayerProfile => ({ name: ["Alphonzo", "Braden", "Charlie", "Dennis"][i], position: (["North", "South", "East", "West"] as PlayerPosition[])[i], }); const makePlayerJoinPhase = (i: PlayerIndex): PendingPlayer => ({ ...makePlayerProfile(i), ready: false, }); const makePlayerDealPhase = (i: PlayerIndex): DealPhasePlayer => ({ profile: makePlayerProfile(i), connected: true, firstDeal: { cards: cardsDealt[i].cards.slice(0, 8) }, secondDeal: { cards: cardsDealt[i].cards.slice(8, 14) }, tookSecondDeal: false, }); const makePlayerPassPhase = (i: PlayerIndex): PassPhasePlayer => ({ profile: makePlayerProfile(i), connected: true, inHand: cardsDealt[i], give: { leftOpponent: cardsDealt[i].cards[0], partner: null, rightOpponent: cardsDealt[i].cards[1], }, ready: false, }); const makePlayerPlayPhase = (i: PlayerIndex): PlayPhasePlayer => ({ profile: makePlayerProfile(i), connected: true, inHand: sortCards(cardsDealt[i]), tricksWon: EmptyTripleStack, staged: EmptyStack, }); const makePlayerScorePhase = (i: PlayerIndex): ScorePhasePlayer => ({ profile: makePlayerProfile(i), connected: true, cards: cardsDealt[i], readyToPlayAgain: false, }); export const mockJoinPhaseState: JoinPhaseState = { phase: JoinPhaseTag, players: [ makePlayerJoinPhase(0), makePlayerJoinPhase(1), makePlayerJoinPhase(2), makePlayerJoinPhase(3), ], }; export const mockDealPhaseState: DealPhaseState = { phase: DealPhaseTag, players: [ makePlayerDealPhase(0), makePlayerDealPhase(1), makePlayerDealPhase(2), makePlayerDealPhase(3), ], }; export const mockPassPhaseState: PassPhaseState = { phase: PassPhaseTag, players: [ makePlayerPassPhase(0), makePlayerPassPhase(1), makePlayerPassPhase(2), makePlayerPassPhase(3), ], }; export const mockPlayPhaseState: PlayPhaseState = { phase: PlayPhaseTag, currentTrick: EmptyDoubleStack, players: [ makePlayerPlayPhase(0), makePlayerPlayPhase(1), makePlayerPlayPhase(2), makePlayerPlayPhase(3), ], }; export const mockScorePhaseState: ScorePhaseState = { phase: ScorePhaseTag, players: [ makePlayerScorePhase(0), makePlayerScorePhase(1), makePlayerScorePhase(2), makePlayerScorePhase(3), ], };
b9aae22b4f63ac27c72582283f1e68416a8f8430
TypeScript
shiiinji/leetcode
/deno/11.container-with-most-water/test.ts
2.703125
3
import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; import { maxArea } from './index.ts' Deno.test("maxArea() ex1", () => { assertEquals(maxArea([1,8,6,2,5,4,8,3,7]), 49, "Accepted"); }); Deno.test("maxArea() ex2", () => { assertEquals(maxArea([1,1]), 1, "Accepted"); }); Deno.test("maxArea() ex3", () => { assertEquals(maxArea([4,3,2,1,4]), 16, "Accepted"); }); Deno.test("maxArea() ex4", () => { assertEquals(maxArea([1,2,1]), 2, "Accepted"); });
55d46ebdc6f5b5a6bfb12a03970573ad9ade1597
TypeScript
valerk0/react_reddit
/src/store/posts/actions.ts
2.65625
3
import axios from "axios"; import { Action, ActionCreator } from "redux"; import { ThunkAction } from "redux-thunk"; import { IRootState } from "../reducer"; export interface IPostData { title?: string; previewLink?: string; author?: string; timeCode?: number; score?: number; num_comments?: number; id?: string; } export const POSTS_REQUEST_LOADING = 'POSTS_REQUEST_LOADING'; export interface IPostsRequestLoadingAction { type: typeof POSTS_REQUEST_LOADING; } export const postsRequestLoading: ActionCreator<IPostsRequestLoadingAction> = () => ({ type: POSTS_REQUEST_LOADING, }); export const POSTS_REQUEST_SUCCESS = 'POSTS_REQUEST_SUCCESS'; export interface IPostsRequestSuccessAction { type: typeof POSTS_REQUEST_SUCCESS; after: string; data: IPostData[]; } export const postsRequestSuccess: ActionCreator<IPostsRequestSuccessAction> = (after: string, data: IPostData[]) => ({ type: POSTS_REQUEST_SUCCESS, after, data, }); export const POSTS_REQUEST_ERROR = 'POSTS_REQUEST_ERROR'; export interface IPostsRequestErrorAction { type: typeof POSTS_REQUEST_ERROR; error: string; } export const postsRequestError: ActionCreator<IPostsRequestErrorAction> = (error: string) => ({ type: POSTS_REQUEST_ERROR, error, }); export const POSTS_LOAD_COUNTER = 'POSTS_LOAD_COUNTER'; export interface IPostsLoadCounterAction { type: typeof POSTS_LOAD_COUNTER; loadCounter: number; } export const postsLoadCounter: ActionCreator<IPostsLoadCounterAction> = (loadCounter: number) => ({ type: POSTS_LOAD_COUNTER, loadCounter, }); export const POSTS_SORT_BY = 'POSTS_SORT_BY'; export interface IPostsSortByAction { type: typeof POSTS_SORT_BY; sortBy: string; } export const postsSortBy: ActionCreator<IPostsSortByAction> = (sortBy: string) => ({ type: POSTS_SORT_BY, sortBy, }); export const postsRequestAsync = (): ThunkAction<void, IRootState, unknown, Action<string>> => (dispatch, getState) => { async function load() { try { const { data: {data: {after, children}} } = await axios.get(`https://oauth.reddit.com/${getState().posts.sortBy}`, { headers: { Authorization: `bearer ${getState().token.token}`}, params: {limit: 10, after: getState().posts.after}, }); if (children && children[0]) { type post = typeof children[0]; dispatch(postsRequestSuccess(after, getState().posts.data.concat(...children.map((child: post) => { return { title: child.data.title, previewLink: child.data.url, author: child.data.author, timeCode: child.data.created_utc, score: child.data.score, num_comments: child.data.num_comments, id: child.data.id, }; })))); } } catch (error) { dispatch(postsRequestError(error.toString())); } } load(); };
5cdbad997446ebe4f3028df58eedff0ed532f2ae
TypeScript
mohdovais/react-playground
/packages/combobox/combobox.store.ts
2.890625
3
import { extend } from '../utils/object'; export const ACTION_TYPE_COLLAPSE = 0; export const ACTION_TYPE_EXPAND = 1; export const ACTION_TYPE_TOGGLE = 2; export const ACTION_TYPE_KEY_ARROW_DOWN = 3; export const ACTION_TYPE_KEY_ARROW_UP = 4; export const ACTION_TYPE_KEY_ENTER = 5; export const ACTION_TYPE_SELECT = 6; export const ACTION_TYPE_SET_DATA = 7; export const ACTION_TYPE_LOCAL_SEARCH = 8; export const ACTION_TYPE_SET_DATA_AND_EXPAND = 9; export const ACTION_TYPE_SET_WAITING = 10; // not actual definition of JSON (null and Array not used) export type Json = { [prop: string]: string | number | boolean | Date | Json | Json[]; }; export interface ComboboxState<T> { id: string; waiting: boolean; displayField: string; expanded: boolean; focusIndex: number; selection?: T; data: T[]; range: T[]; } export interface ComboboxActionCollpase { type: typeof ACTION_TYPE_COLLAPSE; } export interface ComboboxActionExpand { type: typeof ACTION_TYPE_EXPAND; } export interface ComboboxActionToggle { type: typeof ACTION_TYPE_TOGGLE; } export interface CompobobxActionArrowDown { type: typeof ACTION_TYPE_KEY_ARROW_DOWN; } export interface ComboboxActionArrowUp { type: typeof ACTION_TYPE_KEY_ARROW_UP; } export interface ComboboxActionEnter { type: typeof ACTION_TYPE_KEY_ENTER; } export interface ComboboxActionSelect<T> { type: typeof ACTION_TYPE_SELECT; selection: T; } export interface ComboboxActionSetData<T> { type: typeof ACTION_TYPE_SET_DATA; data: T[]; } export interface ComboboxActionSearch { type: typeof ACTION_TYPE_LOCAL_SEARCH; query: string; } export interface ComboboxActionSetDataAndExpand<T> { type: typeof ACTION_TYPE_SET_DATA_AND_EXPAND; data: T[]; } export interface ComboboxActionSetWating { type: typeof ACTION_TYPE_SET_WAITING; waiting: boolean; } export type ComboboxAction<T> = | ComboboxActionCollpase | ComboboxActionExpand | ComboboxActionToggle | CompobobxActionArrowDown | ComboboxActionArrowUp | ComboboxActionEnter | ComboboxActionSelect<T> | ComboboxActionSetData<T> | ComboboxActionSearch | ComboboxActionSetDataAndExpand<T> | ComboboxActionSetWating; export const initialState = { id: '', displayField: '', expanded: false, waiting: false, focusIndex: -1, selection: undefined, data: [], range: [], }; export function comboboxReducer<T extends Json>( state: ComboboxState<T>, action: ComboboxAction<T> ): ComboboxState<T> { switch (action.type) { case ACTION_TYPE_COLLAPSE: return extend(state, { expanded: false, focusIndex: -1, }); case ACTION_TYPE_EXPAND: return extend(state, { expanded: true, }); case ACTION_TYPE_TOGGLE: return comboboxReducer(state, { type: state.expanded ? ACTION_TYPE_COLLAPSE : ACTION_TYPE_EXPAND, }); case ACTION_TYPE_KEY_ARROW_DOWN: { let count = state.range.length; return extend(state, { expanded: true, focusIndex: count === 0 ? -1 : (state.focusIndex + 1) % count, }); } case ACTION_TYPE_KEY_ARROW_UP: { let count = state.range.length; let index = state.focusIndex === -1 ? count : state.focusIndex; return extend(state, { expanded: true, focusIndex: count === 0 ? -1 : (count + index - 1) % count, }); } case ACTION_TYPE_KEY_ENTER: if (state.focusIndex !== -1) { return extend(state, { expanded: false, focusIndex: -1, range: state.data, selection: state.range[state.focusIndex], }); } break; case ACTION_TYPE_SELECT: return extend(state, { expanded: false, focusIndex: -1, range: state.data, selection: action.selection, }); case ACTION_TYPE_SET_DATA: { let data = action.data; return extend(state, { data, range: data, }); } case ACTION_TYPE_LOCAL_SEARCH: { const search = new RegExp(action.query, 'i'); return extend(state, { expanded: true, range: state.data.filter((record) => search.test(record[state.displayField].toString()) ), }); } case ACTION_TYPE_SET_DATA_AND_EXPAND: return extend(state, { expanded: true, focusIndex: -1, waiting: false, data: action.data, range: action.data, }); case ACTION_TYPE_SET_WAITING: return extend(state, { waiting: action.waiting, }); } return state; }
f98703f6c2c7bdcb6a089929e4e67a635e8d9059
TypeScript
albireox/boson
/src/renderer/tools/stringToColour.ts
2.953125
3
/* * @Author: José Sánchez-Gallego (gallegoj@uw.edu) * @Date: 2022-12-18 * @Filename: stringToColour.ts * @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) */ export default function stringToColour(myString: string) { let hash = 0; for (let i = 0; i < myString.length; i += 1) { hash = myString.charCodeAt(i) + ((hash << 5) - hash); } let colour = '#'; for (let i = 0; i < 3; i += 1) { const value = (hash >> (i * 8)) & 0xff; colour += `00${value.toString(16)}`.slice(-2); } return colour; }
0bc8d71f1002a933024e058e71774ddf80ff94f6
TypeScript
belohnung/Dename
/src/records/types.ts
2.53125
3
export type DNSRecordType = | "A" | "AAAA" | "CNAME" | "MX" | "NS" | "SOA" | "SRV" | "TXT"; export interface IRecord { type: DNSRecordType; target: any; }
5975a763343ba99056daa68d72ec823d5764c02a
TypeScript
IronOnet/codebases
/codebases/outlook.live.com/src/modules/owa-datetime/src/formatters/formatDate.ts
3
3
import { getDate, getDay, getHours, getMilliseconds, getMinutes, getMonth, getSeconds, getYear, getTimestamp, } from '../owaDate/getFields'; import type { OwaDate } from '../schema'; import formatDateStrings from './formatDateStrings'; /** Formats a date according to an OWA-style format string. */ export default function formatDate(date: OwaDate, format: string, strings = formatDateStrings()) { if (date == void 0) { throw TypeError(`Invalid Date (${date})`); } if (isNaN(getTimestamp(date))) { throw TypeError('Invalid Date (NaN)'); } if (format == void 0) { throw TypeError(`Invalid Format (${format})`); } return format.replace(tokens, token => { const fn = tokenFns[token]; return fn ? fn(date, strings, format) : token.slice(1, token.length - 1); }); } type Strings = ReturnType<typeof formatDateStrings>; const d = getDate; const dd = pad(d); const ddd = (date: OwaDate, s: Strings) => s.ddd[getDay(date)]; const dddd = (date: OwaDate, s: Strings) => s.dddd[getDay(date)]; const M = (date: OwaDate) => getMonth(date) + 1; const MM = pad(M); const MMM = (date: OwaDate, s: Strings) => s.MMM[getMonth(date)]; const yy = (date: OwaDate) => getYear(date) % 100; const yyyy = getYear; const h = (date: OwaDate) => getHours(date) % 12 || 12; const hh = pad(h); const H = getHours; const HH = pad(H); const m = getMinutes; const mm = pad(m); const s = getSeconds; const ss = pad(s); const l = pad(getMilliseconds, 3); const amPm = (date: OwaDate, s: string[]) => s[getHours(date) < 12 ? 0 : 1]; const t = (date: OwaDate, s: Strings) => amPm(date, s.AP); const tt = (date: OwaDate, s: Strings) => amPm(date, s.AMPM); const T = (date: OwaDate, s: Strings) => amPm(date, s.ap); const TT = (date: OwaDate, s: Strings) => amPm(date, s.ampm); function pad(fn: typeof getDate, len: number = 2) { return (date: OwaDate) => { var str = String(fn(date)); while (str.length < len) { str = '0' + str; } return str; }; } function MMMM(date: OwaDate, s: Strings, format: string) { let monthNames = s.MMMM; // If the standalone and usual month names are different (more than just case) then we need // to decide which one we want to use; this depends on which fields are asked for in the format string. if (s.MMMM[0].toLowerCase() != s.standaloneMMMM[0].toLowerCase()) { let day = false; let year = false; // Detect which tokens are present in the given format string. format.replace(tokens, token => { day = day || token == 'd' || token == 'dd'; year = year || token == 'yy' || token == 'yyyy'; return ''; }); // This feels a little bit hacky, but it is small and self-contained enough to get us by // without adding extra dependencies (like having to ask for the user's culture or adding extra strings). // If the number of rules grows (which should not, as far as I can tell) then we can revisit this. // See this GIST https://gist.github.com/fpintos/827b369da5bd7f268939c54cf259cb87/ for more info // on how I came up with these rules. const isSimplifiedChinese = s.MMMM[0] == '1 月' && s.standaloneMMMM[0] == '一月'; if (isSimplifiedChinese) { // When Simplified Chinese (zh-Hans) has the strings corrected, use standalone name ONLY when just month is requested. Ex: // | locale | MMMM[0] | standaloneMMMM[0] | ex: month only | ex: month+year | ex: day+month | ex: day+month+year | // | zh-Hans | 1 月 | 一月 | 一月 | 2018 年 1 月 | 1 月 1 日 | 2018 年 1 月 1 日 | monthNames = day || year ? s.MMMM : s.standaloneMMMM; } else { // General Rule, use standalone name if only-Month or Month+Year are specified. If day is requested, use MMMM. Ex: // | locale | MMMM[0] | standaloneMMMM[0] | ex: month only | ex: month+year | ex: day+month | ex: day+month+year | // | cs | ledna | leden | leden | leden 2018 | 1. ledna | 1. ledna 2018 | // | el | Ιανουαρίου | Ιανουάριος | Ιανουάριος | Ιανουάριος 2018 | 1 Ιανουαρίου | 1 Ιανουαρίου 2018 | // Note that Intl API seems to format the month-only version in Greek incorrectly, returning Ιανουαρίου (as of 2019-03). monthNames = day ? s.MMMM : s.standaloneMMMM; } } return monthNames[getMonth(date)]; } const tokens = /d{1,4}|M{1,4}|yy(?:yy)?|([hHmstT])\1?|l|"[^"]*"|'[^']*'/g; const tokenFns = { d, dd, ddd, dddd, M, MM, MMM, MMMM, yy, yyyy, h, hh, H, HH, m, mm, s, ss, l, t, tt, T, TT, };
90358b8b0ad43cdac1f2c102c75f1e8f6d914ea2
TypeScript
jsamezquita/prueba
/src/app/estados-web/estados-web.service.ts
2.5625
3
import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {EstadoWeb} from './estadoWeb'; import {Observable} from 'rxjs'; import {AppConstants} from '../appConstants' import {States} from "./states"; const API_URL = AppConstants.baseURL; const estadosWeb = 'estadosWeb'; @Injectable({ providedIn: 'root' }) export class EstadosWebService { constructor(private http: HttpClient) { } getStatesValues():Observable<States> { return new Observable<States>(observer => { setInterval(() => { this.getStateBarValue().then( value => { observer.next(value); } ); }, 2000); }); } getStateBarValue() : Promise<States> { let tempPromise= new Promise<States>(((resolve) => { let a = this.http.get<EstadoWeb[]>(API_URL + estadosWeb); let b :EstadoWeb[]; let activos: number =0 ; let inavtivos: number =0; let falla: number =0; let otros: number =0; let promise = a.toPromise().then(value => { b = value b.forEach(estado => { switch (estado.estado) { case 'ACTIVO': activos++; break; case'INACTIVO': inavtivos++; break; case 'ENFALLA': falla++; break; case 'OTROS': otros++; break; } }); let totales = activos + inavtivos + falla + otros; activos = (activos / totales)*100; inavtivos = (inavtivos / totales)*100; falla = (falla / totales)*100; otros = (otros / totales)*100; let response = new States(activos, inavtivos, falla, otros); resolve(response); }); })); return tempPromise; } getEstadosSitio(sitio:number) : Observable<EstadoWeb[]> { return new Observable<EstadoWeb[]>(subscriber => { this.http.get<EstadoWeb[]>(API_URL + `websites/${sitio}/states`).subscribe(value => { subscriber.next(value); }); setInterval(() => { this.http.get<EstadoWeb[]>(API_URL + `websites/${sitio}/states`).subscribe(value => { subscriber.next(value); }); }, 1000); }); } getEstadoActual(sitio:number) : Observable<EstadoWeb> { return new Observable<EstadoWeb>(subscriber => { this.http.get<EstadoWeb>(API_URL+`websites/${sitio}/states/last`).subscribe(value => subscriber.next(value)); setInterval(()=>{ this.http.get<EstadoWeb>(API_URL+`websites/${sitio}/states/last`).subscribe(value => subscriber.next(value)) },1000) ; }); } getEstadoActualStatic(sitio:number):Observable<EstadoWeb> { return this.http.get<EstadoWeb>(API_URL+`websites/${sitio}/states/last`); } /** * Creates an EstadoWeb * @param EstadoWeb The new EstadoWeb * @returns The confirmation that the EstadoWeb was created */ createEstadoWeb(EstadoWeb): Observable<EstadoWeb> { return this.http.post<EstadoWeb>(API_URL + "estadosWeb", EstadoWeb); } }
a7445caa86851ed48fcc7f69252858ec644e2284
TypeScript
zcorky/zodash
/packages/event/src/index.ts
3.265625
3
import { once } from '@zodash/once'; export type Arguments<T> = [T] extends [(...args: infer U) => any] ? U : [T] extends [void] ? [] : [T]; export type Listener = any; // T extends any ? (...args: any[]) => void : T; export interface IEvent<Events = any> { on<E extends keyof Events>(event: E, listener: Events[E]): this; off<E extends keyof Events>(event: E, listener: Events[E]): this; addListener<E extends keyof Events>(event: E, listener: Events[E]): this; removeListener<E extends keyof Events>(event: E, listener: Events[E]): this; removeAllListeners<E extends keyof Events>(event: E): this; emit<E extends keyof Events>(event: E, ...args: Arguments<Events[E]>): this; once<E extends keyof Events>(event: E, listener: Events[E]): this; listeners: Record<keyof Events, Listener[]>; } const LISTENERS = Symbol('listeners'); export interface DefaultEvents { error(error: Error): void; } export class Event<Events = any> implements IEvent<Events> { private [LISTENERS]: Record<keyof Events, Listener[]> = {} as any; public get listeners() { return this[LISTENERS]; } public on<E extends keyof Events>(event: E, listener: Events[E]): this; public on(event: 'error', listener: (error: Error) => void): this; public on(event: any, listener: any) { if (!this.listeners[event]) { this.listeners[event] = []; } this.listeners[event].push(listener); return this; } public off<E extends keyof Events>(event: E, listener: Events[E]) { if (this.listeners[event]) { const all = this.listeners[event]; all.splice(all.indexOf(listener), 1); } return this; } public once<E extends keyof Events>(event: E, listener: Events[E]) { if (!this.listeners[event]) { this.listeners[event] = []; } this.listeners[event].push(once(listener as any)); return this; } public emit<E extends keyof Events>( event: E, ...args: Arguments<Events[E]> ): this; public emit<E extends keyof Events>(event: 'error', error: Error): this; public emit(event: any, ...args: any[]) { if (this.listeners[event]) { const partListeners = this.listeners[event]; partListeners.forEach((listener) => { if (event === 'error') { return listener.apply(this, args); } try { listener.apply(this, args); } catch (error) { this.emit('error', error); } }); return this; } // if no error listener, just throw if (event === 'error') { if (args[0] instanceof Error) { throw args[0]; } throw new Error(String(args[0])); } return this; } public addListener<E extends keyof Events>(event: E, listener: Events[E]) { return this.on(event, listener); } public removeListener<E extends keyof Events>( event: E, listener: Events[E], ) { return this.off(event, listener); } public removeAllListeners<E extends keyof Events>(event: E) { if (this.listeners[event]) { delete this.listeners[event]; } return this; } } // alias of Event export const EventEmitter = Event;
a8cd44b3296ee18e62c717fc8ad30f35579de84b
TypeScript
ChlodAlejandro/watchlist-webhooks-backend
/src/util/URLUtils.ts
3.09375
3
import express from "express"; /** * URL utilities for easy URL handling. */ export default class URLUtils { /** * Gets the root path URL (path at `/`) with a trailing slash. * @param req The Express request. */ static rootURL(req : express.Request) : string { return `${req.protocol}://${req.get("host")}/`; } /** * Get the full URL from an Express response * @param req The Express request. */ static fullURL(req : express.Request) : string { return `${req.protocol}://${req.get("host")}${req.originalUrl}`; } }
a3305c1b90666cea995051f7b8b158cec45f905c
TypeScript
danielmoreno510/banking-products
/src/app/redux/selectors/auth.selector.ts
2.515625
3
import { createSelector } from '@ngrx/store'; export interface Authentication { authentication: boolean; } export interface AuthState { auth: Authentication; } export const selectAuth = (state: AuthState) => state.auth; export const selectAuthenticate = createSelector( selectAuth, (state: Authentication) => state.authentication );
bc5f9bbc50502a8242b1b97c1adb34650ad26d7a
TypeScript
kldzj/nextjs-api-common-middleware
/__tests__/handlers/auth-bearer.test.ts
2.671875
3
import jwt from 'jsonwebtoken'; import { createMocks } from 'node-mocks-http'; import { createExport } from '../../src'; import { defaultHandler } from '../setup'; const JWT_SECRET = 'test'; const TOKEN = jwt.sign({ uid: 1 }, JWT_SECRET); const UNAUTHORIZED_CODE = 401; const UNAUTHORIZED_TEXT = 'UNAUTHORIZED'; describe('auth (strategy:bearer) middleware', () => { const m = createExport({ auth: { strategy: 'bearer', secret: JWT_SECRET, uidKey: 'uid', getUser(userId) { if (userId === 1) return { uid: 1, user: { name: 'test' } }; return null; }, unauthorized(_req, res) { res.status(UNAUTHORIZED_CODE).send(UNAUTHORIZED_TEXT); }, }, }); test('works as expected when authorized', async () => { const { req, res } = createMocks({ method: 'GET', headers: { Authorization: `bearer ${TOKEN}`, }, }); await m.auth(defaultHandler)(req, res); expect(res._getStatusCode()).toBe(200); expect(res._getData()).toBe('OK'); }); test('works as expected when unauthorized', async () => { const { req, res } = createMocks({ method: 'GET', }); await m.auth(defaultHandler)(req, res); expect(res._getStatusCode()).toBe(UNAUTHORIZED_CODE); expect(res._getData()).toBe(UNAUTHORIZED_TEXT); }); test('works as expected when providing wrong credentials', async () => { const { req, res } = createMocks({ method: 'GET', headers: { Authorization: `bearer ${jwt.sign({ uid: 2 }, 'test2')}`, }, }); await m.auth(defaultHandler)(req, res); expect(res._getStatusCode()).toBe(UNAUTHORIZED_CODE); expect(res._getData()).toBe(UNAUTHORIZED_TEXT); }); test('works as expected when unauthorized but anonymous access is allowed', async () => { const { req, res } = createMocks({ method: 'GET', }); await m.auth(defaultHandler, { allowAnonymous: true })(req, res); expect(res._getStatusCode()).toBe(200); expect(res._getData()).toBe('OK'); }); test('works as expected when custom decodeToken method is provided', async () => { const mm = createExport({ auth: { strategy: 'bearer', decodeToken: (token) => { try { const { uid } = jwt.verify(token, JWT_SECRET) as any; return uid; } catch (_error) { return null; } }, getUser: (userId) => { if (userId === 1) return { uid: 1, user: { name: 'test' } }; return null; }, }, }); }); });
4f7c9ef2c01ac5292f768f10419692d898bcaf65
TypeScript
jymfony/jymfony
/src/Component/Logger/types/Handler/SocketHandler.d.ts
2.59375
3
declare namespace Jymfony.Component.Logger.Handler { import FormatterInterface = Jymfony.Component.Logger.Formatter.FormatterInterface; export class SocketHandler extends AbstractProcessingHandler { private _connectionString: string; private _connection: Promise<void>; private _socket: any; /** * Constructor. */ // @ts-ignore __construct(connectionString: string, level?: number, bubble?: boolean): void; constructor(connectionString: string, level?: number, bubble?: boolean); /** * Closes the connection. */ close(): void; /** * Connects the handler. */ connect(): void; /** * Generates data to be sent via socket. */ protected _generateDataStream(record: LogRecord): string; /** * @inheritdoc */ protected _write(record: LogRecord): void; } }
59e096a3ade88bb570f3530ae357f153557c3281
TypeScript
franckLdx/StarWarsClients
/material-mobx/src/api/Starship.ts
2.53125
3
import { GraphQLClient } from 'graphql-request'; import { IStarship } from 'src/model/Starship'; import { IFetcher } from '.'; import { Mapper } from './FetchResource'; import { getRessourceFragment, movieRessourceFragment } from './Tools'; const fragment = ` {id,name,model,starship_class,manufacturer,cost_in_credits,length,crew,passengers,max_atmosphering_speed,hyperdrive_rating,MGLT,cargo_capacity,consumables, ${movieRessourceFragment}, ${getRessourceFragment('pilots')} }`; const queryStarships = () => `{ starships ${fragment} }`; const queryStarship = (id: string) => `{ starshipById(id:"${id}") ${fragment} }`; const starshipMapper: Mapper<IStarship> = (item: any) => ({ cargoCapacity: item.cargo_capacity, class: item.starship_class, consumables: item.consumables, cost: item.cost_in_credits, crew: item.crew, hyperdriveRating: item.hyperdrive_rating, id: item.id, length: item.length, manufacturer: item.manufacturer, maxAtmospheringSpeed: item.max_atmosphering_speed, mlgt: item.MGLT, model: item.model, movies: item.films, name: item.name, passengers: item.passengers, pilots: item.pilots, }); export function getStarshipsFetcher(graphQLClient: GraphQLClient): IFetcher<IStarship> { return { async fetchResource(id: string) { const payload = await graphQLClient.request<any>(queryStarship(id)); return payload ? starshipMapper(payload.starshipById) : undefined; }, async fetchResources() { const payload = await graphQLClient.request<any>(queryStarships()); return payload.starships.map(starshipMapper); } }; }
0b2b54947b19a18196af9e34d79beb7d2d2c5457
TypeScript
Scorpionsc/sh2
/src/api/sugarCollector/hooks/useGetRequest.ts
2.8125
3
import {useCallback, useEffect, useState} from 'react'; import {ApiResponse} from '../interfaces/apiResponse'; const useGetRequest = <T>(path: string): ApiResponse<T> => { const [isLoading, setIsLoading] = useState<boolean>(false); const [data, setData] = useState<T | null>(null); const [error, setError] = useState<Error | null>(null); const fetchData = useCallback(async () => { await setIsLoading(true); try { const res = await fetch(path); const result = await res.json(); setData(result); setIsLoading(false); return result; } catch (err) { setError(err); setIsLoading(false); } }, [path]); useEffect(() => { fetchData().then(); }, [fetchData]); const reFetch = useCallback(() => { fetchData().then(); }, [fetchData]); return { isLoading, data, error, reFetch, }; }; export default useGetRequest;
045a207d4130ac062f33c31c81a61b4d319a81cc
TypeScript
kartikpatel28199/task-analyser-runnable
/src/task/task.entity.ts
2.53125
3
import { Exclude } from 'class-transformer'; import { Status } from 'src/status/status.entity'; import { User } from 'src/user/user.entity'; import { Column, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, } from 'typeorm'; @Entity() export class Task { @PrimaryGeneratedColumn('uuid') id: string; @Column() title: string; @Column() description: string; @Column({ type: 'date' }) creationDate: Date; @ManyToOne((type) => User, (user) => user.task, { eager: false }) @Exclude({ toPlainOnly: true }) user: User; @ManyToOne(() => Status, (status) => status.id, { cascade: true, eager: true, }) status?: Status; }
6f27b920cadf1f7e23fca7ea54551c63bd40cf04
TypeScript
Esilthir/DTA_javascript
/TP_cours_1/exercice12.ts
3.453125
3
// Pas fini (function () { // Let's get started! console.log("Let's get started!"); // "this" works differently in different circumstances. // In this class "this" works in a way you might now expect. class employee { userId: string; displayUserId() { setTimeout(function () { console.log(`"this.UserId" is: ${this.userId}`); }, 1000); } } // Creating an object of type employee. var myEmployee = new employee(); myEmployee.userId = 'abc123'; // Calling the displayUserId method. // Notice "this.userId" returns "undefined". myEmployee.displayUserId(); } )();
a8c7e439b90d62ef9b736b4ef280568458795aa5
TypeScript
rxweb/rxweb
/client-side/angular/packages/reactive-forms/util/date-provider.ts
2.75
3
import { ReactiveFormConfig } from "./reactive-form-config"; import {ApplicationUtil } from './app-util' const ISO_DATE_REGEX = /^(\d{4}-\d{1,2}-\d{1,2})$/; export class DateProvider{ isDate(value: any): Boolean { return value instanceof Date && !isNaN(value.valueOf()); } private getRegex(dateFormat:string) : RegExp{ var regExp:string; switch(dateFormat){ case 'ymd': regExp = "^(?:[0-9]{4})-(1[0-2]|0?[1-9])-(3[01]|[12][0-9]|0?[1-9])$"; break; case 'dmy': regExp = "^(3[01]|[12][0-9]|0?[1-9])-(1[0-2]|0?[1-9])-(?:[0-9]{2})?[0-9]{2}$"; break; case 'mdy': regExp = "^(1[0-2]|0?[1-9])-(3[01]|[12][0-9]|0?[1-9])-(?:[0-9]{2})?[0-9]{2}$"; break; } return new RegExp(regExp); } regex(){ var regExp:RegExp; if(ReactiveFormConfig && ReactiveFormConfig.json && ReactiveFormConfig.json.internationalization && ReactiveFormConfig.json.internationalization.dateFormat && ReactiveFormConfig.json.internationalization.seperator) regExp = this.getRegex(ReactiveFormConfig.json.internationalization.dateFormat) else regExp = (ReactiveFormConfig && ReactiveFormConfig.json && ReactiveFormConfig.json.baseConfig && ReactiveFormConfig.json.baseConfig.dateFormat) ? this.getRegex(ReactiveFormConfig.json.baseConfig.dateFormat) : this.getRegex("mdy"); return regExp; } getDate(value:string | Date,isBaseFormat:boolean = false): Date{ let year:any,month:any,day:any; if(!this.isDate(value)){ let seperator:string; let dateFormat:string; if(ISO_DATE_REGEX.test(<string>value)){ seperator = "-"; dateFormat = "ymd" }else{ seperator = ReactiveFormConfig && ReactiveFormConfig.json && ReactiveFormConfig.json.baseConfig && ReactiveFormConfig.json.baseConfig.seperator ? ReactiveFormConfig.json.baseConfig.seperator : "/"; dateFormat = ReactiveFormConfig && ReactiveFormConfig.json && ReactiveFormConfig.json.baseConfig && ReactiveFormConfig.json.baseConfig.dateFormat ? ReactiveFormConfig.json.baseConfig.dateFormat : "mdy"; } if(!isBaseFormat && ReactiveFormConfig && ReactiveFormConfig.json && ReactiveFormConfig.json.internationalization && ReactiveFormConfig.json.internationalization.dateFormat && ReactiveFormConfig.json.internationalization.seperator) { seperator = ReactiveFormConfig.json.internationalization.seperator; dateFormat = ReactiveFormConfig.json.internationalization.dateFormat; } switch(dateFormat){ case 'ymd': [year, month, day] = (<String>value).split(seperator).map((val: string) => +val); break; case 'dmy': [day,month,year] = (<String>value).split(seperator).map((val: string) => +val); break; case 'mdy': [month,day,year] = (<String>value).split(seperator).map((val: string) => +val); break; } return new Date(year,month-1,day); }else return <Date>value; } isValid(value:string | Date) : Boolean{ if(typeof value == "string"){ if(ISO_DATE_REGEX.test(<string>value)) return true; let seperator = '/' if(ReactiveFormConfig.json && ReactiveFormConfig.json.internationalization && ReactiveFormConfig.json.internationalization.seperator) seperator = ReactiveFormConfig.json.internationalization.seperator; value = value.replace(seperator,'-').replace(seperator,'-'); return this.regex().test(value); }else return this.isDate(value); } getConfigDateValue(config:any){ let date = config.value; if(config.value && typeof config.value == "string"){ date = this.getDate(config.value,true); } return date; } getCompareDate(config:any,control:any){ let date = this.getConfigDateValue(config); if(config.fieldName){ let checkControl : any = ApplicationUtil.getFormControl(config.fieldName,control); if(checkControl && checkControl.value){ date = this.getDate(checkControl.value) } } return date; } }
6ae153d7c5331066246ca0e46a335dfbdb5b630e
TypeScript
KuuuPER/ParentsProject
/ParentsSite/SantexFrontend/src/app/core/home/manufactures/store/reducers/manufactures.reducers.ts
2.625
3
import * as Actions from '../manufactures.actions'; import { ManufactureModel } from '../../src/ManufactureModel'; import * as fromApp from '../../../../../store/app.reducers'; import { PageInfo } from '../../../src/PageInfo'; import { INameId } from '../../../src/INameId'; export interface FeatureState extends fromApp.AppState { manufactures: State; } export interface State{ ids: string[], manufactures: {[id: string]: ManufactureModel}; editedManufacture: ManufactureModel; pageInfo: PageInfo; } const initialState: State = { ids: [], manufactures: {}, editedManufacture: null, pageInfo: null } export function manufacturesReducer(state: State = initialState, action: Actions.ManufactureActions): State{ switch (action.type) { case Actions.SET_MANUFACTURES: const payloads = <ManufactureModel[]>action.payload; const fetchedManufactures: {[id: string]: ManufactureModel} = {}; const idsArray = []; payloads.forEach(p => {fetchedManufactures[p.id] = p}); payloads.forEach(p => idsArray.push(p.id)); return { ...state, ids: [...idsArray], manufactures: {...fetchedManufactures} }; case Actions.SET_EDIT_MANUFACTURE: const manufacture = <ManufactureModel>action.payload; return { ...state, editedManufacture: {...manufacture} }; case Actions.ADD_MANUFACTURE: if (Object.keys(state.manufactures).length < state.pageInfo.itemsPerPage) { const newManufacture: {[id: number]: ManufactureModel} = {}; const payload = <ManufactureModel>action.payload; newManufacture[payload.id] = payload; return{ ...state, manufactures: { ...state.manufactures, ...newManufacture } }; } else{ return { ...state }; } case Actions.EDIT_MANUFACTURE: const payload = <{manufacture: ManufactureModel, id: string}>action.payload; const manufactureToUpdate = { ...state.manufactures[payload.id], ...payload.manufacture }; const manufactures = {...state.manufactures}; manufactures[payload.id] = manufactureToUpdate; const newManufactures = {...manufactures}; return { ...state, manufactures: newManufactures }; case Actions.DELETE_MANUFACTURE: const id = <string>action.payload; const oldState = {...state}; delete oldState.manufactures[id]; const ids = oldState.ids.filter(i => i !== id); return { ...state, ids: [...ids], manufactures: {...oldState.manufactures}, }; case Actions.SET_PAGEINFO: const pageInfo = <PageInfo>action.payload; const newPageInfo = new PageInfo(pageInfo.itemsPerPage, pageInfo.itemsCount, pageInfo.currentPage); return <State>{ ...state, pageInfo: newPageInfo }; case Actions.CHANGE_PAGE: const newCurrentPage = <number>action.payload; return { ...state, pageInfo: <PageInfo>{ ...state.pageInfo, currentPage: newCurrentPage } }; default: return state; } } export const getManufactures = (state: State) => state.manufactures; export const getIds = (state: State) => state.ids; export const getEditManufacture = (state: State) => state.editedManufacture; export const getPageInfo = (state: State) => state.pageInfo;
bdb43d08aa773c1815d3368e54f3407f4b59490b
TypeScript
PACKED-vzw/CultURIze
/test/common/Objects/User.test.ts
2.703125
3
import { expect } from "chai"; import { User } from "../../../src/common/Objects/User"; describe("UserObject", () => { it("user construction", () => { const user = new User("token", "user", "URL"); expect(user.userName).to.eql("user"); expect(user.avatarURL).to.eql("URL"); expect(user.token).to.eql("token"); }); it("user without token", () => { const user = new User("token", "user", "URL"); const nUser = user.withoutToken(); expect(nUser.userName).to.eql("user"); expect(nUser.avatarURL).to.eql("URL"); expect(nUser.token).to.be.null; }); });
033cb6e24ee61185eedc62e4e010766755a9c869
TypeScript
Armor-cn/magnus
/libs/server/__tests__/entities/entities/permission/permission.entity.ts
2.640625
3
import { Column, CreateDateColumn, Entity, Index, JoinTable, ManyToMany, ManyToOne, PrimaryColumn, UpdateDateColumn, PrimaryGeneratedColumn, OneToMany } from 'typeorm'; import { AddonEntity } from './addon.entity'; import { RoleEntity } from './role.entity'; import { UserEntity } from './user.entity'; /** * 应用权限表 */ @Entity({ name: 'permission' }) export class PermissionEntity { @PrimaryGeneratedColumn() id: number; /** * 英文代号 * 格式: addonName.permissionName * 唯一 */ @Column() // @Index() name: string; /** * 上级 */ @Column({ type: 'varchar' }) father_name: string; /** * 汉语名称 */ @Column({ type: 'varchar', length: 255 }) title: string; /** * 权限简介 */ @Column({ type: 'varchar', length: 255, default: '' }) decription: string; // description /** * 权限值,即操作符 * 如:read,write,all... */ @Column({ type: "varchar", length: 255 }) value: string[]; /** * 图标 */ @Column({ type: 'varchar', length: 255, default: '' }) icon: string; /** * 状态 -1禁止,0开发中,1正常 */ @Column({ type: 'smallint', default: 0 }) @Index() status: number; /** * 排序 */ @Column({ type: 'int', default: 0 }) displayorder: number; /** * 创建时间 */ @CreateDateColumn({ type: 'timestamptz' }) create_time: Date; /** * 更新时间 */ @UpdateDateColumn({ type: 'timestamptz' }) update_time: Date; /** * 常用的,所以定义一下,查询后挂载到Permission上 */ /** * 拥有此权限的所有模块 */ @ManyToMany(() => AddonEntity) addons: AddonEntity[]; /** * 拥有此权限的所有用户 */ @ManyToMany(() => UserEntity) users: UserEntity[]; /** * 拥有此权限的所有角色 */ @ManyToMany(() => RoleEntity) roles: RoleEntity[]; }
9b684f070a802cfb653be93ca9d4b6178f231477
TypeScript
briggs-milburn/project-lazy
/src/pages/bills/bills.ts
2.515625
3
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular'; import { FormGroup, Validators, FormBuilder } from '@angular/forms'; import { HttpClient, HttpHeaders } from '@angular/common/http'; /** * Generated class for the BillsPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-bills', templateUrl: 'bills.html', }) export class BillsPage { constructor(public navCtrl: NavController, public navParams: NavParams,public http : HttpClient,) { } ionViewDidLoad() { console.log('ionViewDidLoad BillsPage'); } /** * @name items * @type {Array} * @public * @description Used to store returned PHP data */ public items : Array<any> = []; /** * Triggered when template view is about to be entered * Returns and parses the PHP data through the load() method * * @public * @method ionViewWillEnter * @return {None} */ ionViewWillEnter() : void { this.load(); } /** * Allow navigation to the AddTechnologyPage for creating a new entry * * @public * @method addEntry * @return {None} */ addEntry() : void { this.navCtrl.push('FinancialPage'); } /** * Retrieve the JSON encoded data from the remote server * Using Angular's Http class and an Observable - then * assign this to the items array for rendering to the HTML template * * @public * @method load * @return {None} */ load() : void { this.http .get('http://ec2-18-225-37-153.us-east-2.compute.amazonaws.com/resources/retrieve-finance.php') .subscribe((data : any) => { console.dir(data); this.items = data; }, (error : any) => { console.dir(error); }); } /** * Allow navigation to the AddTechnologyPage for amending an existing entry * (We supply the actual record to be amended, as this method's parameter, * to the AddTechnologyPage * * @public * @method viewEntry * @param param {any} Navigation data to send to the next page * @return {None} */ viewEntry(param : any) : void { this.navCtrl.push('FinancialPage', param); } }
64509cda312a86479ba51844fc586cec053457a3
TypeScript
LahcenHaouch/bounding-boxes
/src/App/types.ts
2.53125
3
export interface Category { id: string; name: string; color: string; items?: Array<Item>; } export interface Item { id: string; name: string; x: string; y: string; width: string; height: string; display: boolean; } export interface ImageObjectDetection { jsonResponse: { OBJECT_DETECTION_JOB: { annotations: BoundingPoly[]; }; }; } interface BoundingPoly { boundingPoly: BoundingPolyVertices[]; categories: BoundingPolyCategory[]; mid: string; score: null; type: "rectangle"; } interface BoundingPolyCategory { name: string; confidence: 100; } export interface BoundingPolyVertices { normalizedVertices: Array<Vertice>; } interface Vertice { x: number; y: number; }
28a9a2a95afbfed80a26564e3421007896e00544
TypeScript
kovlento/blog-api
/src/posts/posts.controller.ts
2.671875
3
import { Controller, Get, Post, Body, Query, Put, Param, Delete } from '@nestjs/common'; import { ApiUseTags, ApiOperation, ApiModelProperty } from '@nestjs/swagger'; import { IsNotEmpty } from 'class-validator' import { InjectModel } from 'nestjs-typegoose'; import {Post as PostSchema} from './post.model' import { ModelType } from '@typegoose/typegoose/lib/types'; class CreatePostDto { @ApiModelProperty({description:'帖子标题', example: '帖子标题1'}) @IsNotEmpty({message:'请填写标题'}) title: string; @ApiModelProperty({description:'帖子内容', example: '帖子内容1'}) content: string; } @Controller('posts') @ApiUseTags('帖子') export class PostsController { constructor( @InjectModel(PostSchema) private readonly postModel: ModelType<PostSchema> ){} @Get() @ApiOperation({ title: '显示帖子列表' }) async index() { return await this.postModel.find() } @Post() @ApiOperation({ title: '创建帖子' }) async create(@Body() createPostDto:CreatePostDto) { await this.postModel.create(createPostDto) return { success: true, }; } @Get(':id') @ApiOperation({ title: '帖子详情' }) async detail(@Param('id') id:string) { return await this.postModel.findById(id) } @Put(':id') @ApiOperation({ title: '编辑帖子' }) async update(@Body() createPostDto:CreatePostDto, @Param('id') id:string) { await this.postModel.findByIdAndUpdate(id, createPostDto); return { success: true, }; } @Delete(':id') @ApiOperation({ title: '删除帖子' }) async remove(@Param('id') id:string){ await this.postModel.findByIdAndDelete(id); return { success:true } } }
9ac6212c6256d297486af55be59cce1f131ff800
TypeScript
TimCN/async-module-import
/src/index.ts
2.671875
3
declare global { var webpackModuleFiles: any; var __webpack_require__: any; } /** * * 加载远程模块 * @param {string} moduleUrl module的路径 * @returns {Promise<boolean>} 动态加载module成功 */ function loadModule(moduleUrl: string): Promise<boolean> { return new Promise(function (resolve) { // TODO: handler timeout // step2-1: 如果不存在,先利用jsonp,加载module const scriptTag = document.createElement("script") scriptTag.onload = function (e) { resolve(true); } scriptTag.onerror = function (e) { resolve(false) } document.body.appendChild(scriptTag) scriptTag.src = moduleUrl }) } /** * 根据moduleId获取其远程资源路径 * * @param {string} moduleId * @returns {string} */ function getModuleUlr(moduleId: string): string { return window.webpackModuleFiles[moduleId] } export function asyncImport(moduleId: string): Promise<any> { return new Promise(function (resolve, reject) { // step1: 确认全局module中是否存在moduleId if (!__webpack_require__.m.hasOwnProperty(moduleId)) { const moduleUrl = getModuleUlr(moduleId); // loadModule 会自动载入至全局module中 loadModule(moduleUrl).then(function (status) { if (status) { resolve(__webpack_require__(moduleId)) } else { reject("async import module: " + moduleId + " failed") } }) } else { resolve(__webpack_require__(moduleId)) } }) } export default function asyncImportDefault(moduleId: string) { return asyncImport(moduleId).then(function (all: { default?: any }) { return all["default"] }) }
4152a55085f835ca3709a5ace041c46c78608b85
TypeScript
ytchang05/N-lang
/js/src/type-checker/display-lines.ts
2.84375
3
import { ParseOptions, parse } from '../grammar/parse' import { Block } from '../grammar/ast' export interface FileLinesOptions {} export class FileLines { name: string lines: string[] lineNumWidth: number constructor (file: string, name: string = '<file>', _: FileLinesOptions = {}) { this.name = name this.lines = file.split(/\r?\n/) this.lineNumWidth = (this.lines.length + 1 + '').length } getLine (line: number): string { return this.lines[line - 1] || '' } parse (options: ParseOptions = {}): Block { return parse(this.toString(), options) } toString (): string { return this.lines.join('\n') } }
571e81f065b4a220ab4857f7a0f3af9c68175a2f
TypeScript
kaulart/archref
/ArchRefClient/ArchRefClient/src/app/shared/dataservices/metrics/property.service.ts
2.765625
3
import { Logger } from '../../../../logger/logger'; import { Property } from '../../datamodels/metrics/property'; import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs'; /********************************************************************************************************************************************************************************************************** * * @service - PropertyService - Implements the calls to the rest interface of the application server and * handle the request construction and response extraction for Property data * *********************************************************************************************************************************************************************************************************/ @Injectable() export class PropertyService { // URL of the REST Interface End-Point private propertyUrl = '/api/properties'; constructor(private http: Http) { } /******************************************************************************************************************************************************************************************************** * * @request - getProperties - Send GET all Properties REQUEST * *******************************************************************************************************************************************************************************************************/ public getProperties(): Observable<Property[]> { Logger.info('[REQUEST - PROPERTY] Send GET Properties Request', PropertyService.name); return this.http.get(this.propertyUrl).map(this.extractProperties).catch(this.handleError); } /******************************************************************************************************************************************************************************************************** * * @request - getProperty - Send GET Property REQUEST * * @param - id: number - Property which should be created * *******************************************************************************************************************************************************************************************************/ public getProperty(id: number): Observable<Property> { Logger.info('[REQUEST - PROPERTY] Send GET Property Request with ID:' + id, PropertyService.name); return this.http.get(this.propertyUrl + '/' + id).map(this.extractProperty).catch(this.handleError); } /******************************************************************************************************************************************************************************************************** * * @request - createProperty - Send POST Property REQUEST * * @param - property: Property - Property which should be created * *******************************************************************************************************************************************************************************************************/ public createProperty(property: Property): Observable<Property> { Logger.info('[REQUEST - PROPERTY] Send POST Property Request', PropertyService.name); Logger.data('[REQUEST - PROPERTY]' + JSON.stringify(property), PropertyService.name); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post(this.propertyUrl, property, options).map(this.extractProperty).catch(this.handleError); } /******************************************************************************************************************************************************************************************************** * * @request - updateProperty - Send PUT Property REQUEST * * @param - property: Property - Property which should be updated * *******************************************************************************************************************************************************************************************************/ public updateProperty(property: Property): Observable<Property> { Logger.info('[REQUEST - PROPERTY] Send PUT Request Property', PropertyService.name); Logger.data('[REQUEST - PROPERTY] ' + JSON.stringify(property), PropertyService.name); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.put(this.propertyUrl + '/' + property.id, property, options).map(this.extractProperty).catch(this.handleError); } /******************************************************************************************************************************************************************************************************** * * @request - deleteProperty - Send DELETE Property REQUEST * * @param - id: number - ID of the Property which should be deleted from the database * *******************************************************************************************************************************************************************************************************/ public deleteProperty(id: number): Observable<Property> { Logger.info('[REQUEST - PROPERTY] Send DELETE NodeType Request with ID: ' + id, PropertyService.name); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.delete(this.propertyUrl + '/' + id, options).map(res => res).catch(this.handleError); } /******************************************************************************************************************************************************************************************************** * * @response -extractProperties - Extract data from response data list * * @param - res: Response - Response Object * *******************************************************************************************************************************************************************************************************/ public extractProperties(res: Response) { Logger.info('[RESPONSE - PROPERTY]: Extract Data of Response Body', PropertyService.name); let body = res.json(); let propertyList: Property[] = []; Logger.data('[RESPONSE - PROPERTY]: ' + JSON.stringify(body), PropertyService.name); for (let property of body) { let tempProperty: Property = new Property(property.name, property.value); tempProperty = property; propertyList.push(tempProperty); } return propertyList || {}; } /******************************************************************************************************************************************************************************************************** * * @response - extractProperty - Extract data from response data object * * @param - res: Response - Response Object * *******************************************************************************************************************************************************************************************************/ private extractProperty(res: Response) { Logger.info('[RESPONSE - PROPERTY]: Extract Data of Response Body', PropertyService.name); let body = res.json(); Logger.data('[RESPONSE - PROPERTY]: ' + JSON.stringify(body), PropertyService.name); let property: Property = new Property(body.name, body.value); property = body; return property || {}; } /******************************************************************************************************************************************************************************************************** * * @error - handleError - Error Handling * * @param - error: Response - Response Object * *******************************************************************************************************************************************************************************************************/ private handleError(error: Response | any) { let errMsg: string; if (error instanceof Response) { const body = error.json() || ''; const err = body.error || JSON.stringify(body); errMsg = `${error.status} - ${error.statusText || ''} ${err}`; } else { errMsg = error.message ? error.message : error.toString(); } console.error(errMsg); return Observable.throw(errMsg); } }
0d9b500bc2f00493f0a6b54aacedb68634bad1af
TypeScript
a7650/uniapp-chat
/types.d.ts
2.796875
3
export type ContentType = 'text' | 'voice' | 'image' export type ID = string export type TextContent = string export type ImageContent = string export type VoiceContent = string export interface MessageInstance< T = ContentType, S = TextContent | ImageContent | VoiceContent > { readonly id: ID senderAvatarUrl: string senderId: ID senderName: string contentType: T content: S createTime: number } export interface SendMessageInstance extends MessageInstance { isSent?: boolean loading?: boolean duration?: number }
4a3b4a9e19f972ad74bd180bf6a41405632aa308
TypeScript
mertsincan/primevue
/src/components/menubar/Menubar.d.ts
2.515625
3
import { VNode } from 'vue'; import { ClassComponent, GlobalComponentConstructor } from '../ts-helpers'; import { MenuItem } from '../menuitem'; export interface MenubarProps { /** * An array of menuitems. */ model?: MenuItem[] | undefined; /** * Whether to apply 'router-link-active-exact' class if route exactly matches the item path. * Default value is true. */ exact?: boolean | undefined; } export interface MenubarSlots { /** * Custom start template. */ start: () => VNode[]; /** * Custom end template. */ end: () => VNode[]; /** * Custom item template. * @param {Object} scope - item slot's params. */ item: (scope: { /** * Menuitem instance */ item: MenuItem; }) => VNode[]; } export declare type MenubarEmits = { } declare class Menubar extends ClassComponent<MenubarProps, MenubarSlots, MenubarEmits> { } declare module '@vue/runtime-core' { interface GlobalComponents { Menubar: GlobalComponentConstructor<Menubar> } } /** * * Menubar is a horizontal menu component. * * Helper API: * * - [MenuItem](https://www.primefaces.org/primevue/showcase/#/menumodel) * * Demos: * * - [Menubar](https://www.primefaces.org/primevue/showcase/#/menubar) * */ export default Menubar;
468fbf5b79e70a96d6f8a84f5061be4feec776d9
TypeScript
ipf-klee/cartwheel
/src/main/websites_handler.ts
2.6875
3
const fs = require('fs'); import * as URL from 'url'; import { app, IpcMainEvent } from "electron"; import { WebsiteMetadata } from '../common/website'; export default { configurations: `${ app.getPath('userData') }/websites.json`, read(): Array<WebsiteMetadata> { return JSON.parse(fs.readFileSync(this.configurations)); }, write(data: Array<WebsiteMetadata>): void { fs.writeFileSync(this.configurations, JSON.stringify(data)); }, get(e: IpcMainEvent): void { if (!fs.existsSync(this.configurations)) this.write([]); e.reply('websites-get-reply', this.read()); }, add(e: IpcMainEvent, website: WebsiteMetadata): void { let data = this.read(); data.push(website); this.write(data); e.reply('website-add-reply', website); }, update(e: IpcMainEvent, website: WebsiteMetadata): void { const items = this.read(); const targetIdx = items.findIndex(item => item.url === website.url); items[targetIdx] = website; this.write(items); e.reply('website-update-reply', website); }, deleteUserData(hostname) { fs.rmdirSync(`${ app.getPath('userData') }/${ hostname }`, { recursive: true, }); }, delete(e: IpcMainEvent, website: WebsiteMetadata): void { const hostname = URL.parse(website.url).hostname; this.deleteUserData(hostname); const items = this.read(); const targetIdx = items.findIndex(item => item.url === website.url); items.splice(targetIdx, 1); this.write(items); e.reply('website-remove-reply', website); }, };
5e08c1e67963f8dbd0c0638152b0d6239e901267
TypeScript
fabinwen/angular2-study
/src/app/shared/user.service.ts
2.5625
3
/** * Created by fabin on 2016-10-28. */ import { Injectable } from '@angular/core'; import {Headers, Http, URLSearchParams, Response} from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/delay'; import {ResponseResult, User} from './'; @Injectable() export class UserService { public isLoggedIn:boolean = false; // store the URL so we can redirect after logging in redirectUrl:string; loginUrl:string = '/WebService/student/login'; public user:User; constructor(private http:Http){} login(userNo:string, password:string):Observable<boolean> { let loginParam = { user: { userNo: userNo, password: password, isLogin: false } } ; return this.http.post(this.loginUrl, JSON.stringify(loginParam),{headers: new Headers({"Accept":"application/json","Content-Type":"application/json"})}) .do(res=>{ let resResult = res.json() as ResponseResult; if(resResult.status == 1){ this.isLoggedIn = true; this.user = resResult.data as User; }else{ this.isLoggedIn = false; } }) .map(this.extractData); } private extractData(res:Response) { let resResult = res.json() as ResponseResult; return resResult.status == 1; } private handleError (error: any) { // In a real world app, we might use a remote logging infrastructure // We'd also dig deeper into the error to get a better message let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; console.error(errMsg); // log to console instead return Observable.throw(errMsg); } logout():void { this.isLoggedIn = false; } }
c64c9a86a1754e1577a298d7e17593edb2ae19d8
TypeScript
muratkeremozcan/testing-angular-apps
/chapter06/src/app/contacts/shared/services/preferences-async.service.spec.ts
2.6875
3
// listing 6.11 6.12 // import asynchronous testing methods import { TestBed, fakeAsync, flushMicrotasks, inject } from '@angular/core/testing'; import { BrowserStorageAsync } from "./browser-storage.service"; import { PreferencesAsyncService } from './preferences-async.service'; // when testing async services, the mocks for these services also have to be asynchronous class BrowserStorageAsyncMock { getItem = (property: string) => Promise.resolve({ key: 'testKey', value: 'testValue' }); setItem = ({ key: key, value: value }) => Promise.resolve(true); } describe('PreferencesAsyncService', () => { // TestBed is configured with PreferencesAsyncService before every test // BrowserStorageAsyncMock is used instead of the real service BrowserStorage // By using the token from BrowserStorage and supplying the same methods, you can use your mock for unit testing instead of relying on the real implementation // You only need to configure TestBed to use BrowserStorageAsyncMock whenever a service calls for BrowserStorage as a dependency beforeEach(() => { TestBed.configureTestingModule({ providers: [PreferencesAsyncService, { provide: BrowserStorageAsync, useClass: BrowserStorageAsyncMock }] }); }); it('should get a value', fakeAsync(inject([PreferencesAsyncService, BrowserStorageAsync], (service: PreferencesAsyncService, browserStorage: BrowserStorageAsyncMock) => { // fakeasync test helper reduces the amount of boilerplate code and makes it easy to inject to provide instances // add a spy to browserStorage.getItem spyOn(browserStorage, 'getItem').and.callThrough(); let results, error; // call getPropertyAsync method from preferences-async-service and save the results to results and error // getPropertyAsync triggers BrowserStorageAsyncMock.getItem, which takes property 'testProp', // returns key 'testKey and returns value 'testValue service.getPropertyAsync('testProp') .then(val => results = val) // uses the BrowserStorageAsyncMock default return value .catch(err => error = err); // catches the expected error and assigns it locally // you need to call flushMicrotasks to let Angular know that it's time to process promises in the test // this is a testing-only helper method to make it easier to test asynchronous services // with fakeAsync you do not need to use done() method at the end of an async test // you can use done, async await or fakeAsync, Angular team seems to prefer fakeAsync flushMicrotasks(); expect(browserStorage.getItem).toHaveBeenCalledWith('testProp'); expect(results.key).toEqual('testKey'); expect(results.value).toEqual('testValue'); expect(error).toBeUndefined(); // ensures error value wasn't assigned })) ); it('should throw an error if the key is missing', fakeAsync(inject([PreferencesAsyncService], (service: PreferencesAsyncService) => { let result, error; service.getPropertyAsync('') // call getPropertyAsync with an invalid value .then(value => result = value) // uses the BrowserStorageAsyncMock default return value .catch((err) => error = err); // catches the expected error and assigns it locally // when something goes wrong calling a promise, the catch methods handles the error flushMicrotasks(); expect(result).toBeUndefined(); expect(error).toEqual('getPropertyAsync requires a property name'); })) ); });
a88b55884807f1a77b027a6d6fe827a1bb9929ea
TypeScript
wmoai/kaimono
/src/reducers/modal.ts
2.9375
3
import { ReactNode } from 'react'; import { OPEN, open, CANCEL, cancel, CONFIRM, confirm } from '../actions/modal'; export interface State { isOpen: boolean; contents?: ReactNode; onConfirm?: () => void; } const initialState: State = { isOpen: false }; type Actions = | ReturnType<typeof open> | ReturnType<typeof cancel> | ReturnType<typeof confirm>; export default function(state = initialState, action: Actions) { switch (action.type) { case OPEN: { if (state.isOpen) { break; } const { contents, onConfirm } = action.payload; return { ...state, isOpen: true, contents, onConfirm }; } case CANCEL: { return { ...state, isOpen: false, contents: null, onConfirm: null }; } case CONFIRM: { return { ...state, isOpen: false, contents: null, onConfirm: null }; } } return state; }
05f1a67be58b7acf2cf5ebf9e0c7efb417011235
TypeScript
ccarazasc/angular
/dev-infra/utils/console.ts
3.03125
3
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import chalk from 'chalk'; import {prompt} from 'inquirer'; /** Reexport of chalk colors for convenient access. */ export const red: typeof chalk = chalk.red; export const green: typeof chalk = chalk.green; export const yellow: typeof chalk = chalk.yellow; /** Prompts the user with a confirmation question and a specified message. */ export async function promptConfirm(message: string, defaultValue = false): Promise<boolean> { return (await prompt<{result: boolean}>({ type: 'confirm', name: 'result', message: message, default: defaultValue, })) .result; } /** * Supported levels for logging functions. * * Levels are mapped to numbers to represent a hierarchy of logging levels. */ export enum LOG_LEVELS { SILENT = 0, ERROR = 1, WARN = 2, LOG = 3, INFO = 4, DEBUG = 5, } /** Default log level for the tool. */ export const DEFAULT_LOG_LEVEL = LOG_LEVELS.INFO; /** Write to the console for at INFO logging level */ export function info(...text: string[]): void; export function info(color: typeof chalk, ...text: string[]): void; export function info(color: typeof chalk|string, ...text: string[]) { runConsoleCommand(console.info, LOG_LEVELS.INFO, color, ...text); } /** Write to the console for at ERROR logging level */ export function error(...text: string[]): void; export function error(color: typeof chalk, ...text: string[]): void; export function error(color: typeof chalk|string, ...text: string[]) { runConsoleCommand(console.error, LOG_LEVELS.ERROR, color, ...text); } /** Write to the console for at DEBUG logging level */ export function debug(...text: string[]): void; export function debug(color: typeof chalk, ...text: string[]): void; export function debug(color: typeof chalk|string, ...text: string[]) { runConsoleCommand(console.debug, LOG_LEVELS.DEBUG, color, ...text); } /** Write to the console for at LOG logging level */ export function log(...text: string[]): void; export function log(color: typeof chalk, ...text: string[]): void; export function log(color: typeof chalk|string, ...text: string[]) { // tslint:disable-next-line: no-console runConsoleCommand(console.log, LOG_LEVELS.LOG, color, ...text); } /** Write to the console for at WARN logging level */ export function warn(...text: string[]): void; export function warn(color: typeof chalk, ...text: string[]): void; export function warn(color: typeof chalk|string, ...text: string[]) { runConsoleCommand(console.warn, LOG_LEVELS.WARN, color, ...text); } /** * Run the console command provided, if the environments logging level greater than the * provided logging level. */ function runConsoleCommand( command: Function, logLevel: LOG_LEVELS, color: typeof chalk|string, ...text: string[]) { if (getLogLevel() >= logLevel) { if (typeof color === 'function') { text = text.map(entry => color(entry)); } else { text = [color as string, ...text]; } for (const textEntry of text) { command(textEntry); } } } /** * Retrieve the log level from environment variables, if the value found * based on the LOG_LEVEL environment variable is undefined, return the default * logging level. */ function getLogLevel() { const logLevelEnvValue: any = (process.env[`LOG_LEVEL`] || '').toUpperCase(); const logLevel = LOG_LEVELS[logLevelEnvValue]; if (logLevel === undefined) { return DEFAULT_LOG_LEVEL; } return logLevel; }
73aabd6aeb50ef78680dbb3758fe97f7af1b1af5
TypeScript
dvlyon/evolution
/src/lib/constants.ts
2.890625
3
import { PipeType } from '../lib/types' export interface IPipes { value: PipeType check: boolean[] rotation: number } export const pipes: IPipes[] = [ { value: '━', check: [false, true, false, true], rotation: 0, }, { value: '┃', check: [true, false, true, false], rotation: 0, }, { value: '┏', check: [false, true, true, false], rotation: 1, }, { value: '┓', check: [false, false, true, true], rotation: 1, }, { value: '┗', check: [true, true, false, false], rotation: 1, }, { value: '┛', check: [true, false, false, true], rotation: 1, }, { value: '┣', check: [true, true, true, false], rotation: 2, }, { value: '┫', check: [true, false, true, true], rotation: 2, }, { value: '┳', check: [false, true, true, true], rotation: 2, }, { value: '┻', check: [true, true, false, true], rotation: 2, }, { value: '╋', check: [true, true, true, true], rotation: 3, }, { value: '╸', check: [false, false, false, true], rotation: 4, }, { value: '╹', check: [true, false, false, false], rotation: 4, }, { value: '╺', check: [false, true, false, false], rotation: 4, }, { value: '╻', check: [false, false, true, false], rotation: 4, }, ] export const rotations: PipeType[][] = [ ['━', '┃'], ['┏', '┓', '┛', '┗'], ['┣', '┳', '┫', '┻'], ['╋'], ['╸', '╹', '╺', '╻'] ]
cadac934ccd98d9cd2b792b2be073083957c7cb6
TypeScript
wizdmio/wizdm
/connect/src/lib/database/document/batch.ts
2.84375
3
import { WriteBatch, DocumentRef, DocumentData } from './types'; import { DatabaseApplication } from '../database-application'; export class DatabaseBatch { constructor(readonly db: DatabaseApplication, readonly btc: WriteBatch) { } /** * Creates / destructively re-writes the document content. * Adds the 'created' timestamp */ public set<T extends DocumentData>(ref: DocumentRef<T>, data: T): this { const created = this.db.timestamp; return this.btc.set(ref, { ...data as any, created }), this; } /** * Updates the document content by merging the new data with the existing one including sub objects. * Adds / updates the 'updated' timestamp */ public merge<T extends DocumentData>(ref: DocumentRef<T>, data: T): this { const updated = this.db.timestamp; return this.btc.set(ref, { ...data as any, updated }, { merge: true } ), this; } /** * Updates the document content with the new data. Unlike merge, it overwrites sub objects. * Adds / updates the 'updated' timestamp */ public update<T extends DocumentData>(ref: DocumentRef<T>, data: T): this { const updated = this.db.timestamp; return this.btc.update(ref, { ...data as any, updated }), this; } /** Deletes the document */ public delete<T extends DocumentData>(ref: DocumentRef<T>): this { return this.btc.delete(ref), this; } /** Commits the batch for multiple writes */ public commit(): Promise<void> { return this.btc.commit(); } }
ef0b4f9c83594ba71eddbfe5070d97412499bee6
TypeScript
paytm/paytm-pg-node-sdk
/src/com/paytm/pg/response/NativePaymentStatusResponse.ts
2.640625
3
/** * Copyright (C) 2019 Paytm. */ import * as _SecureResponse from "./interfaces/SecureResponse"; /* class: NativePaymentStatusResponse */ export class NativePaymentStatusResponse implements _SecureResponse.SecureResponse { /** * @var SecureResponseHeader */ public head; /** * @var NativePaymentStatusResponseBody */ public body; /** * Paytm\pg\response\NativePaymentStatusResponse constructor. * @param SecureResponseHeader head * @param NativePaymentStatusResponseBody body */ public constructor(head, body) { this.head = head; this.body = body; } /** * @return SecureResponseHeader */ public getHead() { return this.head; } /** * @param SecureResponseHeader head * @return void */ public setHead(head): void { this.head = head; } /** * @return BaseResponseBody|NativePaymentStatusResponseBody */ public getBody() { return this.body; } /** * @param NativePaymentStatusResponseBody body * @return void */ public setBody(body): void { this.body = body; } public toJSON() { return { 'head': this.getHead(), 'body': this.getBody() }; } }
5283063293a11ef69b72815e9eb5fca1b822e1bb
TypeScript
DaveYognaught/pokeclicker
/src/modules/underground/UndergroundItemNameType.ts
2.875
3
/* To update this type when adding new items: Open the game, and run the following code in the browser console copy(`type UndergroundItemNameType = ${[...new Set(Object.values(UndergroundItems.list).map(i => i.name))].map(i => `'${i.replace(/'/g, "\\'")}'`).join('\n | ')};`); Replace the everything in this file (except for this comment) with what was copied */ type UndergroundItemNameType = 'Rare Bone' | 'Star Piece' | 'Revive' | 'Max Revive' | 'Iron Ball' | 'Heart Scale' | 'Light Clay' | 'Odd Keystone' | 'Hard Stone' | 'Oval Stone' | 'Everstone' | 'Smooth Rock' | 'Heat Rock' | 'Icy Rock' | 'Damp Rock' | 'Draco Plate' | 'Dread Plate' | 'Earth Plate' | 'Fist Plate' | 'Flame Plate' | 'Icicle Plate' | 'Insect Plate' | 'Iron Plate' | 'Meadow Plate' | 'Mind Plate' | 'Sky Plate' | 'Splash Plate' | 'Spooky Plate' | 'Stone Plate' | 'Toxic Plate' | 'Zap Plate' | 'Pixie Plate' | 'Helix Fossil' | 'Dome Fossil' | 'Old Amber' | 'Root Fossil' | 'Claw Fossil' | 'Armor Fossil' | 'Skull Fossil' | 'Cover Fossil' | 'Plume Fossil' | 'Jaw Fossil' | 'Sail Fossil' | 'Fossilized Bird' | 'Fossilized Fish' | 'Fossilized Drake' | 'Fossilized Dino' | 'Fire Stone' | 'Water Stone' | 'Thunder Stone' | 'Leaf Stone' | 'Moon Stone' | 'Sun Stone' | 'Shiny Stone' | 'Dusk Stone' | 'Dawn Stone' | 'Ice Stone' | 'Red Shard' | 'Yellow Shard' | 'Green Shard' | 'Blue Shard' | 'Grey Shard' | 'Purple Shard' | 'Ochre Shard' | 'Black Shard' | 'Crimson Shard' | 'Lime Shard' | 'White Shard' | 'Pink Shard' | 'Cyan Shard' | 'Rose Shard' | 'Brown Shard'; //| 'Beige Shard'; export default UndergroundItemNameType;
97376f133c71d0a94155ed1b58b4b8b6ccf3a5f0
TypeScript
ottoBitPd/colletta
/code/src/ts/presenter/ProfilePresenter.ts
2.65625
3
import {PagePresenter} from "./PagePresenter" import {Client} from "../model/Client/Client"; import {UserKind} from "../view/PageView"; var session = require('express-session'); /** * */ class ProfilePresenter extends PagePresenter{ constructor(view : any){ super(view); this.client = (new Client.builder()).buildUserClient().buildExerciseClient().build(); } /** * This method provides to manage the view urls. * @param app */ update(app : any){ app.post('/update', async (request: any, response: any) => { let userClient = this.client.getUserClient(); if (userClient){ const id = await userClient.search(session.username); const userData = await userClient.getUserData(id); let check : boolean =false; if(request.body.oldpassword==="" && request.body.password==="") { check = true; } if(request.body.oldpassword!=="" && request.body.password!=="") { if (userClient.checkPassword(request.body.oldpassword,userData.password)) { request.body.password = userClient.hashPassword(request.body.password); check = true; this.view.setError("Password modificata"); } else { check = false; this.view.setError("Modifica abortita username esistente o password errata"); } } if(check===true && request.body.username==="") { check = true; } else { if(check===true && await userClient.search(request.body.username)==="false") { check=true; } else { check=false; this.view.setError("Modifica abortita username esistente o password errata"); } } if(check) { this.view.setError(""); let userUpdateData: any = {}; for (let i in request.body) { if (i !== "oldpassword" && i!=="inps"){ if (request.body[i]!=="") { userUpdateData[i] = request.body[i]; } else userUpdateData[i] = userData[i]; } } if (await userClient.isTeacher(session.username)) { if (/^[^\s]$/.test(request.body.inps)) userUpdateData.inps = request.body.inps; else userUpdateData.inps = userData.inps; this.view.setUserKind(UserKind.teacher); } else { this.view.setUserKind(UserKind.student); } await userClient.updateUser(session.username, userUpdateData); session.username = userUpdateData.username; } } response.redirect('/profile'); }); app.get('/profile', async (request: any, response: any) => { let userClient = this.client.getUserClient(); if (userClient && session.username){ const id = await userClient.search(session.username); const userData = await userClient.getUserData(id); this.view.setUserData(userData); if (await userClient.isTeacher(session.username)){ this.view.setUserKind(UserKind.teacher); } else { this.view.setUserKind(UserKind.student); } } if (session.username === undefined) response.redirect('/'); this.view.setTitle("Profilo"); response.send(await this.view.getPage()); }); } public async getStudentClass () { let userClient= this.client.getUserClient(); if(userClient){ const id = await userClient.search(session.username); const userData = await userClient.getUserData(id); return userData.classId; } } /** * This method provides all the info related to the exercise's valutation of a student */ public async getAverageInfo() : Promise<Map<number,number>>{ let userClient= this.client.getUserClient(); let exerciseClient= this.client.getExerciseClient(); if(userClient && exerciseClient) { let id = await userClient.search(session.username); let result = await exerciseClient.getStudentAverage(id); return result; } return new Map(); } } export {ProfilePresenter};
d9d9383e256d02b3aa3671cb4f16b459479f10db
TypeScript
neoskop/adamant
/src/utils/defer.ts
3.078125
3
export type Deffered<T> = Promise<T> & { resolve(v: T): void; reject(e: any): void }; export function defer<T>(): Deffered<T> { let resolve: any, reject: any, promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; }); return Object.assign(promise, { resolve, reject }); }
9357abc4d1bf6bec18f54f1ca284f5c2b16553a5
TypeScript
just-anohaker/smartdb-ts
/dist/Common.d.ts
2.90625
3
export declare type MaybeUndefined<T> = T | undefined; export declare type Nullable<T> = T | null | undefined; export interface ObjectLiteral { [key: string]: any; } export declare type JsonObject = ObjectLiteral; export declare type Entity = ObjectLiteral; export declare type Property<T> = keyof T & string; export declare type Partial<T> = { [P in keyof T]?: T[P]; }; export declare type ReadonlyPartial<T> = { readonly [P in keyof T]?: T[P]; }; export declare type Minix<T1, T2> = T1 & T2; export declare type FilterFunction<T> = (e: T) => boolean; export declare type Callback<T> = (err: Nullable<Error>, data: T) => void; export declare function makeJsonObject<T>(iterable: Iterable<T>, getKey: (t: T) => string, getValue: (t: T) => any): JsonObject; export declare function deepCopy<T>(src: T): T; export declare function partialCopy<T extends object>(src: T, keysOrKeyFilter: string[] | ((key: string) => boolean), dest?: Partial<T>): Partial<T>; export declare function isPrimitiveKey(key: any): boolean; export declare class NotImplementError extends Error { constructor(message?: string); } export declare class CodeContractError extends Error { constructor(message: string); } export declare type ContractCondition = boolean | (() => boolean); export declare type ContractMessage = string | (() => string); export declare type ContractVerifyResult = { result: boolean; message: Nullable<string>; }; export declare type VerifyFunction = () => ContractVerifyResult; export declare class CodeContract { static verify(condition: ContractCondition, message: ContractMessage): void; static argument(argName: string, verify: VerifyFunction | ContractCondition, message?: ContractMessage): void; static notNull(arg: any): ContractVerifyResult; static notNullOrEmpty(str: Nullable<string>): ContractVerifyResult; static notNullOrWhitespace(str: Nullable<string>): ContractVerifyResult; }
4653bf6a99ca5fc1b357979702f5d4e450bf6852
TypeScript
bynaki/ts-webapi.boilerplate
/playground/play01.ts
3.203125
3
const arr = [] arr[1] = function() { console.log('Hello') } console.log(arr[0]) console.log(arr[1]) console.log(arr[2]) function say(...args) { args.forEach((i, idx) => { i() }) } say(...arr.filter(i => i))