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
92cf237a2e154938719fefdd162d5514dc1ec884
TypeScript
SaffronCode/SaffronCodeJS
/src/framework/pageManager/PageData.ts
2.625
3
export default class PageData{ url:string; pageName:string; component?:React.ComponentClass; pageData:any; pageParams?:string[] constructor(URL:string='',PageName:string='', Component?:React.ComponentClass, PageParams?: string[]) { this.url = URL ; this.pageName = PageName ; this.component = Component ; this.pageData = {} ; this.pageParams = PageParams; } }
095cb7772d0bf2794e4277204c1902f763dbda41
TypeScript
GoVivant/govivant-sdk
/src/api/addresses.ts
2.5625
3
import ApiClient from '.' import Address from '../models/Address' export default class ApiAddresses { private api: ApiClient constructor(api: ApiClient) { this.api = api } list(customer_id: string, page: number = 1, limit: number = 15) { return this.api.get(`/addresses/${customer_id}?page=${page}&limit=${limit}`) } create(data: Address) { return this.api.post(`/addresses`, data) } update(id: string, data: Address) { return this.api.put(`/addresses/${id}`, data) } remove(id: string) { return this.api.delete(`/addresses/${id}`) } }
3bb79f8287df7fe14cfbb3af5d88cb4e1163b1ef
TypeScript
pedromsilvapt/data-collectors
/src/collections/groupingBy.ts
2.84375
3
import { Collector, BaseCollector, Supplier, collect } from "../collector"; import { toArray } from "./toArray"; import { mapping } from "../transformers/mapping"; export interface Mapper<T, U> { ( value : T ) : U; } export class GroupingByCollector<T, K, A, D, M extends Map<K, D>> extends BaseCollector<T, Map<K, A>, Map<K, D>> { protected mapper : Mapper<T, K>; protected supplier : Supplier<M>; protected collector : Collector<T, A, D>; constructor ( mapper : Mapper<T, K>, supplier : Supplier<M>, collector : Collector<T, A, D> ) { super(); this.mapper = mapper; this.supplier = supplier; this.collector = collector; } supply () : Map<K, A> { return new Map<K, A>(); } accumulate ( container : Map<K, A>, item : T ) : void { const key = this.mapper( item ); if ( !container.get( key ) ) { const subContainer = this.collector.supply(); container.set( key, subContainer ); this.collector.accumulate( subContainer, item ); } else { this.collector.accumulate( container.get( key ), item ); } } combine ( container1 : Map<K, A>, container2 : Map<K, A> ) : Map<K, A> { for ( let [ key, value ] of container2 ) { container1.set( key, this.collector.combine( container1.get( key ), value ) ); } return container1; } finish ( container : Map<K, A> ) : Map<K, D> { let finished = this.supplier(); for ( let [ key, value ] of container ) { finished.set( key, this.collector.finish( value ) ); } return finished; } } export function groupingBy<T, K> ( mapper : ( item : T ) => K ) : Collector<T, Map<K, T[]>, Map<K, T[]>>; export function groupingBy<T, K, A, D> ( mapper : ( item : T ) => K, collector : Collector<T, A, D> ) : Collector<T, Map<K, A>, Map<K, D>>; export function groupingBy<T, K, A, D, M extends Map<K, D>> ( mapper : ( item : T ) => K, supplier : Supplier<M>, collector : Collector<T, A, D> ) : Collector<T, Map<K, A>, Map<K, D>>; export function groupingBy<T, K, A, D, M extends Map<K, D>> ( mapper : ( item : T ) => K, supplier ?: Supplier<M> | Collector<T, A, D>, collector ?: Collector<T, A, D> ) : Collector<T, any, any> { if ( !supplier && !collector ) { return groupingBy( mapper, () => new Map(), toArray() ); } else if ( !collector ) { return groupingBy( mapper, () => new Map(), supplier as Collector<T, A, D> ); } return new GroupingByCollector( mapper, supplier as Supplier<M>, collector ); }
8c4e171731a14ef60857ede5eea0ecebf6d259bc
TypeScript
robertherber/kingstinct-utils
/src/node/graphql/scalars/Time.ts
2.640625
3
import * as validator from 'is-my-date-valid'; import ScalarFactory from './utils/ScalarFactory'; const validateTime = validator({ format: 'HH:mm:ss' }); const GraphQLTimeScalar = ScalarFactory( 'Time', 'Represents a specific time of day. Format: HH:mm:ss', validateTime, ); export default GraphQLTimeScalar;
91987d247b2fab8d7c5f9b8d6d34f345adc7483c
TypeScript
sourcegraph/sourcegraph
/client/shared/src/util/rxjs/throttleTimeWindow.test.ts
2.828125
3
import { of } from 'rxjs' import { mergeMap } from 'rxjs/operators' import { TestScheduler } from 'rxjs/testing' import { throttleTimeWindow } from './throttleTimeWindow' const scheduler = (): TestScheduler => new TestScheduler((a, b) => expect(a).toEqual(b)) describe('throttleTimeWindow', () => { test('emit the first value (immediately) and last value (at the end) in each time window', () => { scheduler().run(({ hot, expectObservable, expectSubscriptions }) => { const observable = hot('-a-x-y----b---x-cx---|') const subscriptions = '^--------------------!' const expected = '-a----y---b----xc----(x|)' const result = observable.pipe(throttleTimeWindow(5, 1)) expectObservable(result).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('emit the first 2 values (immediately) and last value (at the end) in each time window', () => { scheduler().run(({ hot, expectObservable, expectSubscriptions }) => { const observable = hot('-a-x-y----b---x-cx---|') const subscriptions = '^--------------------!' const expected = '-a-x--y---b---x-cx---|' const result = observable.pipe(throttleTimeWindow(5, 2)) expectObservable(result).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('emit the first 3 values (immediately) and last value (at the end) in each time window', () => { scheduler().run(({ hot, expectObservable, expectSubscriptions }) => { const observable = hot('-a-x-y----bxy-z-cx---|') const subscriptions = '^--------------------!' const expected = '-a-x-y----bxy--zcx---|' const result = observable.pipe(throttleTimeWindow(5, 3)) expectObservable(result).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('simply mirror the source if values are not emitted often enough', () => { scheduler().run(({ hot, expectObservable, expectSubscriptions }) => { const observable = hot('-a--------b-----c----|') const subscriptions = '^--------------------!' const expected = '-a--------b-----c----|' expectObservable(observable.pipe(throttleTimeWindow(5, 2))).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('handle a busy producer emitting a regular repeating sequence', () => { scheduler().run(({ hot, expectObservable, expectSubscriptions }) => { const observable = hot('abcdefabcdefabcdefabcdefa|') const subscriptions = '^------------------------!' const expected = 'ab---fab---fab---fab---fa|' expectObservable(observable.pipe(throttleTimeWindow(5, 2))).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('complete when source does not emit', () => { scheduler().run(({ hot, expectObservable, expectSubscriptions }) => { const observable = hot('-----|') const subscriptions = '^----!' const expected = '-----|' expectObservable(observable.pipe(throttleTimeWindow(5, 2))).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('raise error when source does not emit and raises error', () => { scheduler().run(({ hot, expectObservable, expectSubscriptions }) => { const observable = hot('-----#') const subscriptions = '^----!' const expected = '-----#' expectObservable(observable.pipe(throttleTimeWindow(1, 2))).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('handle an empty source', () => { scheduler().run(({ cold, expectObservable, expectSubscriptions }) => { const observable = cold('|') const subscriptions = '(^!)' const expected = '|' expectObservable(observable.pipe(throttleTimeWindow(3, 2))).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('handle a never source', () => { scheduler().run(({ cold, expectObservable, expectSubscriptions }) => { const observable = cold('-') const subscriptions = '^' const expected = '-' expectObservable(observable.pipe(throttleTimeWindow(3, 2))).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('handle a throw source', () => { scheduler().run(({ cold, expectObservable, expectSubscriptions }) => { const observable = cold('#') const subscriptions = '(^!)' const expected = '#' expectObservable(observable.pipe(throttleTimeWindow(3, 2))).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('throttle and does not complete when source does not completes', () => { scheduler().run(({ hot, expectObservable, expectSubscriptions }) => { const observable = hot('-a--(bc)-------d----------------') const unsub = '-------------------------------!' const subscriptions = '^------------------------------!' const expected = '-a----c--------d----------------' expectObservable(observable.pipe(throttleTimeWindow(5)), unsub).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('not break unsubscription chains when result is unsubscribed explicitly', () => { scheduler().run(({ hot, expectObservable, expectSubscriptions }) => { const observable = hot('-a--(bc)-------d----------------') const subscriptions = '^------------------------------!' const expected = '-a----c--------d----------------' const unsub = '-------------------------------!' const result = observable.pipe( mergeMap(emission => of(emission)), throttleTimeWindow(5), mergeMap(emission => of(emission)) ) expectObservable(result, unsub).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) test('throttle values until source raises error', () => { scheduler().run(({ hot, expectObservable, expectSubscriptions }) => { const observable = hot('-a--(bc)-------d---------------#') const subscriptions = '^------------------------------!' const expected = '-a----c--------d---------------#' expectObservable(observable.pipe(throttleTimeWindow(5))).toBe(expected) expectSubscriptions(observable.subscriptions).toBe(subscriptions) }) }) })
30d0a44519727511a8b50038bad53df61eede630
TypeScript
ChaoSun02/WFE-1-Final-project-skeleton
/src/app/models/mine-mines.ts
2.75
3
export class MineMines { constructor( private Name: string, // this is the level name private X: number, private Y: number, private id: string = null ) { } public getLevelName():string { return this.Name; } public getX() : number { return this.X; } public getY() : number { return this.Y; } public getId(): string { return this.id; } }
6c5d1656bdd525fdbb10b461858582cf53b21883
TypeScript
RiinaVi/yalantis-node-test
/src/utils/deleteImageById.ts
2.5625
3
import fs from 'fs'; import path from 'path'; import { IMAGES_DIRECTORY } from './constants'; const deleteImageById = (id: string) => { fs.readdirSync(IMAGES_DIRECTORY).find((file) => { if (file.includes(id)) { fs.unlinkSync(path.join(IMAGES_DIRECTORY, file)); } }); }; export default deleteImageById;
a6532723ad9d4103e6124b217b5e59e643dfeccb
TypeScript
pppguru/MEAN-learning
/cgi-she-exam-app/src/app/model/exam/CategoryScore.ts
2.703125
3
export class CategoryScore { constructor() {} public name: string; public id: string; get data(): any[] { return [this.correct, this.total - this.correct]; } public correct: number; public total: number; get percent(): string { if (this.total === 0) return '(0%)' return `(${Math.floor((this.correct / this.total * 100)).toString()})%`; } }
baa165aa58b168d288f8460627a65ec94983322c
TypeScript
meganetaaan/alife
/src/life-game/index.ts
3.34375
3
const HEIGHT = 50; const WIDTH = 50; class Matrix { #matrix: Uint8Array; #height: number; #width: number; constructor({ height, width }: { height: number; width: number }) { this.#matrix = new Uint8Array(height * width); this.#height = height; this.#width = width; } get(top: number, left: number): number { top = top % this.#height; left = left % this.#width; return this.#matrix[this.#width * top + left]; } set(top: number, left: number, value: number): void { top = top % this.#height; left = left % this.#width; this.#matrix[this.#width * top + left] = value; } toString(): string { let str = ""; for (let i = 0; i < this.#height; i++) { const start = i * this.#width; str += this.#matrix.slice(start, start + this.#width - 1).join("") + "\n"; } return str; } } let state = new Matrix({ height: HEIGHT, width: WIDTH, }); let nextState = new Matrix({ height: HEIGHT, width: WIDTH, }); export function init(state: Matrix) { for (let i = 0; i < HEIGHT; i++) { for (let j = 0; j < WIDTH; j++) { state.set(i, j, Math.round(Math.random())); } } } function tick() { for (let i = 0; i < HEIGHT; i++) { for (let j = 0; j < WIDTH; j++) { const nw = state.get(i - 1, j - 1); const n = state.get(i - 1, j); const ne = state.get(i - 1, j + 1); const w = state.get(i, j - 1); const c = state.get(i, j); const e = state.get(i, j + 1); const sw = state.get(i + 1, j - 1); const s = state.get(i + 1, j); const se = state.get(i + 1, j + 1); const neighborSum = nw + n + ne + w + e + sw + s + se; if (c === 0 && neighborSum === 3) { nextState.set(i, j, 1); } else if (c === 1 && [2, 3].includes(neighborSum)) { nextState.set(i, j, 1); } else { nextState.set(i, j, 0); } } } [state, nextState] = [nextState, state]; } init(state); setInterval(() => { tick(); console.log(state.toString()); }, 125);
9ec26bf1480d43077ef35e58d665a485be9447d0
TypeScript
bagbag/tstdl
/base/source/collections/observable/observable-sorted-array-list.ts
3.125
3
import { binarySearch, binarySearchFirst, binarySearchFirstIndexEqualOrLarger, binarySearchInsertionIndex, binarySearchLast, binarySearchLastIndexEqualOrSmaller } from '#/utils/binary-search.js'; import { compareByValue } from '#/utils/comparison.js'; import type { Comparator } from '#/utils/sort.js'; import { isDefined, isUndefined } from '#/utils/type-guards.js'; import type { ObservableListIndexedEvent, ObservableSortedList } from './observable-list.js'; import { ObservableListBase } from './observable-list-base.js'; export class ObservableSortedArrayList<T extends TComparator, TComparator = T> extends ObservableListBase<T, ObservableSortedArrayList<T>> implements ObservableSortedList<T, TComparator> { private readonly comparator: Comparator<TComparator>; backingArray: T[]; get self(): this { return this; } get length(): number { return this.backingArray.length; } constructor(comparator: Comparator<TComparator> = compareByValue) { super(); this.comparator = comparator; this.backingArray = []; } get(index: number): T { this.verifyIndexIsInBounds(index); return this.backingArray[index]!; } override getFirst(): T { return this.get(0); } override getLast(): T { return this.get(this.length - 1); } getByComparison(value: TComparator): T | undefined { const index = this.indexOfByComparison(value); return isDefined(index) ? this.get(index) : undefined; } getRangeByComparison(from: TComparator, to: TComparator): T[] { const left = this.findFirstIndexEqualOrLargerThan(from); const right = this.findLastIndexEqualOrSmallerThan(to); if (isUndefined(left) || isUndefined(right)) { return []; } return this.backingArray.slice(left, right + 1); } set(_index: number, _value: T): void { throw new Error('Assignment by index not allowed in sorted collections.'); } addAt(_index: number, ..._values: T[]): void { throw new Error('Adding at index not allowed in sorted collections.'); } removeAt(index: number): T { this.verifyIndexIsInBounds(index); const value = this.backingArray.splice(index, 1)[0]!; this.onRemoveAt([{ index, value }]); return value; } removeRange(index: number, count: number): T[] { this.verifyIndexIsInBounds(index); this.verifyIndexIsInBounds(index + count - 1); const values = this.backingArray.splice(index, count); const events: ObservableListIndexedEvent<T>[] = values.map((value, i) => ({ index: index + i, value })); this.onRemoveAt(events); return values; } clear(): void { this.backingArray = []; this.onClear(); } add(value: T): void { const index = binarySearchInsertionIndex(this.backingArray, value, this.comparator); this.backingArray.splice(index, 0, value); this.onAddAt([{ value, index }]); } addMany(values: T[]): void { const events: ObservableListIndexedEvent<T>[] = []; for (const value of values) { const index = binarySearchInsertionIndex(this.backingArray, value, this.comparator); this.backingArray.splice(index, 0, value); events.push({ value, index }); } this.onAddAt(events); } has(value: T): boolean { const index = binarySearch(this.backingArray, value, this.comparator); return index != undefined; } hasByComparison(value: TComparator): boolean { const index = this.indexOfByComparison(value); return index != undefined; } remove(value: T): boolean { const index = binarySearch(this.backingArray, value, this.comparator); if ((index == undefined) || (this.backingArray[index] != value)) { return false; } this.backingArray.splice(index, 1); this.onRemoveAt([{ value, index }]); return true; } removeMany(values: T[]): number { const events: ObservableListIndexedEvent<T>[] = []; for (const value of values) { const index = binarySearch(this.backingArray, value, this.comparator); if ((index == undefined) || (this.backingArray[index] != value)) { continue; } this.backingArray.splice(index, 1); events.push({ value, index }); } this.onRemoveAt(events); return events.length; } removeRangeByComparison(from: TComparator, to: TComparator): T[] { const left = this.findFirstIndexEqualOrLargerThan(from); const right = this.findLastIndexEqualOrSmallerThan(to); if (isUndefined(left) || isUndefined(right)) { return []; } return this.removeRange(left, (right - left) + 1); } indexOf(value: T): number | undefined { const left = this.findFirstIndexEqualOrLargerThan(value); const right = this.findLastIndexEqualOrSmallerThan(value); if (isUndefined(left) || isUndefined(right)) { return undefined; } for (let i = left; i <= right; i++) { if (this.backingArray[i] == value) { return i; } } return undefined; } lastIndexOf(value: T): number | undefined { const left = this.findFirstIndexEqualOrLargerThan(value); const right = this.findLastIndexEqualOrSmallerThan(value); if (isUndefined(left) || isUndefined(right)) { return undefined; } for (let i = right; i >= left; i--) { if (this.backingArray[i] == value) { return i; } } return undefined; } indexOfByComparison(value: TComparator): number | undefined { return binarySearch(this.backingArray, value, this.comparator); } firstIndexOfByComparison(value: TComparator): number | undefined { return binarySearchFirst(this.backingArray, value, this.comparator); } lastIndexOfByComparison(value: TComparator): number | undefined { return binarySearchLast(this.backingArray, value, this.comparator); } findFirstIndexEqualOrLargerThan(value: TComparator): number | undefined { return binarySearchFirstIndexEqualOrLarger(this.backingArray, value, this.comparator); } findLastIndexEqualOrSmallerThan(value: TComparator): number | undefined { return binarySearchLastIndexEqualOrSmaller(this.backingArray, value, this.comparator); } [Symbol.iterator](): IterableIterator<T> { return this.backingArray[Symbol.iterator](); } private verifyIndexIsInBounds(index: number): void { if ((index < 0) || (index > (this.backingArray.length - 1))) { throw new Error('Index out of bounds.'); } } }
e56de0cf6e584925b16f2a7eb886f34257f0214c
TypeScript
Luobata/simply-chart
/src/lib/Vector.ts
3.65625
4
/** * @description Vector */ import { IPoint } from '@/lib/interface'; /** * default class Vector */ export default class Vector { public vector: IPoint; public value: number; // 向量长度 constructor(vector: IPoint) { this.vector = vector; this.value = this.getValue(this); } // 向量加 public add(vec: Vector): Vector { return new Vector({ x: this.vector.x + vec.vector.x, y: this.vector.y + vec.vector.y, }); } // 向量减 public minus(vec: Vector): Vector { return new Vector({ x: this.vector.x - vec.vector.x, y: this.vector.y - vec.vector.y, }); } // 向量点积 // 物理含义 可以用来vec 在当前向量上的投影 // 或者用来求两个向量的夹角 public dot(vec: Vector): number { return this.vector.x * vec.vector.x + this.vector.y * vec.vector.y; } // 向量叉积 的值 // 向量叉积的返回值应该是一个向量而非值,只是方向为垂直当前二维平面,所以在二维平面中,忽略他的方向 // 物理含义 用来求向量围成的平行四边形的面积 public cross(vec: Vector): number { return this.vector.x * vec.vector.y - this.vector.y * vec.vector.x; } // 向量模 public mod(isSqrt: boolean = true): number { if (isSqrt) { return Math.sqrt( Math.pow(this.vector.x, 2) + Math.pow(this.vector.y, 2), ); } else { return Math.pow(this.vector.x, 2) + Math.pow(this.vector.y, 2); } } // 垂直向量 默认返回单位向量 public vertical(): Vector { return new Vector({ x: this.vector.y, y: -this.vector.x, }).normaliz(); } // 向量之间夹角 public ankle(vec: Vector): number { const result: number = (Math.acos(this.dot(vec) / (this.mod() * vec.mod())) * 180) / Math.PI; return result > 180 ? result - 180 : result; } // 转化为法向量 public normaliz(): Vector { const x: number = Math.sqrt( 1 / (Math.pow(this.vector.y, 2) / Math.pow(this.vector.x, 2) + 1), ); return new Vector({ x, y: x === 0 ? 1 : (this.vector.y / this.vector.x) * x, }); } private getValue(vec: Vector): number { return Math.sqrt(Math.pow(vec.vector.x, 2) + Math.pow(vec.vector.y, 2)); } }
7b8fc784531dfc18b3a2f6e514f9c9621759f621
TypeScript
jonasalessi/coding-challenge-backend-c
/test/units/FuzzyText.test.ts
3
3
import { expect } from 'chai'; import { describe } from 'mocha'; import { FuzzyVector, SearchCityFuzzy } from '../../src/types/Fuzzy'; import { City } from '../../src/types/City'; import FuzzyResolver from '../../src/services/search/FuzzyResolver'; import FuzzyCityIndexer from '../../src/services/search/FuzzyCityIndexer'; describe('Counting datagram', () => { it('creates a trigram of the word into a vector', () => { const vector = FuzzyResolver.getTrigram('banana'); expect(vector[0]).to.be.eql({ nGram: '-ba', count: 1 }); expect(vector[1]).to.be.eql({ nGram: 'ban', count: 1 }); expect(vector[2]).to.be.eql({ nGram: 'ana', count: 2 }); expect(vector[3]).to.be.eql({ nGram: 'nan', count: 1 }); expect(vector[4]).to.be.eql({ nGram: 'na-', count: 1 }); }); }); describe('Calculating vectors', () => { it('returns banana magnitude 2.828', () => { const vector: FuzzyVector[] = FuzzyResolver.getTrigram('banana'); const result = FuzzyResolver.calculateMagnitude(vector); expect(result).to.be.closeTo(2.828, 0.001); }); it('calculates the cosine similarity score', () => { const bananaGram: FuzzyVector[] = FuzzyResolver.getTrigram('banana'); const searchCity: SearchCityFuzzy = { searchGram: FuzzyResolver.convertVectorToMap(bananaGram), magnitude: FuzzyResolver.calculateMagnitude(bananaGram), }; const city: City = { name: 'Banan', latitude: -27.5853589, longitude: -48.5087219, country: 'XX', population: 5000, province: 'XX', nGram: FuzzyResolver.getTrigram('banan'), }; city.magnitude = FuzzyResolver.calculateMagnitude(city.nGram); const score = FuzzyResolver.calculateCosineSimilarity(searchCity, city); expect(score).to.be.closeTo(0.791, 0.001); }); }); describe('Indexing the cities', () => { let cities: City[]; let fuzzyBuilder: FuzzyCityIndexer; let florianopolis; let metropolis; before((done) => { cities = [{ name: 'Florianópolis', latitude: -27.5853589, longitude: -48.5087219, country: 'BR', population: 477798, province: 'SC', }, { name: 'Metropolis', latitude: 37.1611569, longitude: -88.7298181, country: 'US', population: 6537, province: 'IL', }]; [florianopolis, metropolis] = cities; fuzzyBuilder = new FuzzyCityIndexer(cities); fuzzyBuilder.buildIndexes(); done(); }); it('creates a index for the city Florianópolis', () => { expect(florianopolis.nGram).to.be.instanceOf(Array); expect(florianopolis.nGram).to.be.have.length(13); expect(florianopolis.magnitude).to.be.not.undefined; }); it('creates a index for the city Metropolis', () => { expect(metropolis.nGram).to.be.instanceOf(Array); expect(metropolis.nGram).to.have.length(10); expect(metropolis.magnitude).to.be.not.undefined; }); it('creates a dictionary with 18 elements', () => { expect(fuzzyBuilder.dictionary.size).to.be.equal(18); }); it('creates the group of index by a gram into dictionary', () => { expect(fuzzyBuilder.dictionary.get('pol').length).to.be.equal(2); expect(fuzzyBuilder.dictionary.get('oli').length).to.be.equal(2); expect(fuzzyBuilder.dictionary.get('lis').length).to.be.equal(2); expect(fuzzyBuilder.dictionary.get('is-').length).to.be.equal(2); }); it('finds only Florianópolis with similar gram from the word Florinda', () => { const citiesFiltered: City[] = fuzzyBuilder.findCityByGram(FuzzyResolver.getTrigram('Florinda')); expect(citiesFiltered.length).to.be.equals(1); expect(citiesFiltered[0].name).to.equal('Florianópolis'); }); });
9bdca02bc90e502c1e97268de5b6796f79e87cfc
TypeScript
MacKentoch/react-bootstrap-webpack-starter
/front/src/contexts/withDevTools/index.ts
2.921875
3
// #region types export type DevToolsMessageType = 'DISPATCH' | string; export type DevToolsMessagePayload = { type?: string; state?: any; }; export type DevToolsMessage = { type?: DevToolsMessageType; payload?: DevToolsMessagePayload; }; export type DevTools = { init: () => void; connect: () => any; subscribe: (message: DevToolsMessage) => any; send: (action: { type: string; state?: any }, newState: any) => any; unsubscribe: () => any; dispatch: (action: { type: string }) => any; disconnect: () => any; }; // #endregion // #region constants // @ts-ignore const isDEV = process.env.NODE_ENV === 'development'; export const withDevTools = isDEV && typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__; const devTools: DevTools = !withDevTools ? null : (window as any).__REDUX_DEVTOOLS_EXTENSION__.connect(); // #endregion // #region devtools reducer type State = { auth: any; }; type Action = { type: string; state?: any; }; const initialState: State = { auth: {}, }; export const reducer = (state: State = initialState, action: Action) => { /* eslint-disable no-unused-vars */ switch (action.type) { // #region auth context case 'AUTH_CHECK_IS_AUTHENTICATED': case 'AUTH_CHECK_TOKEN_IS_EXPIRED': case 'AUTH_SET_TOKEN': case 'AUTH_SET_USER_INFO': case 'AUTH_DISCONNECT_USER': { const { type, state: context, ...rest } = action; return { ...state, user: { context, ...rest } }; } // #endregion default: return state; } /* eslint-enable no-unused-vars */ }; // #endregion // #region singleton devtools local state let state: State; // #endregion // #region devToolsStore (redux like) export const devToolsStore = !withDevTools ? null : { ...devTools, dispatch: (action: Action) => { // #region action validation if (!action) { throw new Error('devTools dispatched action should be defined'); } if (typeof action === 'function') { throw new Error('devTools dispatched action should be an object'); } if (typeof action !== 'object') { throw new Error('devTools dispatched action should be an object'); } if (Array.isArray(action)) { throw new Error('devTools dispatched action should be an object'); } // #endregion const newState = reducer(state, action); state = newState; devTools && devTools.send({ ...action }, newState); }, }; // #endregion
1970a2801e80a444156912a030ba4ccfec79b7bc
TypeScript
DianaJT/second-largest-v2
/src/algorithmA.ts
3.15625
3
function secondLargest(numberArray: number[]) { if (numberArray.length < 2) return null; let numberA: number; let numberB: number; if (numberArray[0] > numberArray[1]) { [numberA, numberB] = numberArray; } else { [numberB, numberA] = numberArray; } for (let i = 2; i < numberArray.length; i += 1) { if (numberArray[i] > numberA) { numberB = numberA; numberA = numberArray[i]; } else if (numberArray[i] > numberB) { numberB = numberArray[i]; } } return numberB; } export = secondLargest;
074db44756ac40476de4eafcbfea14e2169ab9d2
TypeScript
mosaicnetworks/evm-lite-cli
/src/commands/accounts-update.ts
2.640625
3
import * as fs from 'fs'; import Inquirer from 'inquirer'; import Vorpal from 'vorpal'; import utils from 'evm-lite-utils'; import Session from '../core/Session'; import Command, { Arguments, Options } from '../core/Command'; type Opts = Options & { old: string; new: string; }; type Args = Arguments<Opts> & { moniker: string; }; type Answers = { moniker: string; oldPass: string; newPass: string; verifyNewPass: string; }; export default (evmlc: Vorpal, session: Session) => { const description = 'Update passphrase for a local account'; return evmlc .command('accounts update [moniker]') .alias('a u') .description(description) .option('-i, --interactive', 'enter interactive mode') .option('-d, --debug', 'show debug output') .option('-o, --old <path>', 'old passphrase file path') .option('-n, --new <path>', 'new passphrase file path') .types({ string: ['_', 'old', 'o', 'n', 'new'] }) .action((args: Args) => new AccountUpdateCommand(session, args).run()); }; class AccountUpdateCommand extends Command<Args> { protected oldPassphrase: string = ''; protected newPassphrase: string = ''; protected async init(): Promise<boolean> { this.args.options.interactive = this.args.options.interactive || this.session.interactive; return this.args.options.interactive; } protected async prompt(): Promise<void> { const keystore = await this.datadir.listKeyfiles(); const first: Inquirer.QuestionCollection<Answers> = [ { choices: Object.keys(keystore).map(moniker => moniker), message: 'Moniker: ', name: 'moniker', type: 'list' }, { message: 'Enter current passphrase: ', name: 'oldPass', type: 'password' }, { message: 'New passphrase : ', name: 'newPass', type: 'password' }, { message: 'Re-enter new passphrase: ', name: 'verifyNewPass', type: 'password' } ]; const answers = await Inquirer.prompt<Answers>(first); if (!(answers.newPass && answers.verifyNewPass)) { throw Error('Fields cannot be blank.'); } if (answers.newPass !== answers.verifyNewPass) { throw Error('Passphrases do not match.'); } this.args.moniker = answers.moniker; this.oldPassphrase = answers.oldPass.trim(); this.newPassphrase = answers.newPass.trim(); } protected async check(): Promise<void> { if (!this.args.moniker) { throw Error('No moniker provided.'); } if (!utils.validMoniker(this.args.moniker)) { throw Error('Invalid characters in moniker.'); } if (!this.oldPassphrase) { if (!this.args.options.old) { throw Error('Old passphrase file path not provided.'); } if (!utils.exists(this.args.options.old)) { throw Error( 'Old passphrase file path provided does not exist.' ); } if (utils.isDirectory(this.args.options.old)) { throw Error( 'Old passphrase file path provided is a directory.' ); } this.oldPassphrase = fs .readFileSync(this.args.options.old, 'utf8') .trim(); } if (!this.newPassphrase) { if (!this.args.options.new) { throw Error('New passphrase file path not provided.'); } if (!utils.exists(this.args.options.new)) { throw Error( 'New passphrase file path provided does not exist.' ); } if (utils.isDirectory(this.args.options.new)) { throw Error( 'Old passphrase file path provided is a directory.' ); } this.newPassphrase = fs .readFileSync(this.args.options.new, 'utf8') .trim(); } if (this.oldPassphrase === this.newPassphrase) { throw Error('New passphrase cannot be the same as old.'); } } protected async exec(): Promise<string> { this.log.info('keystore', this.datadir.keystorePath); this.debug('Attemping to update keyfile with: '); this.debug(`Moniker -> ${this.args.moniker}`); this.debug(`New Passphrase -> ${this.newPassphrase}`); const keyfile = await this.datadir.updateKeyfile( this.args.moniker, this.oldPassphrase, this.newPassphrase ); if (this.args.options.json) { return JSON.stringify(keyfile); } else { return `Passphrase updated: ${keyfile.address}`; } } }
408acefa44ed8d2cf51913e7d428a0f69309a377
TypeScript
shafiqabedin/RsnaDemo-master
/app/directives/vis.text.directive.ts
2.578125
3
/** * @TO DO * * Copyright (c) 2016, acme and/or its affiliates. All rights reserved. * * @author Shafiq Abedin (sabedin@us.acme.com) * @version 1.0 * @since 2016-9-1 */ import { Directive, Input, Renderer, ElementRef } from "@angular/core"; import { TextVisualizationDataModel } from '../models/text-visualization-data-model'; @Directive({ selector: '[textvisualization]' }) /* * The TextVisualizationDirective handles the highlighting of the text */ export class TextVisualizationDirective { constructor( private el: ElementRef, private renderer: Renderer ) { } private textVisualizationData: TextVisualizationDataModel; private textInterval; private currentConcept; /* * Setter for content will trigger drawing (or refreshing) */ @Input() set content(data: TextVisualizationDataModel) { this.textVisualizationData = data; this.render(); } /* * This method highlights the text. First it matches against the tokens and then replaces with the custom replace function */ private render() { this.currentConcept = this.textVisualizationData.concept; this.renderer.setElementProperty(this.el.nativeElement, 'innerHTML', this.currentConcept); var _this = this; for (var i = 1; i <= this.textVisualizationData.textHighlights.length; i++) { (function (index) { setTimeout(function () { _this.highlighter((index-1)); }, i * 1000); })(i); } } /* * Highlighter */ highlighter(i: number) { let tokenized: any[] = []; tokenized.push(this.textVisualizationData.textHighlights[i]); let regex = new RegExp(tokenized.join('|'), 'gmi'); let html = this.currentConcept.replace(regex, (match, item) => { return this.replace(match, item); }); this.currentConcept = html; this.renderer.setElementProperty(this.el.nativeElement, 'innerHTML', html); } /* * Custom replace function */ replace(match, item) { return `<span style="text-shadow: 10 0 5px white">${match}</span>`; } }
461aa8d269c3dd98dfa8eb6ccf1d2aa4985030fb
TypeScript
AjaiGuvaliour/doodle-chart-app
/client/app/helpers/password-match.validation.ts
2.703125
3
import { AbstractControl } from '@angular/forms'; export const mustMatchPassword = (controlName: string, matchingControlName: string) => { return (control: AbstractControl): { mismatch: boolean } | null => { const input = control.get(controlName); const matchingInput = control.get(matchingControlName); if (matchingInput?.errors && !matchingInput.errors.mismatch) { return null; } if (input?.value !== matchingInput?.value) { matchingInput?.setErrors({ mismatch: true }); return { mismatch: true }; } else { matchingInput?.setErrors(null); return null; } }; };
985ec6004ce32375e8ad1086790feeabb39fbeb6
TypeScript
ZdravkoKirilov/rademono
/apps/clients/projects/ui/src/lib/helpers/OnChange.ts
2.734375
3
import { Dictionary } from '@end/global'; export interface PropChange<T> { firstChange: boolean; previousValue: T; currentValue: T; isFirstChange: () => boolean; } export function OnChange<T, Self>( callback: (value: T, self: Self, simpleChange?: PropChange<T>) => void, ) { let _cachedValue: T; let _isFirstChange = true; return (target: Self, key: PropertyKey) => { Object.defineProperty(target, key, { set: function (value) { // No operation if new value is same as old value if (!_isFirstChange && _cachedValue === value) { return; } const oldValue = _cachedValue; _cachedValue = value; const simpleChange: PropChange<T> = { firstChange: _isFirstChange, previousValue: oldValue, currentValue: _cachedValue, isFirstChange: () => _isFirstChange, }; _isFirstChange = false; callback.call(this, _cachedValue, this, simpleChange); }, get: function () { return _cachedValue; }, }); }; } // eslint-disable-next-line @typescript-eslint/ban-types export function NgOnChange<T, Self extends object>( callback: (value: T, self: Self, simpleChange?: PropChange<T>) => void, ) { return (target: Self, key: string) => { const cacheKey = '__' + key + '_cached'; const firstChangeKey = '__' + key + '_firstChange'; Object.defineProperty(target, key, { set: function (value) { // No operation if new value is same as old value if (!this[firstChangeKey] && this[cacheKey] === value) { return; } const oldValue = this[cacheKey]; this[cacheKey] = value; const simpleChange: PropChange<T> = { firstChange: this[firstChangeKey], previousValue: oldValue, currentValue: this[cacheKey], isFirstChange: () => this[firstChangeKey], }; this[firstChangeKey] = false; callback.call(this, this[cacheKey], this, simpleChange); }, get: function () { return this[cacheKey]; }, }); }; }
6fa318d1688a036ebf7dffd29c57068b81bb818a
TypeScript
ca0v/html-playground
/collage/fun/getImageResolution.ts
2.671875
3
export function getImageResolution(image: HTMLImageElement) { let style = getComputedStyle(image); let w = parseFloat(style.width); let h = parseFloat(style.height); let isPortrait = h > w; // 512 is the maximum width/height of the placeholder image let scale = (isPortrait ? h : w) / 512.0; let rect = image.getBoundingClientRect(); scale *= rect.width / w; return scale; }
6902a95b84d24c324a70663ac2a3bb6577a6c057
TypeScript
unbyte/deno-xml-parser
/parser.ts
2.6875
3
import { matchAttrs, MatchedFragment, matchFragments } from './regexp.ts' import { reflectValue, removeNamespace } from './utils.ts' import { Node } from './xml.ts' export interface Options { // skip parsing some tags, default to false (comparison of tag names is after removing namespace if ignoreNamespace) ignoreTags: false | string[] // skip parsing some attributes, default to false (true means skip all attributes) ignoreAttrs: boolean | string[] // skip namespace in tag names and attributes ignoreNamespace: boolean // parse node value to string | number | boolean reflectValues: boolean // parse node attributes to string | number | boolean reflectAttrs: boolean // trim string values of tags trimValues: boolean // trim string values of attributes trimAttrs: boolean } const defaultOptions: Options = { ignoreTags: false, ignoreAttrs: false, ignoreNamespace: true, reflectValues: true, reflectAttrs: true, trimValues: true, trimAttrs: true, } export class Parser { public options: Options constructor(options: Partial<Options>) { this.options = { ...defaultOptions, ...options, } } parse(raw: string): Node { const ctx: ParseContext = new ParseContext(this.options) const matched = matchFragments(raw) for (const item of matched) { const fragment = item.groups as MatchedFragment if (fragment.tagStart) { // ignore namespace? const tag = ctx.options.ignoreNamespace ? removeNamespace(fragment.tagStart) : fragment.tagStart if (ctx.options.ignoreTags) { // is ignored tag? if (ctx.options.ignoreTagsSet.has(tag)) { if (fragment.selfEnd) continue ctx.pushIgnoringTag(tag) } // is inside a ignored tag? if (ctx.isIgnoring) continue } ctx.newNode(tag) const rawAttrs = fragment.attrs?.trim() || '' if (rawAttrs) parseAttrs(rawAttrs, ctx) if (fragment.selfEnd) ctx.doneNode() if (fragment.content) setNodeValue(fragment.content, ctx) } else if (fragment.tagEnd) { // ignore namespace? const tag = ctx.options.ignoreNamespace ? removeNamespace(fragment.tagEnd) : fragment.tagEnd if (ctx.options.ignoreTags) { // is ignored tag? if (ctx.isIgnoring) { if (ctx.options.ignoreTagsSet.has(tag)) ctx.popIgnoringTag(tag) continue } } // try match tag if (ctx.node.tag !== tag) { throw new Error( `unmatched close-tag near '${raw.substr(item.index!, 8)}'`, ) } ctx.doneNode() } else if (fragment.cdata) { if (ctx.options.ignoreTags && ctx.isIgnoring) continue setNodeValue(fragment.cdata, ctx) } else if (fragment.prolog) { parseAttrs(fragment.prolog, ctx, true) } else { // won't implement for other fragments } } if (ctx.node !== ctx.root) throw new Error('XML format error') return ctx.root } } export class ParseContext { #node: Node readonly #root: Node #ignoringStack: string[] = [] options: Options & { ignoreAttrsSet: Set<string> ignoreTagsSet: Set<string> } constructor(options: Options, root: Node = new Node('ROOT')) { this.#node = root this.#root = root this.options = { ...options, ignoreAttrsSet: new Set( options.ignoreAttrs === true ? [] : (options.ignoreAttrs || []), ), ignoreTagsSet: new Set(options.ignoreTags || []), } } get root() { return this.#root } get node() { return this.#node } get isIgnoring() { return this.#ignoringStack.length > 0 } pushIgnoringTag(tag: string) { return this.#ignoringStack.push(tag) } popIgnoringTag(tag: string) { if (this.#ignoringStack.pop() !== tag) throw new Error('XML format error') } doneNode() { this.#node = this.node.parent || this.#root } newNode(tag: string): Node { const node = new Node(tag) node.parent = this.#node this.#node.addChildren(node) return this.#node = node } } export function parseAttrs( rawAttrs: string, ctx: ParseContext, useRoot: boolean = false, ) { if (ctx.options.ignoreAttrs === true) return const node = useRoot ? ctx.root : ctx.node const matched = matchAttrs(rawAttrs.trim()) // [1] key [2] ?value for (const item of matched) { // is ignored if (ctx.options.ignoreAttrsSet.has(item[1])) return const key = ctx.options.ignoreNamespace ? removeNamespace(item[1]) : item[1] if (!key) return // only when key is `xmlns:` if (!item[2]) { // value is empty => a boolean attr node.setAttr(key, true) return } const value = ctx.options.reflectAttrs ? reflectValue(item[2]) : ctx.options.trimAttrs ? item[2].trim() : item[2] node.setAttr(key, value) } } export function setNodeValue(value: string, ctx: ParseContext) { ctx.node.value = ctx.options.reflectValues ? reflectValue(value) : ctx.options.trimValues ? value.trim() : value }
243633740c6d82327e54acfaddc9de8831ea4e5a
TypeScript
laolarou726/larou-azure-devops-status
/src/helper/randomHelper.ts
3.5
4
export default class RandomHelper { public static randomSample<T>(arr: T[]): T | null { if (arr.length === 0) { return null; } return arr[this.randomNumber(0, arr.length)]; } public static randomSamples<T>(arr: T[], count: number): T[] { const result: T[] = []; if (arr.length === 0) { return []; } for (let i = 0; i < count; i++) { result.push(this.randomSample(arr) as T); } return result; } public static randomNumber(min: number, max: number) { switch (arguments.length) { case 1: return parseInt(String(Math.random() * min + 1), 10); case 2: return parseInt(String(Math.random() * (max - min + 1) + min), 10); default: return 0; } } }
97ee7948bcf06a10ed3dfc5d017dc2f4d176a6cc
TypeScript
cejaramillof/ts-data-structures-and-design-patterns
/patterns/structural/proxy/ServerProxy.ts
2.6875
3
import { IServer } from "./IServer" import { Server } from "./Server" export class ServerProxy implements IServer { private server: Server; constructor(public serverUrl: string) { this.server = new Server(serverUrl) } isUserLogged(): boolean { return Math.round(Math.random()) === 1 } triggerPetition() { if (this.isUserLogged()) { this.server.triggerPetition() } else { console.log('User is not logged') } } }
f3fc09bd21a11a23c24c70b4a004b92d7a760ec0
TypeScript
magsouza/formation
/formation-common/musica.ts
2.578125
3
import { Usuario } from './usuario'; export class Musica { titulo: string; artista: string; integrantes: String []; usuariosInteressados: Usuario[]; constructor() { this.titulo = ""; this.artista = ""; this.integrantes = []; this.usuariosInteressados = []; } clean(): void { this.titulo = ""; this.artista = ""; this.integrantes = []; this.usuariosInteressados = []; } clone(): Musica { var musica: Musica = new Musica(); musica.copyFrom(this); return musica; } copyFrom(from: Musica): void { this.titulo = from.titulo; this.artista = from.artista; this.integrantes = from.integrantes; this.usuariosInteressados = from.usuariosInteressados; } }
d3836c0e414cdb163151007ed5cb727918398acb
TypeScript
trueutkarsh/WookiesMovieApp
/data/Data.ts
2.59375
3
const BASE_URL = "https://wookie.codesubmit.io"; export function getMovies() { let URL = BASE_URL + "/movies" let headers = new Headers(); headers.append("Authorization", "Bearer Wookie2019"); return fetch(URL, { method: 'GET', headers: headers }) .then(response => response.json()) .catch((error) => { console.log(error) } ) } export function searchMovies(entry) { let URL = BASE_URL + "/movies?q=" + (entry || "") let headers = new Headers(); headers.append("Authorization", "Bearer Wookie2019"); return fetch(URL, { method: 'GET', headers: headers }) .then(response => { return response.json() }) .catch((error) => { console.log("searching error on this", entry, error) } ) }
1a6f23e4d247bafad561fada69ec498107b974c5
TypeScript
xuxicheta/swagger-interface-generator
/src/tools/dash-to-camel.ts
2.78125
3
export function dashToCamel(str: string|undefined): string { return str ? str .replace(/(-[a-z])/g, $1 => $1.toUpperCase().replace('-', '')) .replace(/^[a-z]/, s => s.toUpperCase()) : ''; }
81b0e9cc74863301f5ac9852c9838fd7e12e232a
TypeScript
SergioMorchon/fitbit-sdk-types
/types/device/exercise.d.ts
2.515625
3
declare module 'exercise' { export interface ExerciseStats { readonly activeTime: number; readonly calories: number; readonly distance: number; readonly elevationGain: number; readonly heartRate: { readonly current: number; readonly max: number; readonly average: number; }; readonly pace: { readonly current: number; readonly average: number; }; readonly speed: { readonly current: number; readonly max: number; readonly average: number; }; readonly steps: number; readonly swimLengths: number | undefined; } export interface SwimLengthEvent extends Event { readonly dominantStroke: | 'back' | 'unknown' | 'freestyle' | 'breast' | 'butterfly'; readonly lengthDuration: number; readonly lengthStart: number; readonly strokes: number; } export interface ExerciseOptions { autopause?: boolean; disableTouch?: boolean; gps?: boolean; poolLength?: number; } export interface Exercise extends EventTarget<{ statechange: Event; swimlength: SwimLengthEvent; }> { readonly currentLapStats: ExerciseStats | undefined; readonly startDate: Date | undefined; readonly state: 'started' | 'paused' | 'stopped'; readonly stats: ExerciseStats | undefined; readonly type: string | undefined; pause(): void; resume(): void; splitLap(): ExerciseStats; start(exerciseType: string, options?: ExerciseOptions): void; stop(): void; } const exercise: Exercise; export default exercise; }
1fac98e1fa24c89499d7934352290c352b4fe242
TypeScript
ReactiveX/IxJS
/src/asynciterable/operators/buffer.ts
3.453125
3
import { AsyncIterableX } from '../asynciterablex'; import { OperatorAsyncFunction } from '../../interfaces'; import { wrapWithAbort } from './withabort'; import { throwIfAborted } from '../../aborterror'; export class BufferAsyncIterable<TSource> extends AsyncIterableX<TSource[]> { private _source: AsyncIterable<TSource>; private _count: number; private _skip: number; constructor(source: AsyncIterable<TSource>, count: number, skip: number) { super(); this._source = source; this._count = count; this._skip = skip; } async *[Symbol.asyncIterator](signal?: AbortSignal) { throwIfAborted(signal); const buffers: TSource[][] = []; let i = 0; for await (const item of wrapWithAbort(this._source, signal)) { if (i % this._skip === 0) { buffers.push([]); } for (const buff of buffers) { buff.push(item); } if (buffers.length > 0 && buffers[0].length === this._count) { yield buffers.shift()!; } i++; } while (buffers.length > 0) { yield buffers.shift()!; } } } /** * Projects each element of an async-iterable sequence into consecutive non-overlapping * buffers which are produced based on element count information. * * @template TSource The type of elements in the source sequence. * @param {number} count The length of each buffer. * @param {number} [skip] An optional number of elements to skip between creation of consecutive buffers. * @returns {OperatorAsyncFunction<TSource, TSource[]>} An operator which returns anm async-iterable sequence with * consecutive non-overlapping buffers based upon element count information. */ export function buffer<TSource>( count: number, skip?: number ): OperatorAsyncFunction<TSource, TSource[]> { let s = skip; if (s == null) { s = count; } return function bufferOperatorFunction( source: AsyncIterable<TSource> ): AsyncIterableX<TSource[]> { return new BufferAsyncIterable<TSource>(source, count, s!); }; } /** * Projects each element of an async-iterable sequence into consecutive non-overlapping * buffers which are produced based on element count information. * @param count Length of each buffer. * @param skip Number of elements to skip between creation of consecutive buffers. */
84bca575920d1e9ab7b34b01951cb6e86ced89cc
TypeScript
qizhenshuai/nestjs-starter
/src/modules/users/dto/create-user.dto.ts
2.6875
3
import { IsString, IsEmail, IsNotEmpty, Matches, MinLength, MaxLength, IsOptional, ValidateNested, IsArray } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; import { Type } from 'class-transformer'; import { IsUsernameAlreadyExist, IsEmailAlreadyExist } from '../../../common/validators'; import { PATTERN_VALID_USERNAME } from '../../../config/config.constants'; import { ContactInfoDto } from './contact-info.dto'; import { CreateUserMetadataDto } from './create-user-metadata.dto'; export class CreateUserDto { @ApiProperty({ description: 'Email for your account, must be unique.', }) @IsEmailAlreadyExist({ message: 'Email $value already exists. Choose another Email.', }) @IsEmail() @IsString() @IsNotEmpty() email!: string; @ApiProperty({ description: 'Username for your account, must be unique.', }) @IsUsernameAlreadyExist({ message: 'Username $value already exists. Choose another username.', }) @IsString() @MinLength(8) @MaxLength(20) @Matches(PATTERN_VALID_USERNAME, { message: `Username $value don't have a valid format`, }) @IsNotEmpty() username!: string; @ApiProperty({ description: 'Secure password' }) @IsString() @IsNotEmpty() password!: string; @ApiProperty({ description: 'Additional user metadata or custom fields', type: CreateUserMetadataDto, isArray: true }) @IsArray() @ValidateNested({ each: true }) @Type(() => CreateUserMetadataDto) @IsOptional() metadata: CreateUserMetadataDto[]; @ApiProperty({ description: 'Additional user information', type: ContactInfoDto }) @ValidateNested({ each: true }) @Type(() => ContactInfoDto) @IsOptional() contactInfo: ContactInfoDto; }
c9038c207b7c36c1597652c4245a8d9fe6141757
TypeScript
sooty1892/minesweeper_solver
/app/minesweeper.ts
2.96875
3
export interface Minesweeper { initiate(level: Level): void; markAsBomb(square: Square): void; open(square: Square): void; board(): Promise<string[][]>; hasFinished(): boolean; } export interface Square { hCoor: number; wCoor: number; } export interface Level { url: string; height: number; width: number; middlePoint: Square; numberOfMines: number; } export const CustomLevel: Level = { url: 'http://google.com', height: 2, width: 5, middlePoint: {hCoor: 2, wCoor: 1}, numberOfMines: 1 } export const BeginnerLevel: Level = { url: 'http://minesweeperonline.com/#beginner-200', height: 9, width: 9, middlePoint: {hCoor: 5, wCoor: 5}, numberOfMines: 10 } export const IntermediateLevel: Level = { url: 'http://minesweeperonline.com/#intermediate-200', height: 16, width: 16, middlePoint: {hCoor: 8, wCoor: 8}, numberOfMines: 40 } export const ExpertLevel: Level = { url: 'http://minesweeperonline.com/#200', height: 16, width: 30, middlePoint: {hCoor: 8, wCoor: 15}, numberOfMines: 99 }
c6f11996e6c6e17580e60f7768b868a69e387de3
TypeScript
drleq/CppUnitTestFramework
/vscode-cpputf-test-adapter/src/CppUnitTestFramework/DisposableSet.ts
2.671875
3
import * as vscode from 'vscode'; export class DisposableSet implements vscode.Disposable { private readonly _set = new Set<vscode.Disposable>(); public add(disposable: vscode.Disposable) { this._set.add(disposable); } public remove(disposable: vscode.Disposable) { this._set.delete(disposable); } public dispose() { for (var disposable of this._set) { disposable.dispose(); } this._set.clear(); } }
54279f8d54f687cdcd340e74a93865cd4fc81a7e
TypeScript
it-and-services/state-store
/projects/ngx-state-store/src/lib/state/state-context.ts
3.546875
4
export interface StateContext<S> { /** * Get the current state. */ getState(): S; /** * Reset the state to a new value. */ setState(state: S); /** * Patch the existing state with the provided value. */ patchState(val: Partial<S>); }
370ef081c8f67bda9aa5a66f2c13d86cb5e6e149
TypeScript
sfia-andreidaniel/wysiwyg-canvas
/UndoManager.ts
2.734375
3
class UndoManager extends Events { public viewport: Viewport; public entries: UndoEntry[] = []; public index: number = 0; public maxUndoLevels: number = 100; private locked: boolean = false; private prevOp: string = null; constructor ( viewport: Viewport ) { super(); this.viewport = viewport; } public reset() { if ( this.locked ) { return; } this.entries = []; this.index = 0; this.prevOp = null; this.createUndoEntry( 'Document Load' ); // console.info( 'The undo manager has been reseted!' ); } public createUndoEntry( description: string = 'modification' ) { this.prevOp = null; var selection = this.viewport.selection, rng = selection.getRange(), numEntries: number = this.entries.length, entry = { "description": description || "modification", "document": this.viewport.document.innerHTML(), "multiRange": rng.isMultiRange() ? (<HTML_MultiRange>rng.anchorNode().target).serialize() : null, "focus": rng.focusNode() ? rng.focusNode().fragPos : null, "anchor": rng.anchorNode() ? rng.anchorNode().fragPos : null, "time": Date.now() }; if ( numEntries && this.index == numEntries && this.entries[ numEntries - 1 ].description == entry.description && ( entry.time - this.entries[ numEntries - 1 ].time ) < 1000 ) { switch ( this.entries[ numEntries - 1 ].description ) { case 'Delete Text': case 'Write': case 'New Line': //console.info( 'Replace undo', numEntries, this.index ); this.entries[ numEntries - 1 ] = entry; //replace entry return; break; } } //console.warn('Add undo' ); this.truncate(); if ( this.entries.length >= this.maxUndoLevels ) { this.entries.shift(); this.index--; } this.entries.push( entry ); this.index = this.entries.length; this.fire( 'changed' ); } public truncate() { //console.warn( 'truncate...' ); this.entries = this.entries.slice( 0, this.index ); } public canUndo(): boolean { return this.index > 0; } public canRedo(): boolean { return this.entries[ this.index ] ? true : false; } private restore( entry: UndoEntry ) { this.locked = true; this.viewport.document.lockOrphan(); this.viewport.value( entry.document ); this.viewport.document.unlockOrphan(); var selection = this.viewport.selection, rng = selection.getRange(); if ( !entry.multiRange ) { selection.anchorTo( new TRange_Target( this.viewport.document.findNodeAtIndex( entry.anchor ), entry.anchor ) ); if ( entry.focus !== null ) { selection.focusTo( new TRange_Target( this.viewport.document.findNodeAtIndex( entry.focus ), entry.focus ) ); } } else { var multiRange = HTML_MultiRange.unserialize( this.viewport.document, entry.multiRange ); selection.anchorTo( new TRange_Target( multiRange, multiRange.FRAGMENT_START ) ); } this.locked = false; return true; } public undo(): boolean { if ( this.prevOp != 'undo' ) { if ( this.prevOp != 'redo' ) { this.createUndoEntry( 'Last document state' ); this.index--; } this.prevOp = 'undo'; } if ( this.index > 0 ) { this.index--; this.restore( this.entries[ this.index ] ); this.fire( 'changed' ); return true; } else { return false; } } public redo(): boolean { if ( this.prevOp != 'redo' ) { if ( this.prevOp == 'undo' ) { this.index++; } this.prevOp = 'redo'; } if ( this.canRedo() ) { this.index++; this.restore( this.entries[ this.index - 1 ] ); this.fire( 'changed' ); if ( !this.canRedo() ) { this.index--; this.prevOp = null; this.entries.pop(); } return true; } else { return false; } } public undoSummary(): UndoSummary[] { var out: UndoSummary[] = [], i: number = 0; for ( i=0; i<this.index; i++ ) { out.push( { "index": i, "description": this.entries[ i ].description } ); } return out; } public redoSummary(): UndoSummary[] { var out: UndoSummary[] = [], i: number = 0; for ( i=this.index; i<this.entries.length; i++ ) { out.push( { "index": i, "description": this.entries[ i ].description } ); } return out; } }
415059c7969f5901b67e9b134cc6ce2f69c0ba71
TypeScript
waspeer/galassasa-website
/sanity/lib/data-types/date.ts
3.09375
3
import type { DataType, ValidatorFunction, Validator } from './common'; export interface DateValidator extends Validator<DateValidator> { /** * Maximum date (inclusive). maxDate should be in ISO 8601 format. */ max(minDate: string | number | Date): DateValidator; /** * Minimum date (inclusive). minDate should be in ISO 8601 format. */ min(minDate: string | number | Date): DateValidator; } export interface DateType extends DataType { type: 'date'; options?: { /** * Controls how the date input field formats the displayed date. Use any valid Moment * format option. Default is YYYY-MM-DD. */ dateFormat?: string; /** * Label for the "jump to today" button on the date input widget. Default is Today. */ calendarTodayLabel?: string; }; validation?: ValidatorFunction<DateValidator>; }
7a7e48c90bbc36a5916e50594d75a7865831673e
TypeScript
NikitaGlukhi/angular-add-remove-dynamic-components
/src/app/dynamic-components/dynamic.component.ts
2.515625
3
import { Component } from '@angular/core'; export interface myInterface { removeComponent(index: number); } @Component({ templateUrl: './dynamic.component.html' }) export class DynamicComponent { public index: number; public selfRef: DynamicComponent; public compInteraction: myInterface; constructor() { } public removeComponent(index: number) { this.compInteraction.removeComponent(index); } }
7c231aad3861b34ccda2d45e9c46c04444bf6248
TypeScript
aleagustin/pillsbox-server
/src/controllers/medicine.controller.ts
2.609375
3
import { Request, Response} from 'express'; import { medicineDao } from '../dao/medicine.dao'; import { Medicine } from '../models/medicine.model'; class MedicineController { /** * Verificar las credenciales del usuario (email, contrasaña). * Si las credenciales son válidas, se devuelve el token generado. * En caso contrario, devolverá un 403 */ public async getById(req: Request, res: Response) { console.log('medicineController.getById'); const { id } = req.params; let medicine = await medicineDao.getById(parseInt(id)); return res.json(medicine); } public async getByPillsBox(req: Request, res: Response) { console.log('medicineController.getBypillsbox'); const { idUser, idPillsbox } : any = req.params; let medicine: Medicine [] = await medicineDao.getByPillsBox(idUser, idPillsbox, 0, 10); return res.json(medicine); } public async save(req: Request, res: Response) { console.log('medicineController.save') console.log(req.body); const { pillsboxId, nombreComercial, principioActivo, fechaCreacion, fechaInicio, fechaFin, ultimaToma, tomas } = req.body; let medicine: Medicine = new Medicine(0, pillsboxId, nombreComercial,principioActivo, fechaCreacion,fechaInicio,fechaFin,ultimaToma, null, tomas); await medicineDao.save(medicine).then( () => { return res.status(200).json({'message': "Medicina creada correctamente"}) }).catch( (err) => { console.log("medicineController.save", err); return res.status(500).json({'message': "Error creando Medicina"}); }); } public async update(req: Request, res: Response) { console.log('medicineController.update') console.log(req.body); const { id,pillsboxId, nombreComercial,principioActivo,fechaCreacion,fechaInicio,fechaFin,ultimaToma } = req.body; let medicine: Medicine = new Medicine(id, pillsboxId, nombreComercial,principioActivo,new Date(fechaCreacion),fechaInicio,fechaFin,ultimaToma); let result = await medicineDao.update(medicine).catch( (err) => { console.log("MedicineController.update", err) }); if(result) { return res.status(200).json({'message': "Medicina modificada correctamente"}); } return res.status(500).json({'message': "Error modificando Medicina"}); } public async delete(req: Request, res: Response) { let resultado: boolean = false; console.log('medicineController.delete'); const { idUser, id } : any = req.params; resultado = await medicineDao.delete(idUser, new Medicine(id)).catch( err => { console.log(err); return false; }); if(resultado) { return res.json({ 'message': 'Medicina eliminada correctamente'}); } return res.status(500).json({ 'message': 'Error borrando Medicina'}); } } export const medicineController = new MedicineController();
b8e424b139387b243fc159579d6cd5131c862586
TypeScript
bl458/musicians-backend
/src/dto/dto.user.piano.session.ts
2.515625
3
import { IsNotEmpty, IsEmail, MaxLength, Length } from 'class-validator'; export class CreatePianoUserSessionDto { @IsNotEmpty() @IsEmail() @MaxLength(254) readonly email: string; @IsNotEmpty() @Length(8, 25) readonly pw: string; }
3fcf15bc1eef1cb91c87e73a55bee41e38ef8c4d
TypeScript
Rhadow/nature_of_code
/src/experiments/vehicle.ts
2.828125
3
import * as numjs from 'numjs'; import { ICanvasState } from '../components/Canvas/CanvasInterfaces'; import { ICreature, IEnvironment } from "../elements/ElementInterface"; import { width, height } from '../constants/world'; import Vehicle from '../elements/Vehicle'; import Path from '../elements/Path'; import FlowField from '../elements/FlowField'; import { perlin2, seed } from '../utils/noise'; import { mapping } from '../utils/math'; const vehicleForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => { currentEnvironment.forEach((environment: IEnvironment) => { environment.display(canvasState); }); const seeker: Vehicle = <Vehicle>creatures[0]; const wanderer: Vehicle = <Vehicle>creatures[1]; const seekForce = seeker.seek(numjs.array([canvasState.mouseX, canvasState.mouseY])); seeker.applyForce(seekForce); wanderer.wander(); (<Vehicle[]>creatures).forEach((vehicle: Vehicle) => { vehicle.run(canvasState); }); } const generateMagneticFields = (mouseX: number, mouseY: number) => (width: number, height: number, resolution: number): nj.NdArray[][] => { const result: nj.NdArray[][] = []; const rows = Math.floor(width / resolution); const cols = Math.floor(height / resolution); for (let i = 0; i < rows; i++) { result[i] = []; for (let j = 0; j < cols; j++) { const center = numjs.array([ i * Math.floor(resolution / 2) + resolution, j * Math.floor(resolution / 2) + resolution ]); const target = numjs.array([ mouseX, mouseY ]); const newField = numjs.array([ target.subtract(center).get(0), target.subtract(center).get(1) ]); result[i].push(newField); } } return result; } const flowFieldForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => { // Magnetic // currentEnvironment[0] = new FlowField(width, height, 25, generateMagneticFields(canvasState.mouseX, canvasState.mouseY), true) currentEnvironment.forEach((environment: IEnvironment) => { environment.display(canvasState); }); const flowField: FlowField = <FlowField>currentEnvironment[0]; (<Vehicle[]>creatures).forEach((vehicle: Vehicle) => { vehicle.follow(flowField); vehicle.run(canvasState); }); } const generateFlowFields = (width: number, height: number, resolution: number): nj.NdArray[][] => { const result: nj.NdArray[][] = []; const rows = Math.floor(width / resolution); const cols = Math.floor(height / resolution); seed(10); let xOffset = 0; for (let i = 0; i < rows; i++) { result[i] = []; let yOffset = 0; for (let j = 0; j < cols; j++) { const theta = mapping(perlin2(xOffset, yOffset), 0, 1, 0, Math.PI * 2); const newField = numjs.array([ Math.cos(theta), Math.sin(theta) ]) result[i].push(newField); yOffset += 0.04; } xOffset += 0.03; } return result; } const pathForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => { if (canvasState.pressedKey === 'z') { currentEnvironment[0] = new Path( [ numjs.array([0, Math.random() * height / 2 + height / 4]), numjs.array([width / 4, Math.random() * height / 2 + height / 4]), numjs.array([width / 2, Math.random() * height / 2 + height / 4]), numjs.array([width * 3 / 4, Math.random() * height / 2 + height / 4]), numjs.array([width, Math.random() * height / 2 + height / 4]), ], Math.random() * 15 + 10 ) } currentEnvironment.forEach((environment: IEnvironment) => { environment.display(canvasState); }); const path: Path = <Path>currentEnvironment[0]; (<Vehicle[]>creatures).forEach((vehicle: Vehicle) => { vehicle.followPath(path); vehicle.run(canvasState); }); } const groupForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => { currentEnvironment.forEach((environment: IEnvironment) => { environment.display(canvasState); }); (<Vehicle[]>creatures).forEach((vehicle: Vehicle) => { vehicle.applyBehaviors( <Vehicle[]>creatures, numjs.array([canvasState.mouseX, canvasState.mouseY]), 1, 1.1 ); vehicle.run(canvasState); }); } const flockForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => { (<Vehicle[]>creatures).forEach((vehicle: Vehicle) => { vehicle.flock( <Vehicle[]>creatures, 1.5, 5, 2 ); vehicle.run(canvasState); }); } const generateVehicles = (n: number):Vehicle[] => { const result = []; for (let i = 0; i < n; i++) { const w = width / 2 - 100 + Math.random() * 100; const h = height / 2 - 100 + Math.random() * 100; const newVehicle = new Vehicle( 15, numjs.array([w, h]), 6, 0.2 ); newVehicle.velocity = numjs.array([ (Math.random() > 0.5 ? 1 : -1) * Math.random(), (Math.random() > 0.5 ? 1 : -1) * Math.random() ]); result.push(newVehicle); } return result; }; export const vehicleExperiment = { 'label': 'Vehicle', 'creatures': [ new Vehicle(20, numjs.array([80, height / 2]), 4, 0.1), new Vehicle(20, numjs.array([width / 2, height / 2]), 4, 0.2, '#7f80a7', '#4c4b67', true) ], 'environments': [], 'forceFunction': vehicleForceFunction, 'initialForceFunction': () => { } }; export const flowFieldExperiment = { 'label': 'FlowField', 'creatures': [ new Vehicle(20, numjs.array([width / 2, 10]), 6, 0.2, '#f9d71c', '#8b8b8b'), new Vehicle(20, numjs.array([10, 10]), 4, 0.4, '#b60505', '#6b0202') ], 'environments': [ new FlowField(width, height, 25, generateFlowFields, true) ], 'forceFunction': flowFieldForceFunction, 'initialForceFunction': () => { } }; export const pathExperiment = { 'label': 'Path', 'creatures': [ new Vehicle(20, numjs.array([15, 15]), 8, 0.1, '#f9d71c', '#8b8b8b', true), new Vehicle(20, numjs.array([15, 15]), 4, 0.2, '#b60505', '#6b0202', true) ], 'environments': [ new Path( [ numjs.array([0, Math.random() * height / 2 + height / 4]), numjs.array([width / 4, Math.random() * height / 2 + height / 4]), numjs.array([width / 2, Math.random() * height / 2 + height / 4]), numjs.array([width * 3 / 4, Math.random() * height / 2 + height / 4]), numjs.array([width, Math.random() * height / 2 + height / 4]), ], Math.random() * 15 + 10 ) ], 'forceFunction': pathForceFunction, 'initialForceFunction': () => { } }; export const groupExperiment = { 'label': 'Group', 'creatures': generateVehicles(25), 'environments': [], 'forceFunction': groupForceFunction, 'initialForceFunction': () => { } }; export const flockExperiment = { 'label': 'Flock', 'creatures': generateVehicles(25), 'environments': [], 'forceFunction': flockForceFunction, 'initialForceFunction': () => { } };
4ed245f3bd282a8e836e72f448678481f7036c92
TypeScript
jeanmolossi/fuse-dev-courses
/src/validation/validators/required-field/required-field.ts
2.609375
3
import { RequiredFieldError } from '@/validation/errors'; import { FieldValidation } from '@/validation/protocols/field-validation'; export class RequiredFieldValidation implements FieldValidation { constructor(readonly fieldName: string) {} validate(fieldValue: string): Error { return fieldValue ? null : new RequiredFieldError(this.fieldName); } }
05a9a460373ab1fceccb4b84da29129c6191fb5c
TypeScript
tayduivn/SchoolSquirrel
/SchoolSquirrel/src/app/_resources/file-types.ts
2.609375
3
export const documentFileTypes = { text: ["docx", "doc", "txt", "rtf", "odt"], spreadsheet: ["xlsx", "xls", "ods"], presentation: ["pptx", "ppt", "odp"], }; export const fileTypes = { document: [], image: ["jpg", "jpeg", "png", "tif", "svg", "gif", "bmp"], video: ["mp4", "avi", "mov"], audio: ["mp3", "wav"], pdf: ["pdf"], }; for (const type in documentFileTypes) { if (documentFileTypes.hasOwnProperty(type)) { fileTypes.document.push(...documentFileTypes[type]); } } export const editableFileTypes = [ ...fileTypes.document, ];
0c6469a450d6664d744a7d3a3b254224a4269ce8
TypeScript
mvs24/Prisma-Apollo-InstaClone
/apolloServer/resolvers/Mutation/User/User.ts
2.703125
3
import crypto from "crypto"; import bcrypt from "bcryptjs"; import jwt from "jsonwebtoken"; import { Signup, Login, ResetPassword } from "./types"; import { Context } from "./types"; import Email from "../../../../utils/Email"; const signToken: (id: string) => string = (userId) => { if (!process.env.JWT_SECRET) throw new Error("JWT_SECRET is not defined"); const token = jwt.sign( { id: userId, }, process.env.JWT_SECRET ); return token; }; const validateEmail = (email: string): void => { if (!email.match(/\S+@\S+\.\S+/)) { throw new Error("Please provide a valid email!"); } }; const validateEmailAndPassword = (email: string, password: string): void => { validateEmail(email); if (password.length < 6) { throw new Error("Password field must be greater than 6 characters"); } }; const correctPassword: ( candidatePassword: string, userPassword: string ) => Promise<Boolean> = async (candidatePassword, userPassword) => { return await bcrypt.compare(candidatePassword, userPassword); }; const hashToken = (token: string): string => { return crypto.createHash("sha256").update(token).digest("hex"); }; export const User = { async signup(_parent: undefined, args: Signup["args"], { prisma }: Context) { const { password, email, name, lastname } = args.data; if (!name || !lastname) { throw new Error("Please provide a valid name and lastname!"); } validateEmailAndPassword(email, password); const hashedPassword = await bcrypt.hash(password, 10); const user = await prisma.user.create({ data: { ...args.data, password: hashedPassword, }, }); const token = signToken(user.id.toString()); return { user, token, }; }, async login(_parent: undefined, args: Login, { prisma }: Context) { const { email, password } = args; validateEmailAndPassword(email, password); const user = await prisma.user.findOne({ where: { email, }, }); if (!user || !(await correctPassword(password, user.password))) { throw new Error("No user found! Invalid credentials."); } const token = signToken(user.id.toString()); return { user, token, }; }, async forgotPassword( _parent: undefined, { email }: { email: string }, { prisma }: Context ) { validateEmail(email); const user = await prisma.user.findOne({ where: { email, }, }); if (!user) { throw new Error("No user found with that email!"); } const resetToken = crypto.randomBytes(32).toString("hex"); const hashedToken = hashToken(resetToken); const resetExpires = Date.now() + 10 * 60 * 1000; await prisma.user.update({ where: { email, }, data: { passwordResetToken: hashedToken, passwordResetExpires: new Date(resetExpires), }, }); try { const newEmail = new Email({ to: email, text: `Your password reset token is: \n ${resetToken}`, subject: "YOUR PASSWORD RESET TOKEN! (VALID FOR 10 minutes)", }); await newEmail.sendMessage(); console.log("send email", resetToken, new Date(resetExpires)); return { message: "Reset token sent to email" }; } catch (err) { await prisma.user.update({ where: { email, }, data: { passwordResetToken: undefined, passwordResetExpires: undefined, }, }); throw new Error(err); } }, async resetPassword( _parent: undefined, { password, resetToken }: ResetPassword, { prisma }: Context ) { try { if (password.length < 6 || !resetToken) { throw new Error( "Please provide reset token & new password (greater than 6 characters)" ); } const hashedToken = hashToken(resetToken); const [user] = await prisma.user.findMany({ where: { passwordResetToken: hashedToken, passwordResetExpires: { gt: new Date(Date.now()), }, }, }); if (!user) { throw new Error("Your token is invalid or has expired!"); } await prisma.user.update({ where: { id: user.id, }, data: { password: await bcrypt.hash(password, 10), passwordResetExpires: null, passwordResetToken: null, passwordChangedAt: new Date(Date.now() - 1000), }, }); const token = signToken(user.id.toString()); return { user, token, }; } catch (err) { throw new Error(err); } }, };
ebe4bb0d3a08d1ce59d04b11fb3fc262c62fad60
TypeScript
quik-link/core
/ts/objects/Link.ts
2.5625
3
/** * Elijah Cobb * elijah@elijahcobb.com * elijahcobb.com * github.com/elijahjcobb */ import {SiObject} from "@element-ts/silicon"; import {Visit} from "./Visit"; import {HObject} from "@element-ts/hydrogen"; export interface LinkProps { url: string; userId: string; name: string; } export class Link extends SiObject<LinkProps> implements HObject { public constructor() { super("link"); } public async visit(): Promise<void> { const visit = new Visit(); visit.props.linkId = this.getId(); await visit.create(); } public bond(): object { return this.getJSON(); } }
7d5c6c0cb1118828f9986ed52057b469d8fc6bb3
TypeScript
nikhilknoldus/comp-interaction-interceptor
/src/app/my-http-interceptor.ts
2.625
3
import { Injectable, Injector } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { tap } from 'rxjs/operators'; @Injectable() export class MyHttpInterceptor implements HttpInterceptor { constructor() { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { console.log("intercepted request ... "); let loadingContainer: HTMLElement = document.getElementsByClassName('loading').item(0) as HTMLElement; loadingContainer.style.display = 'block'; // Clone the request to add the new header. // const authReq = req.clone({ headers: req.headers.set("headerName", "headerValue") }); console.log("Sending request with new header now ..."); //send the newly created request return next.handle(req).pipe( tap(event => { if (event instanceof HttpResponse) { loadingContainer.style.display = 'none'; } }, error => { loadingContainer.style.display = 'none'; console.error('NICE ERROR', error) }) ) } }
d040a13b2609b9bb96bad5c7cd2ccb8e9c993304
TypeScript
guo-haozhong/RN_ts_example
/src/redux/actions/LoginAction.ts
2.578125
3
import * as actionType from '../actionsTypes/index' export function login(name:string, psw:string) { // console.log(name, psw); return (dispatch:any) => { //登录中 dispatch(logining()) fetch('https://www.baidu.com/', {method:'get'}) .then(res => { dispatch(loginSuccess({ name, psw })) }) .catch(e => { dispatch(loginFail()) }) } } export function logining() { return { type: actionType.LOGINING } } export function loginSuccess(userInfo:{}) { return { type: actionType.LOGIN_SUCCESS, state: userInfo } } export function loginFail() { return { type: actionType.LOGIN_ERROR } } export function loginOut() { return { type: actionType.LOGOUT } }
16ccc9f23b4c00b0474179407f91c273ab10351c
TypeScript
ShawnStewart/admin-bro-sequelize
/src/models/User.ts
3.15625
3
import { Association, DataTypes, HasManyAddAssociationMixin, HasManyAddAssociationsMixin, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin, HasManyGetAssociationsMixin, HasManyHasAssociationMixin, HasManyHasAssociationsMixin, HasManyRemoveAssociationMixin, HasManyRemoveAssociationsMixin, HasManySetAssociationsMixin, Model, Optional, Sequelize, } from 'sequelize'; import Post from './Post'; // These are all the attributes in the User model // You can _kinda_ think of these as columns interface UserAttributes { id: number; name: string; } // Some fields are optional when calling User.create() or User.build() type UserCreationAttributes = Optional<UserAttributes, 'id'>; export default class User extends Model<UserAttributes, UserCreationAttributes> implements UserAttributes { public id!: number; // Note that the `null assertion` `!` is required in strict mode. public name!: string; // timestamps are handled by default public readonly createdAt!: Date; public readonly updatedAt!: Date; // Associations // TS cannot determine model association at compile time, // so we have to declare them here purely virtually. These // don't actually exist until the associations are made. // Ex: `User.hasMany(Posts);` // After the association has been made, these helper methods // exist. All we are really doing here is making TypeScript // aware of them. You likely wouldn't define them all, // just as you need them. public addPost!: HasManyAddAssociationMixin<Post, number>; public addPosts!: HasManyAddAssociationsMixin<Post, number>; public countPosts!: HasManyCountAssociationsMixin; public createPost!: HasManyCreateAssociationMixin<Post>; public getPosts!: HasManyGetAssociationsMixin<Post>; public hasPost!: HasManyHasAssociationMixin<Post, number>; public hasPosts!: HasManyHasAssociationsMixin<Post, number>; public removePost!: HasManyRemoveAssociationMixin<Post, number>; public removePosts!: HasManyRemoveAssociationsMixin<Post, number>; public setPosts!: HasManySetAssociationsMixin<Post, number>; // Inclusions // We can also pre-declare possible inclusions, again, this is just // for TypeScript to be aware. These will only be populated if you // actively `include` a relation. public readonly posts?: Post[]; // This is what we use to declare an inclusion. // Ex: `const user = User.findByPk(123, { include: [User.associations.posts] })` public static associations: { posts: Association<User, Post>; }; // Custom initializer method // This `Model.init` method is where we actually define our // table columns and properties. Notice how we only define // what's in our `ModelAttributes`, no timestamps or foreign // keys - those are handled automatically. public static initModel = (sequelize: Sequelize): void => { User.init( { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true, }, name: { type: DataTypes.STRING(128), allowNull: false, }, }, { sequelize, paranoid: true, // paranoid true gives us a handly soft deletion }, // timestamps and other table options can be configured here ); }; }
54afe0fdf689def9b51b2958e7374e842548dbbc
TypeScript
eguneys/cchheess
/src/isequal.ts
3.515625
4
type Within<A> = A[] type Literal<A> = A type Star = "*" type Matcher<A> = Within<A> | Literal<A> | Star type MapMatcher<A> = { [K in keyof A]: Matcher<A[K]> } export type Query<A> = MapMatcher<A> | Star export function mapmatch<A>(a: A, m: Query<A>): boolean { if (m === '*') { return true; } else if (Array.isArray(a) && Array.isArray(m)) { return refPEqual2(a, m); } else { return objPEqual(a, m); } } export function match<A>(a: A, m: Matcher<A>): boolean { if (m === "*") { return true; } else if (Array.isArray(m)) { return m.includes(a); } else { return a === m; } } type IsEqual<A> = (a: A, _: A) => boolean type PartiallyEqual<A> = (a: A, _: Matcher<A>) => boolean export const isEqualAny = <A>(a: A, b: A): boolean => { if (a === b) return true; if (Array.isArray(a) && Array.isArray(b)) return refEqual2(a, b) if (a instanceof Map && b instanceof Map) return mapEqual(a, b) else { return objEqual(a, b); } } export const refEqual = <A>(a: A, b: A) => a === b; export const refEqual2 = <A>(a: A[], b: A[]) => { if (a.length === b.length) { for (let key in a) { if (a[key] !== b[key]) { return false; } } return true; } return false; }; export const mapEqual = <A, B>(a: Map<A, B>, b: Map<A, B>): boolean => { if (a.size !== b.size) { return false; } for (var [key, _a] of a) { let _b = b.get(key); if (_a !== _b || (_b === undefined && !a.has(key))) { return false; } } return true; }; export const objEqual = <A>(a: A, b: A): boolean => { if (typeof a === 'object' && typeof b === 'object') { if (Object.keys(a).length !== Object.keys(b).length) { return false; } for (let key in a) { if (a[key] !== b[key]) { return false; } } return true; } return false; } export const refPEqual2 = <A>(a: A[], b: MapMatcher<A[]>) => { for (let key in b) { if (!match(a[key], b[key])) { return false; } } return true; } export const objPEqual = <A>(a: A, b: MapMatcher<A>): boolean => { if (typeof a === 'object' && typeof b === 'object') { for (let key in b) { if (!match(a[key], b[key])) { return false; } } return true; } else { return false; } }
7b630cdfcd37d91196afe6afe7803bcca7149a79
TypeScript
superdesk/superdesk-planning
/e2e/cypress/support/planning/events/linkInput.ts
2.84375
3
import {Input} from '../../common/inputs'; /** * Wrapper class for Superdesk Event's website link input * @extends Input */ export class LinkInput extends Input { /** * Returns the dom node for the ADD button * @returns {Cypress.Chainable<JQuery<HTMLElement>>} */ get addButton() { return this.parent.find('[data-test-id="event-links__add-new-button"]'); } /** * Returns the dom nodes for all the links added to the component * @returns {Cypress.Chainable<JQuery<HTMLElement>>} */ get inputs() { return this.parent.find('.link-input__input'); } /** * Adds all the links to the component at the specified starting index * @param {Array<string>} values - The list of links to add * @param {number} startingIndex - The index to start adding links to */ type(values, startingIndex = 0) { cy.log('Planning.Events.LinkInput.type'); cy.wrap(values).each((value, index) => { this.addButton.click({force: true}); const input = new Input( this.getParent, `textarea[name="links[${startingIndex + index}]"]` ); input.type(value); }); } /** * Assert all the link values have been added to the component * @param {Array<string>} values - The expected list of links to have been added */ expect(values) { cy.log('Planning.Events.LinkInput.expect'); cy.wrap(values).each((value) => { this.inputs.should('contain.text', value); }); } }
eaab491fc0d8c2f446c88090efb6bd1795aeef5a
TypeScript
yagoananias/typescript-course
/scripts/interface_readonly.ts
2.765625
3
interface ICurso { readonly titulo: string; descricao?: string; preco: number; cargaHoraria: number; classificacao: number; } const curso: ICurso = { titulo: "Typescript", preco: 5000, cargaHoraria: 10, classificacao: 5 } curso.titulo = "Php 8"
3a25c98aeca496ba6811c1bd7e62add5ec884f1d
TypeScript
grlgmrs/DevChallenge
/music-library-page-react/src/services/api.ts
2.671875
3
import playlistData from "./playlists.json"; import profileViewData from "./profile_views.json"; import trackData from "./tracks.json"; export interface Playlist { image: string; title: string; trackCount: number; } export interface ProfileView { image: { path: string; anchor: { x: number; y: number; }; zoom: number; }; name: string; visitedAt: string; albumsCount: number; } export interface Track { image: { path: string; anchor: { x: number; y: number; }; zoom: number; }; title: string; album: string; } export function getPlaylistData(): Playlist[] { return playlistData.map((pD) => { return { ...pD, trackCount: pD.tracks_count, }; }); } export function getProfileViewData(): ProfileView[] { return profileViewData.map((pvD) => { return { ...pvD, visitedAt: pvD.visited_at, albumsCount: pvD.albums_count, }; }); } export function getTrackData(): Track[] { return trackData; }
603e6de361f6aa8291a234f726087ff269f5741d
TypeScript
dizco/LOG3900
/serveur/test/websockets/websocket-rooms.test.ts
2.625
3
import { Room } from "../../src/websockets/room"; import { WebSocketDecorator } from "../../src/decorators/websocket-decorator"; import { expect } from "chai"; import * as sinon from "sinon"; import { SinonSandbox } from "sinon"; import { FakeWebSocket } from "./fake-websocket"; describe("rooms", function() { describe("creation", function() { it("should create a new room", function() { const room = new Room("test"); expect(room).to.not.be.undefined; }); }); describe("properties", function() { let sandbox: SinonSandbox; const roomId = "test"; let room: Room; beforeEach(function() { sandbox = sinon.sandbox.create(); room = new Room(roomId); }); afterEach(function() { sandbox.restore(); }); it("should get the id", function() { expect(room.getId()).to.be.equal(roomId); }); it("should contain no clients", function() { expect(room.getClients()).to.be.empty; }); it("should be empty", function() { expect(room.isEmpty()).to.be.true; }); it("should not be empty", function() { const ws1 = new FakeWebSocket("ws://localhost"); const user1 = new WebSocketDecorator(sandbox.spy() as any, ws1); room.addClient(user1); expect(room.isEmpty()).to.be.false; }); }); describe("clients management", function() { let sandbox: SinonSandbox; const roomId = "test"; let room: Room; beforeEach(function() { sandbox = sinon.sandbox.create(); room = new Room(roomId); }); afterEach(function() { sandbox.restore(); }); it("should add a client", function() { const ws1 = new FakeWebSocket("ws://localhost"); const user1 = new WebSocketDecorator(sandbox.spy() as any, ws1); room.addClient(user1); expect(room.getClients()).to.deep.equal([user1]); }); it("should not add an existing client", function() { const ws1 = new FakeWebSocket("ws://localhost"); const user1 = new WebSocketDecorator(sandbox.spy() as any, ws1); room.addClient(user1); room.addClient(user1); expect(room.getClients()).to.deep.equal([user1]); }); it("should remove a client", function() { const ws1 = new FakeWebSocket("ws://localhost"); const ws2 = new FakeWebSocket("ws://localhost"); const user1 = new WebSocketDecorator(sandbox.spy() as any, ws1); const user2 = new WebSocketDecorator(sandbox.spy() as any, ws2); room.addClient(user1); room.addClient(user2); expect(room.getClients()).to.deep.equal([user1, user2]); room.removeClient(user1); expect(room.getClients()).to.deep.equal([user2]); }); }); describe("broadcast", function() { let sandbox: SinonSandbox; let room: Room; const roomId = "test"; const data = "test"; beforeEach(function() { sandbox = sinon.sandbox.create(); room = new Room(roomId); }); afterEach(function() { sandbox.restore(); }); it("should broadcast to all users of the room", function() { const ws1 = new FakeWebSocket("ws://localhost"); const ws2 = new FakeWebSocket("ws://localhost"); const ws3 = new FakeWebSocket("ws://localhost"); const wsSpy1 = sandbox.spy(ws1, "send"); const wsSpy2 = sandbox.spy(ws2, "send"); const wsSpy3 = sandbox.spy(ws3, "send"); const user1 = new WebSocketDecorator(sandbox.spy() as any, ws1); const user2 = new WebSocketDecorator(sandbox.spy() as any, ws2); const user3 = new WebSocketDecorator(sandbox.spy() as any, ws3); room.addClient(user1); room.addClient(user2); room.addClient(user3); room.broadcast(data, user1); expect(wsSpy2.withArgs(data).calledOnce).to.be.true; expect(wsSpy2.withArgs(data).calledOnce).to.be.true; expect(wsSpy3.withArgs(data).calledOnce).to.be.true; }); }); });
33c4977cc1cf8a39911ab0f9cb51a3b9827f19be
TypeScript
ludative/paybook
/client/src/utils/generateUniqueString.ts
2.96875
3
const generateUniqueString = ():string => { const ts:string = String(new Date().getTime()) let out:string = ''; for (let i = 0; i < ts.length; i += 2) { out += Number(ts.substr(i, 2)).toString(36); } return out; } export default generateUniqueString;
f0bfcff7d4c5a8e464a47efb0b286d9be6d323d5
TypeScript
koddsson/island.is
/.github/actions/detection.ts
2.796875
3
import { ActionsListWorkflowRunsForRepoResponseData } from '@octokit/types' const getSuccessWorkflowsForBranch = ( response: ActionsListWorkflowRunsForRepoResponseData, ) => { return response.workflow_runs .map((wr) => ({ run_number: wr.run_number, sha: wr.head_sha, branch: wr.head_branch, })) .sort((a, b) => b.run_number - a.run_number) } const pickFirstMatchingSuccess = ( shas: string[], runsBranch: { run_number: number; sha: string }[], ) => { for (const sha of shas) { const lastGoodRun = runsBranch.filter((runs) => runs.sha === sha) if (lastGoodRun.length > 0) { return lastGoodRun[0] } } } export interface WorkflowQueries { getData(branch: string): Promise<ActionsListWorkflowRunsForRepoResponseData> } export const findLastGoodBuild = async ( shas: string[], branch, base, workflowQueries: WorkflowQueries, ) => { // First we try to find the last successful workflow build on our branch const successWorkflows = await workflowQueries.getData(branch) let successOnBranch = getSuccessWorkflowsForBranch(successWorkflows) const matchOnBranch = pickFirstMatchingSuccess(shas, successOnBranch) if (matchOnBranch) { return matchOnBranch } // Fallback we try to find the last successful workflow build on the base branch const successWorkflowsBase = await workflowQueries.getData(base) let successOnBase = getSuccessWorkflowsForBranch(successWorkflowsBase) const matchOnBase = pickFirstMatchingSuccess(shas, successOnBase) if (matchOnBase) { return matchOnBase } // Unlikely but still return {} }
c0debdccf228358f45bcf0b4fa88a0f32111df62
TypeScript
nest-don/veu3-examples-ts
/src/pages/vuejs.org-examples/git-commits/helpers.ts
2.734375
3
export function truncate(v: string): string { const newline = v.indexOf("\n"); return newline > 0 ? v.slice(0, newline) : v; } export function formatDate(v: string): string { return v.replace(/T|Z/g, " "); }
5f60338c5fc032622c4d1008e7100a22b0097b55
TypeScript
Belphemur/condo-seacher
/server/business/action/pushbullet/PushbulletAction.ts
2.546875
3
import { ISearchKeyword } from '@business/search/SearchKeyword' import { IAd } from '@business/search/provider/IProvider' import { ISearchService } from '@services/searches/SearchService' import { IActionExecutor } from '@business/action/IActionExecutor' export class PushbulletAction<T extends ISearchKeyword> implements IActionExecutor<T> { private client: any private service: ISearchService constructor(client: any, service: ISearchService) { this.client = client this.service = service } /** * Execute the action * @param search * @param result */ execute(search: T, result: IAd[]): void { result.forEach((ad) => { const title = `${search.key}: ${ad.title} (${ad.attributes.price})` this.client.link({}, title, ad.url, ad.description) }) search.setMatched() this.service.save(search) } }
bf87e4b97171e429a23f68d1af6ba60526e5090e
TypeScript
albertivini/api-blog-ts
/src/useCases/UpdateUser/UpdateUserController.ts
2.640625
3
import { Request, Response } from "express" import { UpdateUserUseCase } from "./UpdateUserUseCase" export class UpdateUserController { async handle(req: Request, res: Response) { try { const id = req.userId const token = req.headers.authorization.split(' ')[1] const { username, password, email, tagList, bio, image} = req.body const updateUserUseCase = new UpdateUserUseCase() const update = await updateUserUseCase.execute({ id, username, password, email, bio, image }) const response = { "user": { "email": update.email, "token": token, "username": update.username, "bio": update.bio, "image": update.image, } } return res.status(200).json(response) } catch (err) { return res.status(401).json({ success: false, message: err.message }) } } }
11f814389166d35351749f1abcd05d7405e8e884
TypeScript
ukon1990/wow-auction-helper
/api/src/utils/pet.util.spec.ts
2.546875
3
import {PetUtil} from './pet.util'; import {Pet} from '../shared/models'; describe('PetUtil', () => { describe('getPet', () => { it('can get valid id', async () => { const id = 39; const pet: Pet = await PetUtil.getPet(id); expect(pet.speciesId).toBe(id); // Is now a string: expect(pet.petTypeId).toBe(9); // Deprecated param! -> expect(pet.creatureId).toBe(2671); expect(pet.name).toBe('Mechanical Squirrel'); expect(pet.source).toBe('PROFESSION'); expect(pet.canBattle).toBe(true); expect(pet.icon).toBe('inv_pet_mechanicalsquirrel'); }); }); });
358db2f18ce8f25e27132b8ff17b0fa96b54ce2e
TypeScript
NickGreenSF/ilovethissong
/server/src/controllers/listing/postListing.ts
2.625
3
import { Request, Response } from 'express' import { Listing } from '../../database/entities/Listing' import { User } from '../../database/entities/User' import { getConnection } from 'typeorm' export const postListing = async (req: Request, res: Response) => { const connection = getConnection() if ( !req.body || !req.body.title || !req.body.artist || !req.body.userId || !req.body.description ) { res.status(400) return res.send({ listing: null, errors: [{ field: 'all', message: 'incorrect parameters given' }], }) } let newListing: Listing let user: User const userId = req.body.userId try { user = await User.findOne(userId) } catch (e) { res.status(500) return res.send({ message: null, errors: [ { field: 'user', message: 'error finding user making this', }, ], }) } try { newListing = new Listing() newListing.title = req.body.title newListing.artist = req.body.artist newListing.description = req.body.description newListing.user = user await connection.manager.save(newListing) } catch (e) { res.status(500) return res.send({ errors: [ { field: 'all', message: 'error when creating new listing: error given = ' + e.message, }, ], }) } res.send({ message: 'listing successfully created', listing: { id: newListing.listing_id }, errors: [], }) }
199d9e847c1ed5ac14dcca1359814328046f1be3
TypeScript
tnguye20/OurQuirkyAdventure
/functions/src/utils/isFilterEmpty.utils.ts
2.828125
3
import { FilterCriteria } from "../interfaces"; const isFilterEmpty = (filterCriteria: FilterCriteria | null): boolean => { if (filterCriteria === null) return true; return Object.values(filterCriteria).reduce((prev, curr) => { if (Array.isArray(curr)) { return prev && curr.length === 0 } return prev && curr === null; }, true); } export default isFilterEmpty;
5ccef7698fa03eb4674b15d9dddd957b478f350a
TypeScript
Giovanifsa/NFEStatusFrontend
/nfestatus/src/app/data/QueryOption.ts
2.53125
3
export default interface QueryOption { optionLabel: string; } class QueryByDistinctAuthorizerAndLatestCapture implements QueryOption { public optionLabel = "Consultar mais recentes com Autorizadores distintos"; } class QueryTreatUnknownNFEStatusAsOffline implements QueryOption { public optionLabel = "Considerar Status Desconhecido como Offline"; } const queryByDistinctAuthorizerAndLatestCapture = new QueryByDistinctAuthorizerAndLatestCapture(); const queryTreatUnknownNFEStatusAsOffline = new QueryTreatUnknownNFEStatusAsOffline(); export { queryByDistinctAuthorizerAndLatestCapture, queryTreatUnknownNFEStatusAsOffline };
9de1f6eb4a2849c104996bb1437e314312b30809
TypeScript
zxbodya/flowts
/packages/babel-plugin-flow-to-typescript/test/visitors/ImportDeclaration.test.ts
2.875
3
import { testTransform } from '../transform'; test('import type statement', () => { const result = testTransform(`import type { A } from "module"; import type { B, C } from './mod'; import type D from './mod';`); expect(result.babel).toMatchInlineSnapshot(` "import type { A } from "module"; import type { B, C } from './mod'; import type D from './mod';" `); expect(result.recast).toMatchInlineSnapshot(` "import type { A } from "module"; import type { B, C } from './mod'; import type D from './mod';" `); }); test('import type specifier', () => { const result = testTransform(`import A, { type B, C } from "module"; import { type D, type E } from "module";`); expect(result.babel).toMatchInlineSnapshot(` "import A, { C } from "module"; import type { B } from "module"; import type { D, E } from "module";" `); expect(result.recast).toMatchInlineSnapshot(` "import A, { C } from "module"; import type { B } from "module"; import type { D, E } from "module";" `); }); test('import type specifier with comment', () => { const result = testTransform(`// comment import A, { type B, C } from "module";`); expect(result.babel).toMatchInlineSnapshot(` "// comment import A, { C } from "module"; import type { B } from "module";" `); expect(result.recast).toMatchInlineSnapshot(` "// comment import A, { C } from "module"; import type { B } from "module";" `); }); test('mixed type imports', () => { const result = testTransform(`import type A, { B } from "module";`); expect(result.babel).toMatchInlineSnapshot(` "import type A from "module"; import type { B } from "module";" `); expect(result.recast).toMatchInlineSnapshot(` "import type A from "module"; import type { B } from "module";" `); }); test('mixed type imports with comments', () => { const result = testTransform(`// comment import type A, { B } from "module";`); expect(result.babel).toMatchInlineSnapshot(` "// comment import type A from "module"; import type { B } from "module";" `); expect(result.recast).toMatchInlineSnapshot(` "// comment import type A from "module"; import type { B } from "module";" `); }); test('import typeof', () => { const result = testTransform(`import typeof * as N from "a"; import typeof { A } from "a"; import { typeof B } from "a"; import typeof C from "a"; import { typeof D, type E } from "a"; import { F, typeof G } from "a"; import { H, type I, typeof J } from "a";`); expect(result.babel).toMatchInlineSnapshot(` "type N = typeof import("a"); type A = typeof import("a").A; type B = typeof import("a").B; type C = typeof import("a").default; import type { E } from "a"; type D = typeof import("a").D; import { F } from "a"; type G = typeof import("a").G; import { H } from "a"; type J = typeof import("a").J; import type { I } from "a";" `); expect(result.recast).toMatchInlineSnapshot(` "type N = typeof import("a"); type A = typeof import("a").A; type B = typeof import("a").B; type C = typeof import("a").default; import type { E } from "a"; type D = typeof import("a").D; import { F } from "a"; type G = typeof import("a").G; import { H } from "a"; type J = typeof import("a").J; import type { I } from "a";" `); });
93eec5dfa6963b7e7d7c0a4cbfa0015f579ff0c0
TypeScript
TatsuyaYamamoto/coupling-tune-player
/packages/share/src/models/CouplingPlayer/CouplingPlayer.ts
2.625
3
import { EventEmitter } from "eventemitter3"; import { analyzeBpm, AnalyzeResult } from "./BpmAnalyzer"; export type CouplingPlayerEventTypes = "play" | "pause" | "update" | "end"; const log = (message: string, ...data: any[]) => { console.log(`[CouplingPlayer] ${message}`, ...data); }; export class CouplingPlayer extends EventEmitter<CouplingPlayerEventTypes> { public static INTERNAL_LOOPER_INTERVAL = 500; /** * AudioContext instance. * @see https://developer.mozilla.org/ja/docs/Web/API/AudioContext */ private context: AudioContext = new (AudioContext || (window as any).webkitAudioContext)(); private _playing = false; private _currentTime = 0; private _duration = 0; private arrayBuffers: ArrayBuffer[]; private lastCheckedContextTime: number | null = null; private intervalId: NodeJS.Timer | number | null = null; private audioBufferSourceNodes: AudioBufferSourceNode[] | null = null; private sources: | { audioBuffer: AudioBuffer; analyzedData: AnalyzeResult; }[] | null = null; public get playing(): boolean { return this._playing; } public get currentTime(): number { return this._currentTime; } public set currentTime(time: number) { if (this.duration < time) { console.error( `provided time (${time}s) is over duration (${this.duration}s).` ); return; } log("update current time", time); (async () => { const stopOnce = this.playing; if (stopOnce) { log("stop once"); await this.internalStop(); } this._currentTime = time; if (stopOnce) { log("re-play"); await this.internalPlay(); } this.emit("update", { currentTime: this.currentTime }); })(); } public get duration(): number { return this._duration; } public constructor(arrayBuffers: ArrayBuffer[]) { super(); this.arrayBuffers = arrayBuffers; } public async play() { log(`try to start player, currentTime: ${this.currentTime}`); if (this.playing) { log("stop sync-play first."); await this.internalStop(); } if (!this.sources) { this.sources = await this.decodeAudioSources(this.arrayBuffers); this._duration = this.sources[0].audioBuffer.duration; log("player sources are decoded."); } await this.internalPlay(); log(`success to start player. duration: ${this.duration}sec`); log("event - play"); this.emit("play"); } public async pause() { log(`pause`); if (!this.playing) { console.error(`player is not running.`); return; } await this.internalStop(); log("event - pause"); this.emit("pause"); } private async internalPlay() { if (!this.sources) { log("audio source is empty."); return; } this.startSyncPlay(this.sources, this.currentTime); this.intervalId = setInterval(() => { this.onPlayerUpdated(); }, CouplingPlayer.INTERNAL_LOOPER_INTERVAL); log("start internal looper.", this.intervalId); this._playing = true; } private async internalStop() { if (this.intervalId !== null) { log("stop internal looper.", this.intervalId); clearInterval(this.intervalId as number); } this.lastCheckedContextTime = null; this.intervalId = null; this._playing = false; await this.stopSyncPlay(); } /** * Play audio file synchronously. * * @param sources * @param offset * @private */ private startSyncPlay( sources: { audioBuffer: AudioBuffer; analyzedData: AnalyzeResult }[], offset: number = 0 ): void { log(`startSyncPlay offset: ${offset}`); // 音量は入力の数に合わせて下げる const gainNode = this.context.createGain(); gainNode.gain.value = 0.5 + 0.5 / sources.length; // 定位は左端(-1.0)から右端(+1.0)までに等間隔に配置する const space = 2.0 / (sources.length + 1); const pannerNodes = sources.map((_, index) => { const pannerNode = this.context.createStereoPanner(); pannerNode.pan.value = -1.0 + space * (index + 1); pannerNode.connect(gainNode); return pannerNode; }); this.audioBufferSourceNodes = sources.map((source, index) => { const pannerNode = pannerNodes[index]; const audioSource = this.context.createBufferSource(); audioSource.buffer = source.audioBuffer; audioSource.connect(pannerNode); return audioSource; }); gainNode.connect(this.context.destination); const minStartPosition = Math.min( ...sources.map((s) => s.analyzedData.startPosition) ); const offsets = sources.map((s) => { const diff = s.analyzedData.startPosition - minStartPosition; return offset + diff; }); // Start sync play! this.audioBufferSourceNodes.forEach((node, index) => { node.start(0, offsets[index]); }); Promise.race( this.audioBufferSourceNodes.map((node) => { return new Promise((resolve) => { node.addEventListener("ended", () => resolve()); }); }) ).then(() => { if (this.playing) { if (this.intervalId !== null) { log("stop internal looper.", this.intervalId); clearInterval(this.intervalId as number); } this.lastCheckedContextTime = null; this.intervalId = null; this._playing = false; log("event - end"); this.emit("end"); } }); } /** * Stop audio source. */ private async stopSyncPlay(): Promise<void> { log("try to stop sync-play"); if (!this.audioBufferSourceNodes) { console.error("player has no nodes."); return; } const endPromises = this.audioBufferSourceNodes.map((source) => { return new Promise((resolve) => { source.addEventListener("ended", () => resolve()); }); }); this.audioBufferSourceNodes.forEach((node) => { node.stop(0); }); await Promise.race(endPromises).then(() => { log("sync-play is stop"); }); } private onPlayerUpdated() { const currentContextTime = this.context.currentTime; if (this.lastCheckedContextTime === null) { this.lastCheckedContextTime = currentContextTime; return; } const diff = currentContextTime - this.lastCheckedContextTime; this.lastCheckedContextTime = currentContextTime; this._currentTime = this._currentTime + diff; this.emit("update", { currentTime: this.currentTime }); } private decodeAudioSources(arrayBuffers: ArrayBuffer[]) { return Promise.all( arrayBuffers.map(async (buffer) => { const audioBuffer = await this.context.decodeAudioData(buffer); return { audioBuffer, analyzedData: analyzeBpm(audioBuffer), }; }) ); } }
729a6a58a89b181a65dcde211277a714352d7bcd
TypeScript
wix-playground/wix-meido-improver
/extension/src/modules/waitForSelector.ts
2.6875
3
export function waitForSelector(selector: string): Promise<HTMLElement> { return new Promise(resolve => { const el: HTMLElement | null = document.querySelector(selector); if (el) { resolve(el); } else { setTimeout(() => resolve(waitForSelector(selector)), 100); } }); } export function waitForEmptySelector(selector: string): Promise<HTMLElement> { return new Promise(resolve => { const el: HTMLElement | null = document.querySelector(selector); if (el) { setTimeout(() => resolve(waitForEmptySelector(selector)), 100); } else { resolve(); } }); }
17bf27ce84c2f9ed7f2fc116c60f4d100745ce81
TypeScript
simiancraft/Editor
/src/editor/edition-tools/procedural-textures/wood-tool.ts
2.5625
3
import { WoodProceduralTexture } from 'babylonjs-procedural-textures'; import AbstractEditionTool from '../edition-tool'; export default class WoodProceduralTool extends AbstractEditionTool<WoodProceduralTexture> { // Public members public divId: string = 'WOOD-PROCEDURAL-TOOL'; public tabName: string = 'Wood'; /** * Returns if the object is supported * @param object the object selected in the graph */ public isSupported (object: any): boolean { return object instanceof WoodProceduralTexture; } /** * Updates the edition tool * @param object the object selected in the graph */ public update (object: WoodProceduralTexture): void { // Super super.update(object); // Wood const wood = this.tool.addFolder('Wood'); wood.open(); wood.add(object, 'ampScale').step(0.01).name('Amp Scale'); this.tool.addColor(wood, 'Wood Color', object.woodColor, () => object.updateShaderUniforms()).open(); } }
334b5a3bb46b33941b014483f7a11f5422cb8f37
TypeScript
martink-rsa/trivia-app-server
/src/tests/utils.test.ts
2.9375
3
const { generateRandomNumber, getRandomNumbers, getRandomQuestions, } = require('../utils/utils'); describe('utils', () => { describe('getRandomNumber', () => { it('should get a random number between 0 and 1', () => { const minimum = 0; const maximum = 1; for (let i = 0; i < 10; i += 1) { const randomNumber = generateRandomNumber(minimum, maximum); expect(randomNumber).toBeGreaterThanOrEqual(minimum); expect(randomNumber).toBeLessThanOrEqual(maximum); } }); it('should get a random number between 5 and 6', () => { const minimum = 5; const maximum = 6; for (let i = 0; i < 10; i += 1) { const randomNumber = generateRandomNumber(minimum, maximum); expect(randomNumber).toBeGreaterThanOrEqual(minimum); expect(randomNumber).toBeLessThanOrEqual(maximum); } }); }); describe('getRandomNumbers', () => { it('should get 5 random numbers between 1 and 5', () => { const minimum = 1; const maximum = 5; const totalNumbers = 5; const numberArray = [1, 2, 3, 4, 5]; const numbers = getRandomNumbers(minimum, maximum, totalNumbers); numbers.forEach((number: number) => { expect(number).toBeGreaterThanOrEqual(minimum); expect(number).toBeLessThanOrEqual(maximum); }); expect(numbers.length).toBe(5); expect(numbers.sort()).toEqual(numberArray); expect.assertions(totalNumbers * 2 + 2); }); it('should get 5 random numbers with a range of 5', () => { const minimum = 10; const maximum = 15; const totalNumbers = 5; const numbers = getRandomNumbers(minimum, maximum, totalNumbers); numbers.forEach((number: number) => { expect(number).toBeGreaterThanOrEqual(minimum); expect(number).toBeLessThanOrEqual(maximum); }); expect(numbers.length).toBe(totalNumbers); expect.assertions(totalNumbers * 2 + 1); }); it('should get 5 random numbers with a range of 5', () => { const minimum = 10; const maximum = 20; const totalNumbers = 5; const numbers = getRandomNumbers(minimum, maximum, totalNumbers); numbers.forEach((number: number) => { expect(number).toBeGreaterThanOrEqual(minimum); expect(number).toBeLessThanOrEqual(maximum); }); expect(numbers.length).toBe(totalNumbers); expect.assertions(totalNumbers * 2 + 1); }); it('should throw an error if the range of numbers is less than the numbers needed', () => { expect(() => { getRandomNumbers(1, 5, 6); }).toThrowError(); }); }); describe('getRandomQuestions', () => { it('should get a list of 5 random questions for javascript subject without fault 200 times', () => { const numLoops = 200; for (let i = 0; i < numLoops; i += 1) { const totalQuestions = 5; const questions = getRandomQuestions('javascript', totalQuestions); expect(questions.length).toBe(totalQuestions); questions.forEach((question: any) => { expect(question).not.toBeNull(); expect(question).not.toBeUndefined(); }); expect.assertions(numLoops * (totalQuestions * 2 + 1)); } }); it("should throw an error if a topic doesn't exist", () => { expect(() => { getRandomQuestions('1javascript', 5); }).toThrowError(); expect.assertions(1); }); }); }); export {};
ce96aad920864459f2b940d990178d4bec5aaa89
TypeScript
wen-js/wenjs
/src/whois/who.ts
3.515625
4
export default class Who { constructor( // 群友名称 别名 readonly name:string | string[], // 群友简介 readonly dec: string ) {} // 名称匹配规则 pattern(input: string): boolean { const inputName = input.trim() if(Array.isArray(this.name)) { return this.name.some(name => name.trim() === inputName) } return inputName === this.name } }
be25f024260c6aba820c0d3de818bb1574d7ecd8
TypeScript
danikaze/terminal-runner
/src/ui/blessed/widgets/modal/index.ts
3
3
import * as blessed from 'blessed'; import { Widget, WidgetOptions, ResizeData } from '..'; export interface ModalOptions extends WidgetOptions { children: blessed.Widgets.BlessedElement[]; onFocus?: () => void; } /** * Reusable way to create consistent Modal widgets */ export class Modal implements Widget { protected static readonly BORDER?: blessed.Widgets.Border | 'line' | 'bg' = 'line'; protected static readonly PADDING: Required<blessed.Widgets.Padding> = { top: 1, bottom: 1, left: 2, right: 2, }; // options protected readonly screen: blessed.Widgets.Screen; // blessed widgets protected readonly background: blessed.Widgets.BoxElement; protected readonly container: blessed.Widgets.BoxElement; // widget state protected isVisible = false; constructor(options: ModalOptions) { this.screen = options.screen; this.background = blessed.box({ mouse: true, clickable: true, autofocus: true, transparent: true, }); this.container = blessed.box({ border: Modal.BORDER, padding: Modal.PADDING, clickable: true, autofocus: true, }); if (options.onFocus) { this.background.on('focus', options.onFocus); this.container.on('focus', options.onFocus); } this.background.append(this.container); options.children.forEach(child => { this.container.append(child); }); this.onResize(options); } /** * Method called when the widget needs to be resized */ public onResize(data: ResizeData, delayedRender?: boolean | undefined): void { let contentWidth = 0; let contentHeight = 0; (this.container.children as blessed.Widgets.BlessedElement[]).forEach( node => { let left = 0; let top = 0; try { left = node.left as number; } catch (e) {} try { top = node.top as number; } catch (e) {} contentWidth = Math.max(left + (node.width as number), contentWidth); contentHeight = Math.max(top + (node.height as number), contentHeight); } ); this.background.top = 0; this.background.left = 0; this.background.width = data.width; this.background.height = data.height; this.container.width = contentWidth + Modal.PADDING.left + Modal.PADDING.right + (Modal.BORDER ? 2 : 0); this.container.height = contentHeight + Modal.PADDING.top + Modal.PADDING.bottom + (Modal.BORDER ? 2 : 0); this.container.top = Math.floor((data.height - this.container.height) / 2) - (Modal.BORDER ? 1 : 0); this.container.left = Math.floor((data.width - this.container.width) / 2) - (Modal.BORDER ? 1 : 0); if (!delayedRender) { this.screen.render(); } } /** * Shows the widget */ public async show(): Promise<void> { if (this.isVisible) return; this.isVisible = true; this.screen.append(this.background); this.screen.render(); } /** * Hides the widget */ public async hide(): Promise<void> { if (!this.isVisible) return; this.isVisible = false; this.screen.remove(this.background); this.screen.render(); } /** * Toggles the widget between shown/hidden */ public async toggle(): Promise<void> { if (this.isVisible) { this.hide(); } else { this.show(); } } }
7273918ba8de51f9240d358770db19b8f0a4a44b
TypeScript
mymyoux/Typescript-Ghost-framework
/browser/graphics/Sprite.ts
2.71875
3
//missing import {View} from "browser/graphics/View"; //convert /* ghost.events.EventDispatcher */ import {EventDispatcher} from "ghost/events/EventDispatcher"; //convert-files import {ISprite} from "./ISprite"; ///<module="framework/ghost/utils"/> ///<module="framework/ghost/events"/> //convert-import import {Maths} from "ghost/utils/Maths"; export class Sprite extends EventDispatcher implements ISprite { public x: number; public y: number; public z: number; public width: number; public height: number; protected children: ISprite[]; public parent: ISprite; public constructor() { super(); this.x = this.y = this.z = 0; this.width = this.height = 10; this.children = []; } public addChild(sprite: ISprite) { this.children.push(sprite); sprite.parent = this; } public removeChild(sprite) { var index: number = this.children.indexOf(sprite); if (index !== -1) { this.children.splice(index, 1); sprite.dispose(); } } public draw(view:View):void { view.context.save(); view.context.translate(this.x, this.y); view.context.fillStyle = "#0000FF"; view.context.fillRect(0, 0, this.width, this.height); var len: number = this.children.length; for (var i = 0; i < len; i++) { this.children[i].draw(view); } view.context.restore(); } public _tick(round:number): void { this.tick(round); var len: number = this.children.length; for (var i = 0; i < len; i++) { this.children[i]._tick(round); } } public tick(round:number):void { this.x += Maths.randBetween(-10, 10); if (this.x < 0) { this.x = 0; } this.y += Maths.randBetween(-10, 10); if (this.y < 0) { this.y = 0; } } public getGlobalX(): number { return this.x + (this.parent ? this.parent.getGlobalX():0); } public getGlobalY(): number { return this.y + (this.parent ? this.parent.getGlobalY():0); } public getGlobalZ(): number { return this.z + (this.parent ? this.parent.getGlobalZ():0); } public dispose(): void { while(this.children.length) { this.children.shift().dispose(); } this.parent = null; } }
651427a93f470c04ef7abcbe56cdbfc567ccf2cf
TypeScript
f-space/cthulhu-tools
/src/components/pages/character-edit/attribute-input/expression-arranger.ts
2.859375
3
import { AST, Reference, AttributeType, Attribute, PropertyResolver } from "models/status"; export class ExpressionArranger { private context!: Attribute; private depth!: number; public constructor(readonly resolver: PropertyResolver) { } public arrange(attribute: Attribute): string[] { this.context = attribute; this.depth = 0; return this.visit(attribute.expression.ast).split("\x00"); } protected visit(node: AST.Node): string { switch (node.type) { case AST.NodeType.BinaryOp: return this.onBinaryOperator(node); case AST.NodeType.UnaryOp: return this.onUnaryOperator(node); case AST.NodeType.FunctionCall: return this.onFunctionCall(node); case AST.NodeType.Literal: return this.onLiteral(node); case AST.NodeType.Template: return this.onTemplate(node); case AST.NodeType.Substitution: return this.onSubstitution(node); case AST.NodeType.Text: return this.onText(node); case AST.NodeType.Variable: return this.onVariable(node); case AST.NodeType.Reference: return this.onReference(node); } } protected onBinaryOperator(node: AST.BinaryOperator): string { const lhs = this.visit(node.lhs); const rhs = this.visit(node.rhs); const lhsSeg = node.priority < node.lhs.priority ? `(${lhs})` : lhs; const rhsSeg = node.priority > node.rhs.priority ? rhs : `(${rhs})`; return `${lhsSeg} ${node.op} ${rhsSeg}`; } protected onUnaryOperator(node: AST.UnaryOperator): string { const expression = this.visit(node.expression); const exprSeg = node.priority < node.expression.priority ? `(${expression})` : expression; return `${node.op}${exprSeg}`; } protected onFunctionCall(node: AST.FunctionCall): string { const args = node.args.map(x => this.visit(x)); switch (node.fn) { case 'if': return `if ${args[0]} then ${args[1]} else ${args[2]}`; case 'and': return `${args[0]} \u2227 ${args[1]}`; case 'or': return `${args[0]} \u2228 ${args[1]}`; case 'not': return `\u00AC ${args[0]}` case 'floor': return `\u230A ${args[0]} \u230B`; case 'ceil': return `\u2308 ${args[0]} \u2309`; case 'round': return `\u230A ${args[0]} \u2309`; default: return `${node.fn}(${args.join(", ")})`; } } protected onLiteral(node: AST.Literal): string { return String(node.value); } protected onTemplate(node: AST.Template): string { return node.segments.map(x => this.visit(x)).join(""); } protected onSubstitution(node: AST.Substitution): string { return this.visit(node.expression); } protected onText(node: AST.Text): string { return node.value; } protected onVariable(node: AST.Variable): string { return `\x00${node.name}\x00`; } protected onReference(node: AST.Reference): string { const ref = new Reference(node.id, node.modifier, node.scope); const property = this.resolver.resolve({ ref }); if (property) { switch (property.type) { case 'attribute': case 'attribute:min': case 'attribute:max': const attribute = property.attribute; if (ref.id === this.context.id) { return this.recurse(attribute, ref); } else { return ref.modifier ? `${attribute.name}:${ref.modifier}` : attribute.name; } case 'skill': case 'skill:base': case 'skill:points': const skill = property.skill; return ref.modifier ? `${skill.name}:${ref.modifier}` : skill.name; } } return ref.key; } private recurse(attribute: Attribute, ref: Reference): string { const MAX_DEPTH = 3; if (this.depth++ < MAX_DEPTH) { switch (attribute.type) { case AttributeType.Integer: case AttributeType.Number: switch (ref.modifier) { case 'min': return attribute.min ? this.visit(attribute.min.ast) : "-\u221E"; case 'max': return attribute.max ? this.visit(attribute.max.ast) : "+\u221E"; } break; } } return ref.key; } }
a589cdd7e0ca0e4db99248bbc4889aecf5d8d697
TypeScript
willymilimo/lwsc
/redux/actions/theme.ts
2.53125
3
import { ThemeType, ThemeReducer } from "../../types/theme"; import Actions, { ActionI } from "../Actions"; export const setThemeReducer = (payload: ThemeReducer) => ({ type: Actions.SET_THEME_REDUCER, payload, }); export const setTheme = (theme: ThemeType): ActionI => ({ type: Actions.SET_THEME, payload: theme, }); export const setName = (name: string): ActionI => ({ type: Actions.SET_THEME_NAME, payload: name, });
9b0013d1060b3a21ca371a754b25f29d974e1131
TypeScript
mtchdev/Inferno
/api/app/controllers/ReminderController.ts
2.59375
3
import { Controller } from 'vendor/astro/http/Controller'; import { Request } from 'express'; import { Reminder } from 'app/models/Reminder'; export class ReminderController extends Controller { constructor(data) { super(data); } /** * Add a reminder * @param request The API request * @returns Reminder */ async addReminder(request: Request) { let input: any = request.body; let reminder = new Reminder(); reminder.channel_id = input.channel_id; reminder.guild_id = input.guild_id; reminder.time = input.time; reminder.user_id = input.user_id; reminder.message = input.message; await this.db.save(reminder); return this.respondWithSuccess(reminder); } /** * Get all reminders * @returns Array<Reminder> */ async getAllReminders() { let reminders = await this.db.getRepository(Reminder).createQueryBuilder('reminder').getMany(); return this.respondWithSuccess(reminders); } /** * Remove a reminder * @param request The API request */ async removeReminder(request: Request) { let id: string = request.params.id; try { let reminder: Reminder = await this.db.findOneOrFail(Reminder, id); await this.db.getRepository(Reminder).remove(reminder); } catch (e) { return this.respondWithError(); } } }
8fe01fceea8dba49437df55d6120811cde93eabb
TypeScript
PerminovEugene/event-hub
/packages/shared/src/domain/auth.ts
3.25
3
export enum Role { admin = "admin", superAdmin = "superAdmin", manager = "manager", guest = "guest", client = "client" } export enum GroupName { "all" = "all", "authorised" = "authorised", "staff" = "staff", "admins" = "admins", "unauthorised" = "unauthorised" } type Group = { [key in keyof GroupName]?: Array<Role>; }; // TS doesn't support spread for Set :( const setToArray = (set: Set<any>) => Array.from(set.values()); export const groups: Group = {}; groups[GroupName.admins] = new Set([Role.admin, Role.superAdmin]); groups[GroupName.staff] = new Set([ ...setToArray(groups[GroupName.admins]), Role.manager ]); groups[GroupName.authorised] = new Set([ ...setToArray(groups[GroupName.staff]), Role.client ]); groups[GroupName.all] = new Set([ ...setToArray(groups[GroupName.authorised]), Role.guest ]); groups[GroupName.unauthorised] = new Set([Role.guest]); export enum Resource { event = "event", auth = "auth", tag = "tag" } export enum Action { read = "read", create = "create", update = "update", delete = "delete", login = "login", registration = "registration" } export const permissions = { [Resource.event]: { [Action.read]: groups[GroupName.all], [Action.create]: groups[GroupName.authorised], [Action.update]: groups[GroupName.authorised], [Action.delete]: groups[GroupName.authorised] }, [Resource.auth]: { [Action.registration]: groups[GroupName.unauthorised], [Action.login]: groups[GroupName.unauthorised] }, [Resource.tag]: { [Action.read]: groups[GroupName.all], [Action.create]: groups[GroupName.staff], [Action.update]: groups[GroupName.staff], [Action.delete]: groups[GroupName.staff] } }; export type CheckRightsParams = { role: Role; resource: Resource; action: Action; }; export const isUserHasRights = ({ role, resource, action }: CheckRightsParams): boolean => { return permissions[resource][action].has(role); };
e8a91e14ffbdec653eca81d0a0440607b2587bf9
TypeScript
eventia-io/eventia-core
/source/EventHandling/EventHandler.ts
3.15625
3
import { CodeMetadata } from "../Infrastructure/CodeMetadata"; import { EventFactory } from "../Infrastructure/EventFactory"; export type EventHandlerFunction = (event: any, metadata?: any, message?: any) => Promise<void>; export function EventHandler<T>( classConstructor: {}, methodName: string, params: { value?: EventHandlerFunction } ): void { const targetParameters = Reflect.getMetadata("design:paramtypes", classConstructor, methodName); if (targetParameters === undefined || targetParameters.length === 0 || params.value === undefined) { throw new Error( "A function decorated with @EventHandler needs at least " + "one parameter compatible with the Event interface" ); } const className = classConstructor.constructor.name; const fullMethodName = `${className}.${methodName}`; // The method that handles the event must be async if (params.value.constructor.name !== "AsyncFunction") { const errorMessage = `@EventHandler needs function "${fullMethodName}" to be ASYNC`; throw new Error(errorMessage); } // First parameters is an event const eventClassConstructor = targetParameters[0]; const eventClassName = eventClassConstructor.name; EventFactory.register(eventClassName, eventClassConstructor); // TODO: register eventclassconstructor in a factory // Add to list of handled events const handlers = CodeMetadata.getProperty<string[]>( className, "EventHandlers", [] ); handlers.push(eventClassName); CodeMetadata.setProperty<string[]>( className, "EventHandlers", handlers ); // Register as an EventHandler CodeMetadata.setProperty<EventHandlerFunction>( eventClassName, `EventHandlerFunction.${className}`, params.value ); CodeMetadata.setProperty( eventClassName, `EventHandlerFunctionFullMethodName.${className}`, fullMethodName ); }
1eccc738a59be37ceafbcefca99d4f6fbe53262a
TypeScript
meliorence/react-native-render-html
/packages/render-html/src/elements/getDimensionsWithAspectRatio.ts
2.59375
3
export default function getDimensionsWithAspectRatio( width: number | null, height: number | null, aspectRatio: number | undefined ) { return { width: width ?? (aspectRatio && height ? height * aspectRatio : null), height: height ?? (aspectRatio && width ? width / aspectRatio : null) }; }
ac0b4f3e04d919457cff0f9b2fcfebfc2ca201bc
TypeScript
osti2021/demo-crud-nestjs
/src/commons/service.commons.ts
2.625
3
import { FindManyOptions, Repository } from "typeorm"; export abstract class BaseService<T> { abstract getRepository() : Repository<T>; findAll() : Promise<T[]> { return this.getRepository().find(); } findOne(id: any): Promise<T> { return this.getRepository().findOne(id); } save(entity: T) : Promise<T> { return this.getRepository().save(entity); } saveMany(entities: T[]) : Promise<T[]> { return this.getRepository().save(entities); } async delete(id: any) { await this.getRepository().delete(id); } count(options?: FindManyOptions<T>) : Promise<number> { return this.getRepository().count(options); } }
3ad3e580f8dc5053ce95cbf286c58876c6792ff1
TypeScript
PierreCapo/react-native-socials
/src/Twitter/api.ts
2.734375
3
import { TwitterPostApiResponse, UserMention } from "./typings"; import { generateFetchRequestHeaders } from "./generateTwitterHeaders"; export const getPostData = async ( postId: string, consumerKey: string, consumerSecret: string ) => { const url = `https://api.twitter.com/1.1/statuses/show/${postId}.json`; const requestOptions = generateFetchRequestHeaders( url, consumerKey, consumerSecret ); const result = await fetch(url + "?tweet_mode=extended", requestOptions) .then((response) => response.json()) .then((value) => adapter(value)) .catch((error) => { console.log(error); return null; }); return result; }; export const adapter = (data: TwitterPostApiResponse): ITwitterPost => { const response = { createdAt: data.created_at, id: data.id, posterImageUrl: data.user.profile_image_url_https.replace("_normal", ""), posterDisplayName: data.user.name, posterUniqueName: data.user.screen_name, isPosterVerified: data.user.verified, retweetNumber: data.retweet_count, likeNumber: data.favorite_count, textContent: data.full_text.replace("&amp;", "&"), isQuote: data?.is_quote_status, urlList: data?.entities?.urls, hashtagList: data?.entities?.hashtags, userMentionList: data?.entities?.user_mentions, quotedTweet: data?.is_quote_status ? adapter(data?.quoted_status) : null, quoteUrlId: data?.quoted_status_id_str, media: data.extended_entities?.media?.map((element) => { if (element?.type === "video" || element?.type === "animated_gif") { return { type: "video", aspectRatio: element?.video_info?.aspect_ratio?.[0] / element?.video_info?.aspect_ratio?.[1], url: element?.video_info?.variants?.[0]?.url, posterUrl: element?.media_url_https, twitterShortlink: element?.url, }; } if (element?.type === "photo") { return { type: element?.type, aspectRatio: element.sizes.small.w / element.sizes.small.h, url: element.media_url_https, twitterShortlink: element?.url, }; } return null; }), }; response?.media?.forEach((element) => { if (element === null) return; response.textContent = response.textContent.replace( element?.twitterShortlink, "" ); }); // @ts-ignore return response; }; export interface ITwitterPost { createdAt: string; id: number; posterImageUrl: string; posterDisplayName: string; posterUniqueName: string; isPosterVerified: boolean; retweetNumber: number; likeNumber: number; textContent: string; isQuote: boolean; quotedTweet: any; quoteUrlId: string; urlList: Array<{ url: string; expanded_url: string; display_url: string; indices: [number, number]; }>; hashtagList: Array<{ text: string; indices: [number, number]; }>; userMentionList: UserMention[]; media: Array<{ type: string; aspectRatio: number; url: string; twitterShortlink: string; posterUrl: string; }>; }
51773442d425563712d8881a1f375ebb83f94023
TypeScript
YevgeniGitin/Express-Exercise-1and2
/src/controllers/product.controllers.ts
2.546875
3
import { Request, Response, NextFunction } from "express"; import { Product } from "../models/product"; import * as productServices from "../services/product.services"; //handlers to routing export const findProduct = productServices.findProduct; export const findProductIndex = productServices.findProductIndex; export async function getAll(req: Request, res: Response, next: NextFunction) { console.log("get all products"); try { const productarr = await productServices.getAll(); res.status(200).send(productarr); } catch (err) { next(err); } } export function getProductById(req: Request, res: Response, next: NextFunction) { console.log("get product by id"); const { matching, id } = res.locals; res.status(200).send(matching); } export async function addProduct(req: Request, res: Response, next: NextFunction) { try { console.log("add product"); const temp: Product = req.body; const product = await productServices.addProduct(temp); res.status(201).send(product); } catch (err) { next(err); } } export async function updateProductById( req: Request, res: Response, next: NextFunction) { try { console.log("update product by id"); const { matchingIndex, id } = res.locals; let temp: Product = req.body; const product = await productServices.updateProductById( matchingIndex, id, temp ); res.status(200).send(product); } catch (err) { next(err); } } export async function deleteItem( req: Request, res: Response, next: NextFunction) { try { console.log("delete item"); const { matchingIndex, id } = res.locals; productServices.deleteItem(matchingIndex); res.sendStatus(204); } catch (err) { next(err); } }
c9bf433f045862d4f7d8ae0d1a96009e0fe077c1
TypeScript
cavanbecksmith/Phaser-Ts-Examples
/src/Examples/UsingInputsEXT.ts
3.015625
3
class UsingInputsEXT { game: Phaser.Game; jetSprite: Phaser.Sprite; W: Phaser.Key; A: Phaser.Key; S: Phaser.Key; D: Phaser.Key; constructor() { this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', { create: this.create, preload: this.preload }); } preload() { var loader = this.game.load.image("jet", "images/jet.png"); } moveLeft() { this.jetSprite.position.add(-1, 0); } moveRight() { this.jetSprite.position.add(1, 0); } moveUp(e: KeyboardEvent) { // As you can see the event handler is passed an optional event KeyboardEvent // This contains additional information about the key, including the Control // key status. // Basically if the control key is held, we move up or down by 5 instead of 1 if (e.ctrlKey) this.jetSprite.position.add(0, -5); else this.jetSprite.position.add(0, -1); } moveDown(e: KeyboardEvent) { if (e.ctrlKey) this.jetSprite.position.add(0, 1); else this.jetSprite.position.add(0, 1); } create() { var image = <Phaser.Image>this.game.cache.getImage("jet"); this.jetSprite = this.game.add.sprite( this.game.width / 2 - image.width / 2, this.game.height / 2 - image.height / 2, "jet"); // Create a key for each WASD key this.W = this.game.input.keyboard.addKey(Phaser.Keyboard.W); this.A = this.game.input.keyboard.addKey(Phaser.Keyboard.A); this.S = this.game.input.keyboard.addKey(Phaser.Keyboard.S); this.D = this.game.input.keyboard.addKey(Phaser.Keyboard.D); // Since we are allowing the combination of CTRL+W, which is a shortcut for close window // we need to trap all handling of the W key and make sure it doesnt get handled by // the browser. // Unfortunately you can no longer capture the CTRL+W key combination in Google Chrome // except in "Application Mode" because apparently Google thought an unstoppable un prompted // key combo of death was a good idea... this.game.input.keyboard.addKeyCapture(Phaser.Keyboard.W); // Wire up an event handler for each K. The handler is a Phaser.Signal attached to the Key Object this.W.onDown.add(UsingInputsEXT.prototype.moveUp, this); this.A.onDown.add(UsingInputsEXT.prototype.moveLeft, this); this.S.onDown.add(UsingInputsEXT.prototype.moveDown, this); this.D.onDown.add(UsingInputsEXT.prototype.moveRight, this); } }
432d21a123afc3c9f58b0a44ba543599bab20bb1
TypeScript
jiongran/project
/src/util/index.ts
2.65625
3
import setting from '@/settings' import i18n from '@/lang' /** * @remarks 根据语言枚举返回对应翻译(如没有则返回默认) * @param language 语言枚举 * @returns 语言枚举对应翻译 */ const getLange = (language: string = setting.defaultLanguage) => { const stringEmum: any = { 'zhchs': '简体中文', 'en': 'English' } return stringEmum[language] || stringEmum[setting.defaultLanguage] } const getAppdown = (): number => { let mobileSystem = 0 let ua = navigator.userAgent if (/(iPhone|iPad|iPod|iOS)/i.test(ua)) { mobileSystem = 1 } else if (/(Android)/i.test(ua)) { mobileSystem = 2 } return mobileSystem } const clone = (obj: any): any => { if (typeof obj === 'object' && obj !== null) { let o = Object.prototype.toString.call(obj).slice(8, -1) === 'Array' ? [] : {} for (let k in obj) { if (typeof obj[k] === 'object' && obj[k] !== null) { (o as any)[k] = clone(obj[k]) } else { (o as any)[k] = obj[k] } } return o } else { return obj } } const diaplayTime = (dateTimeStamp: number): string => { let result: string = '' const minute = 1000 * 60 const hour = minute * 60 const day = hour * 24 const month = day * 30 const now: number = new Date().getTime() const curTime: number = dateTimeStamp * 1000 const diffValue: number = now - curTime const monthC: number = diffValue / month const weekC: number = diffValue / (7 * day) const dayC: number = diffValue / day const hourC: number = diffValue / hour const minC: number = diffValue / minute if (diffValue >= 0) { if (monthC >= 1) { if (monthC <= 12) { result = monthC + (i18n.t('components.monthLater') as string) } else { result = monthC / 12 + (i18n.t('components.yearLater') as string) } } else if (weekC >= 1) { result = weekC + (i18n.t('components.weekLater') as string) } else if (dayC >= 1) { result = dayC + (i18n.t('components.dayLater') as string) } else if (hourC >= 1) { result = hourC + (i18n.t('components.hourLater') as string) } else if (minC >= 1) { result = minC + (i18n.t('components.minsLater') as string) } else { result = i18n.t('components.just') as string } } return result } const setTitle = (val: string = 'index'): void => { let str = val document.title = (i18n.t('router.' + str) as string) } export default { getLange, getAppdown, clone, diaplayTime, setTitle }
eb7ff41faf6af9d4ebb68e4a8657018ab525f2d6
TypeScript
KiranMantha/plumejs
/src/lib/domTransition.service.ts
2.53125
3
import { Injectable } from './decorators'; import { fromEvent } from './utils'; class DomTransition { private transition = ''; constructor() { this.whichTransitionEnd(); } onTransitionEnd(element: HTMLElement, cb: () => void, duration: number) { let called = false; let unSubscribeEvent = null; const _fn = () => { if (!called) { called = true; cb && cb(); unSubscribeEvent(); unSubscribeEvent = null; } }; unSubscribeEvent = fromEvent(element, this.transition, () => { _fn(); }); setTimeout(_fn, duration); } animationsComplete(element: HTMLElement): Promise<any> { if (element.getAnimations) { return Promise.allSettled(element.getAnimations().map((animation: Animation) => animation.finished)); } else { return Promise.allSettled([true]); } } private whichTransitionEnd() { const element = document.createElement('div'); const styleobj: any = element.style; const transitions: { [key: string]: string } = { transition: 'transitionend', WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'otransitionend' }; for (const t in transitions) { if (typeof styleobj[t] !== 'undefined') { this.transition = transitions[t]; break; } } } } Injectable()(DomTransition); export { DomTransition };
b2db5e7aee045f709ebc0fce60680ae6c5356bd7
TypeScript
tumit/reusable-strategy-demo
/src/app/reusable-route-strategy.ts
2.59375
3
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router'; import { Member } from './member'; export class ReusableRouteStrategy implements RouteReuseStrategy { // handlers to store detached route private handlers: { [key: string]: DetachedRouteHandle } = {}; private reusableUrls = ['members']; /** * Determines if this route (and its subtree) should be detached to be reused later * @param route */ shouldDetach(route: ActivatedRouteSnapshot): boolean { console.log('shouldDetach', route); return this.reusable(route); } /** * Stores the detached route. */ store(route: ActivatedRouteSnapshot, handler: DetachedRouteHandle): void { console.log('store', handler); if (handler) { this.handlers[this.getUrl(route)] = handler; } } /** * Determines if this route (and its subtree) should be reattached * @param route Stores the detached route. */ shouldAttach(route: ActivatedRouteSnapshot): boolean { console.log('shouldAttach', route); return ( (!!route.queryParamMap.get('reusable') || this.forceReuse(this.getUrl(route))) && !!this.handlers[this.getUrl(route)] ); } private forceReuse(url: string) { console.log('url', url); return this.reusableUrls.find(u => u === url); } /** * Retrieves the previously stored route */ retrieve(route: ActivatedRouteSnapshot): {} { console.log('retrieve: route', route); if (!route.routeConfig || route.routeConfig.loadChildren) { return null; } console.log('retrieve: this.handlers[this.getUrl(route)]', this.handlers[this.getUrl(route)]); return this.handlers[this.getUrl(route)]; } /** * Determines if a route should be reused * @param future * @param current */ shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { console.log('shouldReuseRoute: future.routeConfig', future.routeConfig); console.log('shouldReuseRoute: curr.routeConfig', curr.routeConfig); return future.routeConfig === curr.routeConfig; } private getUrl(route: ActivatedRouteSnapshot): string { return route.routeConfig ? route.routeConfig.path : ''; } private reusable(route: ActivatedRouteSnapshot) { if (!route.routeConfig || route.routeConfig.loadChildren) { return false; } return route.routeConfig.data && route.routeConfig.data.reusable; } }
2db64fbd7b39b508be875e84b9f2dc07f6ac42db
TypeScript
Vontus/UrbanDictionaryBot
/src/urban-api/ud-cache.ts
2.765625
3
import { UdDefinition } from './ud-definition' interface IDictionary { [index: string]: UdDefinition[] } const searchCache: IDictionary = {} export function addSearchCache (search: string, definitions: UdDefinition[]) { searchCache[normalizeWord(search)] = definitions } export function getSearchCache (word: string) { return searchCache[normalizeWord(word)] } function normalizeWord (word: string): string { return word.toLowerCase() }
7809c8d72c1be5242e0da477b4937762fb2e431c
TypeScript
crisbeto/material2
/tools/tslint-rules/symbolNamingRule.ts
3.078125
3
import ts from 'typescript'; import * as Lint from 'tslint'; /** Lint rule that checks the names of classes and interfaces against a pattern. */ export class Rule extends Lint.Rules.AbstractRule { /** Pattern that we should validate against. */ private _pattern: RegExp; constructor(options: Lint.IOptions) { super(options); this._pattern = new RegExp(options.ruleArguments[0] || '.*'); } apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithFunction(sourceFile, checkSourceFile, this._pattern); } } function checkSourceFile(context: Lint.WalkContext<RegExp>) { context.sourceFile.forEachChild(function walk(node) { if ( (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) && node.name && !context.options.test(node.name.text) ) { context.addFailureAtNode(node.name, `Symbol name must match pattern ${context.options}`); } node.forEachChild(walk); }); }
ac8be21d55c77a0307761cedd1f500560f3130cd
TypeScript
ALongLi/react-admin
/src/utils/constants.ts
2.71875
3
import { DefaultOptionType } from 'antd/es/select'; /** * @description: 公用常量 */ /** * 颜色 */ export enum colors { success = 'green', primary = '#409EFF', warning = '#E6A23C', danger = 'red', info = '#909399' } export interface Constant extends Omit<DefaultOptionType, 'children'> { value: string | number; label: string; color?: colors; children?: Constant[]; } // 日期格式化 export const DATE_FORMAT = 'YYYY-MM-DD'; export const TIME_FORMAT = 'YYYY-MM-DD hh:mm:ss'; /** * 开启状态 */ export const OPEN_CLOSE: Constant[] = [ { label: '开启', value: 1 }, { label: '关闭', value: 0 } ]; /** * 菜单状态 */ export const MENU_STATUS: Constant[] = [ { label: '显示', value: 1 }, { label: '隐藏', value: 0 } ]; /** * 菜单模块 */ export const MENU_MODULE: Constant[] = [ { value: 'authority', label: '权限系统' }, { value: 'platform', label: '运营系统' }, { value: 'stat', label: '统计系统' }, { value: 'ad', label: '投放系统' }, { value: 'cs', label: '客服系统' }, { value: 'log', label: '日志系统' } ]; /** * 菜单作用类型 */ export const MENU_ACTIONS: Constant[] = [ { value: 'create', label: '创建' }, { value: 'update', label: '更新' }, { value: 'delete', label: '删除' }, { value: 'detail', label: '详情' }, { value: 'export', label: '导出' }, { value: 'status', label: '状态' }, ];
68ce699446c9957e1bfea65d73e08e747aece00f
TypeScript
FleMo93/dcs-kellergeschwader-web
/src/helper/TimeToString.ts
3.15625
3
export function getDateString(date: Date): string { return date.getUTCFullYear() + '-' + (date.getUTCMonth() + 1).toString().padStart(2, '00') + '-' + date.getUTCDate().toString().padStart(2, '00'); } export function getTimeString(date: Date): string { return date.getUTCHours() + ':' + date.getUTCMinutes().toString().padStart(2, '00') + ':' + date.getUTCSeconds().toString().padStart(2, '00') + ''; } export function secondsToTime(seconds: number): string { const hours = Math.floor((seconds / 60 / 60)).toString().padStart(2, '00') const minutes = Math.floor((seconds / 60 % 60)).toString().padStart(2, '00') const secs = Math.floor((seconds % 60)).toString().padStart(2, '00') return hours + ":" + minutes + ":" + secs; } export function secondsToHourMin(seconds: number): string { const hours = Math.floor((seconds / 60 / 60)).toString().padStart(2, '00') const minutes = Math.floor((seconds / 60 % 60)).toString().padStart(2, '00') return hours + "h " + minutes + "m" }
64fccd3937136b0bc597862f6e6d70f7c5256103
TypeScript
clearcodeweb/lorder.ui
/src/#/@store/@common/helpers/mapEnum.ts
3.421875
3
export function mapEnum<EnumType>(enumerable: EnumType, fn: (el: any) => any): any[] { // get all the members of the enum const enumMembers: any[] = Object.keys(enumerable).map(key => enumerable[key]); // we are only interested in the numeric identifiers as these represent the values const enumValues: number[] = enumMembers.filter(v => typeof v === 'number'); // now map through the enum values return enumValues.map(m => fn(m)); }
6fd9b60d3e7a142d83ed34db2bea3a9df0fa9c48
TypeScript
atakangah/banking-api
/src/utilities/bcrypt.hash.ts
2.78125
3
import bcrypt from "bcrypt"; import { User } from "../interfaces/user.interface"; export const encryptPassword = async (user: User) => { return await bcrypt.hash(user?.password, user?.phone.length); }; export const verifyPassword = async (inputPassword: string, userPassword: string) => { return await bcrypt.compare(inputPassword, userPassword); }
fd241ca6488ade75634e410ca1d8506c50b50dbe
TypeScript
I-luv-chuletas/El_Lobby
/src/app/services/in-memory-data.service.ts
2.625
3
import {InMemoryDbService} from 'angular-in-memory-web-api'; export class InMemoryDataService implements InMemoryDbService { createDb(){ let shouts = [ {id:1, rating:6, userID:"Anon2", commentSectionId:1, title:"Cobros tardios departe de @Recursos Humanos", message:"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."}, {id:2, rating:9, userID:"Abdiel Moran", commentSectionId:2, title:"Falta de mantenimiento en laboratorio ac-232", message:"adfasdfadsfasdfadsfadfasfasdfadf"}, {id:3, rating:0, userID:"Andre Walker", commentSectionId:3, title:"Humedad en conductos de aires", message:"adfasdfadsfasdfadsfadfasfasdfadf"}, {id:4, rating:1, userID:"Roberto Rosa", commentSectionId:4, title:"Falta de transparencia de parte del Rector", message:"adfasdfadsfasdfadsfadfasfasdfadf"}, {id:5, rating:15, userID:"Roy Brow", commentSectionId:4, title:"Internet no funciona!!!!!", message:"adfasdfadsfasdfadsfadfasfasdfadf"} ]; let comments = [ {id:1, userID:"Alexandra", message:"Seria bueno si la oficina de Recursos Humanos automatizara el proceso atraves del CTI para que sea algo mecanico."}, {id:2, userID:"Abdiela", message: "Cobrando una vez al mes no se puede, mucho menos cuando nuestro contrato está por quincena."}, {id:3, userID:"Andrea", message: "Cansada de que la internet siempre se caiga, hasta en el trabajo"}, {id:4, userID:"Roberta", message: "Estoy totalmente de acuerdo, esto es ridiculo!!!!!"}, {id:5, userID:"Royina", message: "A-a-a-a-a-alomejor si no dependieran tanto de una sola persona para crear el proceso, los estudiantes por jornal cobrarian a tiempo"} ]; return {shouts, comments}; } }
25d954843dba762f1cb15cdad3d86791d80d144c
TypeScript
tategakibunko/nehan
/src/space-char.ts
3
3
import { ICharacter, LogicalSize, SpaceCharInfo, SpaceCharTable, Font, TextEmphaData, ILogicalNodeEvaluator, TextMeasure, } from "./public-api"; // more detailed version // let rexSpace = /^[\u0009-\u000D\u001C-\u/0020\u00A0\u034F\u11A3-\u11A7\u1680\u180E\u2000-\u200F\u2028-\u202E\u2061-\u2063\u3000\u3164\uFEFE]/; export class SpaceChar implements ICharacter { public text: string; public size: LogicalSize; public info: SpaceCharInfo; public kerning: boolean; public spacing: number; public charCount: number; static zeroWidthSpace: string = "\u200B"; static enSpace: string = "\u2002"; static emSpace: string = "\u2003"; static noBreakSpace: string = "\u00A0"; static ideographicSpace: string = "\u3000"; static markerSpace: string = SpaceChar.enSpace; static charRefToStr(str: string): string { switch (str) { case "&nbsp;": return "\u00A0"; case "&thinsp;": return "\u2009"; case "&ensp;": return "\u2002"; case "&emsp;": return "\u2003"; } throw new Error("invalid space char ref(" + str + ")"); } public constructor(str: string) { this.text = this.normalize(str); this.size = new LogicalSize({ measure: 0, extent: 0 }); this.info = SpaceCharTable.load(str); this.kerning = false; this.spacing = 0; this.charCount = 0; // not count as normal character. } protected normalize(str: string): string { if (str.indexOf("&") === 0) { return SpaceChar.charRefToStr(str); } return str; } public setMetrics(opts: { font: Font; isVertical: boolean; empha?: TextEmphaData; }) { this.size = TextMeasure.getWordSize(opts.font, this.text); // In Safari & Firefox(offscreen-canvas is not supported), // width of getBoundingClientRect for white-spaces is zero. // So this is work around for Safari, Firefox etc. if (this.size.measure === 0) { this.size.measure = this.size.extent * this.info.advanceRate; } } public toString(): string { return this.text; } public isNoBreak(): boolean { return this.info.isNoBreak; } public isZeroWidth(): boolean { return this.info.advanceRate === 0; } public isCarriageReturn(): boolean { return this.text === "\u000D"; // CR } public isLineFeed(): boolean { return this.text === "\u000A"; // LF } public acceptEvaluator(visitor: ILogicalNodeEvaluator): Node { return visitor.visitSpaceChar(this); } }
83906662cd04a45524464640dbd29a9e2cc68541
TypeScript
depekur/eating-time
/frontend/src/app/ration/model/ration.model.ts
2.90625
3
import * as moment from 'moment'; export interface IGetRationRequest { date: string; } export interface IGetRationIntervalRequest { startDate: string; endDate: string; } export interface IDeleteRationRequest { date: number; } export interface IRation { } /** * response and request to get\set day ration */ export interface IRationDay { date?: number; food?: IEating[]; } export interface IEating { eatingOrder: number; eatingTime?: any; textBody?: string; dishes?: IDish[]|any; } export interface IDish { dishOrder: number; recipeId: number; recipeTitle?: string; weight?: string; price?: IDishPrice; } export interface IDishPrice { value: number; measure: string; } export class RationDay implements IRationDay { date: number; food: IEating[]; constructor(data, eatingTime) { this.date = data.date; this.food = data.food.length ? data.food : getDefaultFood(data.date, eatingTime); } } function getDefaultFood(date, eatingTime) { let food = []; for (let i = 1; i <= 5; i++) { food.push({ eatingOrder: i, eatingTime: setTime(date, eatingTime[i-1]), dishes: [], textBody: '' }); } return food; } function setTime(date, time) { let t = moment.unix(date) .subtract(1, 'days') .startOf('day') .hours(time.hours) .minute(time.minutes); return { timestamp: t.unix(), time: t.format('HH:mm') }; } let dishes = [ { dishOrder: 1, eatingOrder: 1, recipeId: 1, recipeTitle: '', // не записывать в базу - подтягивать для каждого recipeCount: '' // кол-во или че там я хотел для рецептиков }, ]; // todo новое json поле в базе рациона // сохранять вместе с рационом - мы ведь не можем поменять время вчерашнего завтрака // новые настройки подсасывать только для новой даты // менять даты отдельно для каждого дня! let eatingTime = [ {hours: 7, minutes: 30}, {hours: 10, minutes: 0}, {hours: 13, minutes: 0}, {hours: 17, minutes: 0}, {hours: 20, minutes: 0}, ];
ead84ba930edaefefc76f407f22077048ab97c3a
TypeScript
ohayobrew/harvester-test
/app/utils/deserializer.ts
2.609375
3
import {Logger} from './logger'; import * as _ from 'lodash'; import {IImageModel, IRequestMetadata, eImageTask, eSkippedCropReason} from '../models/image/image.model.interface' import {ICropArea} from "../models/image/image.model.interface"; import {eImageStatus} from "../models/image/image.model.interface"; import {eCropAreaStatus} from "../models/image/image.model.interface"; import {IEntityPriority} from "../models/config/config.model.interface"; export interface IParsedRequest { imageId: string; entityId: string; tags?: string[]; source: string; reportId: string; requestedSkipCrop: boolean; force?: boolean; reCalc?: boolean; metadata?: IRequestMetadata }; export class Deserializer { // take only supported query params for image filtering static imagesQueryParams = (queryParams: any[]): any => { if (queryParams == null) return {}; let keys = ["status", "entityId"]; let returnObj = {}; keys.forEach(key => { if (queryParams[key]) returnObj[key] = queryParams[key]; }) return returnObj; }; // take string status and return the same string if exist in eImagesStatus enum static imagesStatusBleach = (status: string): string => { let intStatus = parseInt(status); if (!isNaN(intStatus)) return null; return eImageStatus[status]; }; // convert strings of ints to number static paginationScope = (limit: string, offset: string): {limit: number, offset: number} => { let intLimit = parseInt(limit); let intOffset = parseInt(offset); if (isNaN(intLimit) || isNaN(intOffset)) return null; return {limit: intLimit, offset: intOffset}; }; // convert string body of incoming message from long poll queue to object with required params // if not all required params exist, returning null static fromMessageBody = (messageBody: string): IParsedRequest => { try { let tmpObj = JSON.parse(messageBody); Logger.debug(`Message body "${messageBody}" was successfully -parsed- to JSON`); // check for mandatory fields if (tmpObj.data == null || tmpObj.metadata == null){ Logger.warn(`Message body "${messageBody}" is missing mandatory fields. IGNORING!`); return null; } else if (tmpObj.metadata.workloadId == null || tmpObj.metadata.transactionId == null || tmpObj.metadata.reportId == null){ Logger.warn(`Message body "${messageBody}" is missing mandatory fields. IGNORING!`); return null; } else if (tmpObj.data.imageId == null || tmpObj.data.source == null || tmpObj.data.entityId == null){ Logger.warn(`Message body "${messageBody}" is missing mandatory fields. IGNORING!`); return null; } // optional fields that not exist will not be included in the returned object return { imageId: tmpObj.data.imageId, entityId: tmpObj.data.entityId.toString(), tags: tmpObj.data.tags, source: tmpObj.data.source, reportId: tmpObj.data.reportId, requestedSkipCrop: tmpObj.data.skipCrop, force: tmpObj.data.force, reCalc: tmpObj.data.reCalc, metadata: { workloadId: tmpObj.metadata.workloadId, transactionId: tmpObj.metadata.transactionId, reportId: tmpObj.metadata.reportId, companyId: tmpObj.metadata.companyId, version: tmpObj.metadata.version, } }; } catch (error) { Logger.warn(`Failed parsing message body "${messageBody}" to JSON`, error.message); return null; } }; private static getCroppedData(cropAreas: ICropArea[], keepCropAreaImaginaryId: boolean): ICropArea[] { return cropAreas.map( obj => ({ createdAt: obj.createdAt, x: obj.x, y: obj.y, width: obj.width, height: obj.height, status: obj.status, cloudinary: keepCropAreaImaginaryId ? obj.cloudinary : undefined, imaginaryId: keepCropAreaImaginaryId ? obj.imaginaryId : undefined })) } // set proper values when no need cropping, just set the main imaginaryId as a single crop area static skipCrop(image: IImageModel): IImageModel { return Deserializer.getSerializerImg( image, eImageStatus.waitingTask, eImageTask.processComplete, undefined, true, eSkippedCropReason.image) } static skipMultiPage(image: IImageModel): IImageModel { return Deserializer.getSerializerImg( image, eImageStatus.waitingTask, eImageTask.multipageConversion, undefined, true, eSkippedCropReason.multiPages) } static getCropAreasFromLastExist(newImage: IImageModel, image: IImageModel): IImageModel { newImage.cropAreasOriginId = image.id; if (newImage.reCalc) { const wasSkipped = image.skippedCrop && image.cropAreas.length == 1 && image.cropAreas[0].x == null && !image.activeUser; const wasSingleImage = typeof image.singleImage !== "undefined"; // assigned by user, can only do when image type != pdf/tiff const wasSkippedImageType = wasSkipped && image.cropAreas[0].imaginaryId == image.imaginaryIdOriginal; const keepCropAreaImaginaryId = wasSingleImage || wasSkippedImageType; const cropAreas = Deserializer.getCroppedData(image.cropAreas, keepCropAreaImaginaryId); // for multi page, we create a new imaginary in the cropArea const wasSkippedMultipage = wasSkipped && image.cropAreas[0].imaginaryId != image.imaginaryIdOriginal; return Deserializer.getSerializerImg( newImage, eImageStatus.waitingTask, wasSkippedMultipage ? eImageTask.multipageConversion : eImageTask.processComplete, cropAreas, true, eSkippedCropReason.reCalc) } else { const cropAreas = Deserializer.getCroppedData(image.cropAreas, true); return Deserializer.getSerializerImg(newImage, eImageStatus.waitingTask, eImageTask.processComplete, cropAreas) } } private static getSerializerImg( image: IImageModel, status: eImageStatus, nextTask: eImageTask, cropAreas: ICropArea[] = undefined, skippedCrop: boolean = undefined, skippedCropReason: eSkippedCropReason = undefined): IImageModel { const returnImg = _.cloneDeep(image); returnImg.skippedCrop = skippedCrop; returnImg.skippedCropReason = skippedCropReason; returnImg.status = status; returnImg.cropAreas = cropAreas ? cropAreas : [{ createdAt: new Date(), imaginaryId: returnImg.imaginaryIdOriginal}]; returnImg.nextTask = { task: nextTask, retries: 0}; return returnImg; } // most significant priority will have max value static entityPriorities(orderedEntities: string[]): IEntityPriority[] { if (orderedEntities == null || !(orderedEntities instanceof Array)) return; return orderedEntities .filter(entityId => typeof entityId === "string") .map((entityId: string, index: number, arr: string[]) => ({entityId, priority: (arr.length - index), consider: true}) ); } }
f6e140ae118485cbfd30362cede45f396003db9e
TypeScript
tbergqvist/noble-cream
/src/systems/render-player-stats-system.ts
2.515625
3
import {ISystem} from "../engine/isystem"; import {ScoreComponent, HealthComponent} from "../components"; import {requiredComponent} from "../engine/node"; import {Space} from "../engine/space"; import { GameCanvas } from "../game-canvas"; export class PlayerStatsNode { entityId: string; @requiredComponent score: ScoreComponent; @requiredComponent health: HealthComponent; } export function createRenderPlayerStatsSystem(_gameCanvas: GameCanvas) : ISystem { let _space: Space; let _playerScoreText = new PIXI.Text(""); let _playerHealthText = new PIXI.Text(""); _playerScoreText.y = _playerHealthText.y = 10; _playerScoreText.x = 0; _playerHealthText.x = 200; _gameCanvas.guiLayer.addChild(_playerScoreText); _gameCanvas.guiLayer.addChild(_playerHealthText); return { start(space: Space) { _space = space; }, enterFrame() { let player = _space.getNodeForEntity("player", PlayerStatsNode); _playerScoreText.text = `Score : ${player.score.score}`; _playerHealthText.text = `Health : ${player.health.healthLeft}`; } } }
986fdb10531c4d903e52702eae0e92805463d8f6
TypeScript
ajmesa9891/ngrx-generator
/templates/_reducer.ts
2.5625
3
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity'; import { {{ properCase name }} } from '{{position "models"}}/{{ kebabCase name }}.model'; import * as {{ camelCase name }} from '{{position "actions"}}/{{ kebabCase name }}.actions'; // Keep these 2 (and delete the other 3) exports if you are NOT creating a list. Remove this comment. export interface {{ properCase name }}State { loaded: boolean; loading: boolean; {{ camelCase name }}: {{ properCase name }} | null; } export const initialState: {{ properCase name }}State = { loaded: false, loading: false, {{ camelCase name }}: null, }; // Keep these 3 (and delete the other 2) exports if you are creating a list Remove this comment. export interface {{ properCase name }}State extends EntityState<{{ properCase name }}> { loaded: boolean; loading: boolean; } export const adapter: EntityAdapter<{{ properCase name }}> = createEntityAdapter<{{ properCase name }}>({ selectId: {{ first name }} => {{ first name }}.id, sortComparer: false, }); export const initialState: {{ properCase name }}State = adapter.getInitialState({ loaded: false, loading: false, }); export function reducer(state = initialState, action: {{ camelCase name }}.{{ properCase name }}Actions): {{ properCase name }}State { switch (action.type) { case {{ camelCase name }}.LOAD_{{ constantCase name }}: { return { ...state, loading: true } } case {{ camelCase name }}.LOAD_{{ constantCase name }}_SUCCESS: { return { ...state, // keep this and delete comment if you are NOT creating a list {{ camelCase name }}: action.payload, // keep this and delete comment if you are NOT creating a list ...adapter.addMany(action.payload, state), // keep this and delete comment if you are creating a list loaded: true, loading: false, }; } case {{ camelCase name }}.LOAD_{{ constantCase name }}_FAIL: { return { ...state, loaded: false, loading: false, }; } default: { return state; } } } export const get{{ properCase name }}Loaded = (state: {{ properCase name }}State) => state.loaded; export const get{{ properCase name }}Loading = (state: {{ properCase name }}State) => state.loading; export const get{{ properCase name }} = (state: {{ properCase name }}State) => state.{{ camelCase name }}; // keep this and delete comment if you are NOT creating a list
e5b5f4ba8c0a9f258124b917a2b25a111c35b2d9
TypeScript
Rhodanthe1116/lyrics-typing
/src/api/datasources/musixmatch.ts
2.515625
3
import { RESTDataSource, RequestOptions } from 'apollo-datasource-rest' import { Track, Lyrics } from 'shared/interfaces' import { MusixmatchTrackWrapperObject, MusixmatchAlbumWrapperObject, MusixmatchTrack, MusixmatchLyrics, MusixmatchAlbum, } from './interfaces' const apiKey = process?.env?.MUSIXMATCH_APIKEY || '' // interface MusixmatchResponse { // message: { // header: { // status_code: number, // } // body: any // } // } class MusixmatchAPI extends RESTDataSource { constructor() { super() this.baseURL = 'https://api.musixmatch.com/ws/1.1/' } willSendRequest(request: RequestOptions) { request.params.set('format', 'json') request.params.set('apikey', apiKey) } async didReceiveResponse(response: any) { const responseJson = await response.json() if (responseJson.message.header.status_code !== 200) { if (responseJson.message.header.status_code === 401) { throw new Error('no more free Musixmatch api call today 😢😢😢') } console.log(JSON.stringify(responseJson)) throw new Error('Unknown musixmatch error') } return responseJson.message.body } trackReducer(track: MusixmatchTrack) { return { id: track.track_id.toString(), name: track.track_name, artistName: track.artist_name, rating: track.track_rating, numFavourite: track.num_favourite, artistId: track.artist_id.toString(), albumId: track.album_id.toString(), albumName: track.album_name, } as Track } lyricsReducer(lyrics: MusixmatchLyrics) { return { id: lyrics.lyrics_id.toString(), body: lyrics.lyrics_body, language: lyrics.lyrics_language, copyright: lyrics.lyrics_copyright, updatedTime: lyrics.updated_time, } as Lyrics } albumReducer(album: MusixmatchAlbum) { return { id: album.album_id.toString(), name: album.album_name, trackCount: album.album_track_count, artistId: album.artist_id.toString(), coverart: album.album_coverart_100x100, } } async getChartTracks({ country }: { country: string }) { const body = await this.get('chart.tracks.get', { page_size: 10, country: country, f_has_lyrics: true, }) const trackList: MusixmatchTrackWrapperObject[] = body.track_list return Array.isArray(trackList) ? trackList.map((track) => this.trackReducer(track.track)) : [] } async searchTracks({ query, artistId }: { query: string; artistId: number }) { if (query) { const body = await this.get('track.search', { page_size: 10, q_track_artist: query, f_has_lyrics: true, s_track_rating: 'desc', }) const trackList: MusixmatchTrackWrapperObject[] = body.track_list return Array.isArray(trackList) ? trackList.map((track) => this.trackReducer(track.track)) : [] } else if (artistId) { const body = await this.get('track.search', { page_size: 5, f_artist_id: artistId, f_has_lyrics: true, s_track_rating: 'desc', }) const trackList: MusixmatchTrackWrapperObject[] = body.track_list return Array.isArray(trackList) ? trackList.map((track) => this.trackReducer(track.track)) : [] } } async getTrackById({ trackId }: { trackId: number }) { const body = await this.get('track.get', { track_id: trackId, }) return this.trackReducer(body.track) } async getLyricsByTrackId({ trackId }: { trackId: number }) { const body = await this.get('track.lyrics.get', { track_id: trackId, }) return this.lyricsReducer(body.lyrics) } async getTracksByAlbumId({ albumId, size, }: { albumId: number size: number }) { if (size) { const body = await this.get('album.tracks.get', { page_size: size, album_id: albumId, f_has_lyrics: true, }) const trackList: MusixmatchTrackWrapperObject[] = body.track_list return Array.isArray(trackList) ? trackList.map((track) => this.trackReducer(track.track)) : [] } else { const body = await this.get('album.tracks.get', { album_id: albumId, f_has_lyrics: true, }) const trackList: MusixmatchTrackWrapperObject[] = body.track_list return Array.isArray(trackList) ? trackList.map((track) => this.trackReducer(track.track)) : [] } } async getAlbumById({ albumId }: { albumId: number }) { const body = await this.get('album.get', { album_id: albumId, }) return this.albumReducer(body.album) } async getAlbumsByArtistId({ artistId }: { artistId: number }) { const body = await this.get('artist.albums.get', { artist_id: artistId, s_release_date: 'desc', }) const albumList: MusixmatchAlbumWrapperObject[] = body.album_list return Array.isArray(albumList) ? albumList.map((track) => this.albumReducer(track.album)) : [] } } module.exports = MusixmatchAPI
fe8a728ffa8bdc13f164ab9c95dab51c27824b10
TypeScript
2006NodeDev/tattooshop-booking-service
/src/routers/bookings-router.ts
2.640625
3
import express, {Request, Response, NextFunction} from 'express' import { InvalidIdError } from '../errors/InvalidIdError'; import { Bookings } from '../models/Bookings'; import { BookingInputError } from '../errors/BookingInputError'; import { getAllBookingsService, UpdateExistingBookingService, SubmitNewBookingService, findBookingByCustomerService, findBookingByArtistIdService, getAllShopsService } from '../services/booking-service'; //updateBooking //import { getAllBookingsService } from '../services/booking-service'; //import { authorizationMiddleWare } from '../middlewares/authorizationMiddleware'; //import { AuthenticationFailure } from '../errors/AuthenticationFailure'; /* BASIC FUNCTIONALITIES: 1.Submit Booking 2.Update Booking 3.Find Booking by ID 4.Find All Bookings */ export let bookingRouter = express.Router(); //bookingRouter.use(authenticationMiddleware) //updated this func to reflect booking DONE //authorizationMiddleWare(['admin']) bookingRouter.get('/' ,async (req:Request, res:Response, next:NextFunction)=>{ try { let booking = await getAllBookingsService() res.json(booking) } catch (error) { next(error) } }) //updates function name, exports, calls, and variables DONE // Updated booking fields per db PENDING bookingRouter.get('/customer/:userId', async(req:Request, res:Response, next:NextFunction)=>{ let {userId} = req.params if(isNaN(+userId)){ throw new InvalidIdError() } //else if(req.session.user.userId !== +userId && req.session.user.role === "user"){ //next(new AuthenticationFailure()) //} else { try { let bookingByUserId = await findBookingByCustomerService(+userId) res.json(bookingByUserId) } catch (error) { next(error) } } }) // Submit a booking bookingRouter.post('/newbooking', async(req:any, res:Response, next:NextFunction)=>{ console.log(req.body); let{ customer, style, size, location, imageTest, color, artist, shop, date } = req.body //let customer = req.user.user_id //console.log(author) if( !customer || !style || !size || !location){ next(new BookingInputError()) }else{ let newBooking: Bookings ={ bookingId: 0, customer, style, size, location, imageTest, color, artist, shop, date, } try { let submitBookingRes = await SubmitNewBookingService(newBooking) res.json(submitBookingRes) } catch (error) { next(error) } } }) // Update Booking patch //updates function name, exports, calls, and variables DONE // Updated booking fields per db PENDING // , authorizationMiddleWare(['admin', 'artist', 'customer']) bookingRouter.patch('/', async (req:Request, res:Response, next:NextFunction)=>{ let{ bookingId, customer, style, size, location, imageTest, color, artist, shop, date, } = req.body if(!bookingId || isNaN(bookingId)){ next (new InvalidIdError()); }else { let updatedBooking:Bookings ={ bookingId, customer, // req.session.user.user_id, style, size, location, imageTest, color, artist, shop, date, } updatedBooking.customer = customer || undefined updatedBooking.style = style || undefined updatedBooking.size = size updatedBooking.location = location || undefined updatedBooking.imageTest = imageTest || undefined updatedBooking.color = color || undefined updatedBooking.artist = artist || undefined updatedBooking.shop = shop || undefined updatedBooking.date = date || undefined try { let updatedBookingResults = await UpdateExistingBookingService(updatedBooking) res.json(updatedBookingResults) } catch (error) { next(error) } } }) //get booking by Artist bookingRouter.get('/artist/:userId', async(req:any, res:Response, next:NextFunction)=>{ let {userId} = req.params if(isNaN(+userId)){ throw new InvalidIdError() }else { try { let bookingByArtistId = await findBookingByArtistIdService(+userId) res.json(bookingByArtistId) } catch (error) { next(error) } } }) //get shop by Artist bookingRouter.get('/shops', async (req:Request, res:Response, next:NextFunction)=>{ try { let allShops = await getAllShopsService() res.json(allShops) } catch (error) { next(error) } })
dd5079f593a03c95bd6f4b2e5b0a954d1eae2c02
TypeScript
midhatdrops/rpg-sololeveling-generateitemroll
/src/Service/RegularRoll/translators/conditionTranslator.ts
2.921875
3
export function conditionTranslator(equipType: string, roll: number) { if (equipType === 'Arma') { if (roll >= 1 && roll < 7) { return { points: 0, useCondition: 'Ser Arma da Classe' }; } if (roll >= 7) { return { points: -5, useCondition: 'Ter Maestria com a Arma' }; } } else { switch (roll) { case 2: return { points: -5, useCondition: 'Ter no mínimo o valor do bônus em Força bruta', }; case 3: return { points: -5, useCondition: 'Ter no mínimo o valor do bônus em Agilidade bruta', }; case 4: return { points: -5, useCondition: 'Ter no mínimo o valor do bônus em Sentidos bruto', }; case 5: return { points: -5, useCondition: 'Ter no mínimo o valor do bônus em Inteligência bruta', }; case 6: return { points: -5, useCondition: 'Ter no mínimo o valor do bônus em Vitalidade bruta', }; case 7: return { points: 0, useCondition: 'Ter foco em Força' }; case 8: return { points: 0, useCondition: 'Ter foco em Sentidos' }; case 9: return { points: 0, useCondition: 'Ter foco em Agilidade' }; case 10: return { points: 0, useCondition: 'Ter foco em Inteligência' }; case 11: return { points: 0, useCondition: 'Ter foco em Vitalidade' }; case 12: return { points: -5, useCondition: 'Enquanto equipado, receba DoT I Veneno', }; case 13: return { points: -10, useCondition: 'Receba a penalidade' }; default: return { points: 10, useCondition: 'N/A' }; } } return { points: 0, useCondition: '' }; }
687900da4ba7377ddda91698dfcc3f85c14178e1
TypeScript
FrancisRoc/nhl-pool-api
/tests/features/step_definitions/utils.steps.ts
2.96875
3
import { utils } from "../../../src/utils/utils"; import * as Promise from "bluebird"; export default function () { const self = this; let stringToConvert: string; let result: boolean; self.Given(/^Le paramètre "str" est renseigné avec "([^"]*)"$/, function (valParam: string) { const promise = new Promise((resolve, reject) => { if (!valParam) { self.stringToConvert = null; } else { self.stringToConvert = valParam; } return resolve(); }); return promise; }); self.When(/^L'utilitaire de conversion est appelé$/, function () { const promise = new Promise((resolve, reject) => { self.result = utils.stringToBoolean(self.stringToConvert); self.expect(self.result).to.not.equal(null); return resolve(); }); return promise; }); self.Then(/^Le résultat devrait être (true|false)$/, function (param: string) { const promise = new Promise((resolve, reject) => { let expectedResult: boolean; if (param === "true") { expectedResult = true; } else if (param === "false") { expectedResult = false; } else if (param === "1") { expectedResult = true; } else { expectedResult = false; } self.expect(self.result).to.equal(expectedResult); return resolve(); }); return promise; }); }
a465999da3e438e4a833ff073b29e0e197209e93
TypeScript
TFrascaroli/definition-header
/src/utils.ts
2.9375
3
/// <reference path="./../typings/tsd.d.ts" /> 'use strict'; var lineExp = /\r?\n/g; export interface Position { column: number; line: number; } export function getPosition(stream: string, index: number): Position { var position: Position = { column: 0, line: 0 }; var match: RegExpExecArray; var nextLineStart = 0; lineExp.lastIndex = 0; index = Math.min(index, stream.length - 1); while ((match = lineExp.exec(stream))) { if (lineExp.lastIndex > index) { position.column = index - nextLineStart; return position; } position.line += 1; nextLineStart = lineExp.lastIndex; } position.column = index - nextLineStart; return position; } export function getLinesAt(stream: string, start: number, end: number = 0): string[] { // TODO improve line grabber (remove horrible split for top-down line parser) var arr = stream.split(lineExp); start = Math.max(start, 0); if (!end) { end = arr.length - 1; } else { end = Math.min(end, arr.length - 1); } end = Math.max(end, start + 1); return arr.slice(start, end + 1); } export function untrail(str: string): string { if (typeof str !== 'string') { return String(str); } return str.replace(/\/$/, ''); } var longString = '----------------------------------------'; export function charPointer(column: number): string { if (longString.length < column) { for (var i = longString.length; i < column; i++) { longString += '-'; } } return longString.substr(0, column) + '^'; } // TODO harden for deeper lines export function highlightPos(stream: string, line: number, column?: number): string { var lines = getLinesAt(stream, 0, line + 2); if (typeof column === 'number') { lines.splice(line + 1, 0, charPointer(column)); } return lines.join('\n'); } export function linkPos(dest: string, line?: number, column?: number, oneBased: boolean = false): string { if (typeof column !== 'number') { column = 0; } if (typeof line !== 'number') { line = 0; } if (oneBased) { column += 1; line += 1; } // return path.resolve(dest) + '[' + line + ',' + column + ']'; return dest + '[' + line + ',' + column + ']'; }
5f7274bc1fdd7c5d63056870af2b46763a9ebfe1
TypeScript
MihirJayavant/chat-api
/src/api-models/Login.ts
2.75
3
import { IsNotEmpty, IsString, Length } from 'class-validator' export class LoginModel { @IsNotEmpty() @IsString() @Length(3, 50) username: string @IsNotEmpty() @IsString() @Length(5, 20) password: string } export function createLoginModel(data: any): LoginModel { const { username, password } = data const model = new LoginModel() model.password = password model.username = username return model }
72eaf6a5ab88125ae5c38f39babab9e5bb6d62c3
TypeScript
ZeroDAO/socircles-backend
/src/app/comm/utils.ts
2.609375
3
import { Inject, Provide } from '@midwayjs/decorator'; import * as ipdb from 'ipip-ipdb'; import * as _ from 'lodash'; import { Context } from 'egg'; import * as createKeccakHash from 'keccak'; /** * 帮助类 */ @Provide() export class Utils { @Inject() baseDir; /** * 获得请求IP */ async getReqIP(ctx: Context) { const req = ctx.req; return ( req.headers['x-forwarded-for'] || req.socket.remoteAddress.replace('::ffff:', '') ); } /** * 根据IP获得请求地址 * @param ip 为空时则为当前请求的IP地址 */ async getIpAddr(ctx: Context, ip?: string | string[]) { try { if (!ip) { ip = await this.getReqIP(ctx); } const bst = new ipdb.BaseStation( `${this.baseDir}/app/comm/ipipfree.ipdb` ); const result = bst.findInfo(ip, 'CN'); const addArr: any = []; if (result) { addArr.push(result.countryName); addArr.push(result.regionName); addArr.push(result.cityName); return _.uniq(addArr).join(''); } } catch (err) { return '无法获取地址信息'; } } /** * 去除对象的空值属性 * @param obj */ async removeEmptyP(obj) { Object.keys(obj).forEach(key => { if (obj[key] === null || obj[key] === '' || obj[key] === 'undefined') { delete obj[key]; } }); } /** * 线程阻塞毫秒数 * @param ms */ sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } /** * 是否为数字 * @param obj */ isNmber(obj) { if(typeof obj === 'number') { return !isNaN(obj) } else if(typeof obj === 'string'){ return /^[0-9]*$/.test(obj) } return false; } /** * 是否为ETH系地址 * @param address */ isEthAddress(address) { return /^(0x)?[0-9a-fA-F]{40}$/.test(address); } /** * 将地址转换为 EIP-55 格式 * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md * @param address */ toChecksumAddress(address) { address = address.toLowerCase().replace("0x", ""); var hash = createKeccakHash("keccak256").update(address).digest("hex"); var ret = "0x"; for (var i = 0; i < address.length; i++) { if (parseInt(hash[i], 16) >= 8) { ret += address[i].toUpperCase(); } else { ret += address[i]; } } return ret; } }
203ae408fb6c6155252493e181e035bacc5e6032
TypeScript
VanHouten97/simaze-server
/src/lib/config.ts
2.671875
3
import { Error } from '@interfaces'; export const database = { host: 'localhost', port: 27017, dbName: 'simaze', dbUser: 'fl0ppy', dbPass: 'zootek%402018' }; export const secret = 'zootek2018@smz'; export function err(e: number, d?: any): Error { function model(n: number, d: any, internal?: any): Error { if (internal) { return { err: n, data: d, internal: internal }; } return { err: n, data: d }; } switch (e) { // Validação do usuário case 0x00000: return model(e, d); case 0xFFFFF: return model(e, { msg: "Erro interno." }, d); case 0x00001: return model(e, { msg: 'Nome completo deve estar entre 10-60 caracteres.' }); case 0x00002: return model(e, { msg: 'Nome completo não pode conter numeros ou caracteres especiais.' }); case 0x00003: return model(e, { msg: 'CPF deve conter 11 caracteres.' }); case 0x00004: return model(e, { msg: 'CPF deve conter apenas numeros' }); case 0x00005: return model(e, { msg: 'Email deve estar entre 5-40 caracteres.' }); case 0x00006: return model(e, { msg: 'Email inválido.' }); case 0x00007: return model(e, { msg: 'Nome de exibição deve conter entre 5-20 caracteres.' }); case 0x00008: return model(e, { msg: 'Nome de exibição não pode conter numeros ou caracteres especiais.' }); case 0x00009: return model(e, { msg: 'Data inválida.' }); case 0x0000A: return model(e, { msg: 'Data de nascimento inválida.' }); case 0x0000B: return model(e, { msg: 'Telefone inválido.' }); case 0x0000C: return model(e, { msg: 'Cargo deve conter entre 5-15 caracteres.' }); case 0x0000D: return model(e, { msg: 'Cargo não pode conter numeros ou caracteres especiais.' }); case 0x0000E: return model(e, { msg: 'Admissão inválida.' }); case 0x0000F: return model(e, { msg: 'Cargo deve conter entre 3-10 caracteres.' }); case 0x00010: return model(e, { msg: 'Gênero deve ser M ou F.' }); case 0x00011: return model(e, { msg: 'Estado deve conter 2 caracteres.' }); case 0x00012: return model(e, { msg: 'Cidade deve conter entre 3-20 caracteres.' }); case 0x00013: return model(e, { msg: 'Cidade não pode conter numeros ou caracteres especiais.' }); case 0x00014: return model(e, { msg: 'Bairro deve conter entre 3-20 caracteres.' }); case 0x00015: return model(e, { msg: 'Bairro não pode conter numeros ou caracteres especiais.' }); case 0x00016: return model(e, { msg: 'Rua deve conter entre 3-40 caracteres.' }); case 0x00017: return model(e, { msg: 'Rua não pode conter numeros ou caracteres especiais.' }); case 0x00018: return model(e, { msg: 'Endereço n° deve conter menos de 12 caracteres.' }); case 0x00019: return model(e, { msg: 'Endereço n° deve ser um numero' }); case 0x0001A: return model(e, { msg: 'Complemento deve conter menos de 10 caracteres.' }); case 0x0001B: return model(e, { msg: 'Complemento não pode conter caracteres especiais.' }); case 0x0001C: return model(e, { msg: 'CEP deve conter 8 caracteres.' }); case 0x0001D: return model(e, { msg: 'CEP° deve ser numérico.' }); case 0x0001E: return model(e, { msg: 'Senha muito grande.' }); case 0x0001F: return model(e, { msg: 'Informações obrigatórias não preenchidas.' }); } }
ab46763b70266861e4348b14aee98bb7df7fec8f
TypeScript
sh33dafi/adventofcode2020
/day2/solution.ts
3.1875
3
const normalizeInput = (input: string): Array<any> => { const normalizeChar = (char: string): string => { return char.replace(':', ''); }; const normalizeNumbers = (occurrence: string): Array<number> => { return occurrence.split('-').map(v => parseInt(v, 10)); }; const [occurrence, char, password] = input.split(' '); return [...normalizeNumbers(occurrence), normalizeChar(char), password]; } export const validatePassWordOccurrence = (passWithPolicy: string): boolean => { const [min, max, char, password] = normalizeInput(passWithPolicy); const charCount = countChar(password, char); return min <= charCount && charCount <= max; }; export const validatePassWordPosition = (passWithPolicy: string): boolean => { const [pos1, pos2, char, password] = normalizeInput(passWithPolicy); const charMatchAtPos1 = password[pos1 - 1] === char; const charMatchAtPos2 = password[pos2 - 1] === char; return ( charMatchAtPos1 || charMatchAtPos2 ) && !( charMatchAtPos1 && charMatchAtPos2 ); }; const countChar = (value: string, char: string): number => { return value.split('').filter(v => v === char).length; }; export const countValidPasswords = (input: Array<string>, policy: Function): number => { return input.filter(password => policy(password)).length; };