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
d19a4f831e4157241a16ac0136c918320d46f07b
TypeScript
jasper7466/mf.messenger.praktikum.yandex
/src/modules/Component.ts
2.8125
3
import EventBus from './EventBus'; import Store from './Store'; import {PlainObject} from "../types"; type Property = Record<string, any>; interface Meta { tagName: string; props: Property; storePath: string | null; } const store = new Store(); export default class Component { static EVENTS = { CONSTRUCTED: 'construction-done', // Завершена работа конструктора INITIALISED: 'flow:component-did-init', // Завершена инициализация UPDATED: 'flow:component-did-update', // Обновлены параметры компонента COMPILED: 'flow:component-did-compile', // Выполнена сборка компонента MOUNTED: 'status:component-did-mount', // Компонент смонтирован UNMOUNTED: 'status:component-did-unmount' // Компонент демонтирован }; private readonly _meta: Meta; // Мета-данные private readonly _props: {}; // Свойства private _element: HTMLElement; // Корневой HTML-элемент protected _parentNode: HTMLElement | null = null; // Родительский узел в DOM-дереве public eventBus: EventBus; // Внутренняя шина событий жизненного цикла /** * Создаёт экземпляр класса компонента * @param props * @param storePath * @param tagName */ constructor(props = {}, storePath: string | null = null, tagName = 'div') { this.eventBus = new EventBus(); this._meta = { tagName, props, storePath }; this._props = this._makePropsProxy(props); this._registerEvents(); this.eventBus.emit(Component.EVENTS.CONSTRUCTED); } /** * Регистрирует цепочки методов жизненного цикла компонента на внутренней шине событий * @protected */ protected _registerEvents() { // Создание и инициализация, первичная компиляция this.eventBus.subscribe(Component.EVENTS.CONSTRUCTED, this._init.bind(this)); this.eventBus.subscribe(Component.EVENTS.INITIALISED, this._compile.bind(this, true)); // Компиляция при изменениях свойств this.eventBus.subscribe(Component.EVENTS.UPDATED, this._compile.bind(this)); } /** * Инициализирует компонент * @protected */ protected _init() { this._element = document.createElement(this._meta.tagName); if (this._meta.props.hasOwnProperty('classList')) this._meta.props.classList.forEach((className: string) => this._element.classList.add(className)); // Установка наследования всех стилей родителя, чтобы не ломалась вёрстка this._element.setAttribute('style', 'all: inherit'); if (this._meta.storePath) store.subscribe(this._meta.storePath, () => this.eventBus.emit(Component.EVENTS.UPDATED)); this.eventBus.emit(Component.EVENTS.INITIALISED); } /** * Компилирует вёрстку элемента. В приоритете получение свойств из хранилища (если указан путь) * @force - флаг, указывающий на необходимость компиляции, даже если компонент не смонтирован (по умолчанию false) * @protected */ protected _compile(force = false) { // Игнорируем компиляцию, если компонент никуда не смонтирован и не требуется принудительная компиляция force; // if (!this._parentNode && !force) // return; this.beforeCompile(); if (this._meta.storePath) { this._meta.props = (store.get(this._meta.storePath) as Property) || this._meta.props; } const block = this.compile(this._meta.props); if (this._element) { this._element.innerHTML = block; } this.afterCompile(); this.eventBus.emit(Component.EVENTS.COMPILED); } /** * Переопределяемый метод, который получает на вход контекст и должен на выходе вернуть вёрстку компонента * @param context - контекст компиляции */ protected compile(context: PlainObject): string | never { console.log(context); throw new Error(`${this.constructor.name}: Method "compile" must be redefined`); } /** * Помещает корневой элемент компонента в качестве дочернего для указанного DOM-узла * @param parentNode - родительский узел * @protected */ protected mount(parentNode: HTMLElement): void { this.beforeMount(); if (this._parentNode) throw new Error(`${this.constructor.name}: Component is already mounted`); parentNode.appendChild(this._element); this._parentNode = parentNode; this.afterMount(); this.eventBus.emit(Component.EVENTS.MOUNTED); } /** * Открепляет корневой элемент компонента от родительского DOM-узла * @protected */ unmount(): void { if (!this._parentNode) return; this.beforeUnmount(); this._parentNode.removeChild(this._element); this._parentNode = null; this.afterUnmount(); this.eventBus.emit(Component.EVENTS.UNMOUNTED); } /** * Подписывает переданный родительский компонент на событие обновления свойств настоящего компонента. * @param parent - родительский компонент */ bindParent(parent: Component) { if (this._meta.storePath) store.subscribe(this._meta.storePath, () => parent.eventBus.emit(Component.EVENTS.UPDATED)); } /** * Добавляет свойства компоненту * @param nextProps - объект со свойствами */ public setProps = (nextProps: object) => { if (!nextProps) { return; } Object.assign(this._props, nextProps); }; /** * Возвращает корневой HTML-элемент компонента */ public get element() { return this._element; } /** * Отображает скрытый компонент путём установки CSS-свойства "display" в значение "block". * DOM-дерево не модифицируется */ public show() { const element = this.element; if (element) element.style.display = "block"; } /** * Скрывает компонент путём установки CSS-свойства "display" в значение "none". * Вёрстка остаётся в DOM-дереве */ public hide() { const element = this.element; if (element) element.style.display = "none"; } /** * Необязательный переопределяемый метод для выполнения дополнительных действий перед компиляцией */ protected beforeCompile() {} /** * Необязательный переопределяемый метод для выполнения дополнительных действий после компиляции */ protected afterCompile() {} /** * Необязательный переопределяемый метод для выполнения дополнительных действий перед монтированием */ protected beforeMount() {} /** * Необязательный переопределяемый метод для выполнения дополнительных действий после монтирования */ protected afterMount() {} /** * Необязательный переопределяемый метод для выполнения дополнительных действий перед размонтированием */ protected beforeUnmount() {} /** * Необязательный переопределяемый метод для выполнения дополнительных действий после размонтирования */ protected afterUnmount() {} /** * Делает прокси-обёртку для параметров компонента. * После перезаписи параметра прокси инициирует соответствующее событие. * При попытке удаления свойства - прокси выбросит исключение * @param props - объект с параметрами * @protected */ protected _makePropsProxy(props: object) { const self = this; return new Proxy(props, { set(target: any, prop: any, val) { target[prop] = val; self.eventBus.emit(Component.EVENTS.UPDATED); return true; }, deleteProperty() { throw new Error(`${this.constructor.name}: Proxy. Component property deletion is prohibited`); } }); } }
4e978c402beea00472030a4082e7772b716317e2
TypeScript
HerrLoesch/ionic-rc2-workshop-devmedia
/src/providers/movies.ts
2.65625
3
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { forEach } from 'lodash'; import { Movie } from '../domain/Movie'; import {MovieConverter} from '../domain/MovieConverter'; @Injectable() export class Movies { constructor(public http: Http) { } public search(searchText: string){ return new Promise( resolve => { let url = 'http://www.omdbapi.com/?s=' + searchText; this.http.get(url) .map(this.map) .subscribe(data => resolve(data)); }); } map(data:any): Array<Movie>{ let result = new Array<Movie>(); let jsonData = data.json().Search; forEach(jsonData, element => { let movie = MovieConverter.create(element); result.push(movie); }); return result; } public getMovie(id: string){ console.log("Get movie: " + id); return new Promise( resolve => { let url = 'http://www.omdbapi.com/?i=' + id; this.http.get(url) .map(result => { return result.json(); }) .subscribe(data => resolve(data)); }); } }
f72f23079ae39cc371c32c04f2157c6a949eefba
TypeScript
kacchan6/grid-layout
/src/tokenizer/track.ts
3.078125
3
import { Tokenizer } from './base'; const trackListSplitChars = '()[],/'; export class TrackTokenizer extends Tokenizer { getTokens(): string[] { const tokens: string[] = []; let token: string = ''; let index: number = 0; while (index < this.length) { const char = this.text[index]; const isWhitespace = this.isWhitespace(char); if (isWhitespace || trackListSplitChars.indexOf(char) > -1) { if (token) { tokens.push(token); token = ''; } index++; if (!isWhitespace) { tokens.push(char); } continue; } token += char; index++; } if (token) { tokens.push(token); } return tokens; } }
d5f116e01a839eb314cd3b849887b40fc7b5b08e
TypeScript
Jhonatangiraldo/statistics-people
/src/app/people-presentation/people-presentation.component.ts
2.703125
3
import { PeopleState } from './../reducer/appStates'; import { SETPEOPLE } from './../reducer/reducer'; import { Person } from './../models/person'; import { PeopleService } from './../services/people.service'; import { Component, OnInit } from '@angular/core'; import { Store } from '@ngrx/store'; const MALE = 'Male'; const FEMALE = 'Female'; const WORKING = 'Working'; const NOTWORKING = 'Not Working'; const M = 'M'; const F = 'F'; @Component({ selector: 'app-people-presentation', templateUrl: './people-presentation.component.html', styleUrls: ['./people-presentation.component.css'] }) export class PeoplePresentationComponent implements OnInit { private people: Person[]; private peopleStore: Store<{}>; //Pie chart public pieChartLabelsSex:string[]; public pieChartDataSex:number[]; public pieChartLabelsIsWorking:string[]; public pieChartDataIsWorking:number[]; //Radar chart public radarChartLabels: string[]; public radarChartData: object[]; constructor( private peopleService: PeopleService, private store:Store<PeopleState> ) { this.peopleStore = this.store.select('people'); } ngOnInit() { this.people = []; this.setReducerSubscription(); this.setLabels(); this.getData(); } private setReducerSubscription(): void { this.peopleStore.subscribe( (result: Person[]) => { this.people = result this.getPieChartData(); this.getRadarChartData(); }); } private setLabels(): void { this.pieChartLabelsSex = [MALE, FEMALE]; this.pieChartLabelsIsWorking = [WORKING, NOTWORKING]; this.radarChartLabels = [WORKING, 'Over Eighteen', NOTWORKING, 'Not over Eighteen']; } private getData(): void { this.peopleService.getPeople().subscribe( (result: Person[]) => { this.store.dispatch({ type: SETPEOPLE, payload: result}); }); } private getPieChartData(): void { let Male = this.people.filter((person) => person.gender === M).length; let feMale = this.people.filter((person) => person.gender === F).length; let working = this.people.filter((person) => person.isWorking === true).length; let notWorking = this.people.filter((person) => person.isWorking === false).length; this.pieChartDataSex = [Male, feMale]; this.pieChartDataIsWorking = [working, notWorking]; } private getRadarChartData(): void { // Male let workingM = this.people.filter((person) => person.isWorking === true && person.gender === M).length; let notWorkingM = this.people.filter((person) => person.isWorking === false && person.gender === M).length; let overEighteenM = this.people.filter((person) => person.age >= 18 && person.gender === M).length; let notOverEighteenM = this.people.filter((person) => person.age < 18 && person.gender === M).length; // Female let workingF = this.people.filter((person) => person.isWorking === true && person.gender === F).length; let notWorkingF = this.people.filter((person) => person.isWorking === false && person.gender === F).length; let overEighteenF = this.people.filter((person) => person.age >= 18 && person.gender === F).length; let notOverEighteenF = this.people.filter((person) => person.age < 18 && person.gender === F).length; this.radarChartData = [ { data: [ workingM, overEighteenM, notWorkingM, notOverEighteenF ], label: MALE }, { data: [ workingF, notWorkingF, overEighteenF, notOverEighteenF ], label: FEMALE }, ]; } }
0c0f26f9c7996d266d673de71f30b3423a6ec586
TypeScript
jpdenford/advent-of-code-2020
/src/day4/passportProcessing.ts
2.9375
3
import R from 'ramda' import { readFile, readFileLines } from '../fileUtils' const passportDetails = (contents: string) => R.pipe(R.split(/\s+/), R.map(R.split(':')), Object.fromEntries)(contents) const REQUIRED_FIELDS = ['ecl', 'pid', 'eyr', 'hcl', 'byr', 'iyr', 'hgt'] const chunkPassports = (fileContents: string) => R.pipe(R.split('\n\n'), R.map(R.replace(/\n/g, ' ')))(fileContents) const hasAllProperties = (required: string[]) => (obj: object) => { const keys = Object.entries(obj) .filter((kv) => !!kv[1]) .map((kv) => kv[0]) return R.all((r) => keys.includes(r), required) } export const betweenIncl = (min: number, max: number) => R.pipe( (i: string) => parseInt(i), (num) => num >= min && num <= max ) export const validateHeight = R.allPass([ R.complement(R.isNil), (hgt: string) => { // TODO probably a nicer way to do this whole thing with cond const cmGroups = [...(hgt.match(/([0-9]+)cm/) ?? [])] const inGroups = [...(hgt.match(/([0-9]+)in/) ?? [])] const cms = cmGroups[1] const inchs = inGroups[1] return cms ? betweenIncl(150, 193)(cms) : betweenIncl(59, 76)(inchs) }, ]) export const validatePassport = R.allPass([ R.pipe(R.prop('byr'), betweenIncl(1920, 2002)), R.pipe(R.prop('iyr'), betweenIncl(2010, 2020)), R.pipe(R.prop('eyr'), betweenIncl(2020, 2030)), R.pipe(R.prop('hgt'), validateHeight), R.pipe(R.prop('hcl'), (hcl: string) => /^#[0-9,a-f]{6}$/.test(hcl)), R.pipe(R.prop('ecl'), (ecl: string) => /^(amb|blu|brn|gry|grn|hzl|oth)$/.test(ecl) ), R.pipe(R.prop('pid'), (ecl: string) => /^[0-9]{9}$/.test(ecl)), ]) export const rawInputToPassports = R.pipe( chunkPassports, R.map(passportDetails) ) export const main1 = R.pipe( readFile, rawInputToPassports, R.map(hasAllProperties(REQUIRED_FIELDS)), R.filter(R.identity), R.length ) export const main2 = R.pipe( readFile, rawInputToPassports, R.map(validatePassport), R.filter(R.identity), R.length )
b6c6ad52049fb5f62ace4616be315d2cbdc37d29
TypeScript
vittorfigueiredo/crud-nestjs
/src/user/create-user-dto.ts
2.546875
3
/** * DTO são os dados modelados e prontos que são passados pela rede, * mais especificamente, ente o service e o controller. */ export class CreateUserDto { name: string; email: string; }
d4ab928824f733750ff91902b6491378db2874d9
TypeScript
zimejin/SlagalicaGame
/apps/slagalica-api/src/app/models/multiplayer-game-result.model.ts
2.59375
3
import { model, Schema, Document } from 'mongoose'; import { MultiplayerGame as IMultiplayerGame, PlayerRole } from '@slagalica/data'; import moment from 'moment'; type MultiplayerGameResult = IMultiplayerGame & Document; export const MultiplayerGameResultSchema = new Schema({ red: { type: Schema.Types.ObjectId, ref: 'users' }, blue: { type: Schema.Types.ObjectId, ref: 'users' }, redPoints: Number, bluePoints: Number, won: { type: String, enum: [PlayerRole.Red, PlayerRole.Blue] }, played_at: { type: Date, default: moment().format() } }); export const MultiplayerGameResultModel = model<MultiplayerGameResult>( 'multiplayer_game_results', MultiplayerGameResultSchema ); export async function getAllMultiplayerGameResults() { return MultiplayerGameResultModel.find({}).populate( 'red', 'userName', 'users' ); } export async function createMultiplayerGameResult(game: IMultiplayerGame) { return new MultiplayerGameResultModel(game).save(); } function getLast10DaysCondition() { const start = moment() .startOf('day') .subtract(10, 'days') .toDate(); const end = moment() .endOf('day') .toDate(); return { $gte: start, $lt: end }; } export async function getAllUserMultiplayerGameResults(userId: string) { return MultiplayerGameResultModel.find({ $and: [ { $or: [{ red: userId }, { blue: userId }] }, { played_at: getLast10DaysCondition() } ] }) .populate('red') .populate('blue') .exec(); }
2aae72344334f2d4f4ea44e4a9ac226d74c0ad11
TypeScript
hive-lang/hive-lang
/src/functional/collections/assoc-lists/lookup.spec.ts
2.609375
3
import { expect } from "chai"; import { lookup } from './lookup'; import { assocFromObject } from "./assoc-list"; describe('function/collections/asssoc-lists/lookup', function() { it('finds nothing in null', function() { expect(lookup(null, 'a')).equals(null); }); it('finds nothing if key missing', function() { expect(lookup(assocFromObject({a: 1, b: 2, c: 3}), 'd')) .equals(null); }); it('finds value for key', function() { expect(lookup(assocFromObject({a: 1, b: 2, c: 3}), 'b')) .equals(2); }); });
196283abc7a76df014a95c00cdf0bf4c11d33d61
TypeScript
felipeneuhauss/tech-challenge-backend
/src/lib/actors.ts
2.984375
3
import { knex } from '../util/knex' import { Movie } from './movies' import Knex from "knex"; export interface Actor { id: number name: string bio: string born_at: Date } export interface FavouriteGenre { name: string appearances: number } export function list(): Promise<Actor[]> { return knex.from('actor').select() } export function find(id: number): Promise<Actor> { return knex.from('actor').where({ id }).first() } /** @returns whether the ID was actually found */ export async function remove(id: number): Promise<boolean> { const count = await knex.from('actor').where({ id }).delete() return count > 0 } /** @returns the ID that was created */ export async function create(name: string, bio: string, bornAt: Date): Promise<number> { const [ id ] = await (knex.into('actor').insert({ name, bio, born_at: bornAt })) return id } /** @returns whether the ID was actually found */ export async function update(id: number, name: string, bio: string, bornAt: Date): Promise<boolean> { const count = await knex.from('actor').where({ id }).update({ name, bio, born_at: bornAt }) return count > 0 } /** * Return a list of characters given an actor * @param actorId */ export function characters(actorId: number): Promise<any[]> { return knex.from('cast').where('actor_id', actorId).select('character_name') } /** @returns the ID that was created */ export async function createCharacter(actor_id: number, movie_id: number, characterName: string): Promise<number> { const [ id ] = await (knex.into('cast').insert({ actor_id, movie_id, character_name: characterName })) return id } /** @returns the actor's movies **/ export async function movies(actorId: number): Promise<Movie[]> { return knex.table('movie').select( 'movie.id', 'movie.name', 'movie.synopsis', 'movie.runtime', {genre_name: 'genre.name'}) .innerJoin('cast', 'movie.id', 'cast.movie_id') .innerJoin('genre', 'genre.id', 'movie.genre_id') .where('cast.actor_id', actorId) } /** @returns the actor's favourite genre **/ export async function favouriteGenre(actorId: number): Promise<FavouriteGenre[]> { return knex.table('movie').select( 'genre.name', knex.raw('sum(movie.appearances) as appearances')) .innerJoin('cast', 'movie.id', 'cast.movie_id') .innerJoin('genre', 'genre.id', 'movie.genre_id') .where('cast.actor_id', actorId) .groupBy('genre.name') .orderBy('appearances', 'desc') .limit(1) }
6f9c8fb36854c324871c2b87de498da9439f0826
TypeScript
LloydTDavies/angular-fitness
/src/app/store/actions/training.actions.ts
2.703125
3
import { Action } from '@ngrx/store'; import { Exercise } from 'src/app/training/exercise.model'; export enum TrainingActionTypes { SetAvailableTraining = '[Training] Set Available Training', SetFinishedTraining = '[Training] Set Finished Training', StartTraining = '[Training] Start Training', StopTraining = '[Training] Stop Training' } export class SetAvailableTraining implements Action { readonly type = TrainingActionTypes.SetAvailableTraining; constructor(public payload: Exercise[]) {} } export class SetFinishedTraining implements Action { readonly type = TrainingActionTypes.SetFinishedTraining; constructor(public payload: Exercise[]) {} } export class StartTraining implements Action { readonly type = TrainingActionTypes.StartTraining; constructor(public payload: string) {} } export class StopTraining implements Action { readonly type = TrainingActionTypes.StopTraining; } export type TrainingActions = SetAvailableTraining | SetFinishedTraining | StartTraining | StopTraining;
ddd26e4901483b4d3bf209d19c6e04e07ef78640
TypeScript
atsumaru/mv-plugins
/src/AtsumaruGlobalServerVariable.ts
3.171875
3
/*: * @plugindesc RPGアツマールのグローバルサーバー変数のためのプラグインです * @author RPGアツマール開発チーム * * @param value * @type variable * @text 現在値 * @desc グローバルサーバー変数の取得時に、現在値を代入する変数の番号を指定します。 * @default 0 * * @param minValue * @type variable * @text 最小値 * @desc グローバルサーバー変数の取得時に、最小値を代入する変数の番号を指定します。 * @default 0 * * @param maxValue * @type variable * @text 最大値 * @desc グローバルサーバー変数の取得時に、最大値を代入する変数の番号を指定します。 * @default 0 * * @param name * @type variable * @text 変数名 * @desc グローバルサーバー変数の取得時に、変数名を代入する変数の番号を指定します。 * @default 0 * * @param errorMessage * @type variable * @text エラーメッセージ * @desc エラーが発生した場合に、エラーメッセージを代入する変数の番号を指定します。 * @default 0 * * @help * このプラグインは、アツマールAPIの「グローバルサーバー変数」を利用するためのプラグインです。 * 詳しくはアツマールAPIリファレンス(https://atsumaru.github.io/api-references/global-server-variable)を参照してください。 * * プラグインコマンド(英語版と日本語版のコマンドがありますが、どちらも同じ動作です): * TriggerCall <triggerId> * トリガー発動 <triggerId> * # 指定した<triggerId>の「固定値を増減」トリガーを発動させる * # 例: TriggerCall 1 * # : トリガー発動 1 * * TriggerCall <triggerId> <valueVariableId> * トリガー発動 <triggerId> <valueVariableId> * # 変数<valueVariableId>から値を読み取り、指定した<triggerId>の「最大値・最小値の範囲で増減」トリガー、または「値を代入」型トリガーを発動させる * # 例: TriggerCall 1 5 * # : トリガー発動 1 5 * * TriggerCallByName <globalServerVariableName> <triggerName> * 名前でトリガー発動 <globalServerVariableName> <triggerName> * # 指定した<globalServerVariableName> <triggerName>の「固定値を増減」トリガーを発動させる * # 例: TriggerCallByName 変数1 トリガー名1 * # : 名前でトリガー発動 変数1 トリガー名1 * * TriggerCallByName <globalServerVariableName> <triggerName> <valueVariableId> * 名前でトリガー発動 <globalServerVariableName> <triggerName> <valueVariableId> * # 変数<valueVariableId>から値を読み取り、指定した<globalServerVariableName> <triggerName>の「最大値・最小値の範囲で増減」トリガー、または「値を代入」型トリガーを発動させる * # 例: TriggerCallByName 変数1 トリガー名1 5 * # : 名前でトリガー発動 変数1 トリガー名1 5 * * GetGlobalServerVariable <globalServerVariableId> * グローバルサーバー変数取得 <globalServerVariableId> * # グローバルサーバー変数<globalServerVariableId>の情報(現在値・最小値・最大値・変数名)を読み込み、 * プラグインパラメータで指定した変数に値をセットする。 * # 例: GetGlobalServerVariable 1 * # : グローバルサーバー変数取得 1 * * GetGlobalServerVariableByName <globalServerVariableName> * 名前でグローバルサーバー変数取得 <globalServerVariableName> * # グローバルサーバー変数<globalServerVariableName>の情報(現在値・最小値・最大値・変数名)を読み込み、 * プラグインパラメータで指定した変数に値をセットする。 * # 例: GetGlobalServerVariableByName 変数1 * # : 名前でグローバルサーバー変数取得 変数1 * * アツマール外(テストプレイや他のサイト、ダウンロード版)での挙動: * TriggerCall(トリガー発動) * 無視される(エラーメッセージにも何も代入されない) * GetGlobalServerVariable(グローバルサーバー変数取得) * 無視される(エラーメッセージにも何も代入されない) * * ※「並列処理」の中でプラグインコマンドを利用しますと * その時セーブしたセーブデータの状態が不確定になりますので、 * 可能な限り「並列処理」以外のトリガーでご利用ください。 */ import { toInteger, toNatural, toValidVariableIdOrUndefined, toTypedParameters, ensureValidVariableIds } from "./utils/parameter"; import { addPluginCommand, prepareBindPromise } from "./utils/rmmvbridge"; interface Parameters { value: number minValue: number maxValue: number name: number errorMessage: number } declare const window: Window; const parameters = toTypedParameters(PluginManager.parameters("AtsumaruGlobalServerVariable")) as Parameters; const globalServerVariable = window.RPGAtsumaru && window.RPGAtsumaru.globalServerVariable; const triggerCall = globalServerVariable && globalServerVariable.triggerCall; const triggerCallByName = globalServerVariable && globalServerVariable.triggerCallByName; const getGlobalServerVariable = globalServerVariable && globalServerVariable.getGlobalServerVariable; const getGlobalServerVariableByName = globalServerVariable && globalServerVariable.getGlobalServerVariableByName; ensureValidVariableIds(parameters); prepareBindPromise(); addPluginCommand({ TriggerCall, "トリガー発動": TriggerCall, TriggerCallByName, "名前でトリガー発動": TriggerCallByName, GetGlobalServerVariable, "グローバルサーバー変数取得": GetGlobalServerVariable, GetGlobalServerVariableByName, "名前でグローバルサーバ変数取得": GetGlobalServerVariableByName }); function TriggerCall(this: Game_Interpreter, command: string, triggerIdStr?: string, valueVariableIdStr?: string) { const triggerId = toNatural(triggerIdStr, command, "triggerId"); const valueVariableId = toValidVariableIdOrUndefined(valueVariableIdStr, command, "valueVariableId"); if (triggerCall) { if (valueVariableId === undefined) { this.bindPromiseForRPGAtsumaruPlugin(triggerCall(triggerId), () => $gameVariables.setValue(parameters.errorMessage, 0), error => $gameVariables.setValue(parameters.errorMessage, error.message) ); } else { const value = $gameVariables.value(valueVariableId); this.bindPromiseForRPGAtsumaruPlugin(triggerCall(triggerId, value), () => $gameVariables.setValue(parameters.errorMessage, 0), error => $gameVariables.setValue(parameters.errorMessage, error.message) ); } } } function TriggerCallByName(this: Game_Interpreter, command: string, globalServerVariableName: string = "" , triggerName: string = "", valueVariableIdStr?: string) { const valueVariableId = toValidVariableIdOrUndefined(valueVariableIdStr, command, "valueVariableId"); if (triggerCallByName) { if (valueVariableId === undefined) { this.bindPromiseForRPGAtsumaruPlugin(triggerCallByName(globalServerVariableName, triggerName), () => $gameVariables.setValue(parameters.errorMessage, 0), error => $gameVariables.setValue(parameters.errorMessage, error.message) ); } else { const value = $gameVariables.value(valueVariableId); this.bindPromiseForRPGAtsumaruPlugin(triggerCallByName(globalServerVariableName, triggerName, value), () => $gameVariables.setValue(parameters.errorMessage, 0), error => $gameVariables.setValue(parameters.errorMessage, error.message) ); } } } function GetGlobalServerVariable(this: Game_Interpreter, command: string, globalServerVariableIdStr?: string) { const globalServerVariableId = toNatural(globalServerVariableIdStr, command, "globalServerVariableId"); if (getGlobalServerVariable) { this.bindPromiseForRPGAtsumaruPlugin(getGlobalServerVariable(globalServerVariableId), globalServerVariable => { $gameVariables.setValue(parameters.value, globalServerVariable.value); $gameVariables.setValue(parameters.minValue, globalServerVariable.minValue); $gameVariables.setValue(parameters.maxValue, globalServerVariable.maxValue); $gameVariables.setValue(parameters.name, globalServerVariable.name); $gameVariables.setValue(parameters.errorMessage, 0); }, error => $gameVariables.setValue(parameters.errorMessage, error.message) ); } } function GetGlobalServerVariableByName(this: Game_Interpreter, command: string, globalServerVariableName: string = "") { if (getGlobalServerVariableByName) { this.bindPromiseForRPGAtsumaruPlugin(getGlobalServerVariableByName(globalServerVariableName), globalServerVariable => { $gameVariables.setValue(parameters.value, globalServerVariable.value); $gameVariables.setValue(parameters.minValue, globalServerVariable.minValue); $gameVariables.setValue(parameters.maxValue, globalServerVariable.maxValue); $gameVariables.setValue(parameters.name, globalServerVariable.name); $gameVariables.setValue(parameters.errorMessage, 0); }, error => $gameVariables.setValue(parameters.errorMessage, error.message) ); } }
ca403a696a0ae9ac2e1a767b8980b39170c35d91
TypeScript
FabricioHQ/Comfeco-Sapper
/src/components/Auth/signup_validate.ts
3.21875
3
export const validateEmail = (email: string) => { const regex = /^(?:[^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*|"[^\n"]+")@(?:[^<>()[\].,;:\s@"]+\.)+[^<>()[\]\.,;:\s@"]{2,63}$/i if (regex.test(email)) { return { valid: true, message: 'El correo es uno válido.' }; } else { return {valid: false, message: 'El correo no es uno válido.'}; } } export const validateNumUsername = (username: string) => { if (username.length >= 4) { return { valid: true, message: 'El nombre de usuario tiene +4 caracteres.' }; } else { return { valid: false, message: 'La nombre de usuario no tiene +4 caracteres.' }; } } export const validateNumPassword = (password: string) => { if (password.length >= 8) { return { valid: true, message: 'La contraseña tiene +8 caracteres.' }; } else { return { valid: false, message: 'La contraseña no tiene +8 caracteres.' }; } } export const validateMayusPassword = (password: string) => { const regex = /[A-Z]/g if (regex.test(password)) { return { valid: true, message: 'La contraseña tiene una mayúscula.' }; } else { return { valid: false, message: 'La contraseña no tiene una mayúscula.' }; } } export const validateANumPassword = (password: string) => { const regex = /[1-9]/g if (regex.test(password)) { return {valid: true, message: 'La contraseña tiene un número.'} } else { return {valid: false, message: 'La contraseña no tiene un número.'}; } } export const validatePasswords = (password: string, repassword:string) => { if (password === repassword) { return {valid: true, message: 'Las contraseñas coinciden.'}; } else { return {valid: false, message: 'Las contraseñas no coinciden.'}; } }
b9407e1f47e198204f7ff4561a7a21f947844a8f
TypeScript
adhywiranata-tiketdotcom/rest-query
/src/utils/cachePersistor.ts
3.140625
3
import { CachedData, StoreHashMap } from '../interfaces'; const CACHE_PERSISTOR_KEY_PREFIX = 'tix_rest_query_persisted_cache'; const INITIAL_CACHE_VAL = '{}'; const storageEngine = window.localStorage; /** * CachePersistor works as a single source of truth - engine on cache persistence * This pattern avoids any direct access to any other means of browser storage, * hence, close for modification outside this particular class. */ abstract class CachePersistor { /** * Mutate the store based on changes on a single key */ static save(cacheKey: string, serializedData: CachedData) { const store = CachePersistor.getStore(); store[cacheKey] = serializedData; CachePersistor.setStore(store); } /** * Get the value of store from the storage engine */ static getStore(): StoreHashMap { return JSON.parse(storageEngine.getItem(CACHE_PERSISTOR_KEY_PREFIX) || INITIAL_CACHE_VAL); } /** * Overwrite the value of store inside the storage engine */ static setStore(persistedCacheStore: StoreHashMap) { storageEngine.setItem(CACHE_PERSISTOR_KEY_PREFIX, JSON.stringify(persistedCacheStore)); } /** * Purge the cached data from the storage engine. This won't directly affect the context's store. */ static removeStore() { storageEngine.removeItem(CACHE_PERSISTOR_KEY_PREFIX); } } export default CachePersistor;
ec089c0ea0e4d080851a76047f0af7b3d5d8953e
TypeScript
n0uk/glorio-client
/src/services/hatservice.ts
2.578125
3
import {Service} from "./servicemanager"; import Game from "../states/game"; import {Protocol} from "../protocol/protocol"; import MessageType = Protocol.MessageType; import Message = Protocol.Message; import HatComponent from "../factory/components/hat"; import {EventEmitter} from "events"; import HatType = Protocol.HatType; import {Images} from "../assets"; import TeamManager from "./teammanager"; class HatListElement extends EventEmitter { public element: HTMLElement; private wearButton: HTMLElement; private hatType: number; public static getHatSprite(type: HatType) { if (type === HatType.WhiteBearHat) { return Images.ImagesWhitebearhaticon.getPNG(); } else if (type === HatType.BrownBearHat) { return Images.ImagesBrownbearhaticon.getPNG(); } else if (type === HatType.ChessHat) { return Images.ImagesChesshaticon.getPNG(); } else if (type === HatType.CowboyHat) { return Images.ImagesCowboyhaticon.getPNG(); } else if (type === HatType.ChickenHat) { return Images.ImagesChickenhaticon.getPNG(); } else if (type === HatType.FoxHat) { return Images.ImagesFoxhaticon.getPNG(); } else if (type === HatType.VikingHat) { return Images.ImagesVikinghaticon.getPNG(); } else if (type === HatType.BuilderHat) { return Images.ImagesBuilderhaticon.getPNG(); } else if (type === HatType.HockeyHat) { return Images.ImagesHockeyhaticon.getPNG(); } else if (type === HatType.TankHat) { return Images.ImagesTankhaticon.getPNG(); } else if (type === HatType.DruidHat) { return Images.ImagesDruidhaticon.getPNG(); } else if (type === HatType.IceHat) { return Images.ImagesIcehaticon.getPNG(); } else { return Images.ImagesKnight.getPNG(); } } public constructor(hatType: number, active: boolean) { super(); this.hatType = hatType; this.element = document.createElement('div'); if (!active) { this.element.className = 'ui-hat-list-item is-aviable'; } else { this.element.className = 'ui-hat-list-item is-active'; } this.element.innerHTML = ` <div class="ui-hat-image"> <img src="${HatListElement.getHatSprite(hatType)}" /> </div> `; if (!active) { this.element.onclick = function () { this.emit('wear'); }.bind(this); } } } class HatList { private listContainer: HTMLDivElement; private elements: Array<HTMLElement>; private world: Game; public constructor(world: Game, listContainer: HTMLDivElement) { this.listContainer = listContainer; this.world = world; } private cleanup() { this.elements = []; this.listContainer.innerHTML = ""; } public updateHats(hatTypes: Array<number>, currentHat: number) { this.cleanup(); for (let i = 0; i < hatTypes.length; i++) { let hatType = hatTypes[i]; let element = new HatListElement(hatType, hatType === currentHat); element.on('wear', function () { this.world.socket.sendMessage(MessageType.PlayerSelectHat, {hatType: hatType}); (this.world.services.getService(HatManager) as HatManager).toggle(); }.bind(this)); this.listContainer.appendChild(element.element); } let hatType = -1; let element = new HatListElement(hatType, hatType === currentHat); element.on('wear', function () { this.world.socket.sendMessage(MessageType.PlayerSelectHat, {hatType: hatType}); (this.world.services.getService(HatManager) as HatManager).toggle(); }.bind(this)); this.listContainer.appendChild(element.element); } } export default class HatManager extends Service { private container: HTMLElement; private isEnabled = false; private hatList: HatList; public constructor(world: Game) { super(world); this.world.socket.onMessage(MessageType.SyncHats, this.onSyncHats.bind(this)); this.container = document.getElementById("ui-hat-list-container"); document.getElementById('ui-hat-list-close').onclick = function () { this.toggle(); }.bind(this); document.getElementById('ui-hat-close-button').onclick = function () { this.toggle(); }.bind(this); this.hatList = new HatList(world, document.getElementById('ui-hat-list-content') as HTMLDivElement); } private onSyncHats(message: Message) { let hatTypes = message.content['hatTypes']; let currentHatType = message.content['currentHat']; this.hatList.updateHats(hatTypes, currentHatType); } public hide() { if (this.isEnabled) { this.toggle(); } } public toggle() { this.isEnabled = !this.isEnabled; if (this.isEnabled) { (this.world.services.getService(TeamManager) as TeamManager).hide(); } this.container.style.display = this.isEnabled ? 'block' : 'none'; } public destroy() { if (this.isEnabled) { this.toggle(); } } }
9425d5dd56fbeb5003ffc68f3bc53c63f2b5f178
TypeScript
curuvijam/frontPoslovna
/poslovna-front/src/app/services/valute.service.ts
2.5625
3
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import { catchError, map, tap } from 'rxjs/operators'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Valuta } from '../modeli/valuta'; import { NovaValuta } from '../modeli/nova-valuta'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable() export class ValuteService { private url = 'http://localhost:8080/valute'; getValute(): Observable<Valuta[]> { return this.http.get<Valuta[]>(this.url); } getValuta(id: string): Observable<Valuta> { return this.http.get<Valuta>(this.url + '/' + id); } insertValuta(kategorija: NovaValuta): Observable<NovaValuta> { return this.http.post<NovaValuta>(this.url, kategorija, httpOptions).pipe( catchError(this.handleError<NovaValuta>('insertValuta')) ); } updateValuta(kategorija: Valuta): Observable<Valuta> { const id = typeof kategorija === 'string' ? kategorija : kategorija.id; const url = `${this.url}/${id}`; return this.http .put<Valuta>(url, kategorija, httpOptions) .pipe(catchError(this.handleError<Valuta>('updateValuta'))); } deleteValuta(kategorija: Valuta | string): Observable<Valuta> { const id = typeof kategorija === 'string' ? kategorija : kategorija.id; const url = `${this.url}/${id}`; return this.http .delete<Valuta>(url, httpOptions) .pipe(catchError(this.handleError<Valuta>('deleteValuta'))); } constructor(private http: HttpClient) {} private handleError<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // TODO: better job of transforming error for user consumption // Let the app keep running by returning an empty result. return of(result as T); }; } }
a27f3b84dc021080e2de4c16867126d149e9a569
TypeScript
ehab180hb/tessel2framework
/src/test/handlers/button.handler.test.ts
2.6875
3
import * as five from 'johnny-five' import { buttonHandler } from '../../button/button.handler' import { PIN } from '../../board/board.model' import { DeviceButton } from '../../button/button.model' let buttonOnSpy: string[] = [] let buttonRemoveListenerSpy: string[] = [] let createdButtons: DeviceButton[] = [] beforeEach(() => { buttonOnSpy = [] buttonRemoveListenerSpy = [] ;(five.Button as any) = jest.fn(pin => ({ on: (e: string, fn: Function) => { buttonOnSpy.push(JSON.stringify({ e, fn: fn.name, pin })) }, removeAllListeners: (e?: string) => { buttonRemoveListenerSpy.push(JSON.stringify({ e, pin })) }, })) Object.defineProperty(buttonHandler, 'createdButtons', { value: [ { name: 'red', pin: PIN.b5, listener: new five.Button(PIN.b5), }, { name: 'green', pin: PIN.b6, listener: new five.Button(PIN.b6), }, { name: 'blue', pin: PIN.b7, listener: new five.Button(PIN.b7), }, ], }) createdButtons = Object.getOwnPropertyDescriptor(buttonHandler, 'createdButtons')!.value }) describe('Button handler tests', () => { describe('checkButtonExistence()', () => { test('When button exists', () => { const res = buttonHandler.checkButtonExistence(PIN.b5, 'red') expect(res).toMatchSnapshot() }) test('When button does not exit', () => { const res = buttonHandler.checkButtonExistence(PIN.b1, 'white') expect(res).toMatchSnapshot() }) }) describe('findOrCreateButton()', () => { test('when button exists', () => { const res = buttonHandler.findOrCreateButton(PIN.b5, 'red') expect(res).toMatchSnapshot() }) test('when button does not exist', () => { const res = buttonHandler.findOrCreateButton(PIN.b1, 'white') expect(res).toMatchSnapshot() }) }) describe('createButton()', () => { test('when pin and name are available', () => { const res = buttonHandler.createButton(PIN.b2, 'white') expect(res).toMatchSnapshot() }) test('when pin is occupied', async () => { expect(() => buttonHandler.createButton(PIN.b5, 'white')).toThrowErrorMatchingSnapshot() }) test('when name is taken', () => { expect(() => buttonHandler.createButton(PIN.b1, 'red')).toThrowErrorMatchingSnapshot() }) }) describe('initDefaultButtons()', () => { test('when buttons are available', () => { const mockDefaultButtons = [ { name: 'white', pin: PIN.b1, }, { name: 'black', pin: PIN.b2, }, { name: 'purple', pin: PIN.b3, }, ] buttonHandler.initDefaultButtons(mockDefaultButtons) expect(createdButtons).toMatchSnapshot() }) test('when buttons are not available', () => { const mockDefaultButtons = [ { name: 'red', pin: PIN.b5, }, { name: 'green', pin: PIN.b6, }, { name: 'blue', pin: PIN.b7, }, ] buttonHandler.initDefaultButtons(mockDefaultButtons) expect(createdButtons).toMatchSnapshot() }) }) describe('findButton()', () => { test('when button exists', () => { const res = buttonHandler.findButton('red') expect(res).toMatchSnapshot() }) test('when button does not exist', () => { const res = buttonHandler.findButton('white') expect(res).toBeFalsy() }) }) describe('clearButton()', () => { test('when button exists', () => { buttonHandler.clearButton('red') expect(buttonRemoveListenerSpy).toMatchSnapshot() }) test('when button exists and event type specified', () => { buttonHandler.clearButton('red', 'press') expect(buttonRemoveListenerSpy).toMatchSnapshot() }) test('when button does not exist', () => { expect(() => buttonHandler.clearButton('white')).toThrowErrorMatchingSnapshot() }) }) describe('updateButton()', () => { const cb = () => {} test('when button exists', () => { buttonHandler.updateButton('red', 'hold', cb) expect({ buttonRemoveListenerSpy, buttonOnSpy }).toMatchSnapshot() }) test('when button does not exist', () => { expect(() => buttonHandler.updateButton('white', 'hold', cb)).toThrowErrorMatchingSnapshot() }) }) describe('updateButtonPress()', () => { const cb = () => {} test('when button exists', () => { buttonHandler.updateButtonPress('red', cb) expect({ buttonRemoveListenerSpy, buttonOnSpy }).toMatchSnapshot() }) test('when button does not exist', () => { expect(() => buttonHandler.updateButtonPress('white', cb)).toThrowErrorMatchingSnapshot() }) }) })
78583db77c2652db2a20703a0717cb984ce56edb
TypeScript
edipoelwes/sonhos-de-ninar-web
/src/rules/schemas/schemasValidation.ts
2.640625
3
import * as Yup from 'yup' export const registerForm = Yup.object().shape({ name: Yup.string().required('Nome obrigatório!'), email: Yup.string() .required('E-mail obrigatório!') .email('Digite um e-mail válido!'), password: Yup.string().min(6, 'No minimo 6 dígitos!'), social_name: Yup.string().required('Empresa obrigatório'), alias_name: Yup.string().required('Nome Fantasia obrifatório'), document_company: Yup.string().required('CNPJ obrigatório'), document_company_secondary: Yup.string() .required('Incrição Estadual obrigatório') }) export const loginForm = Yup.object().shape({ email: Yup.string() .required('E-mail obrigatório!') .email('Digite um e-mail válido!'), password: Yup.string().min(6, 'No minimo 6 dígitos!') })
2e8b47f629c72295e2797bd0225fb46e7ae8184a
TypeScript
EduardoKO/RentxServer
/src/modules/cars/repositories/ISpecificationsRepository.ts
2.65625
3
import Specification from "../entities/Specification"; export interface ICreateSpecificationDTO { name:string; description:string; } export interface ISpecificationsRepository { create({name, description}: ICreateSpecificationDTO): Promise<Specification>; findByName(name: string): Promise<Specification>; }
bdb5b20d6197d2c3bd90ddf24d3b4dc01e951c85
TypeScript
CivicDataLab/cheyyali
/frontend/repositories/tasks/sequenceLabeling/apiRelationRepository.ts
2.53125
3
import ApiService from '@/services/api.service' import { RelationRepository } from "~/domain/models/tasks/relationRepository" import { RelationItem } from "~/domain/models/tasks/relation" export class ApiRelationRepository implements RelationRepository { constructor( private readonly request = ApiService ) { } async list(projectId: string, exampleId: number): Promise<RelationItem[]> { const url = `/projects/${projectId}/examples/${exampleId}/relations` const response = await this.request.get(url) return response.data.map((relation: any) => RelationItem.valueOf(relation)) } async create(projectId: string, exampleId: number, item: RelationItem): Promise<RelationItem> { const url = `/projects/${projectId}/examples/${exampleId}/relations` const response = await this.request.post(url, item.toObject()) return RelationItem.valueOf(response.data) } async update(projectId: string, exampleId: number, relationId: number, relationType: number): Promise<RelationItem> { const url = `/projects/${projectId}/examples/${exampleId}/relations/${relationId}` const response = await this.request.patch(url, {type: relationType}) return RelationItem.valueOf(response.data) } async delete(projectId: string, exampleId: number, relationId: number): Promise<void> { const url = `/projects/${projectId}/examples/${exampleId}/relations/${relationId}` const response = await this.request.delete(url) } async bulkDelete(projectId: string, exampleId: number, relationIds: number[]): Promise<void> { const url = `/projects/${projectId}/examples/${exampleId}/relations` await this.request.delete(url, {ids: relationIds}) } }
54ade2c5c1d421eaf73d21dc2211fedab2b21bfd
TypeScript
huytq000605/mapAsyncAction
/mapAsyncAction.ts
3.453125
3
// Idea: Muốn thực hiện hàm map async song song với nhau và có limit function *createGeneratorFromArray (arr: any[]) { for(let i = 0; i < arr.length; i++) { yield [arr[i], i, arr] } } /** * * @param arr Array muốn truyền vào * @param fn Một hàm async muốn thực hiện với mỗi phần tử của mảng * @param limit Giới hạn số concurrency thực hiện (Default: Chạy tất cả) * @returns một mảng các kết quả theo tứ tự của mảng nhập vào */ const mapAsyncAction = async <T> (arr: T[], fn: (currentValue: T, index: number) => Promise<any>, limit = arr.length): Promise<T[]|any> => { const result = Array(arr.length); if(arr.length === 0) return []; limit = Math.min(arr.length, limit); let workers = [] const generator = createGeneratorFromArray(arr) for(let i = 0; i < limit; i++) { workers.push(createWorker(generator, fn, result)) } await Promise.all(workers); return result; } const createWorker = async ( generator: Generator<Array<any>>, fn: (currentValue: any, index: number) => Promise<any>, result: any[] ) => { for (let gen of generator) { const currentValue = gen[0]; const index = gen[1]; result[index] = await fn(currentValue, index); // can custom: wrap this fn to return the result we want } return; /* Distributed System return new Promise(async (resolve, reject) => { worker.on('finished', () => resolve()) }) */ }; export default mapAsyncAction;
7bda9a9baf38fb58dcd668b21bf97dd4961b6379
TypeScript
yiyb0603/CoCode_Web
/src/stores/CommunityStore/CommunityStore.ts
2.53125
3
import { observable, action } from 'mobx'; import { autobind } from 'core-decorators'; import CommunityRepository from './CommunityRepository'; import { IPostListTypes, IPostWriteTypes, IPostCommentTypes, } from 'interface/PostTypes'; @autobind class CommunityStore { @observable pageCount = 0; @observable postList: IPostListTypes[] = []; @action handlePostList = async () => { const response = await CommunityRepository.handlePostList(this.pageCount); if (this.pageCount === 0) { this.postList = response.posts; } else if (this.pageCount !== 0) { this.postList = [...this.postList, response.posts]; } return response; }; @action handlePostWrite = async (request: IPostWriteTypes) => { const response = await CommunityRepository.handlePostWrite(request); return response; }; @action handlePageCount = async (page: number | null) => { if (page === null) { this.pageCount = this.pageCount + 1; } else { this.pageCount = page; } }; @action handlePostDelete = async (idx: number) => { const response = await CommunityRepository.handlePostDelete(idx); this.postList = this.postList.filter( (post: IPostListTypes) => post.id !== idx ); return response; }; @action handleCommentList = async (id: number) => { const response = await CommunityRepository.handleCommentList(id); return response; }; @action handleCommentWrite = async (request: IPostCommentTypes) => { const response = await CommunityRepository.handleCommentWrite(request); return response; }; @action handleCommentDelete = async (id: number) => { const response = await CommunityRepository.handleCommentDelete(id); return response; }; } export default CommunityStore;
71c13b3fa1da49a2b399198a7f9b824d7ba7af0a
TypeScript
flarum/framework
/framework/core/js/src/common/helpers/textContrastClass.ts
2.546875
3
import isDark from '../utils/isDark'; export default function textContrastClass(hexcolor: string | null | undefined): string { if (!hexcolor) return 'text-contrast--unchanged'; return isDark(hexcolor) ? 'text-contrast--light' : 'text-contrast--dark'; }
54bd3c513694e21482c7a4e9c0c19a177c5b0fef
TypeScript
skumar4120/nwsearch
/src/main/typescript/_string.ts
2.765625
3
// Module: _string.ts // Description: String-handling helper functions. // Also-see: // Tab-stops: 4 // Author: DR // Language: js // Creation Date: 07/18/2018 // Description: // Revisions: // // // ========================================================================== // See global.d.ts for global definitions. // ========================================================================== // MapTSV is a helper function that takes our TSV data (e.g., "_coldata.ts") // and maps it into an associative array. It also returns a pipe-delimited // string for regular expression matching, levenshteinArray, etc. // export function mapTSV(sTSV: string, sDelim: string, oMappedDetail: Map<string, string>) { // let aLines = sTSV.split(sDelim); let aColumns; let oMap = new Map(); // let sOutput = ''; // for (let i = 0; i < aLines.length; i++) { // aColumns = aLines[i].split('\t'); if (aColumns.length !== 2) { continue; } // let sKeyLowercase = aColumns[1].toLowerCase(); if (typeof oMap[sKeyLowercase] === 'undefined') { oMap[sKeyLowercase] = aColumns[0]; if (sOutput.length) { sOutput += '|'; } sOutput += aColumns[1]; } // sKeyLowercase = aColumns[0].toLowerCase(); if (typeof oMappedDetail[sKeyLowercase] === 'undefined') { oMappedDetail[sKeyLowercase] = aColumns[1]; } else { // TODO fixme - Enable the warning. Currently it affects test cases execution time. // console.warn('Element skipped - Not added to GlobalBase (Key already exist): ' + sKeyLowercase + ':' + aColumns[1]); } // } // return (sOutput); } // Function matchPhrase is a helper function that handles potential // multi-word attribute values (e.g., "Alfa Romeo"). // export function matchPhrase(xLookup: any, aWords: string[], nCurrentWord: number, nTotalWords: number, upperCase: boolean = false) { // let bFound = false; let bRegex = ('global' in xLookup) ? true : false; let nNumberOfWordsToTry = nTotalWords - nCurrentWord; let sPhrase: string; for (let i = nNumberOfWordsToTry; i >= 1; i--) { sPhrase = ''; for (let j = 0; j < i; j++) { if (j) { sPhrase += ' '; } sPhrase += aWords[nCurrentWord + j]; } if (xLookup instanceof Array) { bFound = xLookup.indexOf(upperCase ? sPhrase.toUpperCase() : sPhrase.toLowerCase()) > -1; } else { bFound = (bRegex) ? xLookup.test(sPhrase) : (typeof xLookup[sPhrase.toLowerCase()] !== 'undefined'); } if (bFound) { break; } } return ((bFound) ? sPhrase : ''); } // Useful function for cleansing models. Models Synonyms and Models endswith and special chars in models words are handled. Ex: Hurricane to Huracan, CX 3 to CX-3 and '1 Series 128i' to 128i. export function matchPhraseInAlias(xLookup: Map<string, string>, aWords: string[], nCurrentWord: number, nTotalWords: number, oCustomAlias: Map<string, string>, endsWithFlag: boolean = false) { // let bFound = false; let nNumberOfWordsToTry = nTotalWords - nCurrentWord; let sPhrase: string; let lowestLimit = nTotalWords === 1 ? 1 : 2; // This is needed to handle the Alfa Romeo being matched against Seller 'Alfa' only. for (let i = nNumberOfWordsToTry; i >= lowestLimit; i--) { sPhrase = ''; for (let j = 0; j < i; j++) { if (j) { sPhrase += ' '; } sPhrase += aWords[nCurrentWord + j]; } let value; Object.keys(xLookup).forEach(function (key) { value = xLookup[key]; if (key.indexOf('-') > 0 || key.indexOf('/') > 0) { let tempItem1 = key.replace('-', ''); let tempItem2 = key.replace('-', ' '); let tempItem3 = key.replace('/', ' '); if (tempItem1 === sPhrase.toLowerCase() || tempItem2 === sPhrase.toLowerCase() || tempItem3 === sPhrase.toLowerCase()) { sPhrase = value; return; } } if (sPhrase.toLowerCase().length > 2 && key.endsWith(' ' + sPhrase.toLowerCase())) { // Handle BMW '1 Series 128i'. Check for atleast 2 chars in model name. sPhrase = value; return; } }); bFound = (typeof xLookup[sPhrase.toLowerCase()] !== 'undefined'); if (bFound) { break; } else if (oCustomAlias.get(sPhrase.toLowerCase())) { sPhrase = oCustomAlias.get(sPhrase.toLowerCase()); bFound = true; break; } } return ((bFound) ? sPhrase : (endsWithFlag ? wordEndsWith(xLookup, aWords[nCurrentWord]) : '')); } function wordEndsWith(xLookup, word) { let value; let returnValue = ''; Object.keys(xLookup).forEach(function (key) { value = xLookup[key]; if (word.toLowerCase().length > 2 && key.endsWith(' ' + word.toLowerCase())) { // Handle BMW '1 Series 128i'. Check for at least 2 chars in model name. returnValue = value; return; } }); return returnValue; } // [EOF]
ccfbfb52e4805079c925feb1792a6a74771cde46
TypeScript
buttercubz/chat-realtime-deno
/chat.ts
2.71875
3
import { WebSocket, isWebSocketCloseEvent, } from "https://deno.land/std/ws/mod.ts"; import { v4 } from "https://deno.land/std/uuid/mod.ts"; interface usersList { userId: string; name: string; groupName: string; ws: WebSocket; } interface IMessage { userId: string; name: string; message: string; } const usersMap = new Map(); const groupsMap = new Map(); const messagesMap = new Map(); export default async function Chat(ws: WebSocket) { const userId = v4.generate(); for await (let data of ws) { const event = typeof data === "string" ? JSON.parse(data) : data; if (isWebSocketCloseEvent(data)) { leaveGroup(userId); break; } let userObj: usersList; switch (event.event) { case "join": userObj = { userId, name: event.name, groupName: event.groupName, ws, }; usersMap.set(userId, userObj); const users = groupsMap.get(event.groupName) || []; users.push(userObj); groupsMap.set(event.groupName, users); emitUserList(event.groupName); emitPreviousMessages(event.groupName, ws); break; case "message": userObj = usersMap.get(userId); const message = { userId, name: userObj.name, message: event.data, }; const messages = messagesMap.get(userObj.groupName) || []; messages.push(message); messagesMap.set(userObj.groupName, messages); emitMessage(userObj.groupName, message, userId); break; } } } function emitUserList(groupName: string) { const users = groupsMap.get(groupName) || []; for (const user of users) { const event = { event: "users", data: getDisplayUsers(groupName), }; user.ws.send(JSON.stringify(event)); } } function getDisplayUsers(groupName: string) { const users = groupsMap.get(groupName) || []; // @ts-ignore return users.map((u) => { return { userId: u.userId, name: u.name }; }); } function emitMessage(groupName: string, message: IMessage, senderId: string) { const users = groupsMap.get(groupName) || []; for (const user of users) { const tmpMessage = { ...message, sender: user.userId === senderId ? "me" : senderId, }; const event = { event: "message", data: tmpMessage, }; user.ws.send(JSON.stringify(event)); } } function emitPreviousMessages(groupName: string, ws: WebSocket) { const messages = messagesMap.get(groupName) || []; const event = { event: "previousMessages", data: messages, }; ws.send(JSON.stringify(event)); } function leaveGroup(userId: string) { const userObj = usersMap.get(userId); if (!userObj) { return; } let users = groupsMap.get(userObj.groupName) || []; // @ts-ignore users = users.filter((u) => u.userId !== userId); groupsMap.set(userObj.groupName, users); usersMap.delete(userId); emitUserList(userObj.groupName); }
40e9c840fac52dc37a7fb84befa1e847580c3a10
TypeScript
codehub0x/TypeScript-DeFi
/src/gambling-strategies/archive/buy-low-sell-high2.ts
2.96875
3
import { BinanceConnector } from "../../binance/binance-connector" const pair = process.argv[2] // e.g. ETHUSDT or BTCUSDT const binanceApiKey = process.argv[3] // check your profile on binance.com --> API Management const binanceApiSecret = process.argv[4] // check your profile on binance.com --> API Management export class BuyLowSellHighGambler { private binanceConnector: BinanceConnector private historicData: any[] = [] public constructor(apiKey: string, apiSecret: string) { this.binanceConnector = new BinanceConnector(apiKey, apiSecret) } public async investWisely(): Promise<void> { const currentPrices = await this.binanceConnector.getCurrentPrices() const price = Number(currentPrices.filter((e: any) => e.coinSymbol === pair)[0].price) console.log(`Current Price: ${price}`) if (this.historicData.length === 500000) { this.historicData.splice(this.historicData.length - 1, 1) } this.historicData.unshift(price) const lowestSinceX = this.getIsLowestSinceX(price) const highestSinceX = this.getIsHighestSinceX(price) console.log(`This is the lowest Price since: ${lowestSinceX} intervals`) console.log(`This is the highest Price since: ${highestSinceX} intervals`) const accountData = await this.binanceConnector.getFuturesAccountData() if (Number(accountData.totalWalletBalance) > 850) { await this.binanceConnector.transferFromUSDTFuturesToSpotAccount(2) } else if (Number(accountData.totalWalletBalance) === 0) { await this.binanceConnector.transferFromSpotAccountToUSDTFutures(50) } let theBuyFactor = lowestSinceX / 100 const theSellFactor = highestSinceX / 100 theBuyFactor = (theBuyFactor > 0.2) ? 0.2 : theBuyFactor if (lowestSinceX >= 5) { const amountToBeInvested = Number((((Number(accountData.availableBalance)) / price) * theBuyFactor).toFixed(3)) if (amountToBeInvested >= 0.001) { console.log(`amountToBeInvested: ${amountToBeInvested}`) await this.binanceConnector.buyFuture(pair, amountToBeInvested) } else { console.log(`${amountToBeInvested} is below minimum buy amount of 0.001 with theBuyFactor: ${theBuyFactor}`) } } else if (highestSinceX >= 5) { const xPosition = accountData.positions.filter((entry: any) => entry.symbol === pair)[0] let amountToBeSold = Number(((Number(xPosition.positionAmt)) * theSellFactor).toFixed(3)) amountToBeSold = (amountToBeSold <= Number(xPosition.positionAmt)) ? amountToBeSold : Number(xPosition.positionAmt) if (amountToBeSold >= 0.001) { console.log(`amountToBeSold: ${amountToBeSold}`) const r = await this.binanceConnector.sellFuture(pair, amountToBeSold) console.log(r) } else { console.log(`below minimum buy amount of 0.001 with theSellFactor: ${theSellFactor}`) } } else { console.log("relax") } } private getIsLowestSinceX(price: number) { let counter = 0 for (const e of this.historicData) { if (price > e) { return counter } counter++ } return counter } private getIsHighestSinceX(price: number) { let counter = 0 for (const e of this.historicData) { if (price < e) { return counter } counter++ } return counter } } const instance = new BuyLowSellHighGambler(binanceApiKey, binanceApiSecret) setInterval(async () => { instance.investWisely() }, 11 * 1000)
d31b1c06d63551372f4f15d25178a91f2ef56397
TypeScript
dingfengquek/dingfengquek-pelago-assessment-20200308
/src/dataSource/wwwReader/index.ts
2.71875
3
import path from 'path'; import stream from 'stream'; import tar from 'tar'; import axios from 'axios'; import * as rr from '../../result'; const getListURL = `https://cran.r-project.org/src/contrib/PACKAGES`; const getItemURL = (name: string, version: string) => `https://cran.r-project.org/src/contrib/${name}_${version}.tar.gz`; export const getListData = async (): Promise<rr.Result<string, string>> => { try { const axiosGetResult = await axios.get(getListURL); const data = axiosGetResult.data; if (typeof data !== 'string') { return rr.err(`Error while getting data from ${getListURL}: Did not receive a text or string from the URL.`); } // --- return rr.ok(data); } catch (e) { return rr.err(`[getListData] Error while getting data from ${getListURL}: ${e.toString()}`); } }; export const getPackageDescriptionFile = async (name: string, version: string): Promise<rr.Result<string, string>> => { const url = getItemURL(name, version); try { const axiosResponse = await axios.get(url, { responseType: 'stream' }); const axiosResponseStream: stream.Readable = axiosResponse.data; // --- // Untar the ${name}/DESCRIPTION file into a string const descriptionChunks: any[] = []; const tarStream = axiosResponseStream.pipe( tar.t({ onentry: (entry) => { entry.on('data', chunk => { descriptionChunks.push(chunk); }); }, }, [`${name}/DESCRIPTION`]) ); await new Promise(resolve => tarStream.on('finish', resolve)); const descriptionData = descriptionChunks.toString(); return rr.ok(descriptionData); } catch (err) { return rr.err(`[getPackageDescriptionFile] Error while getting description file from url [${url}]: ${err.toString()}`); } };
04b85e45a2cebbb346c9c8d674f44ff8a5813d83
TypeScript
vladimir-tikhonov/string-to-argv
/src/state_machine/states/empty.ts
2.671875
3
import baseState, { State, StateHandle } from 'src/state_machine/states/state'; const emptyState: State = { ...baseState, stateHandle: StateHandle.Empty, onCharacter(character: string) { return [character, StateHandle.InsideToken]; }, onSingleQuote() { return [null, StateHandle.InsideSingleQuotedToken]; }, onDoubleQuote() { return [null, StateHandle.InsideDoubleQuotedToken]; }, onEscape() { return [null, StateHandle.AfterEscapeInsideToken]; }, }; export default emptyState;
b9b156850d2f35ddcfe4a0c2711cc9ddb67017a7
TypeScript
arpitparmar5739/uemail
/uemail_backend/src/models/User.ts
2.671875
3
import * as bcrypt from 'bcrypt'; import * as SequelizeStatic from 'sequelize'; import { DataTypes, Sequelize } from 'sequelize'; import { UserAttributes, UserInstance } from './interfaces/UserInterface'; const saltRounds = 10; export default function (sequelize: Sequelize, dataTypes: DataTypes): SequelizeStatic.Model<UserInstance, UserAttributes> { let User = sequelize.define<UserInstance, UserAttributes>("User", { id: { type: dataTypes.INTEGER, primaryKey: true, allowNull: false, autoIncrement: true }, username: { type: dataTypes.STRING, allowNull: false, unique: true }, email: { type: dataTypes.STRING, allowNull: false, unique: true }, password: { type: dataTypes.STRING, allowNull: false }, firstname: { type: dataTypes.STRING, allowNull: false }, lastname: { type: dataTypes.STRING, allowNull: false }, phone: { type: dataTypes.STRING, allowNull: true } }, { underscored: true }); User.beforeCreate((user: UserInstance) => { user.dataValues.password = bcrypt.hashSync(user.dataValues.password, saltRounds); }); return User; }
f102caa53ad3dc52bb32b7f73f06798a9099ef28
TypeScript
liuyics15/RPGGame
/src/game/role/ActionStatusDic.ts
2.640625
3
import {KeyPropertyDic} from "../property/KeyPropertyDic"; import {IKeyPropertyHandle, IKeyPropertyLock} from "../property/Interface"; import {EEntityAction, EEntityStatus} from "../../define/GameDefine"; //行动状态 export interface IActionStatusDic { //是否允许行为 isAllowed(action:EEntityAction):boolean; //设置是否允许 setActionAllowed(action:EEntityAction,value:boolean,setter:IKeyPropertyHandle):void; //锁住行动状态 lockAction(action:EEntityAction,setter:IKeyPropertyLock):void; //解锁 unlockAction(action:EEntityAction,setter:IKeyPropertyLock):void; } class ActionStatusDic_P extends KeyPropertyDic implements IActionStatusDic { constructor() { super(); this.registerProperty(EEntityAction.MOVE,true); this.registerProperty(EEntityAction.ATTACK,true); this.registerProperty(EEntityAction.DEFEND,true); this.registerProperty(EEntityAction.SPELL,true); this.registerProperty(EEntityAction.USE_ITEM,true); } //是否允许行为 isAllowed(action:EEntityAction):boolean { return this.getProperty(action); } //设置是否允许 setActionAllowed(action:EEntityAction,value:boolean,setter:IKeyPropertyHandle):void { this.setProperty(action,value,setter); } //锁住行动状态 lockAction(action:EEntityAction,setter:IKeyPropertyLock):void { this.lockProperty(action,setter); } //解锁 unlockAction(action:EEntityAction,setter:IKeyPropertyLock):void { this.unlockProperty(action,setter); } } export const ActionStatusDic:{new():IActionStatusDic} = ActionStatusDic_P;
88264cd9b337ff283f516bb972966ba8be6fcdc5
TypeScript
dp28/constraints
/json-constraints/src/constraints/variable.spec.ts
3
3
import 'mocha'; import { expect } from 'chai'; import { buildDecisionVariable, buildConstant, toVariableReference, combine, add, subtract, multiply, divide } from './variable'; describe('buildConstant', () => { const constant = buildConstant(1); it('should have an id', () => { expect(constant.id).not.to.be.undefined; }); it('should have a unique id', () => { expect(constant.id).not.to.equal(buildConstant(1).id); }); it('should have the specified value', () => { expect(constant.value).to.equal(1); }); }); describe('buildDecisionVariable', () => { const variable = buildDecisionVariable({ min: 1, max: 2 }, 1); it('should have an id', () => { expect(variable.id).not.to.be.undefined; }); it('should have a unique id', () => { expect(variable.id).not.to.equal(buildDecisionVariable({ min: 1, max: 2 }).id); }); it('should have the specified range', () => { expect(variable.range).to.deep.equal({ min: 1, max: 2 }); }); it('should have the specified value', () => { expect(variable.value).to.equal(1); }); }); describe('toVariableReference', () => { it('should return a variable\'s id if passed a variable', () => { const variable = buildDecisionVariable({ min: 1, max: 2 }, 1); expect(toVariableReference(variable)).to.equal(variable.id); }); it('should return a passed in variable id without changing it', () => { expect(toVariableReference('id2')).to.equal('id2'); }); }); describe('combine', () => { it('should return a VariableRelation with the specified operation', () => { expect(combine('test')().operation).to.equal('test'); }); it('should return a VariableRelation with references to the specified variables', () => { const variable = buildDecisionVariable({ min: 1, max: 2 }, 1); const otherVariable = buildDecisionVariable({ min: 1, max: 2 }, 2); const combined = combine('bla')(variable, otherVariable); expect(combined.variableReferences).to.deep.equal([variable.id, otherVariable.id]); }); }); const operations: any = { add, subtract, multiply, divide }; Object .keys(operations) .forEach((name: string) => { const operation = operations[name]; describe(name, () => { it(`should return a VariableRelation with the '${name}' operation`, () => { expect(operation().operation).to.equal(name); }); }); });
a90f8318671e608a84a258ffc5f82f41d4083971
TypeScript
Mmalikov1337/led-vled-frontend
/src/helpers/localStorageHelper.ts
2.8125
3
import DeliveryDataDTO from "@src/types/DeliveryDataDTO"; import OrderDataDTO from "@src/types/OrderDataDTO"; import PaymentDataDTO from "@src/types/PaymentDataDTO"; import React from "react"; import { productStorageName, productsQuantity, tempItems, tempDeliveryData } from "./../config"; class LocalStorageHepler { stateFunction: React.Dispatch<React.SetStateAction<number[] | number>> | null; constructor(stateFunction: React.Dispatch<React.SetStateAction<number[] | number>> | null) { this.stateFunction = stateFunction; } static getFromStorage(key) { return window.localStorage.getItem(key); } static setToStorage(key, value) { window.localStorage.setItem(key, value); } getSelectedProducts(): number[] { let selectedProducts = LocalStorageHepler.getFromStorage(productStorageName); if (!selectedProducts) { selectedProducts = JSON.stringify([...Array(5)].fill(0)); } return JSON.parse(selectedProducts); } setSelectedProducts(value: number[] = null) { //меняет стейт if (!this.stateFunction) return; if (!value) { this.stateFunction(this.getSelectedProducts()); return; } const stringifyed = JSON.stringify(value); LocalStorageHepler.setToStorage(productStorageName, stringifyed); this.stateFunction(value); } setSelectedProductByIndex(index: number, value: number) { //меняет стейт if (!this.stateFunction) return; const temp = this.getSelectedProducts(); temp[index] = value; this.stateFunction(temp); this.setSelectedProducts(temp); } increaseProductsQuantity(index: number, summand: number = 1) { //меняет стейт const selectedProducts = this.getSelectedProducts(); selectedProducts[index] += summand; this.setSelectedProducts(selectedProducts); } decreaseProductsQuantity(index: number, min: number = 0) { //меняет стейт if (!this.stateFunction) return; const selectedProducts = this.getSelectedProducts(); if (selectedProducts[index] > min) { selectedProducts[index]--; } this.stateFunction(selectedProducts); this.setSelectedProducts(selectedProducts); } static getInitialState() { return React.useState([...Array(5)].fill(0)); } /* NAVBAR */ setProductQuantity() { this.stateFunction(this.getProductQuantity()); } getProductQuantity() { const products = this.getSelectedProducts(); const selected = products.filter((it) => it > 1); return selected.length; } /* ORDER */ setOrderData(orderData: OrderDataDTO | null) { if (!orderData) return; const stringifyed = JSON.stringify(orderData); LocalStorageHepler.setToStorage("orderData", stringifyed); } getOrderData(): OrderDataDTO | null { const stringifyed = LocalStorageHepler.getFromStorage("orderData"); if (!stringifyed) { return null; } return JSON.parse(stringifyed) as OrderDataDTO; } /*DELIVERY */ setDeliveryData(deliveryData: DeliveryDataDTO | null) { if (!deliveryData) return; const stringifyed = JSON.stringify(deliveryData); LocalStorageHepler.setToStorage("deliveryData", stringifyed); } getDeliveryData(): DeliveryDataDTO | null { const stringifyed = LocalStorageHepler.getFromStorage("deliveryData"); if (!stringifyed) { return null; } return JSON.parse(stringifyed) as DeliveryDataDTO; } /*PAYMENT */ setPaymentData(paymentData: PaymentDataDTO) { if (!paymentData) return; const stringifyed = JSON.stringify(paymentData); LocalStorageHepler.setToStorage("paymentData", stringifyed); } getPaymentData(): PaymentDataDTO | null { const stringifyed = LocalStorageHepler.getFromStorage("paymentData"); if (!stringifyed) { return null; } return JSON.parse(stringifyed) as PaymentDataDTO; } /*RAIF */ countTotalPrice(): number | null { const selectedProducts = JSON.parse( LocalStorageHepler.getFromStorage("selectedProducts") ) as Array<number>; const deliveryData = JSON.parse( LocalStorageHepler.getFromStorage("deliveryData") ) as DeliveryDataDTO; const deliveryCost = tempDeliveryData.find((it) => it.method == deliveryData.method); if (!selectedProducts || !deliveryData) { return null; } if (!deliveryCost) { console.log("Wrong delivery method LS countTotalPrice"); return null; } if (!deliveryCost.price) { console.log("Wrong deliveryCost.price LS countTotalPrice"); return null; } const productSum = selectedProducts.reduce((acc, i, index) => { acc += Number(tempItems[index].price); return acc; }, 0); const final = productSum + deliveryCost.price; this.stateFunction(final) return final; } } export default LocalStorageHepler;
d6adcded9b7991bfedb5cb2f4a3f68d77ffb5467
TypeScript
frank-26/ts
/src/tips.ts
3.609375
4
// https://medium.com/@tomsu/typescript-tips-tricks-c8fdef998d50 // # 使用字面量类型 // 泛型 Id 类型 type Id<T extends string> = { type: T; value: string; }; // 特殊的 Id 类型 type FooId = Id<'foo'>; type BarId = Id<'bar'>; // 可选:构造函数 const createFoo = (value: string): FooId => ({ type: 'foo', value }); const createBar = (value: string): BarId => ({ type: 'bar', value }); let foo11 = createFoo('sample'); let bar1 = createBar('sample'); foo11 = bar; // Error foo11 = foo11; // Okey const textEl = document.querySelector('input'); console.log(textEl.value); console.log(textEl!.value); interface Movie { id: string; name: string; } class SearchPageComponent { movie: Movie; constructor(private bs: BookmarksService) {} getFirstMovie() { // 🛑 types are not assignable this.movie = this.bs.items[0]; // 👍 so you have to manually assert type: this.movie = this.bs.items[0] as Movie; } getSecondMovie() { this.movie = this.bs.items[1] as Movie; } } interface RootObject { cats: Cat[]; favoriteNumber: number; favoriteWord: string; } interface Cat { name: string; nullableId?: number | string; optionalFeature?: string; }
c68a7f8aaaa8e3f213f7242224836fea03471a36
TypeScript
sliker/angular2starter
/src/app/counter/counter.reducer.ts
2.9375
3
import { Actions } from './counter.actions'; import { counterIncrement, counterDecrement, counterReset } from './counter.action-types'; import { CounterState } from './counter.model'; export const initialState: CounterState = { count: 0 }; export const counterReducer = (state = initialState, action: Actions) => { switch (action.type) { case counterIncrement: return Object.assign({}, state , { count: state.count + 1 }); case counterDecrement: return Object.assign({}, state , { count: state.count - 1 }); case counterReset: return Object.assign({}, state , { count: 0 }); default: return state; } }; export const getCount = (state: CounterState) => state.count;
51122c0ab72e84532b8ebe01d2fc85e692416ccc
TypeScript
akky-xxxx/boilerplate-nunjucks-scss-ts
/src/ts/modules/validationMain.ts
2.6875
3
import { combine } from 'favalid' import { checkBlank, checkNumber, checkMax, checkMin, checkEqual, checkRadio, checkCheckbox, checkSelect, } from './validationRules' export default (targetElement: HTMLInputElement) => { const isRequired = targetElement.hasAttribute('required') if (!isRequired && !targetElement.value) return '' const validateRules = [] const needValidateRules = <string>targetElement.dataset.validationRules validateRules.push(checkBlank) if (needValidateRules.includes('number')) { validateRules.push(checkNumber) } if (needValidateRules.includes('maxLength')) { const maxNumber = parseInt( <string>targetElement.dataset.validationMaxLength, 10, ) validateRules.push(checkMax(maxNumber)) } if (needValidateRules.includes('minLength')) { const minNumber = parseInt( <string>targetElement.dataset.validationMinLength, 10, ) validateRules.push(checkMin(minNumber)) } if (needValidateRules.includes('equalLength')) { const equalNumber = parseInt( <string>targetElement.dataset.validationEqualLength, 10, ) validateRules.push(checkEqual(equalNumber)) } if (needValidateRules.includes('radio') && isRequired) { validateRules.push(checkRadio) } if (needValidateRules.includes('checkbox') && isRequired) { validateRules.push(checkCheckbox) } if (needValidateRules.includes('select')) { validateRules.push(checkSelect) } return combine(...validateRules)(targetElement).message }
8c405afa675456d32050c759dd6cf68e97acbeda
TypeScript
oozcitak/util
/test/CompareCache.test.ts
3.015625
3
import * as util from "../src" describe('NodeCompareCache', () => { test('check()', () => { for (let i = 0; i < 100; i++) { const cache = new util.CompareCache<string>() const str1 = "a" const str2 = "b" const val1 = cache.check(str1, str2) const val2 = cache.check(str2, str1) expect(val1 || val2).toBe(true) expect(val1 && val2).toBe(false) } }) test('check() with limit', () => { const cache = new util.CompareCache<number>(10) for (let i = 0; i < 100; i++) { const num1 = i const num2 = 1000 + i const val1 = cache.check(num1, num2) const val2 = cache.check(num2, num1) expect(val1 || val2).toBe(true) expect(val1 && val2).toBe(false) } }) })
4766b8912146694250d077a36c08e0c9ec7b004f
TypeScript
daryl-cecile/Tasty-Treats-Inquiry-Form
/src/public/scripts/Modal.ts
2.890625
3
interface IMessageOptions { message:string; timeout?:number; buttons:{ text:string; type?:"primary"|"negative"|"default"; callback?:()=>{}; }[] } class Modal extends HTMLElement{ public open(options:IMessageOptions){ this.innerHTML = [ `<div class="modal">`, `<p>${options.message}</p>`, `<div class="modal-buttons"></div>`, `</div>` ].join('\n'); options.buttons.forEach(btn => { let button = document.createElement('button'); if (btn.type !== "default") button.classList.add(`btn-${btn.type}`); button.innerHTML = btn.text; button.addEventListener('click',()=>{ btn.callback?.(); this.close(); }); this.querySelector('.modal-buttons').appendChild(button); }); this.setAttribute('open',''); return this; } public close(){ this.removeAttribute('open'); setTimeout(()=>{ }, 300); return this; } } customElements.define("x-modal", Modal);
ebf41ef5d3ec4bf65c3163c3506dbe896eec01dd
TypeScript
Ulisseruiz/node-auth
/api/src/validation.ts
2.65625
3
import { celebrate, SchemaOptions, Modes, Segments, Joi } from "celebrate"; import { PWD_RESET_TOKEN_BYTES } from "./config"; export const validate = (schema: SchemaOptions) => celebrate( schema, { abortEarly: false, // validate all fields in the segment }, { mode: Modes.FULL, // validate all segments (body, query, etc.) } ); const email = Joi.string().email().required(); // NOTE instead of prehashing passwords with SHA256, we could limit // them to 72 bytes (important: not characters) like so: .max(72, 'utf8') // However, this would likely leak our password algorithm (i.e. bcrypt). const password = Joi.string().max(256).required(); // TODO password strength export const loginSchema = { [Segments.BODY]: Joi.object().keys({ email, password, }), }; export const registerSchema = { [Segments.BODY]: Joi.object().keys({ email, password, name: Joi.string().max(256).required(), }), }; // Based on Postgres `serial` type (4 bytes, roughly 2.1B) // https://www.postgresql.org/docs/9.1/datatype-numeric.html const id = Joi.number() .positive() // can't be zero or negative .max(2 ** 31 - 1) .required(); export const verifyEmailSchema = { [Segments.QUERY]: { id, expires: Joi.date().timestamp().raw().required(), // `raw` means it's not casted to a Date signature: Joi.string().length(64).required(), // 256 / 8 * 2 (hex) }, }; export const resendEmailSchema = { [Segments.BODY]: Joi.object().keys({ email, }), }; export const sendResetSchema = { [Segments.BODY]: Joi.object().keys({ email, }), }; export const resetPasswordSchema = { [Segments.QUERY]: { id, token: Joi.string() .length(PWD_RESET_TOKEN_BYTES * 2) // hex .required(), }, [Segments.BODY]: Joi.object().keys({ password, }), }; export const confirmPasswordSchema = { [Segments.BODY]: Joi.object().keys({ password, }), };
d830404bca9e58a5d2d0ae3ac4e64c76d218cecf
TypeScript
shujathkhan/fluentui
/packages/react-checkbox/src/components/Checkbox/Checkbox.types.ts
2.953125
3
import * as React from 'react'; import { ComponentPropsCompat, ComponentStateCompat, ShorthandPropsCompat } from '@fluentui/react-utilities'; import { LabelProps } from '@fluentui/react-label'; /** * TODO: * - Remove as from Omit. Currently it's needed since checkbox Commons shouldn't have as. * - Instead of extending LabelProps, extend LabelCommons once it's added. */ export interface CheckboxCommons extends Omit<LabelProps, 'defaultChecked' | 'onChange' | 'as'> { /** * Disabled state of the checkbox. */ disabled?: boolean; /** * Required state of the checkbox. */ required?: boolean; /** * A checkbox can be rendered with a circular shape. */ circular?: boolean; /** * A checkbox's state can be controlled. * @defaultvalue false */ checked?: 'mixed' | boolean; /** * Whether the checkbox should be rendered as checked by default. */ defaultChecked?: 'mixed' | boolean; /** * Checkbox supports two different checkbox sizes. * @defaultvalue 'medium' */ size: 'medium' | 'large'; /** * Determines whether the label should be positioned before or after the checkbox. * @defaultvalue 'after' */ labelPosition: 'before' | 'after'; /** * ID of the root element that wraps the checkbox and label. */ rootId?: string; /** * ID of the native element that represents the checkbox. */ id?: string; /** * Callback to be called when the checked state value changes. */ onChange?: (ev: React.FormEvent<HTMLInputElement>, data: CheckboxOnChangeData) => void; } /** * Data for the onChange event for checkbox. */ export interface CheckboxOnChangeData { checked: 'mixed' | boolean; } /** * Checkbox Props */ export interface CheckboxProps extends ComponentPropsCompat, Partial<CheckboxCommons> { /** * Hidden input that handles the checkbox's functionality. */ input?: ShorthandPropsCompat<React.InputHTMLAttributes<HTMLInputElement> & React.RefAttributes<HTMLInputElement>>; /** * Renders the checkbox, with the checkmark icon as its child when checked. */ indicator?: ShorthandPropsCompat<React.HTMLAttributes<HTMLDivElement>>; } /** * State used in rendering Checkbox */ export interface CheckboxState extends ComponentStateCompat<CheckboxProps, 'input' | 'indicator', 'size' | 'labelPosition' | 'input' | 'indicator'> { /** * Ref to the root element. */ ref: React.Ref<HTMLElement>; /** * CSS class for the container of the input element and indicator slot. */ containerClassName?: string; }
0ae6750a3d3101c471ca6652cb704adef06547f5
TypeScript
redaktor/widgets
/src/common/activityPub.ts
2.765625
3
function apObj(prev: any, cur: any) { prev[cur.name] = { ...cur, id: `https://www.w3.org/ns/activitystreams#${cur.name}`, url: `https://www.w3.org/TR/activitystreams-vocabulary/#dfn-${cur.name.toLowerCase()}` }; return prev } const actors = [ { name: 'Application', summary: `Describes a software application.` },{ name: 'Group', summary: `Represents a formal or informal collective of Actors.` },{ name: 'Organization', summary: `Represents an organization.` },{ name: 'Person', summary: `Represents an individual person.` },{ name: 'Service', summary: `Represents a service of any kind.` } ]; const activities = [ {name: 'Activity', summary: 'Generic Activity'}, { name: 'Accept', summary: `Indicates that the actor accepts the object. The target property can be used in certain circumstances to indicate the context into which the object has been accepted.` },{ name: 'Add', summary: `Indicates that the actor has added the object to the target. If the target property is not explicitly specified, the target would need to be determined implicitly by context. The origin can be used to identify the context from which the object originated.` },{ name: 'Announce', summary: `(aka 'share') Indicates that the actor is calling the target's attention the object. The origin typically has no defined meaning.` },{ name: 'Arrive', summary: `An IntransitiveActivity that indicates that the actor has arrived at the location. The origin can be used to identify the context from which the actor originated. The target typically has no defined meaning.` },{ name: 'Block', summary: `Indicates that the actor is blocking the object. Blocking is a stronger form of Ignore. The typical use is to support social systems that allow one user to block activities or content of other users. The target and origin typically have no defined meaning.` },{ name: 'Create', summary: `Indicates that the actor has created the object.` },{ name: 'Delete', summary: `Indicates that the actor has deleted the object. If specified, the origin indicates the context from which the object was deleted.` },{ name: 'Dislike', summary: `Indicates that the actor dislikes the object.` },{ name: 'Flag', summary: `Indicates that the actor is "flagging" the object. Flagging is defined in the sense common to many social platforms as reporting content as being inappropriate for any number of reasons.` },{ name: 'Follow', summary: `Indicates that the actor is "following" the object. Following is defined in the sense typically used within Social systems in which the actor is interested in any activity performed by or on the object. The target and origin typically have no defined meaning.` },{ name: 'Ignore', summary: `Indicates that the actor is ignoring the object. The target and origin typically have no defined meaning.` },{ name: 'Invite', summary: `A specialization of Offer in which the actor is extending an invitation for the object to the target.` },{ name: 'Join', summary: `Indicates that the actor has joined the object. The target and origin typically have no defined meaning.` },{ name: 'Leave', summary: `Indicates that the actor has left the object. The target and origin typically have no meaning.` },{ name: 'Like', summary: `Indicates that the actor likes, recommends or endorses the object. The target and origin typically have no defined meaning.` },{ name: 'Listen', summary: `Indicates that the actor has listened to the object.` },{ name: 'Move', summary: `Indicates that the actor has moved object from origin to target. If the origin or target are not specified, either can be determined by context.` },{ name: 'Offer', summary: `Indicates that the actor is offering the object. If specified, the target indicates the entity to which the object is being offered.` },{ name: 'Question', summary: `Represents a question being asked. Question objects are an extension of IntransitiveActivity. That is, the Question object is an Activity, but the direct object is the question itself and therefore it would not contain an object property. Either of the anyOf and oneOf properties may be used to express possible answers, but a Question object must not have both properties.` },{ name: 'Reject', summary: `Indicates that the actor is rejecting the object. The target and origin typically have no defined meaning.` },{ name: 'Read', summary: `Indicates that the actor has read the object.` },{ name: 'Remove', summary: `Indicates that the actor is removing the object. If specified, the origin indicates the context from which the object is being removed.` },{ name: 'TentativeReject', summary: `A specialization of Reject in which the rejection is considered tentative.` },{ name: 'TentativeAccept', summary: `A specialization of Accept indicating that the acceptance is tentative.` },{ name: 'Travel', summary: `Indicates that the actor is traveling to target from origin. Travel is an IntransitiveObject whose actor specifies the direct object. If the target or origin are not specified, either can be determined by context.` },{ name: 'Undo', summary: `Indicates that the actor is undoing the object. In most cases, the object will be an Activity describing some previously performed action (for instance, a person may have previously "liked" an article but, for whatever reason, might choose to undo that like at some later point in time). The target and origin typically have no defined meaning.` },{ name: 'Update', summary: `Indicates that the actor has updated the object. Note, however, that this vocabulary does not define a mechanism for describing the actual set of modifications made to object. The target and origin typically have no defined meaning.` },{ name: 'View', summary: `Indicates that the actor has viewed the object.` } ]; const objects = [ {name: 'Object', summary: 'Generic Object'}, { name: 'Article', summary: `Represents any kind of multi-paragraph written work.` },{ name: 'Audio', summary: `Represents an audio document of any kind.` },{ name: 'Document', summary: `Represents a document of any kind.` },{ name: 'Event', summary: `Represents any kind of event.` },{ name: 'Image', summary: `Represents an image document of any kind.` },{ name: 'Note', summary: `Represents a short written work typically less than a single paragraph in length.` },{ name: 'Page', summary: `Represents a Web Page.` },{ name: 'Place', summary: `Represents a logical or physical location.` },{ name: 'Video', summary: `Represents a video document of any kind.` }, { name: 'Profile', summary: `A Profile is a content object that describes another Object, typically used to describe Actor Type objects. The describes property is used to reference the object being described by the profile.` },{ name: 'Relationship', summary: `Describes a relationship between two individuals. The subject and object properties are used to identify the connected individuals.` },{ name: 'Tombstone', summary: `A Tombstone represents a content object that has been deleted. It can be used in Collections to signify that there used to be an object at this position, but it has been deleted.` }, { name: 'Collection', summary: `A Collection is a subtype of Object that represents ordered or unordered sets of Object or Link instances.` },{ name: 'OrderedCollection', summary: `A subtype of Collection in which members of the logical collection are assumed to always be strictly ordered.` },{ name: 'CollectionPage', summary: `Used to represent distinct subsets of items from a Collection. Refer to the Activity Streams 2.0 Core for a complete description.` },{ name: 'OrderedCollectionPage', summary: `Used to represent ordered subsets of items from an OrderedCollection. Refer to the Activity Streams 2.0 Core for a complete description.` }, /* redaktor: 1, chat: 1, terminal: 1, map: 1 */ ]; const links = [ { name: 'Link', summary: `Represents a link.` },{ name: 'Mention', summary: `A specialized Link that represents an @mention.` } ] export const ActivityPubActors = actors.reduce(apObj, {}); export const ActivityPubActivities = activities.reduce(apObj, {}); export const ActivityPubObjects = objects.reduce(apObj, {}); export const ActivityPubLinks = links.reduce(apObj, {});
b0389066b369d59ed086e0a943d5eff96f5e21e9
TypeScript
DanielMSchmidt/cdktf-local-docker
/src/dockerImage.ts
2.5625
3
import { Construct, } from "constructs"; import { Resource, TerraformResource } from 'cdktf'; import { CustomDataSource } from './custom-data-source' export interface IImage { digest: string; } export interface DockerImageConfig { name: string, dependsOn?: TerraformResource[]; } interface CustomDockerImageInput { name: string; } interface CustomDockerImageOutput { sha256Digest: string; } class CustomDockerImage extends CustomDataSource<CustomDockerImageInput, CustomDockerImageOutput> {}; export class DockerImage extends Resource implements IImage { public readonly data: CustomDockerImage; public readonly digest: string; public readonly url: string; constructor(scope: Construct, name: string, config: DockerImageConfig) { super(scope, name); this.data = new CustomDockerImage(this, 'fetchImage', { inputs: { name: config.name, }, code: async (args) => { const drc = require('docker-registry-client') return new Promise((resolve, reject) => { var rar = drc.parseRepoAndRef((args as any).repositoryUrl); var client = drc.createClientV2({ repo: rar, insecure: false, maxSchemaVersion: 2 }); var tagOrDigest = rar.tag || rar.digest; client.getManifest({ref: tagOrDigest}, function (err:any, _manifest:any, _res:any, manifestStr:any) { client.close(); if (err) { reject(err) } resolve({sha256Digest: drc.digestFromManifestStr(manifestStr)}); }); }); }, dependsOn: config.dependsOn }) this.digest = this.data.result("sha256Digest") this.url = `${config.name}@${this.digest}` } }
a266df43bcf3a4958b10913e01fbc6f0823456a7
TypeScript
dconyers/TypeScriptPlayground
/other.ts
2.984375
3
function dougTest() { return "Doug is Cool"; } // This works, but throws errors in Typescript // dougTest = function() { // return "Doug is Cool"; // };
6de10376127f944abcf34b6bb246214e976d6574
TypeScript
mhreza76/one_month_skill_test
/ES2015/methods.ts
3.71875
4
class Person{ constructor(name){ this.name = name; console.log(name + " Constructor"); } static staticMethod(){ console.log("Static Method Called") } greeetPerson(){ console.log("Hello " + this.name); } } let p1 = new Person("Reza"); Person.staticMethod(); p1.greeetPerson();
18196120880f65b7de15a01ded629a79cc320e92
TypeScript
Pokonelakokode/VodafonePhoneBookTest
/src/utils.test.ts
3.078125
3
import {getHash, isObject, loadFromStorage, saveToStorage, setHash, validateEmail} from "./utils"; import JSONusers from './users.json'; describe("setHash",() => { it('should return an empty string for an empty object', function () { setHash(); expect(window.location.hash).toBe("") }); it('should set correct user id to hash', function () { setHash({user:2}); expect(window.location.hash).toBe("#user=2") }); it('should set correct user id for negative number', function () { setHash({user: -1}); expect(window.location.hash).toBe("#user=-1"); }); it('should set empty hash to non object parameter', function () { setHash("Not an object" as {}); expect(window.location.hash).toBe(""); }); }); describe("saveToStorage",() => { it('should create an empty users storage without param', function () { saveToStorage(); expect(JSON.parse(localStorage.getItem("users")!)).toStrictEqual([]); }); it('should be able to save to storage and read it back', function () { const test = [{name: "TEST",phone:"1234678",email:"test@email.com",id:1}]; saveToStorage(test); expect(JSON.parse(localStorage.getItem("users")!)).toStrictEqual(test); }); }); describe("validateEmail",() => { it('should return true for valid email', function () { expect(validateEmail("test@example.com")).toBe(true); }); it('should return false if the structure is wrong', function () { expect(validateEmail("@asd.com")).toBe(false); expect(validateEmail("asd@.com")).toBe(false); expect(validateEmail("asd@om")).toBe(false); }); }); describe("loadFromStorage", () => { it('should be able to load from JSON file', function () { localStorage.removeItem("users"); expect(loadFromStorage()).toStrictEqual(JSONusers); }); it('should be able to read from storage if it exists', function () { saveToStorage(); expect(loadFromStorage()).toStrictEqual([]); }); it('should load from JSON if the storage unparsable', function () { localStorage.setItem("users","45gfsdfgh"); expect(loadFromStorage()).toStrictEqual(JSONusers); }); }); describe("getHash",() => { it('should be able to get hash and return an object', function () { setHash({users:2}); expect(getHash()).toStrictEqual({users: "2"}); }); }); describe("isObject", () => { it('should return true for object', function () { expect(isObject({})).toBe(true); }); it('should return false for not objects', function () { expect(isObject("sdfs")).toBe(false); expect(isObject(1)).toBe(false); expect(isObject([])).toBe(false); expect(isObject(Symbol('123123'))).toBe(false); }); });
0eaf4510ab1864b2676c52e01361e2f2a5d17d78
TypeScript
GabrielPinedo/PrimeropasosTS
/src/ejercicios/06-desestructurandoFunciones.ts
3.109375
3
export interface Producto { desc: string; precio: number; } const telefono : Producto = { desc: 'Nokia V3', precio: 2000000, } const tableta : Producto = { desc: 'samsung tap 3', precio: 4000000 } export function calculaISV(productos: Producto[]) :[number, number]{ let total = 0; let nproducto = 0; let desc2 =''; productos.forEach(({precio, desc}) =>{ total += precio; nproducto += 1; }) return [total, total * 0.19]; } const articulos = [telefono, tableta]; const [total, isv] = calculaISV(articulos); console.log('El total es- : ', total); console.log('el impuesto sobre la venta es dse : ', isv);
ba616076c7804a4c4231e7d0f9e2d1511a99b55f
TypeScript
jobayersarkar/ivr-tester
/packages/cli/src/options/config/json/validateJsonConfig.spec.ts
2.53125
3
import { JsonConfig } from "./JsonConfig"; import { validateConfig } from "./validateJsonConfig"; const validConfig: JsonConfig = { transcriber: { name: "test", options: {}, }, recording: { audio: { filename: "/test-filename", outputPath: "/test/path", }, transcript: { filename: "/test-filename", outputPath: "/test/path", includeResponse: false, }, }, }; test("Return JSON recording config if no errors", () => { const validationResult = validateConfig(validConfig); expect(validationResult.error).not.toBeDefined(); expect(validationResult.config).toMatchObject(validConfig); }); test("Return errors if invalid", () => { const invalidConfig = { recording: { audio: { filename: 123, outputPath: "/test/path", }, transcript: { outputPath: "/test/path", }, }, }; const validationResult = validateConfig(invalidConfig); expect(validationResult.error).toBeDefined(); expect(validationResult.config).not.toBeDefined(); }); test("Return JSON with default localServerPort", () => { const validationResult = validateConfig(validConfig); expect(validationResult.error).not.toBeDefined(); expect(validationResult.config).toMatchObject({ localServerPort: 8080 }); });
bd91bdfddc8ddeed8a04ceae4223b60b69ee9330
TypeScript
teraSurfer/software-temp
/packages/rent-app-server/src/entities/roles.ts
2.546875
3
import { Entity, BaseEntity, PrimaryGeneratedColumn, Column } from 'typeorm'; import { Field, ID, ObjectType, } from 'type-graphql'; @ObjectType() @Entity('roles') export class Role extends BaseEntity { @Field(() => ID) @PrimaryGeneratedColumn('increment') id: number; @Field() @Column('varchar',{name:'role_name', nullable:false, unique: true}) roleName: string; @Field() @Column('text',{name: 'role_description'}) roleDescription: string; }
d5a92f357caeafd85b55c2b568ca7e5e836d3fa7
TypeScript
animesh-code/my_town_app_backend
/src/auth/domain/User.ts
2.515625
3
export default class User { constructor( public readonly id: string, public readonly place_id: string, public readonly number: string, public readonly name: string, public readonly gender?: string, public readonly age?: Date, public readonly donor?: boolean, public readonly bloodGroup?: string ) {} } // enum BloodGroup { // "A+", // "A-", // "B+", // "B-", // "AB+", // "AB-", // "O+", // "O-", // }
8d0de81e5dda67cc6959dfe9ef523b6daa698ea5
TypeScript
Anmol-dev/instantsearch.js
/src/lib/routers/history.ts
3.03125
3
import qs from 'qs'; import { Router, RouteState } from '../../types'; type CreateURL = ({ qsModule, routeState, location, }: { qsModule: typeof qs; routeState: RouteState; location: Location; }) => string; type ParseURL = ({ qsModule, location, }: { qsModule: typeof qs; location: Location; }) => RouteState; type BrowserHistoryArgs = { windowTitle?: (routeState: RouteState) => string; writeDelay?: number; createURL?: CreateURL; parseURL?: ParseURL; }; const defaultCreateURL: CreateURL = ({ qsModule, routeState, location }) => { const { protocol, hostname, port = '', pathname, hash } = location; const queryString = qsModule.stringify(routeState); const portWithPrefix = port === '' ? '' : `:${port}`; // IE <= 11 has no proper `location.origin` so we cannot rely on it. if (!queryString) { return `${protocol}//${hostname}${portWithPrefix}${pathname}${hash}`; } return `${protocol}//${hostname}${portWithPrefix}${pathname}?${queryString}${hash}`; }; const defaultParseURL: ParseURL = ({ qsModule, location }) => { // `qs` by default converts arrays with more than 20 items to an object. // We want to avoid this because the data structure manipulated can therefore vary. // Setting the limit to `100` seems a good number because the engine's default is 100 // (it can go up to 1000 but it is very unlikely to select more than 100 items in the UI). // // Using an `arrayLimit` of `n` allows `n + 1` items. // // See: // - https://github.com/ljharb/qs#parsing-arrays // - https://www.algolia.com/doc/api-reference/api-parameters/maxValuesPerFacet/ return qsModule.parse(location.search.slice(1), { arrayLimit: 99 }); }; const setWindowTitle = (title?: string): void => { if (title) { window.document.title = title; } }; class BrowserHistory implements Router { /** * Transforms a UI state into a title for the page. */ private readonly windowTitle?: BrowserHistoryArgs['windowTitle']; /** * Time in milliseconds before performing a write in the history. * It prevents from adding too many entries in the history and * makes the back button more usable. * * @default 400 */ private readonly writeDelay: Required<BrowserHistoryArgs>['writeDelay']; /** * Creates a full URL based on the route state. * The storage adaptor maps all syncable keys to the query string of the URL. */ private readonly _createURL: Required<BrowserHistoryArgs>['createURL']; /** * Parses the URL into a route state. * It should be symetrical to `createURL`. */ private readonly parseURL: Required<BrowserHistoryArgs>['parseURL']; private writeTimer?: number; private _onPopState?(event: PopStateEvent): void; /** * Initializes a new storage provider that syncs the search state to the URL * using web APIs (`window.location.pushState` and `onpopstate` event). */ public constructor( { windowTitle, writeDelay = 400, createURL = defaultCreateURL, parseURL = defaultParseURL, }: BrowserHistoryArgs = {} as BrowserHistoryArgs ) { this.windowTitle = windowTitle; this.writeTimer = undefined; this.writeDelay = writeDelay; this._createURL = createURL; this.parseURL = parseURL; const title = this.windowTitle && this.windowTitle(this.read()); setWindowTitle(title); } /** * Reads the URL and returns a syncable UI search state. */ public read(): RouteState { return this.parseURL({ qsModule: qs, location: window.location }); } /** * Pushes a search state into the URL. */ public write(routeState: RouteState): void { const url = this.createURL(routeState); const title = this.windowTitle && this.windowTitle(routeState); if (this.writeTimer) { window.clearTimeout(this.writeTimer); } this.writeTimer = window.setTimeout(() => { if (window.location.href !== url) { setWindowTitle(title); window.history.pushState(routeState, title || '', url); } this.writeTimer = undefined; }, this.writeDelay); } /** * Sets a callback on the `onpopstate` event of the history API of the current page. * It enables the URL sync to keep track of the changes. */ public onUpdate(callback: (routeState: RouteState) => void): void { this._onPopState = event => { if (this.writeTimer) { window.clearTimeout(this.writeTimer); this.writeTimer = undefined; } const routeState = event.state; // At initial load, the state is read from the URL without update. // Therefore the state object is not available. // In this case, we fallback and read the URL. if (!routeState) { callback(this.read()); } else { callback(routeState); } }; window.addEventListener('popstate', this._onPopState); } /** * Creates a complete URL from a given syncable UI state. * * It always generates the full URL, not a relative one. * This allows to handle cases like using a <base href>. * See: https://github.com/algolia/instantsearch.js/issues/790 */ public createURL(routeState: RouteState): string { return this._createURL({ qsModule: qs, routeState, location: window.location, }); } /** * Removes the event listener and cleans up the URL. */ public dispose(): void { if (this._onPopState) { window.removeEventListener('popstate', this._onPopState); } if (this.writeTimer) { window.clearTimeout(this.writeTimer); } this.write({}); } } export default function(props?: BrowserHistoryArgs): BrowserHistory { return new BrowserHistory(props); }
6d5232978c258d40040d1b9b8ecb3a64b9bfb65b
TypeScript
3askaal/3oilerplate
/src/core/style/utils/color.ts
2.640625
3
import chroma from 'chroma-js' export function darken (color: string, amount: number = 0.2) { return chroma(color).darken(amount).hex() } export function brighten (color: string, amount: number = 0.2) { return chroma(color).brighten(amount).hex() } export function rgba (color: string, amount: number = 0.2) { return chroma(color).alpha(amount).hex() } export function mix (firstColor: string, secondColor: string, amount?: number) { return chroma.mix(firstColor, secondColor, amount).hex() }
85d449a6d5c74955228dfda27b398dfa5c24aeb8
TypeScript
olehcambel/telegram-bot-tours
/src/modules/winston-telegram.ts
2.59375
3
import Telegraf from 'telegraf'; import Transport /* , { TransportStreamOptions } */ from 'winston-transport'; import config from '../config'; const pre = '```'; const logLevel = (level: string): string => { switch (level) { case 'error': return 'ERROR'; case 'warn': return 'WARN'; case 'info': return 'INFO'; case 'verbose': return 'VERBOSE'; case 'debug': return 'DEBUG'; case 'http': return 'HTTP'; default: return 'UNKNOWN_LVL'; } }; // Inherit from `winston-transport` so you can take advantage // of the base functionality and `.exceptions.handle()`. // export default class WinstonRocket extends Transport { bot = new Telegraf(config.botToken); // constructor(opts: TransportStreamOptions) { // super(opts); // Consume any custom options here. e.g.: // - Connection information for databases // - Authentication information for APIs (e.g. loggly, papertrail, // logentries, etc.). // // } async log(info: WinstonLog, callback: () => void): Promise<void> { setImmediate(() => { this.emit('logged', info); }); const lvl = logLevel(info.level); // prettier-ignore const message = info.stack || info.message.length > 100 ? `module **${info.label}** (${lvl})\n\n${pre}${info.stack || info.message}${pre}` : `module **${info.label}** (${lvl}) - \`${info.message}\``; await this.bot.telegram.sendMessage(config.channel.logId, message, { parse_mode: 'Markdown', }); // await this.rocketAgent.channelSendWithReconnect(this.channel, message, attachments); // Perform the writing to the remote service callback(); } } interface WinstonLog { level: string; label: string; timestamp: string; message: string; stack?: string; }
63db01673655a7925fd1d59f4169cc56863c935a
TypeScript
Nick-Mazuk/traveling-salesman
/_javascript/Road.ts
3
3
import { City } from './City' export class Road { cityA: City cityB: City #color = '#757575' #realityColor = '#FCCE00' static width = 3 constructor(cityA: City, cityB: City) { this.cityA = cityA this.cityB = cityB } draw(ctx: CanvasRenderingContext2D, cityGrid: boolean, blockXSize?: number) { if (cityGrid) { ctx.beginPath() // start position ctx.moveTo(this.cityA.anchorX, this.cityA.anchorY) if (this.cityA.onSameHorizontalRoad(this.cityB)) { ctx.lineTo(this.cityB.anchorX, this.cityB.anchorY) } else if (this.cityA.blockColumn == this.cityB.blockColumn) { if (this.cityA.blockColumnPosition > 0 && this.cityB.blockColumnPosition > 0) { const xDiff = 3 - this.cityA.blockColumnPosition ctx.lineTo(this.cityA.anchorX + xDiff * blockXSize, this.cityA.anchorY) ctx.lineTo(this.cityA.anchorX + xDiff * blockXSize, this.cityB.anchorY) } else { const xDiff = this.cityA.blockColumnPosition + 1 ctx.lineTo(this.cityA.anchorX - xDiff * blockXSize, this.cityA.anchorY) ctx.lineTo(this.cityA.anchorX - xDiff * blockXSize, this.cityB.anchorY) } ctx.lineTo(this.cityB.anchorX, this.cityB.anchorY) } else { if (this.cityA.anchorX < this.cityB.anchorX) { const xDiff = 3 - this.cityA.blockColumnPosition ctx.lineTo(this.cityA.anchorX + xDiff * blockXSize, this.cityA.anchorY) ctx.lineTo(this.cityA.anchorX + xDiff * blockXSize, this.cityB.anchorY) } else { const xDiff = this.cityA.blockColumnPosition + 1 ctx.lineTo(this.cityA.anchorX - xDiff * blockXSize, this.cityA.anchorY) ctx.lineTo(this.cityA.anchorX - xDiff * blockXSize, this.cityB.anchorY) } ctx.lineTo(this.cityB.anchorX, this.cityB.anchorY) } ctx.strokeStyle = this.#color if (cityGrid) ctx.strokeStyle = this.#realityColor ctx.lineWidth = Road.width ctx.stroke() } else { ctx.beginPath() ctx.moveTo(this.cityA.xPos, this.cityA.yPos) ctx.lineTo(this.cityB.xPos, this.cityB.yPos) ctx.strokeStyle = this.#color if (cityGrid) ctx.strokeStyle = this.#realityColor ctx.lineWidth = Road.width ctx.stroke() } } length(cityGrid: boolean): number { return this.cityA.distanceFromCity(this.cityB, cityGrid) } }
849ff405e432289b4f39f86ad15b9947aedb01f4
TypeScript
one-fwk/owe-cli
/src/util/filter-async.ts
2.9375
3
import { pipe, from, MonoTypeOperatorFunction } from 'rxjs'; import { map, filter, concatMap } from 'rxjs/operators'; export function filterAsync<T>(predicate: (value: T, index: number) => Promise<boolean>): MonoTypeOperatorFunction<T> { let count = 0; return pipe( // Convert the predicate Promise<boolean> to an observable (which resolves the promise, // Then combine the boolean result of the promise with the input data to a container object concatMap((data: T) => { return from(predicate(data, count++)) .pipe(map((isValid) => ({filterResult: isValid, entry: data}))); }), // Filter the container object synchronously for the value in each data container object filter(data => data.filterResult === true), // remove the data container object from the observable chain map(data => data.entry) ); }
55688d3e5991718a708bb6203d3ee317c8c28765
TypeScript
mariyanuzunov/nest-api-blindoor
/src/auth/auth.service.ts
2.59375
3
import { Injectable, BadRequestException, UnauthorizedException, } from '@nestjs/common'; import { RegisterUserDto } from './dto/register-user.dto'; import * as bcrypt from 'bcrypt'; import { UserService } from 'src/user/user.service'; import { LoginCredentialsDto } from './dto/login-credentials.dto'; import { JwtService } from '@nestjs/jwt'; import { IUser } from 'src/shared/interfaces/user.interface'; @Injectable() export class AuthService { constructor( private userService: UserService, private jwtService: JwtService, ) {} async validateUser(credentials: LoginCredentialsDto): Promise<IUser> { try { const user: IUser = await this.userService.getUserByEmail( credentials.email, ); const isValid = await bcrypt.compare(credentials.password, user.password); if (user && isValid) { return user; } } catch (error) { console.error(error); throw new UnauthorizedException('Invalid e-mail or password.'); } return null; } async login(user: IUser) { const accessToken = this.jwtService.sign({ id: user._id, email: user.email, }); return { _id: user._id, role: user.role, email: user.email, firstName: user.firstName, lastName: user.lastName, phone: user.phone, purcases: user.purchases, accessToken, }; } async register(userData: RegisterUserDto) { try { userData.password = await bcrypt.hash(userData.password, 10); return await this.userService.create(userData); } catch (error) { console.error(error); throw new BadRequestException(); } } async getProfile(userId: string) { return this.userService.getUserById(userId); } }
62e01e6d375c32dbdb593f873f9473bc9f4d21bc
TypeScript
pitaj/nodebb-plugin-calendar
/src/lib/translatorModule.ts
2.84375
3
import moment, { RelativeTimeKey } from 'moment'; import { NodebbTranslator } from 'translator'; const justDate = 'dddd, LL'; const justTime = 'LT'; const dateAndTime = 'LLLL'; const formatDates = ( s: number, e: number, allday: boolean, lang: string, utc: boolean ): string => { const mom = utc ? moment.utc : moment; const start = mom(s).locale(lang); const end = mom(e).locale(lang); if (Math.abs(s - e) <= 60 * 1000) { if (allday) { return start.format(justDate); } return start.format(dateAndTime); } if ( start.dayOfYear() === end.dayOfYear() && start.year() === end.year() ) { if (allday) { return start.format(justDate); } return `${start.format(justDate)}<br>` + `${start.format(justTime)} - ${end.format(justTime)}`; } if (allday) { return `${start.format(justDate)} - ${end.format(justDate)}`; } return `${start.format(dateAndTime)} - ${end.format(dateAndTime)}`; }; const initialize = (Translator: NodebbTranslator): void => { Translator.registerModule('moment', (lang) => { const momentLang = lang.replace(/[_@]/g, '-'); const zero = moment(0).locale(momentLang); const timeago = (key: string, [duration]: string[]) => { const ms = parseInt(duration, 10); switch (key) { case 'time-ago': return zero.from(ms); case 'time-in': return zero.to(ms); case 'time-duration': return zero.to(ms, true); default: return ''; } }; const timeDateView = ( key: string, [timezone, start, end, allday]: string[] ) => { const s = parseInt(start, 10); const e = parseInt(end, 10); const isAllday = allday === 'true'; if (timezone === 'utc') { return formatDates(s, e, isAllday, momentLang, true); } if (timezone === 'local') { return formatDates(s, e, isAllday, momentLang, false); } return ''; }; const data = zero.localeData(); const localeData = (key: string, [method, a, b, c, d]: string[]) => { switch (method) { case 'months': case 'monthsShort': case 'weekdays': case 'weekdaysShort': case 'weekdaysMin': { const i = parseInt(a, 10); return data[method]()[i]; } case 'relativeTime': { const isFuture = d === 'true'; const withoutSuffix = b === 'true'; const num = parseInt(a, 10); const unit = c.slice(0, (num === 1) ? 1 : 2) as RelativeTimeKey; if (a.trim() === '') { return data.relativeTime('', withoutSuffix, unit, isFuture).trim(); } return data.relativeTime(num, withoutSuffix, unit, isFuture); } default: return ''; } }; return (key, args) => { switch (key) { case 'time-in': case 'time-ago': case 'time-duration': return timeago(key, args); case 'time-date-view': return timeDateView(key, args); case 'locale-data': return localeData(key, args); default: return ''; } }; }); }; export { formatDates, initialize };
982e05ac3c200c267649ae57267e6579a642c95f
TypeScript
elrancid/easylib-log
/lib/loggable.component.d.ts
2.71875
3
import { Loggable } from './loggable'; /** * Extend `Loggable` in components and set boolean `logs` property * to enable logs. Use `this.log()` and the other methods to print to console * if `logs` is `true`. */ export declare class LoggableComponent extends Loggable { logs: boolean; constructor(); }
8b2430332496ac882631398d23dd8ec0a7079fd3
TypeScript
RafaelSalguero/linqjs
/src/nullsafe.ts
3.140625
3
import { pipe } from "./pipe"; export type NonNullable<T> = T extends null | undefined ? never : T; export type ExtractNullType<T> = T extends null | undefined ? T : never; type NSF<I, O> = (x: NonNullable<I>) => O; export function nullsafe<T1, T2, T3, T4, T5, T6>(value: T1, m1: NSF<T1, T2>, m2: NSF<T2, T3>, m3: NSF<T3, T4>, m4: NSF<T4, T5>, m5: NSF<T5, T6>): T6 | ExtractNullType<T1 | T2 | T3 | T4 | T5> export function nullsafe<T1, T2, T3, T4, T5>(value: T1, m1: NSF<T1, T2>, m2: NSF<T2, T3>, m3: NSF<T3, T4>, m4: NSF<T4, T5>): T5 | ExtractNullType<T1 | T2 | T3 | T4> export function nullsafe<T1, T2, T3, T4>(value: T1, m1: NSF<T1, T2>, m2: NSF<T2, T3>, m3: NSF<T3, T4>): T4 | ExtractNullType<T1 | T2 | T3> export function nullsafe<T1, T2, T3>(value: T1, m1: NSF<T1, T2>, m2: NSF<T2, T3>): T3 | ExtractNullType<T1 | T2> export function nullsafe<T1, T2>(value: T1, m1: NSF<T1, T2>): T2 | ExtractNullType<T1> //export function nullsafe<N extends null | undefined | never, T1, T2>(value: T1 | N, m1: (x: NonNullable<T1>) => T2 | N): T2 | N export function nullsafe<T>(value: T): T export function nullsafe(value: any, ...maps: ((x: any) => any)[]) { const nullMaps = maps.map(func => value => value == null ? value : func(value)); return (pipe as any)(value, ...nullMaps); }
9b69e08a9c9a9e89d9b2da1c1cfe177b1d0d489a
TypeScript
Joshimcse/bongo
/tests/1-anagram.test.ts
3.59375
4
import { assert } from "chai"; import isAnagram from "../anagram/anagram"; /** * @test :: Unit testing for Q.1 - Is Anagram or Not * @passingData :: * * expected case - 1: should return true when two string is anagram - ['table', 'bleat'] * expected case - 2: should return false when two string are not anagram - ['tar', 'eat'] * expected case - 3: Should return true when passing value with whitespace but strings are still anagram - ['William Shakespeare', 'I am a weakish speller'] */ describe("Unit testing for Q.1: Anagram ", () => { it("should return true when two string is anagram - ['table', 'bleat']", (done) => { assert.equal(isAnagram("table", "bleat"), true); done(); }); it("should return false when two string are not anagram - ['tar', 'eat']", (done) => { assert.equal(isAnagram("tar", "eat"), false); done(); }); it("Should return true when passing value with whitespace but strings are still anagram - ['William Shakespeare', 'I am a weakish speller']", (done) => { assert.equal( isAnagram("William Shakespeare", "I am a weakish speller"), true ); done(); }); });
c7a63dc561e34e28ce37c0af0e29d95f7598359e
TypeScript
iamgilvan/ImageRotation
/src/test/index.test.ts
3.09375
3
import { PixelArrayRotator } from './../index'; // BB // WW // WW const uArr = new Uint8Array([ 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, ]); // WWB // WWB const uArr2 = new Uint8Array([ 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 255, ]); // WW // WW // BB const uArr3 = new Uint8Array([ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 255, 0, 0, 0, 255, ]); // BWW // BWW const uArr4 = new Uint8Array([ 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, ]); const blackPixel = [0, 0, 0, 255]; const whitePixel = [255, 255, 255, 255]; const assertBlackPixel = (pixel: Array<any>) => expect(pixel).toEqual(blackPixel); const assertWhitePixel = (pixel: Array<any>) => expect(pixel).toEqual(whitePixel); describe('PixelArrayRotator', () => { let rotator: PixelArrayRotator; beforeEach(() => { rotator = new PixelArrayRotator(uArr, 2, 3); }); it('#getPixelStartIndexForCoord should return the starting index of the pixel at (X, Y)', async () => { const rotator2 = new PixelArrayRotator(uArr2, 3, 3); let i = rotator.getPixelStartIndex(0, 0); const firstPixel = [ rotator.pixelArray[i], rotator.pixelArray[i + 1], rotator.pixelArray[i + 2], rotator.pixelArray[i + 3], ]; let i2 = rotator2.getPixelStartIndex(0, 0); const firstPixel2 = [ rotator2.pixelArray[i2], rotator2.pixelArray[i2 + 1], rotator2.pixelArray[i2 + 2], rotator2.pixelArray[i2 + 3], ]; assertBlackPixel(firstPixel); assertWhitePixel(firstPixel2); i = rotator.getPixelStartIndex(0, 1); const secondRowFirstPixel = [ rotator.pixelArray[i], rotator.pixelArray[i + 1], rotator.pixelArray[i + 2], rotator.pixelArray[i + 3], ]; i2 = rotator2.getPixelStartIndex(0, 1); const secondRowFirstPixel2 = [ rotator2.pixelArray[i2], rotator2.pixelArray[i2 + 1], rotator2.pixelArray[i2 + 2], rotator2.pixelArray[i2 + 3], ]; assertWhitePixel(secondRowFirstPixel); assertWhitePixel(secondRowFirstPixel2); }); it('#rotate by default should return a 90 degree rotated-rightwards array', async () => { expect(rotator.rotate()).toEqual(uArr2); }); it('#rotate(-90) should return a -90 degree rotated-leftwards array', async () => { expect(rotator.rotate(-90)).toEqual(uArr4); }); it('#rotate(180) should return a 180 degree rotated-rightwards array', async () => { expect(rotator.rotate(180)).toEqual(uArr3); }); it('#rotate(-180) should return a -180 degree rotated-leftwards array', async () => { expect(rotator.rotate(-180)).toEqual(uArr3); }); it('#rotate(270) should return a 270 degree rotated-rightwards array', async () => { expect(rotator.rotate(270)).toEqual(uArr4); }); it('#rotate(-270) should return a -270 degree rotated-leftwards array', async () => { expect(rotator.rotate(-270)).toEqual(uArr2); }); }); describe('ImageDataRotator#rotate', () => { let page: any; const browserRotate = async function( pixelArray: any, width: number, height: number, degree: number ) { return page.evaluate( (pixelArr: any, w: number, h: number, d: number) => { const data: Uint8ClampedArray = new Uint8ClampedArray(pixelArr); const image = new window.ImageData(data, w, h); // @ts-ignore const rotatedImage = rotator.ImageDataRotator.rotate(image, d); return { pixelArray: Array.from(rotatedImage.data), height: rotatedImage.rotatedHeight, width: rotatedImage.rotatedWidth, }; }, pixelArray, width, height, degree ); }; beforeAll(async () => { page = await browser.newPage(); await page.addScriptTag({ path: 'dist/rotator.umd.development.js', }); }); afterAll(async () => page.close()); it('should return a rotated-rightwards array', async () => { const result = await browserRotate(Array.from(uArr), 2, 3, 90); expect(result.pixelArray).toEqual(Array.from(uArr2)); }); });
aea170660ee4890bd18d59896abd6a8569a62b54
TypeScript
JasonWeinzierl/simple-chatroom
/src/client.ts
2.953125
3
/** * TCP client uses Node.js net module * to chat with TCP server over command line */ import { Socket } from 'net'; import { createInterface } from 'readline'; import ora from 'ora'; export default function startClient() { // spinner for console notifications const spinner = ora().start('Connecting...'); // open socket, connect to localhost const client = new Socket(); client.connect(10119, 'localhost', function() { spinner.succeed('Connected to localhost:10119.'); console.log(`Client: ${client.localAddress}:${client.localPort}`); console.log(`Server: ${client.remoteAddress}:${client.remotePort}`); }); /** * incoming data handler */ client.on('data', (data: string) => { console.log(`> ${data}`); //rl.prompt(); }); /** * socket close handler */ client.on('close', hadError => { if (hadError) { spinner.fail('Connection closed due to error.'); } else { spinner.info('Connection closed.'); } // stop watching stdin rl.close(); }); /** * error handler */ client.on('error', (err: NodeJS.ErrnoException) => { switch (err.code) { case 'ECONNREFUSED': spinner.fail('Server refused connection. The server is probably inactive.'); break; default: spinner.fail(err.message); } }); /** * stdin reader */ const rl = createInterface({ input: process.stdin, output: process.stdout, // AUTO COMPLETION completer: (line: string) => { const completions = 'help login logout newuser who exit send'.split(' '); const hits = completions.filter( c => c.startsWith(line) ); return [hits.length ? hits : completions, line]; }, }); rl.on('line', line => { spinner.start('Sending...'); // don't send if connection isn't set up if (client.pending || client.connecting) { spinner.fail('Message send failed. No connection.'); return; } // send data and stop spinner when data is written out. client.write(line + '\n', 'utf8', () => { spinner.stop(); }); //rl.prompt(); }); // end client when we can't read stdin any more. // usually because of interrupt or EOL signal rl.on('close', () => { client.end(); }); // prompt user for first input //rl.prompt(); }
379e9a571f4316e7b146166a9c7fdbd337bd71f1
TypeScript
pokemondev/smogon-stats-discord
/src/commands/setsCommand.ts
2.78125
3
import Discord = require('discord.js'); import { CommandBase } from "./command"; import { AppDataSource } from "../appDataSource"; import { ColorService } from '../pokemon/colorService'; import { FormatHelper } from '../smogon/formatHelper'; import { ImageService } from '../pokemon/imageService'; export class SetsCommand extends CommandBase { name = "sets"; description = "Lists the Smogon Sets for the Pokémon"; aliases = [ 'set' ]; constructor(dataSource: AppDataSource) { super(dataSource); } async execute(message: any, args: any) { const argsData = this.tryParseCommandArgs(message, args); if (!argsData.valid) { return message.channel.send(argsData.errorMessage); } const format = argsData.format; const pokemon = argsData.pokemon; const sets = this.dataSource.smogonSets.get(pokemon, format); const embed = new Discord.MessageEmbed() .setColor(ColorService.getColorForType(pokemon.type1)) .setThumbnail(ImageService.getPngUrl(pokemon)) .setFooter("More details on smogon.com") sets.forEach((set) => { var setText = FormatHelper.getSmogonSet(pokemon, set); embed.addField(`${set.name}`, `${setText}\u2006`, true); }); const msgHeader = `**__Sets:__** Top ${pokemon.name} sets of ${FormatHelper.toString(format)}`; message.channel.send(msgHeader, embed); } }
58254811075363157772deb4013000d20ca4c31f
TypeScript
lichenchen-lcc/lcc_resource
/example-3d-master/simple-fps/assets/TS/levelscol1.ts
2.65625
3
import { _decorator, Component, Node } from "cc"; const { ccclass, property } = _decorator; import { Con } from './Constants'; @ccclass("levelscol1") export class levelscol1 extends Component { /* class member could be defined like this */ // dummy = ''; /* use `property` decorator if your want the member to be serializable */ // @property // serializableDummy = 0; start () { // Your initialization goes here. Con._LevelsCount=cc.math.randomRangeInt(4,6); } update (deltaTime: number) { // Your update function goes here. if(Con._AtLevel==Con._LevelsCount){ //发出Boss出现信号 Con.BossReSignal=true; } } recoil(){ Con.RecoilSwitch=!Con.RecoilSwitch; } }
8a599bc03dce9ec45489037f73ed302bb8402fdc
TypeScript
kemila/Kemila
/06知识积累/react/redux原子化实现/redux-实现/define.ts
2.71875
3
import { KV } from '../../lib'; export type Class<T> = { new(...args: any[]): T, [k: string]: any; }; export type ActionKV = { type: string; module?: string; payload?: any }; export type PrepareFn = (payload: KV, moduleState: KV) => Promise<KV>; export type ReducerFn = (action: ActionKV, moduleState: KV) => KV; export type AnyClass = Class<any>; export type ActionClass = AnyClass & { Module: string; // 模块名 Prepare?: PrepareFn; // 如果是异步动作,通过提供此方法来获取数据,并返回获取的数据,返回的数据会被外层manager传给Process来处理 Process: ReducerFn; }; export interface ModuleStore extends KV { module: string; }
93cd940c20f484fb35e2a5e74c10615eda58b485
TypeScript
WesleyCristiano/makelist-backend
/src/modules/lists/infra/typeorm/repository/ListRepository.ts
2.671875
3
import IListRepository from "@modules/lists/repositories/IListRepository"; import ICreateListDTO from "@modules/lists/dtos/ICreateListDTO"; import { Repository, getRepository } from "typeorm"; import List from "../entities/List"; import IFindListDTO from "@modules/lists/dtos/IFindListDTO"; class ListRepository implements IListRepository{ private ormRepository: Repository<List> constructor(){ this.ormRepository = getRepository(List) } public async create({school_id, grade_name, items}:ICreateListDTO): Promise<List>{ const list = this.ormRepository.create({ school_id, grade_name, items }) await this.ormRepository.save(list) return list } public async findList({school_id, grade_name}:IFindListDTO): Promise<List | undefined>{ const list = await this.ormRepository.createQueryBuilder('list') .where("list.school_id = :school_id", {school_id}) .andWhere("list.grade_name = :grade_name", {grade_name}).getOne() return list } public async findBySchool(school_id:string): Promise<List[]>{ const lists = await this.ormRepository.find({ loadRelationIds: true, where: {school_id} }) return lists } } export default ListRepository
553bcfe5be431429938bff99083ab1a4baeb8062
TypeScript
darkman2040/HonestProject
/src/app/screens/time-sheet/timeEntry.ts
2.5625
3
export class TimeEntry { constructor( public name: string, public timeInHours: number ) {} }
69129d0375742ca2f184a56a808a25e84db5d7ce
TypeScript
immybo/Recipes
/mobile/src/model/Category.ts
2.890625
3
export interface Category { id: number, name: string } export interface CategoryState { allCategories: Category[] } export function getBlankCategory(): Category { return { id: getUniqueCategoryId(), name: "", }; } var nextUniqueId: number = 0; export function getUniqueCategoryId(): number{ return nextUniqueId++; }
c8a0fcbf362993901f524662d596a18636482b6c
TypeScript
hien-cao/Game-online-shop
/game/src/interface/End.ts
2.640625
3
import { Button } from "../controls/Button"; import Game from "../Game"; import Overlay, { OverlayUpdateState } from "./Overlay"; export interface EndArgs { game: Game; } export default class End extends Overlay { public prevState: { buttons: Button[] }; constructor({ game, ...args }: EndArgs) { super({ ...args, height: game.canvas.height, width: game.canvas.width, }); const restartButton = new Button({ font: "16px Arial, Helvetica, sans-serif", label: "Restart Game", onClick: () => game.reset(), x: 0, y: this.canvas.height / 2, }); restartButton.x = this.canvas.width / 2 - restartButton.width / 2; const highScoreButton = new Button({ font: "18px Arial, Helvetica, sans-serif", label: "Submit score", onClick: () => { parent.postMessage({ messageType: "SCORE", score: game.score, }, window.location.href); }, x: 0, y: this.canvas.height - 40, }); highScoreButton.x = this.canvas.width / 2 - highScoreButton.width / 2; this.prevState = { buttons: [ restartButton, highScoreButton, ], }; } public render = () => { if (this.rendered) { return; // no need to re-render } const ctx = this.canvas.getContext("2d") as CanvasRenderingContext2D; ctx.fillStyle = "rgba(0, 0, 0, .5)"; ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); ctx.font = "10px Arial, Helvetica, sans-serif"; ctx.textAlign = "center"; ctx.fillStyle = "#eee"; ctx.fillText( "Your journey ended in the vast space,", this.canvas.width / 2, this.canvas.height / 2 - 48 ); ctx.fillText( "where the fragments of your ship fill float until the end of the time.", this.canvas.width / 2, this.canvas.height / 2 - 30 ); ctx.fillText( "You can only hope that your journey was not made in vain, and someone will hear of your heroic exploits", this.canvas.width / 2, this.canvas.height - 60 ); for (const button of this.prevState.buttons) { button.render(ctx); } this.rendered = true; } public update = ({ mouse, keyboard }: OverlayUpdateState) => { for (const button of this.prevState.buttons) { button.update(mouse); } } }
958635b27fd39b7574854b5aa74e5b202251454d
TypeScript
green-fox-academy/juditvarro
/week_4/day_01/student.ts
3.109375
3
import { Person } from "./person"; 'use strict' export class Student extends Person { private previousOrganization: string; private skippedDays: number; constructor(name: string = 'Jane Doe', age: number = 30, gender: string = 'female', previousOrganization: string = 'School of Life') { super(name, age, gender); this.previousOrganization = previousOrganization; this.skippedDays = 0; } getGoal(): void { console.log('My goal is: Be a junior software developer.'); } introduce(): void { console.log(`Hi, I'm ${this.name}, a ${this.age} years old ${this.gender}, from ${this.previousOrganization}, who skipped ${this.skippedDays} days from the course already.`); } skipDays(numberOfDays: number): void { this.skippedDays += numberOfDays; } }
cb7cce8538feae94b04ff98915a2d958b73752c7
TypeScript
moonpyk/gitfetcher
/lib/util.ts
2.59375
3
/* * gitfetcher * https://github.com/moonpyk/gitfetcher * * Copyright (c) 2014 Clément Bourgeois * Licensed under the MIT license. */ ///<reference path="../typings/tsd.d.ts"/> "use strict"; import path = require('path'); import _ = require('lodash'); export function replaceFileExtension(val:string, newExt:string):string { if (!_.isString(val)) { return val; } var currentExt = path.extname(val); return val.substr(0, val.length - currentExt.length) + newExt; } export function inferString(val:any):any { if (_.isString(val)) { var asInt = parseInt(val, 0), asFloat = parseFloat(val); if (_.isNumber(asFloat) && !_.isNaN(asFloat)) { return asFloat; } if (_.isNumber(asInt) && !_.isNaN(asInt)) { return asInt; } switch (val) { case "true": case "yes": return true; case "false": case "no": return false; case "undefined": return undefined; case "null": return null; } return val; } return val; } export function dotNotationToObject(path:string, value:any) { var ret = {}; if (_.isString(path)) { var next = ret; var splt = _(path.split('.')).select(function (v) { return !_.isEmpty(v); }).value(); if (splt.length === 0) { return value; } _(splt).each(function (v, k) { next = next[v] = ( splt.length - 1 === k) ? value : {}; }); } return ret; } export function resolveExpandEnv(f:string):string { return path.resolve( path.normalize(expandEnv(f)) ); } export function expandEnv(val:string):string { if (!_.isString(val)) { return val; } if (process.platform === "win32") { val = val.replace("~", "${USERPROFILE}"); } else { val = val.replace("~", "${HOME}"); } _(process.env).each(function (v, key) { val = val.replace( new RegExp('\\$\\{' + key + '\\}', "g"), process.env[key] ); }); val = val.replace(/\$\{\w*\}/g, ""); return val; } export function prompt(cb:Function) { var stdin = process.stdin; stdin.on('data', function (data) { if (_.isFunction(cb)) { cb(data); } }); return stdin.resume(); }
83d18b86a6d045ee74a134c1a86bd115e818199f
TypeScript
exxcellent/swt2-bsa-frontend
/bogenliga/src/app/modules/shared/pipes/truncation.pipe.ts
2.65625
3
import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'truncation' }) export class TruncationPipe implements PipeTransform { transform(input: string, truncationLength: number): string { if (input.length > truncationLength) { return input.substring(0, truncationLength) + '...'; } else { return input; } } }
18a6d5f03adaa901255b2e9bb56a9899945fe89e
TypeScript
1ncounter/util-libs
/packages/dsa/linked-list/has-cycle.ts
3.15625
3
import { INode } from './linked-list.interface'; export function hasCycle(head: INode<number>) { const set = new Set<INode<number>>(); while (head) { if (set.has(head)) { return true; } else { set.add(head); } head = head.next; } return false; } export function hasCycle2(head: INode<number>) { if (!head || !head.next) return false; let slow = head; let fast = head.next; while (slow !== fast) { if (!fast.next || !fast) return false; slow = slow.next; fast = fast.next.next; } return true; }
8bc0e47ee7c30b9a59edc30ed0f6df22d4dca36b
TypeScript
leon740727/types
/build/src/index.d.ts
2.84375
3
import { Optional } from './optional'; export { Optional } from './optional'; import { Result } from './result'; export { Result } from './result'; export declare type Primitive = string | number | boolean | null; export declare type Json = Primitive | Primitive[] | { [field: string]: Json; } | { [field: string]: Json; }[]; export declare class List<T> extends Array<T> { static of<T>(...data: T[]): List<T>; static make<T>(data: T[]): List<T>; map<S>(f: (v: T, index: number, array: T[]) => S): List<S>; filter(f: any): List<T>; chain<S>(f: (v: T) => S[]): List<S>; } export declare class IO<T> { exec: () => T; constructor(data: () => T); static of<T>(res: T): IO<T>; map<R>(f: (p: T) => R): IO<R>; chain<R>(f: (p: T) => IO<R>): IO<R>; } export declare class PromiseOptional<T> { data: Promise<Optional<T>>; constructor(data: Promise<Optional<T>>); static make<T>(data: Optional<T>): PromiseOptional<T>; static make<T>(data: Promise<Optional<T>>): PromiseOptional<T>; map<R>(f: (p: T) => R): PromiseOptional<R>; chain<R>(f: (p: T) => PromiseOptional<R>): PromiseOptional<R>; chain<R>(f: (p: T) => Promise<Optional<R>>): PromiseOptional<R>; orElse(other: T): Promise<T>; orFail<E>(error: E): PromiseResult<E, T>; } export declare class PromiseResult<E, T> { data: Promise<Result<E, T>>; constructor(data: Promise<Result<E, T>>); static make<E, T>(data: Result<E, T>): PromiseResult<E, T>; static make<E, T>(data: Promise<Result<E, T>>): PromiseResult<E, T>; map<R>(f: (p: T) => R): PromiseResult<E, R>; chain<R>(f: (p: T) => PromiseResult<E, R>): PromiseResult<E, R>; chain<R>(f: (p: T) => Promise<Result<E, R>>): PromiseResult<E, R>; either<R>(f: (e: E) => R, g: (v: T) => R): Promise<R>; } /** 參考 https://llh911001.gitbooks.io/mostly-adequate-guide-chinese/content/ch10.html */ export declare function liftA2<A, B, C>(fun: (a: A, b: B) => C, a: Optional<A>, b: Optional<B>): Optional<C>; export declare function liftA2<A, B, C, E>(fun: (a: A, b: B) => C, a: Result<E, A>, b: Result<E, B>): Result<E, C>; export declare function liftA2<A, B, C>(fun: (a: A, b: B) => C, a: List<A>, b: List<B>): List<C>; export declare function liftA2<A, B, C>(fun: (a: A, b: B) => C, a: IO<A>, b: IO<B>): IO<C>; export declare function liftA3<A, B, C, D>(fun: (a: A, b: B, c: C) => D, a: Optional<A>, b: Optional<B>, c: Optional<C>): Optional<D>; export declare function liftA3<A, B, C, D, E>(fun: (a: A, b: B, c: C) => D, a: Result<E, A>, b: Result<E, B>, c: Result<E, C>): Result<E, D>; export declare function liftA3<A, B, C, D>(fun: (a: A, b: B, c: C) => D, a: List<A>, b: List<B>, c: List<C>): List<D>; export declare function liftA3<A, B, C, D>(fun: (a: A, b: B, c: C) => D, a: IO<A>, b: IO<B>, c: IO<C>): IO<D>; export declare function liftA4<A, B, C, D, E>(fun: (a: A, b: B, c: C, d: D) => E, a: Optional<A>, b: Optional<B>, c: Optional<C>, d: Optional<D>): Optional<E>; export declare function liftA4<A, B, C, D, E, F>(fun: (a: A, b: B, c: C, d: D) => E, a: Result<F, A>, b: Result<F, B>, c: Result<F, C>, d: Result<F, D>): Result<F, E>; export declare function liftA4<A, B, C, D, E>(fun: (a: A, b: B, c: C, d: D) => E, a: List<A>, b: List<B>, c: List<C>, d: Optional<D>): List<E>; export declare function liftA4<A, B, C, D, E>(fun: (a: A, b: B, c: C, d: D) => E, a: IO<A>, b: IO<B>, c: IO<C>, d: Optional<D>): IO<E>;
41b13b037d2ea93b4a4f2b838fc6c513022abd0e
TypeScript
JonathanWilbur/preql
/source/APIObjectKinds/UniqueIndex/spec.ts
2.8125
3
/** * The `spec` section of a PreQL `UniqueIndex`. * * @see /source/APIObjectKinds/UniqueIndex/kind. */ export default interface Spec { /** * The DBMS-friendly name of this index. */ name: string; /** * The DBMS-friendly name of the `Struct` to which this index applies. * * @see /source/APIObjectKinds/Struct/kind */ structName: string; /** * The DBMS-friendly name of the `Entity` to which this index applies. * * @see /source/APIObjectKinds/Entity/kind */ entityName?: string; /** * The DBMS-friendly name of the `Database` to which this index applies. * * @see /source/APIObjectKinds/Database/kind */ databaseName: string; /** * Whether the index should be clustered or not. * * @see https://docs.microsoft.com/en-us/sql/relational-databases/indexes/clustered-and-nonclustered-indexes-described?view=sql-server-2017. */ clustered: boolean; /** * Whether this index should be sparse or not. * * @see https://docs.mongodb.com/manual/core/index-sparse/. */ sparse: boolean; /** * The `Attributes` that should be indexed. * * @see /source/APIObjectKinds/Attribute/kind */ keyAttributes: { name: string; ascending: boolean; }[]; /** * The `Attributes` that should be included with the index while not being * a part of the index. * * @see /source/APIObjectKinds/Attribute/kind * @see https://docs.microsoft.com/en-us/sql/relational-databases/indexes/create-indexes-with-included-columns?view=sql-server-2017. */ includedAttributes?: { name: string; ascending: boolean; }[]; }
24a2f712509e5b3c61c516857354b81266f248cd
TypeScript
981377660LMT/algorithm-study
/17_模式匹配/最小表示法/最小表示法.ts
3.828125
4
/* eslint-disable @typescript-eslint/no-non-null-assertion */ // 字符串最小表示法 O(n)算法 // 有一个首位相连的字符串,我们要寻找一个位置,从这个位置向后形成一个新字符串,我们需要使这个字符串字典序最小。 // 我们这里要i = 0,j = 1,k = 0,表示从i开始k长度和从j开始k长度的字符串相同(i,j表示当前判断的位置) // 当我们str[i] == str[j]时,根据上面k的定义,我们的需要进行k+1操作 // !当str[i] > str[j]时,我们发现i位置比j位置上字典序要大,那么不能使用i作为开头了,我们要将i向后移动,移动多少呢?有因为i开头和j开头的有k个相同的字符,那么就执行 i + = k +1 // 相反str[i] < str[j]时,执行:j = j + k +1 // 滑动方式有个小细节,若滑动后i == j,将正在变化的那个指针再+1 // 最终i和j中较小的值就是我们最终开始的位置 // 相反如果是最大表示法的话,我们就要求解字典序最大的字符串,那么我们只需要在执行第二或第三个操作时选择较大的那个位置较好了 // https://a-wimpy-boy.blog.csdn.net/article/details/80136776?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link // 破环成链,双指针 function findIsomorphic(str: string, isMin = true): string { if (str.length <= 1) return str const n = str.length let i1 = 0 let i2 = 1 let same = 0 while (i1 < n && i2 < n && same < n) { const diff = compare(str[(i1 + same) % n], str[(i2 + same) % n]) if (diff === 0) { same++ continue } if (diff > 0) i1 += same + 1 else if (diff < 0) i2 += same + 1 if (i1 === i2) i2++ same = 0 } const res = Math.min(i1, i2) return `${str.slice(res)}${str.slice(0, res)}` function compare(a: string, b: string): number { if (a === b) return 0 if (isMin) return a > b ? 1 : -1 return a < b ? -1 : 1 } } console.log(findIsomorphic('bcaijab'))
c7abc918fd76a4bb22f80ff0b31ee0a83f1099f8
TypeScript
onomemineadamu/smart-storage
/src/storage/memory.ts
3.1875
3
/* eslint-disable no-unused-vars */ interface ISmartStorageMemory { smartStorageMemory: { [x: string]: any; }; setItem: Function; getItem: Function; removeItem: Function; clearItems: Function; } const SmartStorageMemory: InstanceType<any> = function (this: ISmartStorageMemory) { if (!new.target) { return new SmartStorageMemory(); } if (typeof SmartStorageMemory.instance === "object") { return SmartStorageMemory.instance; } SmartStorageMemory.instance = this; this.smartStorageMemory = {}; this.setItem = function (key: string, value: any) { this.smartStorageMemory[key] = value; }; this.getItem = function (key: string) { if (!this.smartStorageMemory[key]) { console.group("📦 SmartStorage🚨"); console.error(`Unrecognized data ${key} to get`); console.groupEnd(); return; } return this.smartStorageMemory[key]; }; this.removeItem = function (key: string) { if (!this.smartStorageMemory[key]) { console.group("📦 SmartStorage🚨"); console.error(`Unrecognized data ${key} to remove`); console.groupEnd(); return; } delete this.smartStorageMemory[key]; }; this.clearItems = function () { this.smartStorageMemory = {}; }; } as any as { new (): ISmartStorageMemory }; const smartStorageMemory = new SmartStorageMemory(); // positive check smartStorageMemory.setItem("name", "Jeremiah Joseph"); console.log("smartStorageMemory", smartStorageMemory); // positive check console.log("smartStorageMemory", smartStorageMemory.getItem("name")); // negative check console.log("smartStorageMemory", smartStorageMemory.getItem("n")); // negative check console.log("smartStorageMemory", smartStorageMemory.removeItem("n")); const sigletonTest = new SmartStorageMemory(); console.log("Sigleton Test", sigletonTest); // psitive check smartStorageMemory.clearItems();
84722ceb3995108d54e0259fc0bbf9ff5921ab66
TypeScript
cgolobic/ng-nest-starter
/shared/utilities/logger.ts
2.546875
3
export function logMessage(label: string, message: string) { console.log(`[${label}] ${message}`); }
3452bfab273e1995b5ea7d5ffe003c82edb7414d
TypeScript
BartlomiejDarocha/AngularModelsTrain
/angularMaterials/src/app/components/angular/validation/validation-form-group/validation-form-group.component.ts
2.546875
3
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, ValidatorFn, AbstractControl } from '@angular/forms'; import { GetterSetterService } from 'src/app/providers/getter-setter.service'; const AGEPATTERN = /^\d+$/; @Component({ selector: 'app-validation-form-group', templateUrl: './validation-form-group.component.html', styleUrls: ['./validation-form-group.component.less'] }) export class ValidationFormGroupComponent implements OnInit { public form1: FormGroup; private passwordValue = ''; public getStarWarsDataByGetterTest: any; constructor(private getterSetterService: GetterSetterService) { } public ngOnInit(): void { this.getterSetterService.loadData().subscribe((data: any) => { this.getterSetterService.setStarWarsPeople(data); // zastoswoanie prostego gettera; }); this.form1 = new FormGroup({ name: new FormControl('test', [Validators.required]), age: new FormControl('', [Validators.required, Validators.pattern(AGEPATTERN)]), nickName: new FormControl(''), password: new FormControl('', [Validators.required]), confirmPassword: new FormControl('', [Validators.required, this.confirmPassHandler()]) }); } public passwordHandler($event: any): void { this.passwordValue = $event.target.value; this.form1.get('confirmPassword').setValue(this.form1.get('confirmPassword').value); } private confirmPassHandler(): ValidatorFn { return(currentControl: AbstractControl): { [key: string]: boolean } => { if (currentControl.value !== this.passwordValue) { return {missMatchPassword: true}; } }; } public resetForm(): void { this.form1.reset(); } public submitTestForm(): void { console.log('submit testForm'); this.getStarWarsDataByGetterTest = this.getterSetterService.getStarWarsPeople(); console.log(this.getStarWarsDataByGetterTest, 'this.getStarWarsDataByGetterTest'); } public checkValidation(): void { console.log(this.form1, '>>>form1'); } // funckaj do zaznaczna różnych błędów public markAsTouched(): void { // this.form1.markAsTouched(); this.form1.get('name').markAsTouched(); this.form1.get('age').markAsTouched(); this.form1.get('password').markAsTouched(); } // funckja do dodawanianowej wartosci oraz updateFormu public patchValue(): void { this.form1.patchValue({ name: '' }); this.form1.updateValueAndValidity(); } // odrazu po SetValue odpala się sprawdzanie validacji public setValue(): void { this.form1.get('age').setValue('valid test'); this.form1.get('age').markAsTouched(); } public checkFormValue(): void { console.log(this.form1.value, 'form1 values'); } public changeValidationControl(): void { this.form1.get('nickName').setValidators([Validators.required, Validators.pattern(AGEPATTERN)]); } }
957a5761572d80575bb1c88a58af18e18a4abd29
TypeScript
checkupjs/checkup
/packages/core/src/utils/exec.ts
3.21875
3
import util from 'util'; import { exec as cpExec } from 'child_process'; const execAsPromise = util.promisify(cpExec); /** * @param {string} cmd - The command to run * @param {any} options - Options passed to the command * @param {string|number} defaultValue - Default value returned if the command returns no value * @param {Function} toType - A function used to convert a result to a specific type * @returns {string|number} - The result of the command */ export async function exec( cmd: string, options: any, defaultValue: string | number, toType: Function = String ) { const { stdout } = await execAsPromise(cmd, options); return toType(stdout.toString().trim()) || defaultValue; }
ca14245814c40c23a6b8aabc28d13b74151d8547
TypeScript
ksanjaykumar1/fabric-gateway
/scenario/node/src/fabricski.ts
2.546875
3
import * as crypto from 'crypto'; import * as jsrsa from 'jsrsasign'; export function getSKIFromCertificate(pem: string): Buffer { const key = jsrsa.KEYUTIL.getKey(pem); const uncompressedPoint = getUncompressedPointOnCurve(key as jsrsa.KJUR.crypto.ECDSA); const hashBuffer = crypto.createHash('sha256'); hashBuffer.update(uncompressedPoint); const digest = hashBuffer.digest('hex'); return Buffer.from(digest, 'hex'); } function getUncompressedPointOnCurve(key: jsrsa.KJUR.crypto.ECDSA): Buffer { const xyhex = key.getPublicKeyXYHex(); const xBuffer = Buffer.from(xyhex.x, 'hex'); const yBuffer = Buffer.from(xyhex.y, 'hex'); const uncompressedPrefix = Buffer.from('04', 'hex'); const uncompressedPoint = Buffer.concat([uncompressedPrefix, xBuffer, yBuffer]); return uncompressedPoint; }
5b6720678fe13b683cd7b59241f635f07bc97832
TypeScript
hoddy3190/github_project_daily_report
/src/formatter.ts
2.796875
3
import * as Octokit from '@octokit/rest' export default class Formatter { private data: Octokit.IssuesListForRepoResponseItem[] private repoName: string public constructor( repo: string, data: Octokit.IssuesListForRepoResponseItem[] ) { this.data = data this.repoName = repo } public format(): string { const arranged = this.arrangeData() let str = `- ${this.repoName}` Array.from(arranged.keys()) .sort((a, _) => { if (a === 'other') return 1 return -1 }) .forEach((key, _) => { str = `${str}\n - ${key}` arranged.get(key).forEach(element => { str = `${str}\n - ${element}` }) }) return str } private arrangeData(): Map<string, string[]> { let map = new Map<string, string[]>() this.data.forEach(e => { let val: string[] if (e.labels.length) { if (!map.get(e.labels[0].name)) { map.set(e.labels[0].name, []) } val = map.get(e.labels[0].name) } else { if (!map.get('other')) { map.set('other', []) } val = map.get('other') } const statusStr = e.state === 'closed' ? '[Done]' : '' val.push(`${statusStr}[${e.title}](${e.html_url})`) }) return map } }
b041b4c79588d4f7d717533b2e3d09cd19a6b5e1
TypeScript
eulincon/fsfc2-desafio2
/nest-api/src/app.service.ts
2.671875
3
import { Injectable } from '@nestjs/common'; export type Route = { title: String, startPosition: {"lat": String, "long": String}, endPosition: {"lat": String, "long": String} } @Injectable() export class AppService { getHello(): string { return 'Hello World!'; } getRoutes(): Route[] { let routes: Route[] routes = [ {"title": "Rota1", "endPosition": {"lat": "-3.6818489", "long": "-40.3531322"}, "startPosition": {"lat": "-3.6832301", "long": "-40.3582713"}}, {"title": "Rota2", "endPosition": {"lat": "-3.6859441", "long": "-40.3489733"}, "startPosition": {"lat": "-3.6859441", "long": "-40.3489733"}}, {"title": "Rota3", "endPosition": {"lat": "-3.6846821", "long": "-40.3467328"}, "startPosition": {"lat": "-3.6846821", "long": "-40.3467328"}}, {"title": "Rota4", "endPosition": {"lat": "-3.6839127", "long": "-40.3646872"}, "startPosition": {"lat": "-3.6868636", "long": "-40.3502397"}}, {"title": "cred-detran", "endPosition": {"lat": "-3.6730546", "long": "-40.3680094"}, "startPosition": {"lat": "-3.6723767", "long": "-40.35526"}}, ] return routes; } }
a8037498b5a95e83150e13a444bed92a48d070fd
TypeScript
srsantosdev/gostack-database-relations
/src/modules/products/repositories/fakes/FakeProductsRepository.ts
2.84375
3
import { uuid } from 'uuidv4'; import Product from '@modules/products/infra/typeorm/entities/Product'; import ICreateProductDTO from '@modules/products/dtos/ICreateProductDTO'; import IUpdateProductsQuantityDTO from '@modules/products/dtos/IUpdateProductsQuantityDTO'; import IProductsRepository from '../IProductsRepository'; interface IFindProducts { id: string; } export default class FakeProductsRepository implements IProductsRepository { private products: Product[] = []; public async create({ name, price, quantity, }: ICreateProductDTO): Promise<Product> { const product = new Product(); Object.assign(product, { id: uuid(), name, price, quantity }); this.products.push(product); return product; } public async findByName(name: string): Promise<Product | undefined> { const findProduct = this.products.find(product => product.name === name); return findProduct; } public async findAllById(products: IFindProducts[]): Promise<Product[]> { const findAll: Product[] = []; products.map(({ id }) => { const findProduct = this.products.find(product => product.id === id); if (findProduct) { findAll.push(findProduct); } return findProduct; }); return findAll; } public async updateQuantity( products: IUpdateProductsQuantityDTO[], ): Promise<Product[]> { const updatedProducts = products.map(({ id, quantity }) => { const productIndex = this.products.findIndex( product => product.id === id, ); if (productIndex >= 0) { const product = this.products[productIndex]; product.quantity = quantity; this.products[productIndex] = product; } return this.products[productIndex]; }); return updatedProducts; } }
3e53ffb865e3f91daf7181611fdf70709f90de4f
TypeScript
kyawswarthwin/capacitor-app-shortcuts
/src/definitions.ts
2.671875
3
//@ts-ignore declare module "@capacitor/core" { interface PluginRegistry { AppShortcuts: IAppShortcutsPlugin; } } export interface IAppShortcutsPlugin { /** * Resolves promise, if dynamic shortcuts are supported */ supportsDynamic(): Promise<void>; /** * Resolves promise, if dynamic shortcuts are supported */ supportsPinned(): Promise<void>; /** * Add a pinned shortcut */ addPinned(shortcut: Shortcut): Promise<void>; /** * Add dynamic shortcuts - inserted shortcuts always overwrite the preview ones */ setDynamic(shortcut: Array<Shortcut>): Promise<void>; /** * Subscribe on new intent */ onNewIntent(): Promise<any>; /** * Get intent */ getIntent(): Promise<any>; } export interface Shortcut { /** * Unique identifier of the shortcut (can be defined randomly) */ id: string; /** * 'Short description' */ shortLabel: string; /** * Longer string describing the shortcut */ longLabel: string; /** * Base 64 encoded icon for the shortcut. DEFAULT: AppIcon */ iconBitmap?: string; /** * filename w/o extension of an icon that resides on res/drawable-* (hdpi,mdpi..) */ iconFromResource?: string; /** * content for the intent */ intent: { action: 'android.intent.action.RUN', categories: [ 'android.intent.category.TEST', // Built-in Android category 'MY_CATEGORY' // Custom categories are also supported ], flags: 67108864, data: 'myapp://path/to/launch?param=value', // Must be a well-formed URI extras: { 'android.intent.extra.SUBJECT': 'Hello world!', // Built-in Android extra (string) 'MY_BOOLEAN': true, // Custom extras are also supported (boolean, number and string only) } } }
3e6a92d1db5fdb455a94fe1787c060109d859885
TypeScript
GnafGnaf/ngEnigma
/src/enigma/cyphers/simpleSubstitution.ts
3.140625
3
import {InvalidArgumentError} from "../../app/shared/errors/invalidArgumentError"; import {Cypher} from "./cypher"; import {ALPHABET} from "../constants"; export class SimpleSubstitution implements Cypher { private readonly substitutionAlphabet: string; public constructor(substitutionAlphabet: string) { this.substitutionAlphabet = substitutionAlphabet.toUpperCase(); } encode(plaintext: string): string { let cypertext = ''; for (let character of plaintext) { cypertext += SimpleSubstitution.substitute(character, ALPHABET, this.substitutionAlphabet); } return cypertext; } decode(cypherText: string): string { let plaintext = ''; for (let character of cypherText) { plaintext += SimpleSubstitution.substitute(character, this.substitutionAlphabet, ALPHABET); } return plaintext; } private static substitute(character: string, sourceAlphabet: string, targetAlphabet: string): string { let positionInAlphabet = sourceAlphabet.indexOf(character); if (positionInAlphabet < 0) { throw new InvalidArgumentError(character + ' could not be substituted') } return targetAlphabet.charAt(positionInAlphabet); } static nullSubstitution() { return new this(ALPHABET); } }
b8c123e6df33261d7b3ff4b71f7e012adb3dd174
TypeScript
sargis56/sargis56.github.io
/Portfolio_test/TypeScript/BloodBoil2D/Scripts/managers/collisions.ts
2.921875
3
module managers { export class Collision { public static Check(obj1: objects.GameObjectAtlas, obj2: objects.GameObjectAtlas):boolean { let boundsWall: number = 50; if (((obj1.x > (obj2.x - boundsWall) ) && (obj1.x < (obj2.x + boundsWall) )) && ((obj1.y > (obj2.y - boundsWall) ) && (obj1.y < (obj2.y + boundsWall) ))) { switch(obj2.name) { case "enemyPHSprite": console.log("ded1"); break; case "enemyPHSprite2": console.log("ded2"); break; } obj2.isColliding = true; return true; } else { obj2.isColliding = false; return false; } } } }
6bbb8845d07218496f45a88026137aebafe7b6cd
TypeScript
MasashiFukuzawa/design-patterns-learned-in-typescript
/chap21-proxy/src/main.ts
2.84375
3
import { PrinterProxy } from "./printer/printerProxy"; class Main { main(): void { const p = new PrinterProxy('Alice'); console.log(`Current name is ${p.getPrinterName()}.`) p.setPrinterName('Bob'); console.log(`Current name is ${p.getPrinterName()}.`) p.print('Hello, world.'); } } const m = new Main(); m.main();
130351dbf4e29438a828796577a2405bb6ca2ebc
TypeScript
chubozeko/CHAP
/src/app/home/resizer.ts
2.609375
3
export class Resizer { constructor() {} public resizeSymbols(symbol) { if ( symbol.parentElement.parentElement.classList.contains("if_div") || symbol.parentElement.classList.contains("if_div") ) { this.resizeIfCaseBlocks(symbol); } else if ( symbol.parentElement.parentElement.classList.contains("for_div") || symbol.parentElement.classList.contains("for_div") ) { this.resizeForLoopBlocks(symbol); } else if ( symbol.parentElement.parentElement.classList.contains("while_div") || symbol.parentElement.classList.contains("while_div") ) { this.resizeWhileLoopBlocks(symbol); } else if ( symbol.parentElement.parentElement.classList.contains("do_while_div") || symbol.parentElement.classList.contains("do_while_div") ) { this.resizeDoWhileLoopBlocks(symbol); } } resizeIfCaseBlocks(symbol) { // If Case Symbols if (symbol.parentElement.parentElement.classList.contains("if_div")) { if ( symbol.parentElement.id == "ifTrueBlock" || symbol.parentElement.id == "ifFalseBlock" ) { let ifDiv = symbol.parentElement.parentElement as HTMLDivElement; let ifSymbol = ifDiv.getElementsByClassName( "if_sym" )[0] as HTMLDivElement; let falseBlock = ifDiv.getElementsByClassName( "ifFalseBlock" )[0] as HTMLDivElement; let trueBlock = ifDiv.getElementsByClassName( "ifTrueBlock" )[0] as HTMLDivElement; // Resize to the Block with the larger width let gridStr: string = ""; if (trueBlock.offsetWidth > falseBlock.offsetWidth) { gridStr = trueBlock.offsetWidth + "px max-content " + ifSymbol.offsetWidth + "px max-content " + trueBlock.offsetWidth + "px"; ifDiv.style.gridTemplateColumns = gridStr; trueBlock.style.margin = "0px"; falseBlock.style.margin = "auto"; } else if (falseBlock.offsetWidth > trueBlock.offsetWidth) { gridStr = falseBlock.offsetWidth + "px max-content " + ifSymbol.offsetWidth + "px max-content " + falseBlock.offsetWidth + "px"; ifDiv.style.gridTemplateColumns = gridStr; trueBlock.style.margin = "auto"; falseBlock.style.margin = "0px"; } else { gridStr = falseBlock.offsetWidth + "px max-content " + ifSymbol.offsetWidth + "px max-content " + trueBlock.offsetWidth + "px"; ifDiv.style.gridTemplateColumns = gridStr; trueBlock.style.margin = "0px"; falseBlock.style.margin = "0px"; } } this.resizeIfCaseArrows(symbol.parentElement, true); } else if (symbol.parentElement.classList.contains("if_div")) { // If Symbol let ifDiv = symbol.parentElement as HTMLDivElement; let falseBlock = ifDiv.getElementsByClassName( "ifFalseBlock" )[0] as HTMLDivElement; let trueBlock = ifDiv.getElementsByClassName( "ifTrueBlock" )[0] as HTMLDivElement; let gridStr = ""; if (trueBlock.offsetWidth > falseBlock.offsetWidth) { gridStr = trueBlock.offsetWidth + "px max-content " + symbol.offsetWidth + "px max-content " + trueBlock.offsetWidth + "px"; } else if (trueBlock.offsetWidth < falseBlock.offsetWidth) { gridStr = falseBlock.offsetWidth + "px max-content " + symbol.offsetWidth + "px max-content " + falseBlock.offsetWidth + "px"; } else { gridStr = falseBlock.offsetWidth + "px max-content " + symbol.offsetWidth + "px max-content " + trueBlock.offsetWidth + "px"; } ifDiv.style.gridTemplateColumns = gridStr; symbol.style.margin = "0px"; this.resizeIfCaseArrows(symbol, false); } } resizeForLoopBlocks(symbol) { // For Loop Symbols if (symbol.parentElement.parentElement.classList.contains("for_div")) { if ( symbol.parentElement.id == "forTrueBlock" || symbol.parentElement.id == "forFalseBlock" ) { let forDiv = symbol.parentElement.parentElement as HTMLDivElement; let forSymbol = forDiv.getElementsByClassName( "for_sym" )[0] as HTMLDivElement; let falseBlock = forDiv.getElementsByClassName( "forFalseBlock" )[0] as HTMLDivElement; let trueBlock = forDiv.getElementsByClassName( "forTrueBlock" )[0] as HTMLDivElement; // Resize to the Block with the larger width let gridStr: string = ""; gridStr = trueBlock.offsetWidth + "px max-content " + forSymbol.offsetWidth + "px max-content " + trueBlock.offsetWidth + "px"; forDiv.style.gridTemplateColumns = gridStr; trueBlock.style.margin = "0px"; falseBlock.style.margin = "0px"; } this.resizeForLoopArrows(symbol.parentElement, true); } else if (symbol.parentElement.classList.contains("for_div")) { // For Symbol let forDiv = symbol.parentElement as HTMLDivElement; let falseBlock = forDiv.getElementsByClassName( "forFalseBlock" )[0] as HTMLDivElement; let trueBlock = forDiv.getElementsByClassName( "forTrueBlock" )[0] as HTMLDivElement; let gridStr = ""; gridStr = trueBlock.offsetWidth + "px max-content " + symbol.offsetWidth + "px max-content " + trueBlock.offsetWidth + "auto"; forDiv.style.gridTemplateColumns = gridStr; symbol.style.margin = "auto"; symbol.style.clipPath = "polygon(" + (symbol.offsetWidth - 17.5) + "px 0, 100% 17.5px, 100% 100%, 0 100%, 0 17.5px, 17.5px 0)"; symbol.style.webkitClipPath = "polygon(" + (symbol.offsetWidth - 17.5) + "px 0, 100% 17.5px, 100% 100%, 0 100%, 0 17.5px, 17.5px 0)"; this.resizeForLoopArrows(symbol.parentElement, false); } } resizeWhileLoopBlocks(symbol) { // While Loop Symbols if (symbol.parentElement.parentElement.classList.contains("while_div")) { if (symbol.parentElement.id == "whileTrueBlock") { let whileDiv = symbol.parentElement.parentElement as HTMLDivElement; let whileSymbol = whileDiv.getElementsByClassName( "while_sym" )[0] as HTMLDivElement; let falseBlock = whileDiv.getElementsByClassName( "whileFalseBlock" )[0] as HTMLDivElement; let trueBlock = whileDiv.getElementsByClassName( "whileTrueBlock" )[0] as HTMLDivElement; // Resize to the Block with the larger width let gridStr: string = ""; gridStr = trueBlock.offsetWidth + "px max-content " + whileSymbol.offsetWidth + "px max-content " + trueBlock.offsetWidth + "px"; whileDiv.style.gridTemplateColumns = gridStr; trueBlock.style.margin = "0px"; falseBlock.style.margin = "0px"; } this.resizeWhileLoopArrows(symbol.parentElement, true); } else if (symbol.parentElement.classList.contains("while_div")) { // While Symbol let whileDiv = symbol.parentElement as HTMLDivElement; let falseBlock = whileDiv.getElementsByClassName( "whileFalseBlock" )[0] as HTMLDivElement; let trueBlock = whileDiv.getElementsByClassName( "whileTrueBlock" )[0] as HTMLDivElement; let gridStr = ""; gridStr = trueBlock.offsetWidth + "px max-content " + symbol.offsetWidth + "px max-content " + trueBlock.offsetWidth + "auto"; whileDiv.style.gridTemplateColumns = gridStr; symbol.style.margin = "auto"; symbol.style.clipPath = "polygon(" + (symbol.offsetWidth - 17.5) + "px 0, 100% 17.5px, 100% 100%, 0 100%, 0 17.5px, 17.5px 0)"; symbol.style.webkitClipPath = "polygon(" + (symbol.offsetWidth - 17.5) + "px 0, 100% 17.5px, 100% 100%, 0 100%, 0 17.5px, 17.5px 0)"; this.resizeWhileLoopArrows(symbol.parentElement, false); } } resizeDoWhileLoopBlocks(symbol) { // Do While Loop Symbols if (symbol.parentElement.parentElement.classList.contains("do_while_div")) { if (symbol.parentElement.id == "doWhileTrueBlock") { let doWhileDiv = symbol.parentElement.parentElement as HTMLDivElement; let doWhileSymbol = doWhileDiv.getElementsByClassName( "do_while_sym" )[0] as HTMLDivElement; let falseBlock = doWhileDiv.getElementsByClassName( "doWhileFalseBlock" )[0] as HTMLDivElement; let trueBlock = doWhileDiv.getElementsByClassName( "doWhileTrueBlock" )[0] as HTMLDivElement; // Resize to the Block with the larger width let gridStr: string = ""; gridStr = trueBlock.offsetWidth + "px max-content " + doWhileSymbol.offsetWidth + "px max-content " + trueBlock.offsetWidth + "px"; doWhileDiv.style.gridTemplateColumns = gridStr; trueBlock.style.margin = "0px"; falseBlock.style.margin = "0px"; } this.resizeDoWhileLoopArrows(symbol.parentElement, true); } else if (symbol.parentElement.classList.contains("do_while_div")) { // Do While Symbol let doWhileDiv = symbol.parentElement as HTMLDivElement; let falseBlock = doWhileDiv.getElementsByClassName( "doWhileFalseBlock" )[0] as HTMLDivElement; let trueBlock = doWhileDiv.getElementsByClassName( "doWhileTrueBlock" )[0] as HTMLDivElement; let gridStr = ""; gridStr = trueBlock.offsetWidth + "px max-content " + symbol.offsetWidth + "px max-content " + trueBlock.offsetWidth + "auto"; doWhileDiv.style.gridTemplateColumns = gridStr; symbol.style.margin = "auto"; symbol.style.clipPath = "polygon(" + (symbol.offsetWidth - 17.5) + "px 0, 100% 17.5px, 100% 100%, 0 100%, 0 17.5px, 17.5px 0)"; symbol.style.webkitClipPath = "polygon(" + (symbol.offsetWidth - 17.5) + "px 0, 100% 17.5px, 100% 100%, 0 100%, 0 17.5px, 17.5px 0)"; this.resizeDoWhileLoopArrows(symbol.parentElement, false); } } resizeIfCaseArrows(symbol, resizeBlocks: boolean) { // If Case Symbols if (resizeBlocks) { // Resize arrows to the Left and Right let ifDiv = symbol.parentElement as HTMLDivElement; let leftArrowPieces = ifDiv.getElementsByClassName("arrowPiece left"); for (let i = 0; i < leftArrowPieces.length; i++) { let aPiece = leftArrowPieces[i] as HTMLDivElement; let gridStr = ""; let z = aPiece.offsetWidth / 2 - 35 / 2; gridStr = z + "px 35px " + z + "px"; aPiece.style.gridTemplateColumns = gridStr; let arrowP = aPiece.getElementsByClassName("dropzone"); for (let j = 0; j < arrowP.length; j++) { let p = arrowP[j] as HTMLDivElement; p.style.width = z + "px"; } } let rightArrowPieces = ifDiv.getElementsByClassName("arrowPiece right"); for (let i = 0; i < rightArrowPieces.length; i++) { let aPiece = rightArrowPieces[i] as HTMLDivElement; let gridStr = ""; let z = aPiece.offsetWidth / 2 - 35 / 2; gridStr = z + "px 35px " + z + "px"; aPiece.style.gridTemplateColumns = gridStr; let arrowP = aPiece.getElementsByClassName("dropzone"); for (let j = 0; j < arrowP.length; j++) { let p = arrowP[j] as HTMLDivElement; p.style.width = z + "px"; } } } else { // Resize arrows below If Symbol let ifDiv = symbol.parentElement as HTMLDivElement; let arrowPiece = ifDiv.getElementsByClassName( "arrowPiece bottom_center" )[0] as HTMLDivElement; let gridStr = ""; let z = arrowPiece.offsetWidth / 2 - 35 / 2; gridStr = z + "px 35px " + z + "px"; arrowPiece.style.gridTemplateColumns = gridStr; let right1 = arrowPiece.getElementsByClassName( "arrow_right" )[0] as HTMLDivElement; let left1 = arrowPiece.getElementsByClassName( "arrow_left" )[0] as HTMLDivElement; right1.style.width = z + "px"; left1.style.width = z + "px"; } } resizeForLoopArrows(symbol, resizeBlocks: boolean) { // For Loop Symbols if (resizeBlocks) { // Resize arrows to the Left and Right let forDiv = symbol.parentElement as HTMLDivElement; let rightArrowPieces = forDiv.getElementsByClassName("arrowPiece right"); for (let i = 0; i < rightArrowPieces.length; i++) { let aPiece = rightArrowPieces[i] as HTMLDivElement; let gridStr = ""; let z = aPiece.offsetWidth / 2 - 35 / 2; gridStr = z + "px 35px " + z + "px"; aPiece.style.gridTemplateColumns = gridStr; let arrowP = aPiece.getElementsByClassName("dropzone"); for (let j = 0; j < arrowP.length; j++) { let p = arrowP[j] as HTMLDivElement; p.style.width = z + "px"; } } } else { // Resize arrows below For Symbol let forDiv = symbol.parentElement as HTMLDivElement; let arrowPiece = forDiv.getElementsByClassName( "arrowPiece bottom_center" )[0] as HTMLDivElement; let gridStr = ""; let z = arrowPiece.offsetWidth / 2 - 70 / 2; gridStr = z + "px 70px " + z + "px"; arrowPiece.style.gridTemplateColumns = gridStr; let right1 = arrowPiece.getElementsByClassName( "arrow_horizontal" )[0] as HTMLDivElement; let left1 = arrowPiece.getElementsByClassName( "blank_arrow_left" )[0] as HTMLDivElement; right1.style.width = z + "px"; left1.style.width = z + "px"; } } resizeWhileLoopArrows(symbol, resizeBlocks: boolean) { // While Loop Symbols if (resizeBlocks) { // Resize arrows to the Left and Right let whileDiv = symbol.parentElement as HTMLDivElement; let rightArrowPieces = whileDiv.getElementsByClassName( "arrowPiece right" ); for (let i = 0; i < rightArrowPieces.length; i++) { let aPiece = rightArrowPieces[i] as HTMLDivElement; let gridStr = ""; let z = aPiece.offsetWidth / 2 - 35 / 2; gridStr = z + "px 35px " + z + "px"; aPiece.style.gridTemplateColumns = gridStr; let arrowP = aPiece.getElementsByClassName("dropzone"); for (let j = 0; j < arrowP.length; j++) { let p = arrowP[j] as HTMLDivElement; p.style.width = z + "px"; } } } else { // Resize arrows below While Symbol let whileDiv = symbol.parentElement as HTMLDivElement; let arrowPiece = whileDiv.getElementsByClassName( "arrowPiece bottom_center" )[0] as HTMLDivElement; let gridStr = ""; let z = arrowPiece.offsetWidth / 2 - 70 / 2; gridStr = z + "px 70px " + z + "px"; arrowPiece.style.gridTemplateColumns = gridStr; let right1 = arrowPiece.getElementsByClassName( "arrow_horizontal" )[0] as HTMLDivElement; let left1 = arrowPiece.getElementsByClassName( "blank_arrow_left" )[0] as HTMLDivElement; right1.style.width = z + "px"; left1.style.width = z + "px"; } } resizeDoWhileLoopArrows(symbol, resizeBlocks: boolean) { // Do Loop Symbols if (resizeBlocks) { // Resize arrows to the Left and Right let doWhileDiv = symbol.parentElement as HTMLDivElement; let rightArrowPieces = doWhileDiv.getElementsByClassName( "arrowPiece right" ); for (let i = 0; i < rightArrowPieces.length; i++) { let aPiece = rightArrowPieces[i] as HTMLDivElement; let gridStr = ""; let z = aPiece.offsetWidth / 2 - 35 / 2; gridStr = z + "px 35px " + z + "px"; aPiece.style.gridTemplateColumns = gridStr; let arrowP = aPiece.getElementsByClassName("dropzone"); for (let j = 0; j < arrowP.length; j++) { let p = arrowP[j] as HTMLDivElement; p.style.width = z + "px"; } } } else { // Resize arrows below Do While Symbol let doWhileDiv = symbol.parentElement as HTMLDivElement; let arrowPiece = doWhileDiv.getElementsByClassName( "arrowPiece bottom_center" )[0] as HTMLDivElement; let gridStr = ""; let z = arrowPiece.offsetWidth / 2 - 35 / 2; gridStr = z + "px 35px " + z + "px"; arrowPiece.style.gridTemplateColumns = gridStr; let right1 = arrowPiece.getElementsByClassName( "arrow_horizontal" )[0] as HTMLDivElement; let left1 = arrowPiece.getElementsByClassName( "blank_arrow_left" )[0] as HTMLDivElement; right1.style.width = z + "px"; left1.style.width = z + "px"; } } }
5802cf2faf53eb6773ff3a0c423147dd3099fa11
TypeScript
emilia98/SoftUni-JSWeb-OLD
/Angular Fundamentals/03. Observables & Routing/Demo/Dependency Injection/with_DI.ts
3.203125
3
/* WITH DEPENDENCY INJECTION In this case, we do not need to use an instance of Engine class. Whatever changes we made of it, none of the classes with depend on it will need to be changed. All of these classes will have an access to the updates made to the class Engine. */ class Engine { constructor( public model :string, public type :string ) {} } class Car { constructor( public make :string, public model :string, private engine :Engine ) {} } let bigEngine = new Engine('V8', 'gasoline'); let smallEngine = new Engine('1.6', 'diesel'); let mercedes = new Car('Mercedes', '5500', bigEngine); let otherMercedes = new Car('Mercedes', '1100', smallEngine); let audi = new Car('Audi', 'A8', smallEngine);
27504669dac98fb8660a026b3ee22cf525fff360
TypeScript
AndreySotnikov/angular2-systemjs-rollup
/app/app.component.ts
2.59375
3
import {Component, OnInit} from '@angular/core'; import {Subject} from "rxjs"; @Component({ selector: 'my-app', template: `<h1>Hello {{name}}</h1>`, }) export class AppComponent implements OnInit { private subject : Subject<string> = new Subject(); public name: string = undefined; ngOnInit(): void { this.subject.subscribe(val => { this.name = val; }); this.subject.next("Rollup"); } }
b8bd51dd053d518db066eb57d05bcf87c5436836
TypeScript
Ckearns1210/star_wars_angular2
/src/app/home/api_service/api.service.ts
2.6875
3
import {Component, Injectable, OnInit, ElementRef, EventEmitter, Inject} from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs'; import { MovieResult } from '../../models/movie-result' import 'rxjs/Rx' @Injectable() export class ApiService { constructor(public http: Http) { } search(character): Observable<any> { let queryUrl: string = character.url; return this.http.get(character.url) //flatten out results of first results stream and extract the films, flatMap performs map, but instead of returning an observable, it subscribes to each observable returning the data. .flatMap((response: Response) => response.json().films) //flatten out the second request, this request takes the film we extracted and and does a new request for that film, and adds it to the stream as json when it is done .flatMap((film: string) => this.http.get(film), (_, resp) => resp.json()) ////Typescript's object destructuring syntax, takes just the title and release_date from each object coming out of flatMap stream and creates new object .map(({title, release_date}) => ({ title, release_date })) } }
001c382574e0598179ede211b8ff345e4b906587
TypeScript
khle/monadness-js
/lib/maybe.d.ts
3
3
import { Monad, FunctorFunc, ApplicativeFunc } from "./interfaces"; import { Either } from "./either"; export declare abstract class Maybe<T> implements Monad<T> { abstract map<U>(f: (a: T) => U): Maybe<U>; abstract fmap<U>(f: FunctorFunc<T, U>): Maybe<U>; abstract applies<U, V>(f: ApplicativeFunc<T, U, V>): (mb: Maybe<U>) => Maybe<V>; abstract mbind<U>(f: Maybe<FunctorFunc<T, U>>): Maybe<U>; abstract flatten<U>(): Maybe<U>; abstract get(): T | never; abstract getOrElse(f: () => T): T; abstract getOrElseGet(value: T): T; abstract getOrThrow(err?: Error): T | never; abstract orElse(o: () => Maybe<T>): Maybe<T>; abstract toObject(): { just: T | null; }; isDefined(): boolean; isEmpty(): boolean; toEither(): Either<Error, T>; equals(other: Maybe<T>): boolean; toJSON(): { just: T | null; }; toString(): string; } export declare namespace Maybe { function just<T>(value: T): Just<T>; function none<T>(): None<T>; function nothing(): None<void>; function fromNull<T>(value: T | undefined | null): Maybe<T>; function sequence<T>(...maybes: Array<Maybe<T>>): Maybe<T[]>; function traverse<T, U>(f: (a: T) => Maybe<U>): (as: T[]) => Maybe<U[]>; function lift<T>(partialFunction: (...args: any[]) => T): (...args: any[]) => Maybe<T>; class None<T> extends Maybe<T> { constructor(); map<U>(f: (a: T) => U): None<U>; fmap<U>(f: (a: T) => Maybe<U>): None<U>; applies<U, V>(f: (a: T) => (b: U) => Maybe<V>): (mb: Maybe<U>) => None<V>; mbind<U>(f: Maybe<(a: T) => Maybe<U>>): None<U>; flatten(): None<T>; isEmpty(): boolean; get(): never; getOrElse(f: () => T): T; getOrElseGet(value: T): T; getOrThrow(err?: Error): never; orElse(f: () => Maybe<T>): Maybe<T>; toEither(): Either.Left<Error, T>; toObject(): { just: null; }; } class Just<T> extends Maybe<T> { private value; constructor(value: T); map<U>(f: (a: T) => U): Just<U>; fmap<U>(f: (a: T) => Maybe<U>): Maybe<U>; applies<U, V>(f: (a: T) => (b: U) => Maybe<V>): (mb: Maybe<U>) => Maybe<V>; mbind<U>(f: Maybe<(a: T) => Maybe<U>>): Maybe<U>; flatten<U>(): Maybe<U>; isDefined(): boolean; get(): T; getOrElse(value: () => T): T; getOrElseGet(value: T): T; getOrThrow(err?: Error): T; orElse(o: () => Maybe<T>): Maybe<T>; toEither(): Either.Right<Error, T>; toObject(): { just: T; }; } }
d5a592cf3245efbc2059d821bcd35a0919084d6b
TypeScript
cloudhubs/prophet-web
/src/state/initState.ts
2.671875
3
import {State} from "./state"; import {defaultState} from "./defaultState"; export const LOCAL_STORAGE_KEY = "prophetkey2020"; export const parseState = (str: string | null): State | null => { try { const state = JSON.parse(str || ""); return state as State; } catch (e) { return null; } }; const stateFromStorage = parseState(localStorage.getItem(LOCAL_STORAGE_KEY)); export const initialState: State = stateFromStorage || defaultState;
e62ca60dddbc04e78c48378737b6d4f05695365c
TypeScript
zpapoo/ncha-frontend
/__tests__/features/playerSaga.test.ts
2.71875
3
import { FetchStatusCode } from 'api' import { playerToggleSaga, playerUpdateTimeSaga } from 'features/playerSaga' import { PLAYER_PREFIX, playerActions, playerSelectors } from 'features/playerSlice' import { delay, put, select } from 'redux-saga/effects' const initialState = { movie: { id: 0, title: '', running_time: 1, comments: [], }, isPlaying: false, currentTime: 0, fetchState: FetchStatusCode.LOADING, } describe('playerToggleSaga', () => { it('isPlaying값이 true일때 player time을 업데이트 한다.', async () => { // Given const state = { [PLAYER_PREFIX]: { ...initialState, isPlaying: true, }, } const gen = playerToggleSaga() // When // Then expect(gen.next(state[PLAYER_PREFIX] as any).value).toEqual(select(playerSelectors.isPlaying)) expect(gen.next(state[PLAYER_PREFIX] as any).value).toEqual(delay(1000)) expect(gen.next(state[PLAYER_PREFIX] as any).value).toEqual(select(playerSelectors.times)) expect(gen.next({ current: 2 }).value).toEqual( put(playerActions.requestUpdateCurrentTime(3)), ) }) }) describe('playerUpdateTimeSaga', () => { it('requestTime이 current보다 크고 running보다 작을 경우 requestTime만큼 업데이트 한다', async () => { // Given const testAction = { type: `${playerActions.requestUpdateCurrentTime}`, payload: 7, } const state = { [PLAYER_PREFIX]: { ...initialState, currentTime: 5, movie: { ...initialState.movie, running_time: 10, }, }, } const gen = playerUpdateTimeSaga(testAction) // Then expect(gen.next(state[PLAYER_PREFIX] as any).value).toEqual(select(playerSelectors.times)) expect(gen.next({ total: 10 }).value).toEqual( put(playerActions.updateCurrentTime(7)), ) expect(gen.next().done).toBeTruthy() }) it('requestTime이 running보다 클 경우 player의 시간을 running으로 업데이트 한다', async () => { // Given const testAction = { type: `${playerActions.requestUpdateCurrentTime}`, payload: 15, } const state = { [PLAYER_PREFIX]: { ...initialState, currentTime: 5, movie: { ...initialState.movie, running_time: 10, }, }, } const gen = playerUpdateTimeSaga(testAction) // Then expect(gen.next(state[PLAYER_PREFIX] as any).value).toEqual(select(playerSelectors.times)) expect(gen.next({ total: 10 }).value).toEqual( put(playerActions.updateCurrentTime(10)), ) expect(gen.next().done).toBeTruthy() }) it('requestTime이 0보다 작을 경우 player의 시간을 0으로 업데이트 한다', async () => { // Given const testAction = { type: `${playerActions.requestUpdateCurrentTime}`, payload: -10, } const state = { [PLAYER_PREFIX]: { ...initialState, currentTime: 5, movie: { ...initialState.movie, running_time: 10, }, }, } const gen = playerUpdateTimeSaga(testAction) // Then expect(gen.next(state[PLAYER_PREFIX] as any).value).toEqual(select(playerSelectors.times)) expect(gen.next({ total: 10 }).value).toEqual( put(playerActions.updateCurrentTime(0)), ) expect(gen.next().done).toBeTruthy() }) })
9440be8720f31ee4c1251bb688c7cbd31a19899c
TypeScript
lucascaro/ts-monads
/src/monads/Result.ts
3.765625
4
import { none, Option, some } from './Option'; export type Result<T, E> = Ok<T, E> | Err<T, E>; export enum ResultKind { ok = 'ok', err = 'err', } export interface Ok<T, E> extends IResult<T, E> { kind: ResultKind.ok; isOk: true; isErr: false; } export interface Err<T, E> extends IResult<T, E> { kind: ResultKind.err; isOk: false; isErr: true; } export default interface IResult<T, E> { kind: ResultKind; // Returns true if the result is Ok. isOk: boolean; // Returns true if the result is Err. isErr: boolean; // Converts from Result<T, E> to Option<T>. ok: () => Option<T>; // Converts from Result<T, E> to Option<E>. err: () => Option<E>; // Maps a Result<T, E> to Result<U, E> by applying a function to a contained // Ok value, leaving an Err value untouched. map: <U>(fn: (t: T) => U) => Result<U, E>; // Maps a Result<T, E> to U by applying a function to a contained Ok value, // or a fallback function to a contained Err value. mapOrElse: <U>(fallback: (e: E) => U, fn: (t: T) => U) => U; // Maps a Result<T, E> to Result<T, F> by applying a function to a contained // Err value, leaving an Ok value untouched. mapErr: <F>(op: (e: E) => F) => Result<T, F>; // Returns an iterator over the possibly contained value. [Symbol.iterator]: () => Iterator<T>; // Returns res if the result is Ok, otherwise returns the Err value of self. and: <U>(res: Result<U, E>) => Result<U, E>; // Calls op if the result is Ok, otherwise returns the Err value of self. andThen: <U>(res: (t: T) => Result<U, E>) => Result<U, E>; // Returns res if the result is Err, otherwise returns the Ok value of self. or: <F>(res: Result<T, F>) => Result<T, F>; // Calls op if the result is Err, otherwise returns the Ok value of self. orElse: <F>(res: (e: E) => Result<T, F>) => Result<T, F>; // Unwraps a result, yielding the content of an Ok. unwrap: () => T; // Unwraps a result, yielding the content of an Ok. Else, it returns optb. unwrapOr: (optb: T) => T; // Unwraps a result, yielding the content of an Ok. If the value is an Err // then it calls op with its value. unwrapOrElse: (optb: (e: E) => T) => T; // Unwraps a result, yielding the content of an Ok. expect: (msg: string) => T; // Unwraps a result, yielding the content of an Err. unwrapErr: () => E; // Unwraps a result, yielding the content of an Err. expectErr: (msg: string) => E; // Transposes a Result of an Option into an Option of a Result. transpose: () => Option<Result<T, E>>; } // HACK: the following types are needed because the Readonly type removes symbols. type ReadonlyOk<T, E> = Readonly<Ok<T, E>> & { [Symbol.iterator]: () => Iterator<T>; }; type ReadonlyErr<T, E> = Readonly<Err<T, E>> & { [Symbol.iterator]: () => Iterator<T>; }; export function ok<T, E>(value: T): Ok<T, E> { const self: Ok<T, E> = { kind: ResultKind.ok, isOk: true, isErr: false, ok: () => some(value), err: () => none(), map: (fn) => ok(fn(value)), mapOrElse: (fallback, fn) => fn(value), mapErr: () => ok(value), *[Symbol.iterator]() { yield value; }, and: (res) => res, andThen: (fn) => fn(value), or: () => ok(value), orElse: () => ok(value), unwrap: () => value, unwrapOr: () => value, unwrapOrElse: () => value, expect: () => value, unwrapErr: () => { throw new Error(String(value)); }, expectErr: (msg: string) => { throw new Error(msg); }, transpose: () => { throw new Error('not implemented'); }, }; return Object.freeze(self) as ReadonlyOk<T, E>; } export function err<T, E>(value: E): Result<T, E> { const self: Result<T, E> = { kind: ResultKind.err, isOk: false, isErr: true, ok: () => none(), err: () => some(value), map: () => err(value), mapOrElse: (fallback) => fallback(value), mapErr: (fn) => err(fn(value)), *[Symbol.iterator](): Iterator<T> {}, and: () => err(value), andThen: () => err(value), or: (res) => res, orElse: (fn) => fn(value), unwrap: () => { throw new Error(String(value)); }, unwrapOr: (optb) => optb, unwrapOrElse: (fn) => fn(value), expect: (msg) => { throw new Error(msg); }, unwrapErr: () => value, expectErr: () => value, transpose: () => { throw new Error('not implemented'); }, }; return Object.freeze(self) as ReadonlyErr<T, E>; }
7e1e3408678842b037fd1daf067c1f5f0f51ad47
TypeScript
la-guirlande/spotifind-frontend
/src/hooks/authentication-hook.ts
2.515625
3
import randomString from 'crypto-random-string'; import _ from 'lodash'; import { useEffect } from 'react'; import { Config } from '../util/configuration'; import crypto from '../util/crypto'; import { LocalStorageKey } from '../util/local-storage'; import { AccessTokenResponse, SpotifyTokenResponse } from '../util/response-types'; import { Status, useQuery } from './query-hook'; import { useQueryParams } from './query-params-hook'; /** * Authentication hook data. */ export interface Authentication { connect: () => Promise<void>; token: () => void; } /** * Authentication hook. * * This hook is used to connect to Spotify accounts service and Spotifind backend. * * @returns Authentication hook data */ export const useAuthentication = (): Authentication => { const queryParams = useQueryParams(); const tokenQuery = useQuery<SpotifyTokenResponse>(); const accessTokenQuery = useQuery<AccessTokenResponse>(); useEffect(() => { switch (tokenQuery.status) { case Status.SUCCESS: localStorage.removeItem(LocalStorageKey.OAUTH2_CODE_VERIFIER); localStorage.removeItem(LocalStorageKey.OAUTH2_STATE); localStorage.setItem(LocalStorageKey.SPOTIFY_ACCESS_TOKEN, tokenQuery.response.access_token); localStorage.setItem(LocalStorageKey.SPOTIFY_REFRESH_TOKEN, tokenQuery.response.refresh_token); tokenQuery.reset(); accessTokenQuery.post(`${Config.API_URL}/auth/accessToken`, { spotify_access_token: tokenQuery.response.access_token }) break; case Status.ERROR: localStorage.removeItem(LocalStorageKey.OAUTH2_CODE_VERIFIER); localStorage.removeItem(LocalStorageKey.OAUTH2_STATE); console.log('Could not get tokens from Spotify :', tokenQuery.errorResponse.errors); tokenQuery.reset(); break; } }, [tokenQuery.status]); useEffect(() => { switch (accessTokenQuery.status) { case Status.SUCCESS: const { access_token } = accessTokenQuery.response; localStorage.setItem(LocalStorageKey.ACCESS_TOKEN, access_token); window.location.href = '/'; // TODO Make this more user friendly, refreshing page is not good break; case Status.ERROR: console.error('Authentication failed :', accessTokenQuery.errorResponse.errors); break; } }, [accessTokenQuery.status]); const connect = async () => { if (localStorage.getItem(LocalStorageKey.SPOTIFY_REFRESH_TOKEN) == null) { const scopes = 'user-read-private user-read-email'; const responseType = 'code'; const redirectUri = Config.REDIRECT_URI; const codeVerifier = randomString({ length: _.random(43, 128, false) }); const codeChallengeMethod = 'S256'; const codeChallenge = crypto.base64(await crypto.sha256(codeVerifier)); const state = randomString({ length: 10 }); localStorage.setItem(LocalStorageKey.OAUTH2_CODE_VERIFIER, codeVerifier); localStorage.setItem(LocalStorageKey.OAUTH2_STATE, state); window.location.href = `${Config.SPOTIFY_AUTHORIZE_URL}?response_type=${responseType}&client_id=${Config.SPOTIFY_CLIENT_ID}&scope=${encodeURIComponent(scopes)}&redirect_uri=${encodeURIComponent(redirectUri)}&code_challenge_method=${codeChallengeMethod}&code_challenge=${codeChallenge}&state=${state}`; } else { const body = new URLSearchParams(); body.append('grant_type', 'refresh_token'); body.append('refresh_token', localStorage.getItem(LocalStorageKey.SPOTIFY_REFRESH_TOKEN)); body.append('client_id', Config.SPOTIFY_CLIENT_ID); tokenQuery.post(Config.SPOTIFY_TOKEN_URL, body, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); } } const token = () => { if (queryParams.get('state') === localStorage.getItem(LocalStorageKey.OAUTH2_STATE)) { const body = new URLSearchParams(); body.append('client_id', Config.SPOTIFY_CLIENT_ID); body.append('grant_type', 'authorization_code'); body.append('code', queryParams.get('code')); body.append('redirect_uri', Config.REDIRECT_URI); body.append('code_verifier', localStorage.getItem(LocalStorageKey.OAUTH2_CODE_VERIFIER)); tokenQuery.post(Config.SPOTIFY_TOKEN_URL, body, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); } else { console.error('Invalid OAuth2 state'); } } return { connect, token }; }
3a1bc9ac62f60735f0bf92b979f7a7efdf0aaf42
TypeScript
Tcheikovski/express-simple-decorator
/src/__tests__/paramsResolve/ParamResolve.specs.ts
2.625
3
import * as assert from "assert"; import {ParamResolve} from "../../paramsResolve/ParamResolve"; import {Request} from "express"; describe("Test resolve param", () => { it('Haven\'t value', async () => { let resolve = new ParamResolve(); let request = { params: {} }; let result = await resolve.resolve(request as Request, null, null); assert.strictEqual(result, request.params); }); it('Have value', async () => { let resolve = new ParamResolve(); let request = { params: { 'test': 1, } }; let result = await resolve.resolve(request as unknown as Request, null, 'test'); assert.strictEqual(result, 1); }); });
41defdbb37642cc561ceca1cfccbb899cbf8b9b3
TypeScript
Spand0x/DnD-Adventure-Web-app
/src/app/views/dnd-adventure/character/character-stats/character-stats.component.ts
2.640625
3
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core'; import {CharacterStats} from '../../../../shared/models/character-stats.model'; @Component({ selector: 'app-character-stats', templateUrl: './character-stats.component.html', styleUrls: ['./character-stats.component.scss'] }) export class CharacterStatsComponent implements OnInit { @Input() stats: CharacterStats[]; @Output() rollDice: EventEmitter<any> = new EventEmitter<any>(); statsAndModifiers: any = []; constructor() { } ngOnInit(): void { const statsOrder = ['STRENGTH', 'DEXTERITY', 'CONSTITUTION', 'INTELLIGENCE', 'WISDOM', 'CHARISMA']; this.stats.sort((a, b) => statsOrder.indexOf(a.name) - statsOrder.indexOf(b.name)); this.stats.forEach(s => { this.statsAndModifiers.push({ name: s.name.charAt(0).toUpperCase() + s.name.slice(1).toLowerCase(), value: s.value, modifier: Math.floor((s.value - 10) / 2) }); }); } }
5fe7eac10ccb178917c0522aa9665990edc4198a
TypeScript
mathiamry/jhipster-sample-applicationbannk
/src/main/webapp/app/entities/turnover/turnover.model.ts
2.8125
3
import { ISme } from 'app/entities/sme/sme.model'; export interface ITurnover { id?: number; min?: number | null; max?: number | null; description?: string | null; smes?: ISme[] | null; } export class Turnover implements ITurnover { constructor( public id?: number, public min?: number | null, public max?: number | null, public description?: string | null, public smes?: ISme[] | null ) {} } export function getTurnoverIdentifier(turnover: ITurnover): number | undefined { return turnover.id; }
cfd5d9b96c693e0c0a2f42d9b5c642fabd17781c
TypeScript
imralav/TheOrderOfWorms
/src/sorting-algorithms/bubble-sort.ts
3.15625
3
import { SortingAlgorithm, swap } from "./sorting-algorithms"; import { withSortingEvents } from "./sorting-algorithms"; class BubbleSort implements SortingAlgorithm { private data: number[]; constructor(data: number[]) { this.data = [...data]; } sort() { const eventsStream = withSortingEvents((inspected, swapped) => { for (let i = 0; i < this.data.length - 1; i++) { for (let j = 0; j < this.data.length - i - 1; j++) { inspected([j, j + 1]); if (this.data[j] > this.data[j + 1]) { swap(this.data, j, j + 1); swapped([j, j + 1]); } } } }); return { result: this.data, eventsStream, }; } } export { BubbleSort };
02babbc91041117e91ee696e71486dc2f3f446a9
TypeScript
israel1947/App-paises
/src/app/paises/pages/ver-pais/ver-pais.component.ts
2.625
3
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { tap } from 'rxjs/operators'; import { PaisService } from '../../services/pais.service'; import { Country, Language } from '../../interfaces/paises.interface'; @Component({ selector: 'app-ver-pais', templateUrl: './ver-pais.component.html', styles: [ ] }) export class VerPaisComponent implements OnInit { pais!:Country; constructor(private rutaActivada : ActivatedRoute, private paisService:PaisService) { }//es antes de que se inicialize el componente //es cuando el componente ya esta inicializado ngOnInit(): void { //suscribirse a los observables que permitan hacer el cambio de codigo de cada país this.rutaActivada.params .subscribe(({id})=>{ console.log(id) tap(console.log)//forma corta de hacer una impresion en la consola //traer la informacion del pais this.paisService.getPaisByCode(id) .subscribe(pais=>{ this.pais=pais; console.log(pais); }) }) //los params permiten pasar los parámetros opcionales a través de cualquier ruta en la aplicación } }
78a6292a5944d20d5a33012047beec7b8d615e2e
TypeScript
ThoaDuong/beblog-x
/src/entities/topic.entity.ts
2.546875
3
import { TopicDTO } from './../blog/dtos/blog.api.dto'; import { Column, CreateDateColumn, Entity, ObjectID, ObjectIdColumn } from "typeorm"; @Entity() export class TopicEntity{ @ObjectIdColumn() id: ObjectID; @Column() name: string; @CreateDateColumn({ type: 'date' }) created_at: Date @CreateDateColumn({ type: 'date' }) updated_at: Date static from(data: TopicDTO): TopicEntity{ return { ...new TopicEntity(), name: data.name, } } }