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
abd624dcf3717c534974831e9361a2dc938bc75f
TypeScript
ghaisassujit/social-cards-webApp
/src/store/actions.ts
2.84375
3
import {Action} from 'redux'; import { Story, ErrorDetail } from './types'; export enum StoryActions { ListLoading = 'ListLoading', ListLoaded = 'ListLoaded', ListLoadingError = 'ListLoadingError', AddNew = 'addNew', Saving = 'saving', Saved = 'saved', SavingError = 'savingError' } export interface ActionWithData<T> extends Action { payload: T; } export interface ListLoadingAction extends Action { type: StoryActions.ListLoading } export interface ListLoadingErrorAction extends ActionWithData<ErrorDetail> { type: StoryActions.ListLoadingError } export interface ListLoadedAction extends ActionWithData<Story[]> { type: StoryActions.ListLoaded } export interface AddNewAction extends Action { type: StoryActions.AddNew } export interface SavingErrorAction extends ActionWithData<ErrorDetail> { type: StoryActions.SavingError } export interface SavingAction extends ActionWithData<Story> { type: StoryActions.Saving } export interface SavedAction extends ActionWithData<Story> { type: StoryActions.Saved } export function loadList(): ListLoadingAction { return { type: StoryActions.ListLoading }; } export function listLoaded(list: Story[]): ListLoadedAction { return { type: StoryActions.ListLoaded, payload: list }; } export function listLoadingError(error: ErrorDetail): ListLoadingErrorAction { return { type: StoryActions.ListLoadingError, payload: error }; } export function addNew(): AddNewAction { return { type: StoryActions.AddNew }; } export function saving(entity: Story): SavingAction { console.log('Saving: ', entity); return { type: StoryActions.Saving, payload: entity }; } export function saved(entity: Story): SavedAction { return { type: StoryActions.Saved, payload: entity }; } export type StoryAnyAction = | ListLoadingAction | ListLoadingErrorAction | ListLoadedAction | AddNewAction | SavingErrorAction | SavingAction | SavedAction;
c0381fd29a52ccd54389dd89deae6f26bc890e6b
TypeScript
softcontext/workspace_ecma
/typescript/app/example1.ts
3.21875
3
function add(a: number, b:number): number{ return a+b; } (function (){ let result = add(2, 3); console.log('result = '+result); })(); var tasty: boolean; // tasty = "I haven't tried it yet"; tasty = false;
c4707106457e3c69cd1a4d1e8966050c260c694f
TypeScript
brucekruger/TypeScriptTodo
/Utils.ts
3.546875
4
interface IHaveALength { length: number; } export function clone<T>(value: T): T { let serialized = JSON.stringify(value); return JSON.parse(serialized); } export function totalLength<T extends IHaveALength>(x: T, y: T) { var total: number = x.length + y.length; return total; } clone('Hello'); clone(123); clone({ name: 'Jess' }); var length = totalLength('Jess', 'Chadwick');
093954f002dc63da2525736467a633a01048c001
TypeScript
jimbothree/craftbot-api
/src/engine/requests/send-message-request.model.ts
3.203125
3
import { Request } from './request.model'; import { RequestType } from './request-type.enum'; /** * Requests a regular message to be sent. * */ export class SendMessageRequest extends Request<{ message: string }> { public readonly command = RequestType.Message; /** * Creates an instance of SendMessageRequest. * @param id - The unique identifier of the message. * @param message - The message. * @memberof SendMessageRequest */ constructor( protected readonly id: number, protected readonly message: string ) { super(id, { message }); } }
f030d1be9ec87f94ecf8f18d70bc73e4ad1932f7
TypeScript
grzegorz-bielski/newsletter-lambda
/src/EmailRepo.ts
2.578125
3
import type { DynamoDB } from 'aws-sdk'; import * as TE from 'fp-ts/lib/TaskEither'; import * as O from 'fp-ts/lib/Option'; import * as A from 'fp-ts/lib/Array'; import * as t from 'io-ts'; import { pipe } from 'fp-ts/lib/pipeable'; import { flow } from 'fp-ts/lib/function'; import { fromDecoded } from './Errors'; import { Result, fromAWSCall } from './'; export const Emails = t.array(t.string); export type Emails = t.TypeOf<typeof Emails>; export class EmailRepo { constructor( private readonly db: DynamoDB, private readonly dc: DynamoDB.DocumentClient, private readonly tableName: string, ) {} put(email: string): Result<DynamoDB.PutItemOutput> { return fromAWSCall(() => this.db.putItem({ TableName: this.tableName, Item: { email: { S: email } } }).promise(), ); } getAll(): Result<Emails> { return pipe( fromAWSCall(() => this.dc.scan({ TableName: this.tableName }).promise()), TE.chain( flow( a => a.Items, O.fromNullable, O.map(A.chain(a => Object.values(a))), O.getOrElse<unknown[]>(() => []), Emails.decode, fromDecoded, TE.fromEither, ), ), ); } }
b14ef2ac53d4e525c5708d5c525d782195fc2ece
TypeScript
Huddly/sdk
/tests/components/upgrader/upgradeStatus.spec.ts
2.703125
3
import chai, { expect } from 'chai'; import UpgradeStatus, { UpgradeStatusStep } from './../../../src/components/upgrader/upgradeStatus'; chai.should(); describe('UpgradeStatus', () => { it('should not return complete first step is not done', () => { const step = new UpgradeStatusStep('foo'); const status = new UpgradeStatus([step]); const res = status.getStatus(); expect(res.progress).to.not.equal(100.0); }); it('should return progress 100 when step is completed', () => { const step = new UpgradeStatusStep('foo'); const status = new UpgradeStatus([step]); step.progress = 100; const res = status.getStatus(); expect(res.progress).to.equal(100); }); it('should return progress for two steps', () => { const step1 = new UpgradeStatusStep('foo'); const step2 = new UpgradeStatusStep('bar'); const status = new UpgradeStatus([step1, step2]); expect(status.getStatus().progress).to.equal(0); step1.progress = 100; expect(status.getStatus().progress).to.equal(50); step2.progress = 50; expect(status.getStatus().progress).to.equal(75); step2.progress = 100; expect(status.getStatus().progress).to.equal(100); }); it('should allow weighting steps', () => { const step1 = new UpgradeStatusStep('foo'); const weighted = new UpgradeStatusStep('bar', 4); const status = new UpgradeStatus([step1, weighted]); expect(status.getStatus().progress).to.equal(0); step1.progress = 100; expect(status.getStatus().progress).to.equal(20); weighted.progress = 50; expect(status.getStatus().progress).to.equal(60); weighted.progress = 75; expect(status.getStatus().progress).to.equal(80); weighted.progress = 100; expect(status.getStatus().progress).to.equal(100); }); });
5f7651be34b2c7b463d6d5807de3a9f97012cb9a
TypeScript
dmitrygavrish/angular-media-manager
/src/app/common/guards/auth.guard.ts
2.640625
3
import {Injectable} from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router'; import {AuthService} from '../services/auth.service'; @Injectable() export class AuthGuard implements CanActivate { public constructor(private authService: AuthService, private router: Router) { } public canActivate(routeSnapshot: ActivatedRouteSnapshot, routerState: RouterStateSnapshot): boolean { const testState: string = routeSnapshot.data.testState; const conditionValue: boolean = routeSnapshot.data.conditionValue; const redirectTo: string = routeSnapshot.data.redirectTo; const serviceState: boolean = typeof this.authService[testState] === 'function' ? this.authService[testState]() : this.authService[testState]; // if state meets the condition, do redirection if (serviceState === conditionValue) { this.router.navigate([redirectTo]); } // if state doesn't meet the condition, allow user to navigate to the route return serviceState !== conditionValue; } }
b06306746dd202bfa61f9c2ab9a43e6f9a66124a
TypeScript
un33k/atrade
/libs/ag/base/src/lib/ag-logger.spec.ts
2.671875
3
import { BaseLogger } from './ag-logger'; class Logger extends BaseLogger {} describe('Agnostic Base - BaseLogger', function() { let logger; beforeEach(() => { logger = new Logger(); }); it('should create', () => { expect(logger).toBeDefined(); }); it('should not detect IE', () => { expect(logger.isColorLog).toBe(true); }); it('should not log anything at log level of none (default)', () => { const logSpy = jest.spyOn(console, 'log'); logger.log('Testing'); expect(logSpy).not.toHaveBeenCalled(); }); it('should invoke log when logger.info is called', () => { const logSpy = jest.spyOn(logger, 'log'); logger.info('Testing'); expect(logSpy).toHaveBeenCalled(); }); it('should invoke log when logger.warn is called', () => { const logSpy = jest.spyOn(logger, 'log'); logger.info('Testing'); expect(logSpy).toHaveBeenCalled(); }); });
0c102346726ad94b615edbeb12e0dc34581dfee0
TypeScript
JaroslawPokropinski/typescript-aot
/src/compilator/ExpressionImpl/BinaryExpression.ts
2.90625
3
import * as ast from '@typescript-eslint/typescript-estree/dist/ts-estree/ts-estree'; import Expression from '../Expression'; import ExpressionVisitor from '../ExpressionVisitor'; import { AST_NODE_TYPES } from '@typescript-eslint/typescript-estree'; import ParseError from '../ParseError'; import CompilationDirector from '../CompilationDirector'; // TODO: better left side validation export default class BinaryExpression implements Expression { left: Expression; right: Expression; op: string; constructor(ast: ast.BinaryExpression, director: CompilationDirector) { this.right = Expression.fromNode(ast.right, director); this.op = ast.operator; // this.left.assignable() if (ast.left.type !== AST_NODE_TYPES.Identifier) { throw new ParseError( 'Left side of assignment must be Identifier', ast.left ); } this.left = Expression.fromNode(ast.left, director); } static create(left: Expression, right: Expression, op: string) { const be: BinaryExpression = {left, right, op, visit: function(visitor: ExpressionVisitor) {visitor.onBinary(this);}}; return be; } visit(visitor: ExpressionVisitor): void { visitor.onBinary(this); } }
46257f96b1d6415a715aeea68f433d7684a743ca
TypeScript
duanjiuzhou/blogReactProject
/src/api/index.ts
2.71875
3
import Request from '@public/api' // http工具若需前端统一,需要后端统一普通交互格式 export enum Ret { 正常 = 0, 用户名不存在或者密码错误 = 99, 登录失效 = 100, 参数错误 = 400, 无权限 = 401, 系统内部错误 = 1000, 数据过期 = 4001, } // 自定义响应结构体 interface ICommonResponse { ret: number data: any message?: string } export default Request<ICommonResponse>({ // 请求拦截器内处理函数 handleReq: config => { config.baseURL = process.env.API_URL }, // 请求失败处理函数 handleFailRes: res => { const { ret, message } = res.data console.log(Ret[ret], message) }, // 请求成功处理函数 handleSuccessRes: res => { return res.data.data }, })
28e78728a7a820d1eb3062e2694c30e871e618f2
TypeScript
mengtest/home3
/core/clientLaya/game/src/commonGame/net/request/guide/SetMainGuideStepRequest.ts
2.921875
3
namespace Shine { /** 设置主引导步消息(generated by shine) */ export class SetMainGuideStepRequest extends GameRequest { /** 数据类型ID */ public static dataID:number=GameRequestType.SetMainGuideStep; public value:number; constructor() { super(); this._dataID=GameRequestType.SetMainGuideStep; } protected copyData():void { super.copyData(); } /** 获取数据类名 */ public getDataClassName():string { return "SetMainGuideStepRequest"; } /** 写入字节流(简版) */ protected toWriteBytesSimple(stream:BytesWriteStream):void { super.toWriteBytesSimple(stream); stream.writeInt(this.value); } /** 创建实例 */ public static createSetMainGuideStep(value:number):SetMainGuideStepRequest { var re:SetMainGuideStepRequest=new SetMainGuideStepRequest(); re.value=value; return re; } } }
9ae67cc1d592f8bbc416375446a682557b4732bd
TypeScript
neet/masto.js
/src/adapters/serializers/is-record.ts
2.890625
3
export const isRecord = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && x.constructor.name === "Object";
246fc88294d6fb83eaf774242ded2afac84fa775
TypeScript
KevinVelassco/construction-assistant-api
/src/templates/template.service.ts
2.53125
3
import * as path from 'path'; import * as fs from 'fs'; import hbs from 'handlebars'; import mjml2html from 'mjml'; export class TemplateService { static generateHtmlByTemplate(templateName: string, parameters: object = {}) { // get the path of the template const filePath = `./emails/${templateName}.mjml`; const templatePath = path.resolve(__dirname, filePath); // compile the template const template = hbs.compile(fs.readFileSync(templatePath, 'utf8')); // get the result const result = template(parameters); // get the html const { html } = mjml2html(result); return html; } }
3e2862ec8bf973c6b1f6c4618d16e0a002e2e701
TypeScript
Zerrien/sprintplank
/app/client/store.ts
2.6875
3
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { nodes: [], }; const mutations = { createItem(aState, obj) { aState.nodes.push(obj); }, updateItem(aState, obj) { const index = aState.nodes.findIndex(elems => elems.id === obj.id); if(index !== -1) { Vue.set(aState.nodes, index, obj); } else { // Woah, was a node created on the server without updating? throw new Error("AHHH"); } }, } const actions = { addNode: ({ commit }, obj) => commit('createItem', obj), updateNode: ({ commit }, obj) => commit('updateItem', obj), }; export default new Vuex.Store({ state, actions, mutations, });
7050c1005c709d630b2dad261b84bde95e1fa465
TypeScript
ManuRodgers/react-jira
/src/utils/index.ts
2.90625
3
export const matchPartialString = ( sources: string[], match: string ): string[] => sources.filter((source) => source.toLowerCase().includes(match)); export const isFalsy = (value: any): boolean => (value === 0 ? false : !value); export const cleanObject = (object: any): any => { const result = { ...object }; Object.keys(result).forEach((key) => { const value = result[key]; if (isFalsy(value)) { delete result[key]; } }); return result; };
ce29c026a6d75865b96f2d361c8e0a34d1ae6ec6
TypeScript
designdevy/hangman-2019
/src/utils/words.ts
3.203125
3
function getWords(cb: (words: string[]) => void): void { cb(['food', 'drink', 'tool']) } function getRandomWord(): string { let word = '' getWords(words => { const randomWord = words[Math.floor(Math.random() * words.length)] word = randomWord.toUpperCase() }) return word } export default getRandomWord
1205d953396951689f649c43aab9a94c83e09dba
TypeScript
gentics/gentics-ui-core
/src/components/file-drop-area/drag-drop-utils.ts
2.828125
3
export function getDataTransfer(event: any): DataTransfer { // if jQuery wrapped the event which contains the dropped file, unwrap it let ev: DragEvent = event.dataTransfer ? event : event.originalEvent; return ev.dataTransfer; } export function getEventTarget(event: any): HTMLElement { // if jQuery wrapped the event, unwrap it return (event.originalEvent ? event.originalEvent : event).target; } /** * Note: there are issues with current TypeScript lib defs for the DataTransfer interface, which * seems to define the `types` property as a `string[]` rather than a DOMStringList. * See https://github.com/Microsoft/TypeScript/issues/12069 */ export function transferHasFiles(transfer: DataTransfer): boolean { let types: any = transfer.types; if (!transfer || !transfer.types) { return false; } else if (typeof types.contains === 'function') { return types.contains('Files'); } else if (typeof types.indexOf === 'function') { return types.indexOf('Files') >= 0; } else if (typeof types.length === 'number') { for (let i = 0; i < types.length; i++) { if (types.item(i) === 'Files') { return true; } } } return false; } let _mimeTypeSupport: boolean; export function clientReportsMimeTypesOnDrag(): boolean { if (_mimeTypeSupport === undefined) { _mimeTypeSupport = 'items' in DataTransfer.prototype; } return _mimeTypeSupport; } /** * If the browser does not report a MIME type, match against this value instead. */ export const FALLBACK_MIME_TYPE = 'unknown/unknown'; let warnedThatBrowserDoesNotProvideNumberOfItems = false; /** * Returns a list of mime types in a DataTransfer if supported by the browser. * * This is a workaround for missing DataTransfer.items support in Firefox < 52 * https://bugzilla.mozilla.org/show_bug.cgi?id=906420 */ export function getTransferMimeTypes(transfer: DataTransfer): string[] { if (!transfer) { return []; } else if (transfer.items && transfer.items.length > 0) { return Array.from(transfer.items) .filter(item => item.kind === 'file') .map(item => item.type || FALLBACK_MIME_TYPE); } else if ('mozItemCount' in transfer) { return new Array((<any> transfer).mozItemCount).fill(FALLBACK_MIME_TYPE); } else if (!transfer.items && transfer.types.length === 1 && transfer.types[0] === 'Files') { // IE11 return [FALLBACK_MIME_TYPE]; } else { if (!warnedThatBrowserDoesNotProvideNumberOfItems) { console.warn('Client does not provide number of items during drag event'); warnedThatBrowserDoesNotProvideNumberOfItems = true; } return [FALLBACK_MIME_TYPE]; } }
887d02f17e468ba7a2886215d129e56beef88101
TypeScript
noppa/get-optional
/tests/typings/testbed/ts-should-pass/nth.ts
2.75
3
import {nth, get} from 'get-optional'; import {A, B, C, D, E, input} from '../ts-interfaces'; const list = [1, 2, 3]; const first: undefined | number = nth(list, 0); const nonExistent: undefined | number = nth(list, 100); const fromNullableList: undefined | boolean = nth(get(input, 'a', 'b', 'c', 'arr'), 0); const fromNullableReadonlyList: undefined | boolean = nth(get(input, 'a', 'b', 'c', 'readonlyArr'), 0); const noInferenceForT: undefined = nth(null, 5);
da8f4b26b269607620857f9d96a8b0750e4ec7a9
TypeScript
dipali208/Dipali-BT
/Frontend/src/app/Class/state.ts
2.703125
3
export class State { answer:string; questionId:number; userId:number; quizId:number; reamainingTime:number constructor(answer:string,userId:number,queId:number,quizId:number,reamainingTime:number){ this.answer = answer; this.questionId = queId; this.userId = userId; this.quizId = quizId; this.reamainingTime = reamainingTime; } }
80b6d997a54cdd412c6453b40dd8edceab393aa3
TypeScript
dragGH102/angular4-unit-converter
/src/app/unit-converter/units.ts
2.625
3
interface Unit { symbol: string, ratioToMeter: number, } const Meter: Unit = { symbol: 'm', ratioToMeter: 1, }; const Yard: Unit = { symbol: 'yd', ratioToMeter: 1.0936, }; const Inch: Unit = { symbol: 'in', ratioToMeter: 39.3701, }; const Units = [ Meter, Yard, Inch, // ADD MORE UNITS HERE TO EXTEND ]; export { Units, };
b2470b7574310e5ee6aa04002467aa1e6341dffb
TypeScript
xialei520/small-demo
/typescript/demo.ts
4.375
4
// 基本语法 // let bool: boolean = true; // let number: number = 888; // let string: string = '1222'; // let s1:symbol = Symbol() // 数组类型 // let arr1: number[] = [12, 11]; // let arr2: string[] = ['12', '33']; // let arr3: Array<number> = [1, 2, 3]; // let arr4:Array<number | string> = [1, 3, 4]; // 元祖 第一个必须为数字类型, 第二个必须为字符串, 数量必须为2 // let tuple:[number, string] = [11, '22']; // tuple.push('99'); // tuple[3]; //null undefined 如果一个值声明了undefined, 就不能赋值其他类型 // let x: undefined = 'll' //报错 // let y: undefined = undefined; //null 类型可以赋值给undefined和null, 但是不能赋值给数字/字符串/boolean // let h: null = null; // let s: number = undefined; // let o: number | string | undefined = 'undefined'; // function start(){ // console.log('123') // } /* */ // let x:[string, number]; // x = ['Runoob', 1]; // // x = [1, 'Runoob']; // console.log(x[1]); //枚举类型 enum Color {Red, Green, Blue}; let c: Color = Color.Blue; console.log(c)
4f2efbbdf4b16897da313a2b5cdb33d93c5f2479
TypeScript
SuZHui/suzh-cli
/packages/@suzh/cli-service/lib/util/logger.ts
2.96875
3
import chalk from 'chalk'; // import readline from 'readline'; const chalkTag = (msg: string) => chalk.bgBlackBright.white.dim(` ${msg} `); // 格式化输出 const format = (label: string, msg: string) => { return msg .split('\n') .map((line: string, i: number) => { return i === 0 ? `${label} ${line}` : line.padStart(chalk.reset(label).length) }) .join('\n'); } /** * 打印错误 * @param msg string * @param tag string */ export function error(msg: string, tag: string | null = null) { console.log( format(chalk.bgRed(' ERROR ') + (tag ? chalkTag(tag) : ''), chalk.red(msg)) ); }
6257055742dbb960cf67d5bbf86050df85f6d1f1
TypeScript
orionnye/BTTFS
/src/circle.ts
3.171875
3
import { Vector } from "./math"; export default class Circle { pos: Vector vel: Vector radius: number mass: number speed: number acceleration: number color: string constructor(pos: Vector, radius: number, color: string = "black") { this.pos = pos this.vel = new Vector(0, 0) this.radius = radius this.speed = 10 this.acceleration = 1 this.mass = 10 this.color = color } move() { this.pos = this.pos.add(this.vel) } slow(friction: number) { let slower = this.vel.multiply(friction) this.vel = slower } push(force: Vector) { this.vel = this.vel.add(force.multiply(1/this.mass)) } collides(that: Circle) { //Distance between if (that.radius <= 0 || this.radius <= 0) { return false } let distance = this.pos.subtract(that.pos).length //Combined Radius' let minDist = this.radius + that.radius if (distance < minDist) { return true } return false } pendingCollision(that: Circle) { let dummyThat = new Circle(that.pos.add(that.vel), that.radius) let dummyThis = new Circle(this.pos.add(this.vel), this.radius) if (dummyThat.collides(dummyThis)) { return true } return false } correct(that: Circle) { //define angle let angle = that.pos.subtract(this.pos).normalize //define minDist let minDist = this.radius + that.radius //multiply minDist by angle let fix = angle.multiply(minDist) //find distance till acceptable this.pos = that.pos.subtract(fix) } render(g: CanvasRenderingContext2D) { let {pos, color, radius} = this g.beginPath() g.arc(pos.x, pos.y, radius, 0, 2 * Math.PI) g.stroke() g.fillStyle = color g.fill() } }
fab1cdb9cd9129ab677321f7b59d71e600bc6ac5
TypeScript
sweetim/haversine-position
/test/util.test.ts
2.6875
3
import * as assert from 'assert'; import { Util } from '../lib/util'; describe('Util', function() { describe('#toRadian()', function() { it('should return PI when 180 degree', function() { assert.strictEqual(Math.PI, Util.toRadian(180)); }); it('should return 0 when 0 degree', function() { assert.strictEqual(0, Util.toRadian(0)); }); }); describe('#toDegree()', function() { it('should return 180 with PI', function() { assert.strictEqual(180, Util.toDegree(Math.PI)); }); it('should return 0 when 0 degree', function() { assert.strictEqual(0, Util.toDegree(0)); }); }); });
041b74e6a4380b19d13e5de9d6cb14ba78700808
TypeScript
yongwang07/angular2-ngrx-contact
/src/norm.ts
3.109375
3
import { normalize, schema, denormalize } from 'normalizr'; import { Record, List, Map, fromJS, OrderedMap} from 'immutable'; const data = { id: '123', author: { id: '1', name: 'Paul' }, title: 'My awesome blog post', comments: [ { id: '324', commenter: { id: '2', name: 'Nicole' } } ] }; interface author { id: number; name: string; } interface comment { id: number; commenter: author; } interface post { id: number; author: author; title: string; comments: List<comment>; } interface AppState extends List<post> {}; const PostRecord = Record({ id: 123, author: { id: 1, name: 'Paul' }, title: 'My awesome blog post', comments: List<comment>() }); const AuthorRecord = Record({ id: 1, name: 'Paul' }); const commentRecord = Record({ }); const init:AppState = List<post>(); let onePost: post = fromJS({ id: 123, author: { id: 1, name: 'Paul' }, title: 'My awesome blog post', comments: List<comment>() }); const newState: AppState = init.push(onePost); console.log(newState.toJS()); const a: AppState = newState.updateIn([0,'author', 'name'], ()=>'abc'); console.log(a.toJS()); const p = a.updateIn([0, 'comments'], list => list.push(fromJS({ id: 324, commenter: { id: '2', name: 'Nicole' } }))); console.log(JSON.stringify(p.toJS())); /*const author = new schema.Entity('authors'); const comment = new schema.Entity('comments', {commenter: author}); const post = new schema.Entity('posts', {author: author, comments: [comment]});*/ interface Contact { id: number; name: string; star: boolean; } /*interface AppState extends List<Contact>{} const init: AppState = List<Contact>(); const newState = init.push({ id: 1, name: 'Wang', star: false }); console.log(newState.toJS()); const c: AppState = (<any>newState).update(0, (contact: Contact) => { return { id: contact.id, name: contact.name, star: true } }); console.log(c.toJS()); const k: AppState = c.push({ id: 2, name: 'Yong', star: false }); console.log(k.toJS()); const i: AppState = k.delete(0); console.log(i.toJS()); */
b0c9698aed63764df21d74b5842a5402c0e07c22
TypeScript
rockplate/rockplate
/tests/block/LiteralBlock.spec.ts
2.953125
3
import { Builder } from '../../src/Builder'; import { Parser } from '../../src/Parser'; import { LiteralBlock } from '../../src/block/LiteralBlock'; import { getBuilders } from '../shared'; const sch = { my: { name: 'My Name', expertise: 'My Skills', }, skills: [ { skill: { name: 'Skill 1', expertise: 'expert', }, }, { skill: { name: 'Skill 2', expertise: 'beginner', }, }, ], myself: { pro: true, }, }; type MySchema = typeof sch; describe('LiteralBlock', () => { const tpl = 'My name is [my name] and my expertise is in [my expertise]'; for (const builder of getBuilders(tpl, sch)) { it('is built ' + builder.type, () => { expect(builder.blocks.length).toBe(1); const block = builder.blocks[0]; expect(block.children.length).toBe(0); expect(block).toBeInstanceOf(LiteralBlock); expect(block.content).toBe('My name is [my name] and my expertise is in [my expertise]'); }); it('is parsed ' + builder.type, () => { const parser = new Parser(builder); expect( parser.parse({ my: { name: 'Safraz', expertise: 'Programming', }, } as MySchema), ).toBe('My name is Safraz and my expertise is in Programming'); expect( parser.parse({ my: { name: 'Safraz', expertise: 'Designing', }, } as MySchema), ).toBe('My name is Safraz and my expertise is in Designing'); }); } });
37de26b410382506aa4887ab183567618dae04d1
TypeScript
Yoostah/nextjs-sequelize-typescript
/server/repositories/PostRepository.ts
2.703125
3
import { FindOptions } from "sequelize"; import { Post } from "../models"; export class PostRepository extends Post { public static async findAllRaw(options?: FindOptions) { const data = await Post.findAll(options); const rawData = data.map((d) => ({ ...d.toJSON(), createdAt: d.createdAt.toString(), updatedAt: d.updatedAt.toString(), })); return rawData; } public static async findOneRaw(options?: FindOptions): Promise<any> { const data = await Post.findOne(options); if (!data) { throw Error("Not Found"); } const rawData = { ...data.toJSON(), createdAt: data.createdAt.toString(), updatedAt: data.updatedAt.toString(), }; return rawData; } }
a834b87f627bf6c454fb1b070e1e82e84e180ef0
TypeScript
gatsbyjs/gatsby
/packages/gatsby-source-wordpress/src/steps/preview/cleanup.ts
2.703125
3
import { inPreviewMode, PreviewStatusUnion } from "." import { OnPageCreatedCallback } from "~/models/preview" import { getStore } from "~/store" import { NodePluginArgs } from "gatsby" /** * This callback is invoked to send WP the preview status. In this case the status * is that we couldn't find a page for the node being previewed */ const invokeLeftoverPreviewCallback = ({ getNode, status, context, error, }: { status: PreviewStatusUnion context?: string error?: Error getNode: NodePluginArgs["getNode"] }) => async ([nodeId, callback]: [ string, OnPageCreatedCallback ]): Promise<void> => { const passedNode = getNode(nodeId) await callback({ passedNode, nodeId, // we pass null as the path because no page was created for this node. // if it had been, this callback would've been removed earlier in the process pageNode: { path: null }, status, context, error, }) } export const invokeAndCleanupLeftoverPreviewCallbacks = async ({ status, context, error, }: { status: PreviewStatusUnion context?: string error?: Error }): Promise<void> => { const state = getStore().getState() const { getNode } = state.gatsbyApi.helpers const leftoverCallbacks = state.previewStore.nodePageCreatedCallbacks const leftoverCallbacksExist = Object.keys(leftoverCallbacks).length if (leftoverCallbacksExist) { await Promise.all( Object.entries(leftoverCallbacks).map( invokeLeftoverPreviewCallback({ getNode, status, context, error }) ) ) // after processing our callbacks, we need to remove them all so they don't get called again in the future getStore().dispatch.previewStore.clearPreviewCallbacks() } } /** * Preview callbacks are usually invoked during onCreatePage in Gatsby Preview * so that we can send back the preview status of a created page to WP * In the case that no page is created for the node we're previewing, we'll * have callbacks hanging around and WP will not know the status of the preview * So in onPreExtractQueries (which runs after pages are created), we check which * preview callbacks haven't been invoked, and invoke them with a "NO_PAGE_CREATED_FOR_PREVIEWED_NODE" status, which sends that status to WP * After invoking all these leftovers, we clear them out from the store so they aren't called again later. */ export const onPreExtractQueriesInvokeLeftoverPreviewCallbacks = async (): Promise<void> => { if (!inPreviewMode()) { return invokeAndCleanupLeftoverPreviewCallbacks({ status: `GATSBY_PREVIEW_PROCESS_ERROR`, context: `Gatsby is not in Preview mode.`, }) } // check for any onCreatePageCallbacks that weren't called during createPages // we need to tell WP that a page wasn't created for the preview return invokeAndCleanupLeftoverPreviewCallbacks({ status: `NO_PAGE_CREATED_FOR_PREVIEWED_NODE`, context: `invokeAndCleanupLeftoverPreviewCallbacks`, }) }
f1cafe25bb274ebdb97b8f4718fb069727d4401d
TypeScript
Tami1901/Hangman
/src/helpers/calcScore.ts
2.625
3
import { alphabet } from '../constants/alphabet'; import { ATTEMPTS } from '../constants/gameConfig'; const MAX_LEN = 200; type ScoreType = { err: number; unique: number; len: number; duration: number; }; export const calcScore = ({ err, unique, len, duration }: ScoreType): number => { return ( Math.round( ((1 - err / alphabet.length) * 10000 + (unique / alphabet.length) * 100 + (len / MAX_LEN) * 10 + (1 - duration / 1800000)) * 10000 ) / 1000 ); };
f98e09f469a02404dd6a0c1656f4f98dea30451f
TypeScript
tzkmx/papaya
/index.ts
3.59375
4
/** * A Papaya container */ export class Papaya<T extends { [name: string]: any } = any> { private _services: { [name: string]: any } = {} private _functions: { [name: string]: true } = {} private _factories: { [name: string]: true } = {} /** * Gets a service by name. * * If the service is not set, will return undefined. * * @param name The service name * @return The service or undefined if it is not set */ public get<K extends keyof T>(name: K): T[K] { type Service = (this: this, container: this) => T[K] if (this._factories[name]) { return (this._services[name] as Service).call(this, this) } if (this._functions[name]) { this._services[name] = (this._services[name] as Service).call(this, this) delete this._functions[name] } return this._services[name] } /** * Creates a constant by name and value. * * @param name The service name * @param constant The value to be set */ public constant<K extends keyof T>(name: K, constant: T[K]): this { this._setService(name, constant) return this } /** * Sets a service by name and a service function * * The return value of the `service` function will be treated as a singleton * service meaning it will be initialized the first time it is requested and * its value will be cached for subsequent requests. * * @param name The service name * @param service The service singleton function or static service */ public service<K extends keyof T>( name: K, service: (this: this, container: this) => T[K] ): this { this._setService(name, service, this._functions) return this } /** * Sets a factory service by name and value. * * The `factory` function will be called every time the service is requested. * So if it returns an object, it will create a new object for every request. * * @param name The service name * @param factory The service factory function or static service */ public factory<K extends keyof T>( name: K, factory: (this: this, container: this) => T[K] ): this { this._setService(name, factory, this._factories) return this } /** * Extends an existing service and overrides it. * * The `extender` function will be called with 2 argument which will be the * previous value of the service and the Papaya container. If there is no * existing `name` service, it will throw an error immediately. The * `extender` function should return the new value for the service that will * override the existing one. * * If `this.extend` is called for a service that was created with * `this.service`, the resulting service will be a singleton. * * If `this.extend` is called for a service that was created with * `this.factory` the resulting service will be a factory. * * If `this.extend` is called for a service that was created with * `this.constant`, the resulting service will be a singleton. * * @param name The service name * @param extender The service extender function or static service. */ public extend<K extends keyof T>( name: string, extender: (this: this, extended: T[K], container: this) => T[K] ): this { if (!this.has(name)) { throw new Error(`Cannot extend missing service: ${name}`) } const extended = this._services[name] let protect = false const service = () => { return extender.call( this, protect ? extended : extended.call(this, this), this ) } if (this._factories[name]) { return this.factory(name, service) } else { protect = !this._functions[name] return this.service(name, service) } } /** * Register a service provider function. * * `provider` will be called with the container as the context. Service * providers are a good place to register related services using * `this.service` etc. * * @param provider The service provider function */ public register(provider: (this: this, container: Papaya<any>) => void) { provider.call(this, this) return this } /** * Get an array of the regitered service names * * @return An array of service names */ public keys(): Array<keyof T> { return Object.keys(this._services) } /** * Check whether a service has been registered for the given name' * * @return True if a service has been registered for `name`, false otherwise. */ public has<K extends keyof T>(name: K): boolean { return this._services.hasOwnProperty(name) } private _setService( name: string, service: any, registry?: { [name: string]: true } ) { delete this._services[name] delete this._functions[name] delete this._factories[name] if (registry && typeof service === 'function') { registry[name] = true } this._services[name] = service } }
c1e6e96c1cad90c6315337c33062b8fc259a39df
TypeScript
Zielak/cardsGame
/packages/server/src/queries/__test__/queryRunner.test.ts
2.703125
3
import { LabeledEntity } from "../../__test__/helpers/labeledEntities.js" import { SmartEntity, SmartParent, } from "../../__test__/helpers/smartEntities.js" import { Player } from "../../player/player.js" import { State } from "../../state/state.js" import { queryRunner } from "../runner.js" let state: State, parentA: SmartParent, parentB: SmartParent, targetA: SmartEntity, targetB: SmartEntity, parentC: SmartParent, targetC: SmartEntity, targetD: LabeledEntity, playerA: Player, playerB: Player describe("multi tests", () => { beforeEach(() => { state = new State() playerA = new Player({ clientID: "playerA" }) playerB = new Player({ clientID: "playerB" }) // Root parentA = new SmartParent(state, { name: "parentA" }) parentB = new SmartParent(state, { name: "parentB", owner: playerB }) targetD = new LabeledEntity(state, { name: "topLevelTargetD" }) // Parent A new SmartEntity(state, { type: "foo", parent: parentA }) new SmartEntity(state, { type: "baz", parent: parentA }) new SmartEntity(state, { type: "foo", parent: parentA }) targetA = new SmartEntity(state, { type: "bar", name: "targetA", parent: parentA, owner: playerA, }) // Parent B targetB = new SmartEntity(state, { type: "bar", name: "targetB", parent: parentB, }) new SmartEntity(state, { type: "foo", parent: parentB }) new SmartEntity(state, { name: "bar", parent: parentB }) parentC = new SmartParent(state, { name: "parentC", type: "bazzer", parent: parentB, }) new SmartEntity(state, { type: "foo", parent: parentB }) // Parent C new SmartEntity(state, { type: "foo", parent: parentC }) targetC = new SmartEntity(state, { type: "bar", name: "targetC", parent: parentC, }) new SmartEntity(state, { type: "foo", parent: parentC }) new SmartEntity(state, { type: "foo", parent: parentC }) new SmartEntity(state, { type: "foo", parent: parentC }) }) describe("#query", () => { describe("plain values", () => { test("starting from state, finds deeply anywhere", () => { expect(state.query({ name: "parentA" })).toBe(parentA) expect(state.query({ name: "parentB" })).toBe(parentB) expect(state.query({ name: "parentC" })).toBe(parentC) expect(state.query({ name: "targetA" })).toBe(targetA) expect(state.query({ name: "targetB" })).toBe(targetB) expect(state.query({ name: "targetC" })).toBe(targetC) }) test("starting from given parent, finds in it and deeply", () => { expect(parentB.query({ name: "parentC" })).toBe(parentC) expect(parentB.query({ type: "bazzer" })).toBe(parentC) expect(parentB.query({ type: "bazzer", name: "parentC" })).toBe(parentC) expect(parentB.query({ name: "targetB" })).toBe(targetB) expect(parentB.query({ type: "bar" })).toBe(targetB) expect(parentB.query({ type: "bar", name: "targetB" })).toBe(targetB) }) test("ownership", () => { expect(state.query({ type: "bar", owner: playerA })).toBe(targetA) expect(state.query({ type: "bar", owner: playerB })).toBe(targetB) // On entity without ownership trait expect( state.query({ name: "topLevelTargetD", owner: playerA }) ).toBeUndefined() }) }) describe("arrays", () => { test("finds either of given names", () => { expect(state.query({ name: ["whatever", "targetA"] })).toBe(targetA) expect(state.query({ name: ["whatever", "targetC"] })).toBe(targetC) expect( state.query({ name: ["whatever", "nonexistent"] }) ).toBeUndefined() }) }) describe("functions", () => { test("finds first matching name", () => { expect( state.query<SmartEntity>({ name: (v) => v.startsWith("target") }).id ).toBe(targetA.id) expect(state.query({ name: (v) => v.startsWith("parent") })).toBe( parentA ) expect(state.query({ type: (v) => v.includes("zz") })).toBe(parentC) expect(state.query({ name: () => false })).toBeUndefined() }) }) describe("with parent definition", () => { test("starting from state, finds deeply anywhere", () => { expect( state.query({ type: "bazzer", parent: { name: "parentB" } }) ).toBe(parentC) expect(state.query({ type: "bar", parent: { type: "bazzer" } })).toBe( targetC ) }) it("doesn't match a top-level entity", () => { expect(state.query({ name: "parentA", parent: state })).toBeUndefined() }) }) }) describe("#queryAll", () => { describe("plain values", () => { test("starting from state, finds deeply anywhere", () => { expect(state.queryAll({ type: "foo" }).length).toBe(8) expect(state.queryAll({ type: "bar" }).length).toBe(3) }) test("starting from state, target one entity", () => { expect(state.queryAll({ name: "targetA" }).length).toBe(1) expect(state.queryAll({ name: "targetB" }).length).toBe(1) expect(state.queryAll({ name: "targetC" }).length).toBe(1) expect(state.queryAll({ name: "targetA" })[0]).toBe(targetA) expect(state.queryAll({ name: "targetB" })[0]).toBe(targetB) expect(state.queryAll({ name: "targetC" })[0]).toBe(targetC) }) test("starting from given parent, finds in it and deeply", () => { expect(parentB.queryAll({ type: "foo" }).length).toBe(6) }) test("starting from given parent, target one entity", () => { expect(parentB.queryAll({ name: "parentC" })[0]).toBe(parentC) expect(parentB.queryAll({ name: "targetB" })[0]).toBe(targetB) }) }) describe("functions", () => { test("finds deeply anywhere", () => { expect( state.queryAll({ type: (v) => v.startsWith("f"), }).length ).toBe(8) expect( parentB.queryAll({ type: (v) => v.startsWith("f"), }).length ).toBe(6) }) }) describe("with parent", () => { test("starting from state, finds deeply anywhere", () => { expect( state.queryAll({ type: "bazzer", parent: { name: "parentB" }, })[0] ).toBe(parentC) expect( state.queryAll({ type: "bar", parent: { type: "bazzer" }, })[0] ).toBe(targetC) }) }) }) test("various fails", () => { expect(queryRunner({ name: "whatever" })(state)).toBe(false) }) }) describe("queryRunner", () => { test("'empty' query returns nothing", () => { state = new State() expect(state.query({})).toBeUndefined() }) })
df55114cb3bb593d8d47546318f2a0b8775078a7
TypeScript
kinashi/react-redux-example
/src/models/books.ts
2.921875
3
import Book from './book' export default class Books { private _list: Map<string, Book> constructor(books?: Book[]) { this._list = new Map() if (books) this.setList(books) return this } get list() { return Array.from(this._list.values()) } public setList(books: Book[]) { books.forEach((book: Book) => { this._list.set(book.id, new Book(book)) }) return this } }
ea2b2f9e22f89947ab60c960c505de7eb86efc34
TypeScript
Sztimon/Projekt
/ProjektPS/ClientApp/app/services/vehicle.model.ts
2.75
3
import { Contact } from "./contact.model"; export class Vehicle { public id: number; public name: string; public isRegistered: boolean; public image: string; public contact: Contact; public lastUpdate: number; public features: string[]; public description: string; public counter: number; constructor(id: number, name: string, isRegistered: boolean, image: string, contact: Contact, features: string[], counter: number, description: string, lastUpdate: number ) { this.id = id; this.name = name; this.isRegistered = isRegistered; this.image = image; this.contact = contact; this.lastUpdate = lastUpdate; this.features = features; this.description = description; this.counter = counter; } }
5dbc99e6aaf99f5af0506f222db2d9eef9afbbda
TypeScript
rubensworks/community-server
/src/storage/Lock.ts
3.125
3
/** * Lock used by a {@link ResourceLocker} for non-atomic operations. */ export interface Lock { /** * Release this lock. * @returns A promise resolving when the release is finished. */ release: () => Promise<void>; }
f214695edff210b21451546e464710d756f2c002
TypeScript
paf31/typescript-docs-psc
/example/example.d.ts
3.375
3
/** * An example of a module */ declare module ExampleModule { /** * A nested module */ module AnotherModule { /** * An example of a class */ class Foo implements Bar { /** * Constructor example */ constructor(); public getFoo(name: string, optionalParameter?: number): Foo; } /** * An example of an interface */ interface Bar { /** * Get the Foo corresponding to this Bar * * @param { name } The name */ getFoo(name: string, optionalParameter?: number): Foo; } // An interface with a varargs method interface Length { lengthOf<T>(...values: T[]); } } /** * Generics are supported too */ function makeFoo<T1, T2>(options?: { name: string; t1: T1; t2?: T2; }): AnotherModule.Foo; /** * An example of a variable */ var globalVariable: string; /** * An enumeration */ enum Baz { Abc, Xyz, } }
bccaea2260c3d006030dec8eda12e0c9f4615451
TypeScript
Food-Ordering-Application/user-service
/src/customer/entities/customer-address.entity.ts
2.53125
3
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm'; import { Customer } from './customer.entity'; @Entity() export class CustomerAddress { @PrimaryGeneratedColumn('uuid') id: string; @ManyToOne(() => Customer, (customer) => customer.customerAddresses) customer: Customer; @Column() address: string; @Column({ default: 'TPHCM' }) city: string; @Column({ default: 'TPHCM' }) area: string; @Column({ type: 'geometry', spatialFeatureType: 'Point', srid: 4326 }) geom: { type: string; coordinates: number[] }; @Column({ default: false }) default: boolean; }
1c8d4cfaa7c975d6df2e772f855923fae8bbafea
TypeScript
plugjs/plug
/test-d/11-expect5-expectations.test-d.ts
3.109375
3
import { expect, type AsyncExpectations, type Expectations } from '@plugjs/expect5' import { expectError, expectType, printType } from 'tsd' printType('__file_marker__') type TestType = boolean & { __test: never } const expectations = expect(true as TestType) class TestError extends Error { test: boolean = true } expectType<AsyncExpectations<TestType>>(expectations) expectType<TestType>(expectations.value) /* === TO BE A ============================================================== */ expectType<Expectations<string>>(expectations.toBeA('string')) expectType<Expectations<never>>(expectations.toBeA('string', expect.toBeA('number'))) // string & number expectType<Expectations<string & { length: number }>>(expectations.toBeA('string', expect.toHaveLength(12))) expectType<Expectations<number>>(expectations.toBeA('string', (assert) => assert.toBeA('number'))) expectType<Expectations<string>>(expectations.toBeA('string', (assert) => { expectType<Expectations<string>>(assert) assert.toBeA('number') // returns void })) /* === TO BE CLOSE TO ======================================================= */ expectType<Expectations<number>>(expectations.toBeCloseTo(100, 10)) expectType<Expectations<bigint>>(expectations.toBeCloseTo(10n, 1n)) expectError(expectations.toBeCloseTo(100, 1n)) expectError(expectations.toBeCloseTo(10n, 10)) /* === TO BE DEFINED ======================================================== */ expectType<Expectations<TestType>>(expectations.toBeDefined()) /* === TO BE ERROR ========================================================== */ expectType<Expectations<Error>>(expectations.toBeError()) expectType<Expectations<Error>>(expectations.toBeError('message')) expectType<Expectations<TestError>>(expectations.toBeError(TestError)) expectType<Expectations<TestError>>(expectations.toBeError(TestError, 'message')) /* === TO BE FALSE ========================================================== */ expectType<Expectations<false>>(expectations.toBeFalse()) /* === TO BE FALSY ========================================================== */ expectType<Expectations<TestType>>(expectations.toBeFalsy()) /* === TO BE GREATER THAN =================================================== */ expectType<Expectations<number>>(expectations.toBeGreaterThan(100)) expectType<Expectations<bigint>>(expectations.toBeGreaterThan(10n)) /* === TO BE GREATER THAN OR EQUAL ========================================== */ expectType<Expectations<number>>(expectations.toBeGreaterThanOrEqual(100)) expectType<Expectations<bigint>>(expectations.toBeGreaterThanOrEqual(10n)) /* === TO BE INSTANCE OF ==================================================== */ expectType<Expectations<TestError>>(expectations.toBeInstanceOf(TestError)) expectType<Expectations<TestError & { length: number }>>(expectations.toBeInstanceOf(TestError, expect.toHaveLength(12))) expectType<Expectations<number>>(expectations.toBeInstanceOf(TestError, (assert) => assert.toBeA('number'))) expectType<Expectations<TestError>>(expectations.toBeInstanceOf(TestError, (assert) => { expectType<Expectations<TestError>>(assert) assert.toBeA('number') // returns void })) /* === TO BE LESS THAN ====================================================== */ expectType<Expectations<number>>(expectations.toBeLessThan(100)) expectType<Expectations<bigint>>(expectations.toBeLessThan(10n)) /* === TO BE LESS THAN OR EQUAL ============================================= */ expectType<Expectations<number>>(expectations.toBeLessThanOrEqual(100)) expectType<Expectations<bigint>>(expectations.toBeLessThanOrEqual(10n)) /* === TO BE NAN ============================================================ */ expectType<Expectations<number>>(expectations.toBeNaN()) /* === TO BE NULL =========================================================== */ expectType<Expectations<null>>(expectations.toBeNull()) /* === TO BE TRUE =========================================================== */ expectType<Expectations<true>>(expectations.toBeTrue()) /* === TO BE TRUTHY ========================================================= */ expectType<Expectations<TestType>>(expectations.toBeTruthy()) /* === TO BE UNDEFINED ====================================================== */ expectType<Expectations<undefined>>(expectations.toBeUndefined()) /* === TO BE WITHIN RANGE =================================================== */ expectType<Expectations<number>>(expectations.toBeWithinRange(100, 10)) expectType<Expectations<bigint>>(expectations.toBeWithinRange(10n, 1n)) expectError(expectations.toBeWithinRange(100, 1n)) expectError(expectations.toBeWithinRange(10n, 10)) /* === TO EQUAL ============================================================= */ expectType<Expectations<123>>(expectations.toEqual(123)) expectType<Expectations<unknown>>(expectations.toEqual(true as unknown)) expectType<Expectations<number[]>>(expectations.toEqual([ 123 ])) expectType<Expectations<{ foo: string, bar: number, }>>(expectations.toEqual({ foo: 'hello, world!', // straight type bar: expect.toBeA('number'), // matcher })) /* === TO HAVE LENGTH ======================================================= */ expectType<Expectations<TestType & { length: number }>>(expectations.toHaveLength(123)) /* === TO HAVE PROPERTY ===================================================== */ expect<Expectations<TestType & { prop: unknown }>>(expectations.toHaveProperty('prop')) // with matchers expect<Expectations<TestType & { prop: number }>>(expectations.toHaveProperty('prop', expect.toBeA('number'))) expect<Expectations<TestType & { prop: { foo: string } }>>(expectations.toHaveProperty('prop', expect.toEqual({ foo: expect.toBeA('string') }))) // with assertions expect<Expectations<TestType & { prop: number }>>(expectations.toHaveProperty('prop', (assert) => assert.toBeA('number'))) expect<Expectations<TestType & { prop: undefined }>>(expectations.toHaveProperty('prop', (assert) => assert.toBeUndefined())) // with assertion returning "void" expect<Expectations<TestType & { prop: unknown }>>(expectations.toHaveProperty('prop', (assert) => { expectType<Expectations<unknown>>(assert) assert.toBeA('number') })) /* === TO HAVE SIZE ========================================================= */ expectType<Expectations<TestType & { size: number }>>(expectations.toHaveSize(123)) /* === TO INCLUDE =========================================================== */ expectType<Expectations<TestType>>(expectations.toInclude({ foo: 'bar' })) expectType<Expectations<TestType>>(expectations.toInclude([ 'foo', 'bar' ])) expectType<Expectations<TestType>>(expectations.toInclude(new Set<string>())) expectType<Expectations<TestType>>(expectations.toInclude(new Map<number, boolean>())) /* === TO MATCH ============================================================= */ expectType<Expectations<string>>(expectations.toMatch('foobar')) expectType<Expectations<string>>(expectations.toMatch(/foobar/)) /* === TO MATCH CONTENTS =================================================== */ expectType<Expectations<TestType>>(expectations.toMatchContents([ 'foo', 'bar' ])) expectType<Expectations<TestType>>(expectations.toMatchContents(new Set<string>())) /* === TO STRICTLY EQUAL ==================================================== */ expectType<Expectations<123>>(expectations.toStrictlyEqual(123)) expectType<Expectations<unknown>>(expectations.toStrictlyEqual(true as unknown)) expectType<Expectations<number[]>>(expectations.toStrictlyEqual([ 123 ])) expectType<Expectations<{ foo: string}>>(expectations.toStrictlyEqual({ foo: 'bar' })) /* === TO THROW ============================================================= */ expectType<Expectations<() => any>>(expectations.toThrow()) expectType<Expectations<() => any>>(expectations.toThrow(expect.toBeA('string'))) expectType<Expectations<() => any>>(expectations.toThrow((assert) => assert.toBeA('string'))) expectType<Expectations<() => any>>(expectations.toThrow((assert) => { expectType<Expectations<unknown>>(assert) assert.toBeA('string') })) /* === TO THROW ERROR ======================================================= */ expectType<Expectations<() => any>>(expectations.toThrowError()) expectType<Expectations<() => any>>(expectations.toThrowError('message')) expectType<Expectations<() => any>>(expectations.toThrowError(TestError)) expectType<Expectations<() => any>>(expectations.toThrowError(TestError, 'message'))
a191c2187c2901daea754a001974d3e3d1e98c24
TypeScript
paikwiki/ts-algorithm
/src/q0.2.2-swapArr.ts
3.96875
4
{ // Q. // 배열과 배열의 두 원소의 위치를 인자로 받아서 값을 바꾸는 swapArr() 함수 작성 // A1. // 변수에 할당한 값은 함수를 이용해서 swap할 수 없었는데(q0.2.1-swap.ts 참고) // 변수에 할당한 배열은 함수 내에서 순서를 바꾸니까 순서가 바뀐다. const swapArr = (arr: Array<any>, pos1: number, pos2: number): void => { let temp: any; temp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = temp; } // A2. // 구조분해할당 활용 const swapArr2 = (arr: Array<any>, pos1: number, pos2: number): void => { [arr[pos1], arr[pos2]] = [arr[pos2], arr[pos1]]; } // App const arr: Array<any> = [0, 1, 2, 3, 4]; const arr2: Array<any> = ['a', 'b', 'c', 'd', 'e']; swapArr(arr, 1, 3); swapArr2(arr2, 1, 3); console.log(arr); // [0, 3, 2, 1, 4] console.log(arr2); // ['a', 'd', 'c', 'b', 'e'] }
9ee8df909cfe9a8670f07bf763190c474f4fcdb6
TypeScript
hypermedia-app/lit-any-views
/test/render/index.test.ts
2.59375
3
import { expect } from '@open-wc/testing' import { html, render as litRender, TemplateResult } from 'lit-html' import sinon from 'sinon' import render from '../../src/lib/render' describe('render view', () => { let registry: any beforeEach(() => { registry = { getTemplate: sinon.stub(), } }) it('should create TemplateResult for found template', () => { // given registry.getTemplate.returns({ render: (object: any) => html` <span>${object.value}</span> `, }) const container = document.createElement('div') const value = { value: 'test', } // when litRender(render(registry, { value }, false), container) // then const span = container.querySelector('span') expect(span!.textContent).to.equal('test') }) it('should create TemplateResult for template not found', () => { // given registry.getTemplate.returns(null) const value = { value: 'test', } // when const result = render(registry, { value }, false) // then expect(result).to.be.instanceOf(TemplateResult) }) it('should pass down scope parameter', () => { // given registry.getTemplate.returns({ render: (object: unknown, _: Function, scope: string) => html` <span>${scope}</span> `, }) const container = document.createElement('div') const value = { value: 'test', } // when litRender(render(registry, { value, scope: 'some scope' }, false), container) // then expect(container.textContent!.trim()).to.equal('some scope') }) })
be7289f70549fe40b3e73b44571bdc68914dd397
TypeScript
guiseek/angular-gamification
/src/services/progress-bar.service.ts
2.953125
3
import { Injectable } from '@angular/core'; @Injectable() export class ProgressBarService { public maxPoints: number = 0; public isFull: boolean; private updateFn: Function = () => { }; private startFn: Function = () => { }; constructor(maxPoints: number, updateFn?: Function, startFn?: Function) { this.maxPoints = maxPoints || this.maxPoints; this.updateFn = updateFn || this.updateFn; this.startFn = startFn || this.startFn; this.isFull = false; // return this; } public update(points: number) { if (!this.isFull) { this.updateFn(); if (this.maxPoints <= points) { this.isFull = true; } } } public start() { this.startFn(this.maxPoints); } public getProgress(points: number) { return Math.min(Math.max(Math.ceil(100 * points / this.maxPoints), 0), 100) } }
0bdf89c074f3c8a5480fd1953cd6f90f75eeda18
TypeScript
Mikkew/04-PipesApp
/src/app/ventas/pipes/ordernar.pipe.ts
2.578125
3
import { Pipe, PipeTransform } from '@angular/core'; import { Heroe } from '../interfaces/ventas,interface'; @Pipe({ name: 'ordernar' }) export class OrdernarPipe implements PipeTransform { transform(heroes: Heroe[], ordernarPor:string | null = null ): Heroe[] { switch (ordernarPor) { case "nombre": heroes = heroes.sort( (a, b) => (a.nombre > b.nombre) ? 1 : -1 ); return heroes; case "vuela": heroes = heroes.sort( (a, b) => (a.vuela > b.vuela) ? -1 : 1 ); return heroes; case "color": heroes = heroes.sort( (a, b) => (a.color.toString > b.color.toString) ? 1 : -1 ); return heroes; default: return heroes; } } }
a9feb44c20173372f7ffb655d9142c8aa61a6fbf
TypeScript
matt-moser/covid-projections
/scripts/compare_find_diff/find_diff.ts
2.796875
3
/* A throwaway script to generate file with 2 lists (before filling in missing data): 1. Fips included in county_adjacency_msa.json but not in 2018-census-fips-codes.json 2. Fips included in 2018-census-fips-codes.json but not in county_adjacency_msa.json (Fips in list #1 are those of U.S. territories not included in CAN) Used for compare tables -- to find which fips' adjacency data needs to be man manually entered into county_adjacency_msa.json */ import path from 'path'; import fs from 'fs-extra'; import ADJACENCY_FILE from '../prepare_regions_data/county_adjacency_msa.json'; import CENSUS_FIPS from '../what-the-fips/2018-census-fips-codes.json'; function getCensusFipsArr(): string[] { let censusListFips: string[] = []; const states = Object.values(CENSUS_FIPS); states.forEach(state => { const allFipsInState = Object.keys(state); censusListFips = [...censusListFips, ...allFipsInState]; }); return censusListFips; } function getAdjacencyFipsArr(): string[] { const counties = ADJACENCY_FILE.counties; const adjacencyListFips = Object.keys(counties); return adjacencyListFips; } function filterForDiff(listA: string[], listB: string[]): string[] { return listA.filter(listA => !listB.includes(listA)); } function main() { const adjacencyListFips = getAdjacencyFipsArr(); const censusListFips = getCensusFipsArr(); const adjacencyNotInCensusFips = filterForDiff( adjacencyListFips, censusListFips, ); const censusNotInAdjacencyFips = filterForDiff( censusListFips, adjacencyListFips, ); const outputPath = path.join(__dirname, 'fips_diff.json'); const outputData = JSON.stringify( { adjacencyNotInCensusFips, censusNotInAdjacencyFips, }, null, 2, ); fs.writeFileSync(outputPath, outputData); } main();
66ecfc83c0825a07f2e70e7bb28c15de23200a2f
TypeScript
jmacmahon/twitter-utils
/src/modules/muteRetweets.ts
2.59375
3
import { validate } from 'validate-typescript' import { Dict } from '../dict' import { Module } from '../module' import { TwitterClient } from '../twitterApiClient' type Params = { } const Params = (): Params => ({ }) export const defaultInjections = { consoleLog: console.log } export class MuteRetweets implements Module { constructor ( private client: TwitterClient.GetFriends & TwitterClient.DisableRetweets, private injections = defaultInjections ) { } async run (rawParams: Dict<unknown>) { const params = validate(Params(), rawParams) const following = await this.client.getFriends() for (const user of following) { await this.client.disableRetweets(user) this.injections.consoleLog(`Disabling retweets for user ${user.screen_name}`) } } }
37fc63016e473a8486688ab3f460e49e6d8c3714
TypeScript
RainheartLang2/hotaru-web-client
/client/src/common/beans/GoodsDocument.ts
2.546875
3
import Identifiable from "../../core/entities/Identifiable"; import {DocumentState} from "./enums/DocumentState"; import GoodsPackWithPrice from "./GoodsPackWithPrice"; import {ShipingType} from "./enums/ShipingType"; import CustomContainer from "../../core/beans/CustomContainer"; export default class GoodsDocument extends Identifiable { public documentState: DocumentState public shipingType: ShipingType public date: Date public stockId: number public destinationStockId: number | null public counterAgentId: number | null public num: string public goods: CustomContainer<GoodsPackWithPrice> constructor(bean: GoodsDocumentBean) { super(bean.id) this.documentState = bean.documentState this.shipingType = bean.shipingType this.date = new Date(bean.date) this.stockId = bean.stockId this.destinationStockId = bean.destinationStockId this.counterAgentId = bean.counterAgentId this.num = bean.num this.goods = bean.goods } } export type GoodsDocumentBean = { id?: number documentState: DocumentState shipingType: ShipingType date: Date stockId: number destinationStockId: number | null counterAgentId: number | null num: string goods: CustomContainer<GoodsPackWithPrice> }
f62dff90f0ea86a77f87dc1df69fa3923cce8520
TypeScript
luckkiss/CookingGame_H5
/assets/Scripts/MVC/Test/CharacterInfo.ts
2.84375
3
const { ccclass, property } = cc._decorator; @ccclass export default class CharacterInfo { name: string = ''; leve: number = 1; constructor(names: string="", num: number=0) { this.name = names; this.leve = num; } }
f0497986e3be40b69afb6f80be55086bd851d23e
TypeScript
bmaximilian/jet-pack
/store/src/polyfill/constructorName.ts
2.9375
3
/** * Created on 2019-06-03. * * @author Maximilian Beck <maximilian.beck@wtl.de> */ /** * Polyfill for constructor name */ export function polyfillConstructorName() { if (Function.prototype.name === undefined && Object.defineProperty !== undefined) { Object.defineProperty(Function.prototype, 'name', { get() { const funcNameRegex = /function\s([^(]{1,})\(/; const results = (funcNameRegex).exec((this).toString()); return (results && results.length > 1) ? results[1].trim() : ''; }, set(value) { /* nothing */ }, }); } }
b288e8cb7f8ef9fcecc5a887daf96b3b43463ba1
TypeScript
electronicSAINT/jabberwock
/packages/plugin-heading/src/HeadingXmlDomParser.ts
2.8125
3
import { HeadingNode } from './HeadingNode'; import { AbstractParser } from '../../plugin-parser/src/AbstractParser'; import { XmlDomParsingEngine } from '../../plugin-xml/src/XmlDomParsingEngine'; import { nodeName } from '../../utils/src/utils'; const HeadingTags = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']; export class HeadingXmlDomParser extends AbstractParser<Node> { static id = XmlDomParsingEngine.id; engine: XmlDomParsingEngine; predicate = (item: Node): boolean => { return item instanceof Element && HeadingTags.includes(nodeName(item)); }; async parse(item: Element): Promise<HeadingNode[]> { const heading = new HeadingNode({ level: parseInt(nodeName(item)[1], 10) }); const attributes = this.engine.parseAttributes(item); if (attributes.length) { heading.modifiers.append(attributes); } const nodes = await this.engine.parse(...item.childNodes); heading.append(...nodes); return [heading]; } }
df3b74cdc73f79858ddad650ee476f5ffff49531
TypeScript
AlfredsJunior/Dynamics-365-Fraud-Protection-ManualReview
/frontend/src/models/item/purchase/geo-address.ts
2.796875
3
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. import { observable } from 'mobx'; import { getMiles } from '../../../utils/math'; import { Address } from './address'; export class GeoAddress { latitude?: number; longitude?: number; address: Address; @observable distances: Map<string, number | null> = new Map(); constructor(address: Address, latitude?: number, longitude?: number) { this.latitude = latitude; this.longitude = longitude; this.address = address; } get isPointable() { return !!this.latitude && !!this.longitude; } get position() { return [this.longitude || 0, this.latitude || 0]; } setDistanceToAddress(address: GeoAddress, distance: number | null) { this.distances.set(address?.address?.displayLineAddress, distance); } getDistanceToAddress(address: GeoAddress) { const distanceInMeters = this.distances.get(address.address.displayLineAddress); return { distanceInMeters, distanceInMiles: getMiles(distanceInMeters) }; } }
b9895e5fb32e3cdb353167d9adb366da57e7981d
TypeScript
manjirinamjoshi/notes-app
/src/utils/middleware.ts
2.6875
3
import { Request, Response, NextFunction } from "express"; import { validationResult, ValidationError } from "express-validator"; import { generate } from "shortid"; import { REQUEST_ID_HEADER, AUTHORIZATION_HEADER } from "../core/constants"; import { InputValidationError } from "../core/errors"; export const reqIdInterceptor = ( req: Request & { XReqId: string }, res: Response, next: NextFunction ) => { if (req && req.path && req.path.indexOf("/api") > -1) { const header = req.get(REQUEST_ID_HEADER) || generate(); req.XReqId = header; res.set(REQUEST_ID_HEADER, header); } next(); }; export const authInterceptor = ( req: Request & { XReqId: string, XUserId: string }, res: Response, next: NextFunction ) => { if (req && req.path && req.path.indexOf("/api") > -1) { const header = req.get(AUTHORIZATION_HEADER); // TODO authentication and set userId on the request if(!header) { req.XUserId = `12345`; } } next(); }; export const validationCatcher = async ( req: Request, res: Response, next: NextFunction ) => { const errorFormatter = ({ location, msg, param }: ValidationError) => { // Build your resulting errors however you want! String, object, whatever - it works! return `${param} in ${location}: ${msg}`; }; const result = validationResult(req).formatWith(errorFormatter); if (!result.isEmpty()) { throw new InputValidationError(result.array()); } next(); };
9625beeca461364d231048078179db3c36950df1
TypeScript
mmgoodnow/got-meme
/src/Search.ts
2.6875
3
import fetch from "node-fetch"; export default class ImageSearch { static url: string = "https://eastus.api.cognitive.microsoft.com/bing/v7.0/images/search"; static async searchImage(query: string) { try { // Fetches Items from Google Image Search URL let response = await fetch( `${this.url}?q=${encodeURIComponent(query)}`, { method: "GET", headers: { "Ocp-Apim-Subscription-Key": process.env.APIKEY, }, } ); let json: any = await response.json(); return json.value; } catch (e) { console.error(`Failed to search images for ${query}, got ${e}`); } } }
07704a962147b1ff9655770afd97d3a54024e85d
TypeScript
admarket14/n6-geekinsider-be-alpha-6
/src/models/user.ts
2.640625
3
import { IUser } from '@/interfaces/IUser'; import mongoose from 'mongoose'; const User = new mongoose.Schema( { _id: { type: String, // This will the cognito user name itself which will be used as an id paramter required: true, unique: true }, email: { // here we fill the email id for the user type: String, required: true, unique: true }, role: { // there can be two property for a user role either candidate or recruiter type: String, default: "userCandidate", enum: ["userRecruiter", "userCandidate"] } }, ); export default mongoose.model<IUser & mongoose.Document>('User', User);
4117b21e81ecbc6eab3e82535edaa1d2ec747569
TypeScript
friendsoftheweb/catalyst
/packages/catalyst/src/utils/resolveFileConflict.ts
2.703125
3
import inquirer from 'inquirer'; import chalk from 'chalk'; import diffExistingFile from './diffExistingFile'; export default async function resolveFileConflict( filePath: string, fileContent: string ): Promise<'overwrite' | 'skip'> { process.stderr.write('\n'); const config = await inquirer.prompt<{ resolution: 'overwrite' | 'skip' | 'diff'; }>([ { name: 'resolution', message: `File exists: '${filePath}'. Overwrite?`, type: 'expand', choices: [ { name: 'Yes, Overwrite', key: 'y', value: 'overwrite' }, { name: 'No, Skip', key: 'n', value: 'skip' }, { name: 'Diff', key: 'd', value: 'diff' }, ], default: 1, }, ]); if (config.resolution === 'diff') { const diff = await diffExistingFile(filePath, fileContent); process.stderr.write('\n'); diff.forEach((part) => { let value: string; if (part.added) { value = chalk.green(part.value); } else if (part.removed) { value = chalk.red(part.value); } else { value = chalk.white(part.value); } process.stderr.write(value); }); return resolveFileConflict(filePath, fileContent); } else { return config.resolution; } }
806c3a7011ca46751b158721b6705a0b13879e30
TypeScript
malikdul/task-management
/src/tasks/task.mapper.ts
2.515625
3
import { Injectable } from "@nestjs/common"; import {plainToClass } from "class-transformer"; import { TaskDto } from "./task.dto"; import { Task } from "./task.entity"; @Injectable() export class TaskMapper { toDto(entity: Task): TaskDto { return plainToClass<TaskDto, Task>(TaskDto, entity); } toEntity(dto: TaskDto): Task { return plainToClass(Task, dto); } }
9128cea07f1267e62525fabb1d15c6d179ad8e04
TypeScript
FlyingTwigster/yummyplan.github.io
/components/SearchableList/SearchableMealList.ts
2.6875
3
import { Component } from 'vue-property-decorator' import { Meal } from '~/model/meal/Meal' import SearchableList from '~/components/SearchableList/SearchableList.vue' // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore @Component export default class SearchableMealList extends SearchableList<Meal> { /** * Search meals by tag or title * @param term */ getFilterPredicate (term: string): (items: Meal) => boolean { const orTerms = term.split(',').map(s => s.trim()) return (m: Meal): boolean => { return orTerms.some((t: string) => { const andTerms = t.split('&').map(s => s.trim()) return andTerms.every(t => m.doesMatch(t)) }) } } }
61414a3ba5f05d4a3e68f26ef129ce58b8899729
TypeScript
future4code/Guilherme-Galan
/semana19/testes-business/aula64-testes-no-backend-ex-tarde-inicio/tests/UserBusiness/getAllUsers.test.ts
2.828125
3
import { UserBusiness } from "../../src/business/UserBusiness"; import { UserRole, User, stringToUserRole } from "../../src/model/User"; describe("Testing UserBusiness.getAllUsers", () => { let userDatabase = {}; let hashGenerator = {}; let tokenGenerator = {}; let idGenerator = {}; test('Should return "Only Admin can access" if role !== ADMIN', async () => { expect.assertions(2); try{ const userBusiness = new UserBusiness( userDatabase as any, hashGenerator as any, tokenGenerator as any, idGenerator as any ); await userBusiness.getAllUsers(UserRole.NORMAL) }catch(err){ expect(err.errorCode).toBe(400) expect(err.message).toBe('Only Admin can access') } }); test('Should Success', async() => { const getAllUsers = jest.fn(() => [ new User('id', 'Guilherme', 'gui@gmail.com', 'hashPassword', stringToUserRole('ADMIN')) ]); userDatabase = { getAllUsers }; const userBusiness = new UserBusiness( userDatabase as any, hashGenerator as any, tokenGenerator as any, idGenerator as any ); const result = await userBusiness.getAllUsers(UserRole.ADMIN); expect(getAllUsers).toHaveBeenCalledTimes(1); expect(result).toContainEqual({ id: 'id', name: 'Guilherme', email: 'gui@gmail.com', role: 'ADMIN' }) }) })
8bfda3d960fc92ab8ada42c48fb61bbdeebf947e
TypeScript
vikuviku6666/todo-list
/src/app/displaytodo/displaytodo.component.ts
2.515625
3
import { Component, OnInit } from '@angular/core'; import { TodoService } from '../todos/todo.service'; import { Todo } from '../../models/todo.model'; import { Guid } from 'guid-typescript'; @Component({ selector: 'app-displaytodo', templateUrl: './displaytodo.component.html', styleUrls: ['./displaytodo.component.scss'] }) export class DisplaytodoComponent implements OnInit { public todo: Todo[] = []; constructor(private service: TodoService) { } ngOnInit(): void { this.service.$todo.subscribe((todo) => { this.todo = todo; }); } toggle(task: any): void { task.isComplete = !task.isComplete; } deleteTodo(id: Guid): void { const todoItem = this.todo.filter(x => x.id === id)[0]; const index = this.todo.indexOf(todoItem, 0); if (index > -1) { this.todo.splice(index, 1); } } }
c6bba5f9b06352eb4649803b96251a7c1844ccf1
TypeScript
pafrias/40k-dice-roller
/src/Entities/Characteristic/Characteristic.ts
3.515625
4
import {rollD} from '../../helpers' export class Characteristic { D: number = 0; // Number of dice N: number = 0; // Number on the dice C: number = 0; // added constant constructor(str:string) { let {parseInt} = Number; // trim whitespace str = str.split(/\s/).join(''); // parseInt returns the longest valid substring starting at index 0 if (!isNaN(Number(str))) { this.C = 0 + parseInt(str); return; } let isValidDice:boolean = /[1-9]*(d|D)[1-9]+((-|\+)[1-9]+)?/.test(str); if (!isValidDice) { // throw error console.log(`${str} is not a valid Characteristic`); return; } let dIndex:number = str.search(/d|D/); let operatorIndex:number = str.search(/-|\+/); // find and trim any constants, save to C this.C = operatorIndex > -1 ? parseInt(str.slice(operatorIndex)) * 1 : 0; this.N = dIndex === 0 ? 1 : parseInt(str.slice(0, dIndex)); this.D = parseInt(str.slice(dIndex + 1, operatorIndex === -1 ? Infinity : operatorIndex)); } get val():number { let total = this.C; for (let i = 0; i < this.N; i++) total += rollD(this.D); return total; } get max():number { return (this.N * this.D) + this.C; } }
7c16c3dc0fd919e62bad133b7a784b037bca3c56
TypeScript
uncaught/doko
/packages/client/src/store/Games/DetectLastGameAndForcedSolo.ts
2.515625
3
import {Game, GameData, Player, RoundData} from '@doko/common'; import {PlayerStats} from '../Players'; import {findPlayerIndex} from '../Games'; export function detectLastGameAndForcedSolo( roundData: RoundData, gameData: GameData, sortedGames: Game[], newGameDealerId: string, activePlayers: Player[], playersWithStats: PlayerStats[], ): void { //Determine if the number of runs is known: if (!sortedGames.length || (roundData.dynamicRoundDuration && roundData.roundDuration === null)) { return; } //Determine whether we are in the last run - forced soli can only be in the last run: const duration = roundData.dynamicRoundDuration ? roundData.roundDuration : 6; //6 runs = 24 games if (duration !== gameData.runNumber) { return; } const nextDealerIndex = findPlayerIndex(activePlayers, newGameDealerId); const remainingRegularGames = activePlayers.length - nextDealerIndex; if (remainingRegularGames === 1) { gameData.isLastGame = true; } //Find the players that are still present and still need their solo: const open = playersWithStats.filter(({player, dutySoloPlayed}) => !dutySoloPlayed && activePlayers.includes(player)); const openIndexes = open.map(({player}) => activePlayers.indexOf(player)); const countIndexesAfterDealer = openIndexes.filter((idx) => idx > nextDealerIndex).length; if (open.length < remainingRegularGames //Make sure the player does not have to deal when he is supposed to have his forced solo: && (activePlayers.length < 5 || countIndexesAfterDealer !== 1 || remainingRegularGames > 2) && (activePlayers.length < 6 || countIndexesAfterDealer !== 2 || remainingRegularGames > 3) ) { return; } gameData.gameType = 'forcedSolo'; gameData.re.members = []; gameData.contra.members = []; for (let i = 1; i < 5; i++) { const pIndex = (nextDealerIndex + i) % activePlayers.length; const player = activePlayers[pIndex]; if (openIndexes.includes(pIndex) && gameData.re.members.length === 0) { gameData.gameTypeMemberId = player.groupMemberId; gameData.re.members.push(player.groupMemberId); } else { gameData.contra.members.push(player.groupMemberId); } } }
5e2457201d4fafda198fdfba934f37abe6ee68ee
TypeScript
wrdsb/sorting-hat-functions2
/shared/findCreatesAndUpdates.ts
2.828125
3
import { isEqual } from "lodash"; async function findCreatesAndUpdates(context, calculation) { let newRecordsCount = Object.getOwnPropertyNames(calculation.records_now).length; let currentRecordsCount = Object.getOwnPropertyNames(calculation.records_previous).length; context.log('Find creates and updates...'); context.log('Processing ' + newRecordsCount + ' new records and ' + currentRecordsCount + ' current records.'); let records_previous = calculation.records_previous; let records_now = calculation.records_now; // loop through all records in records_now, looking for updates and creates Object.getOwnPropertyNames(records_now).forEach(function (record_id) { let new_record = records_now[record_id]; // get the full person record from records_now let old_record = records_previous[record_id]; // get the corresponding record in records_previous // if we found a corresponding record in records_previous, look for changes if (old_record) { // Compare old and new records using Lodash _.isEqual, which performs a deep comparison let records_equal = isEqual(old_record, new_record); // if record changed, record the change if (!records_equal) { calculation.differences.updated_records.push({ previous: old_record, now: new_record }); } // if we don't find a corresponding record in records_previous, they're new } else { calculation.differences.created_records.push(new_record); } }); context.log('Found ' + calculation.differences.created_records.length + ' created records.') context.log('Found ' + calculation.differences.updated_records.length + ' updated records.') return calculation; } export { findCreatesAndUpdates };
dbc17efac36040b16b6906a79f78ec01c0c422f4
TypeScript
shaziajk/carbon-charts
/packages/core/src/model/meter.ts
2.578125
3
// Internal Imports import * as Configuration from '../configuration'; import { ChartModel } from './model'; import { Tools } from '../tools'; /** The meter chart model layer which extends some of the data setting options. * Meter only uses 1 dataset * */ export class MeterChartModel extends ChartModel { constructor(services: any) { super(services); } getMaximumDomain(data) { const max = data.reduce( (accumulator, datum) => accumulator + datum.value, 0 ); return max; } /** * Use a provided color for the bar or default to carbon color if no status provided. * Defaults to carbon color otherwise. * @param group dataset group label */ getFillColor(group: string) { const options = this.getOptions(); const userProvidedScale = Tools.getProperty(options, 'color', 'scale'); const status = this.getStatus(); // user provided a fill color or there isn't a status we can use the colorScale if (userProvidedScale || !status) { return super.getFillColor(group); } else { return null; } } /** * Get the associated status for the data by checking the ranges */ getStatus() { const options = this.getOptions(); const dataValue = Tools.getProperty(this.getDisplayData(), 0, 'value'); // use max value if the percentage is bigger than 100% const boundedValue = dataValue > 100 ? 100 : dataValue; // user needs to supply ranges const allRanges = Tools.getProperty( options, 'meter', 'status', 'ranges' ); if (allRanges) { const result = allRanges.filter( (step) => step.range[0] <= boundedValue && boundedValue <= step.range[1] ); if (result.length > 0) { return result[0].status; } } return null; } }
544c2e2b4d0a81d455bba2225b3f99e9f9afb608
TypeScript
brunano21/angular-4-data-table
/libs/datatable/src/utils/hide.ts
2.65625
3
import { Directive, ElementRef, Input, Renderer2 } from '@angular/core'; function isBlank(obj: any): boolean { return obj === undefined || obj === null; } @Directive({ selector: '[hide]' }) export class HideDirective { private _prevCondition = false; private _displayStyle: string; constructor(private _elementRef: ElementRef, private renderer: Renderer2) { } @Input() set hide(newCondition: boolean) { this.initDisplayStyle(); if (newCondition && (isBlank(this._prevCondition) || !this._prevCondition)) { this._prevCondition = true; this.renderer.setStyle(this._elementRef.nativeElement, 'display', 'none'); } else if (!newCondition && (isBlank(this._prevCondition) || this._prevCondition)) { this._prevCondition = false; this.renderer.setStyle(this._elementRef.nativeElement, 'display', this._displayStyle); } } private initDisplayStyle() { if (this._displayStyle === undefined) { const displayStyle = this._elementRef.nativeElement.style.display; if (displayStyle !== 'none') { this._displayStyle = displayStyle; } } } }
c614a2047d95b0db0cd191096172ee9410af8b4d
TypeScript
TencentCloud/tencentcloud-sdk-nodejs
/tencentcloud/services/captcha/v20190722/captcha_models.d.ts
2.875
3
/** * DescribeCaptchaOperData返回参数结构体 */ export interface DescribeCaptchaOperDataResponse { /** * 成功返回 0 其它失败 */ CaptchaCode: number; /** * 返回信息 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg: string; /** * 用户操作数据 注意:此字段可能返回 null,表示取不到有效值。 */ Data: CaptchaOperDataRes; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCaptchaOperData方法 拦截情况type = 2 返回的数据结构 */ export interface CaptchaOperDataInterceptUnit { /** * 时间 */ DateKey: string; /** * 停止验证数量 */ AllStopCnt: number; /** * 图片停止加载数量 */ PicStopCnt: number; /** * 策略拦截数量 */ StrategyStopCnt: number; } /** * DescribeCaptchaOperData方法 尝试次数分布 type = 4 */ export interface CaptchaOperDataTryTimesDistributeUnit { /** * 尝试次数 */ TryCount: number; /** * 用户请求数量 */ UserCount: number; } /** * DescribeCaptchaMiniOperData返回参数结构体 */ export interface DescribeCaptchaMiniOperDataResponse { /** * 成功返回 0 其它失败 */ CaptchaCode: number; /** * 返回信息 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg: string; /** * 用户操作数据 注意:此字段可能返回 null,表示取不到有效值。 */ Data: CaptchaOperDataRes; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * GetTotalTicketStatistics请求参数结构体 */ export interface GetTotalTicketStatisticsRequest { /** * 开始时间 */ StartTimeStr: string; /** * 结束时间 */ EndTimeStr: string; /** * 查询粒度 分钟:“1” 小时:“2” 天:“3” */ Dimension: string; } /** * DescribeCaptchaMiniDataSum返回参数结构体 */ export interface DescribeCaptchaMiniDataSumResponse { /** * 请求总量 注意:此字段可能返回 null,表示取不到有效值。 */ GetSum?: number; /** * 请求验证成功量 注意:此字段可能返回 null,表示取不到有效值。 */ VfySuccSum?: number; /** * 请求验证量 注意:此字段可能返回 null,表示取不到有效值。 */ VfySum?: number; /** * 拦截攻击量 注意:此字段可能返回 null,表示取不到有效值。 */ AttackSum?: number; /** * 返回信息 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg?: string; /** * 成功返回0 其它失败 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaCode?: number; /** * 票据校验总量 注意:此字段可能返回 null,表示取不到有效值。 */ CheckTicketSum?: number; /** * 票据验证通过量 注意:此字段可能返回 null,表示取不到有效值。 */ TicketThroughputSum?: number; /** * 票据验证拦截量 注意:此字段可能返回 null,表示取不到有效值。 */ TicketInterceptSum?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * GetRequestStatistics返回参数结构体 */ export interface GetRequestStatisticsResponse { /** * 查询后数据块 注意:此字段可能返回 null,表示取不到有效值。 */ Data?: CaptchaStatisticObj; /** * 验证码返回码 */ CaptchaCode?: number; /** * 验证码返回信息 */ CaptchaMsg?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * GetRequestStatistics请求参数结构体 */ export interface GetRequestStatisticsRequest { /** * 验证码AppId */ CaptchaAppId: string; /** * 开始时间字符串 */ StartTimeStr: string; /** * 结束时间字符串 */ EndTimeStr: string; /** * 查询粒度 */ Dimension: string; } /** * 拦截策略返回信息 */ export interface OutputManageMarketingRiskValue { /** * 账号 ID。对应输入参数: AccountType 是 1 时,对应 QQ 的 OpenID。 AccountType 是 2 时,对应微信的 OpenID/UnionID。 AccountType 是 4 时,对应手机号。 AccountType 是 8 时,对应 imei、idfa、imeiMD5 或者 idfaMD5。 AccountType 是 0 时,对应账号信息。 AccountType 是 10004 时,对应手机号的 MD5。 注意:此字段可能返回 null,表示取不到有效值。 注意:此字段可能返回 null,表示取不到有效值。 */ UserId: string; /** * 操作时间戳,单位秒(对应输入参数)。 注意:此字段可能返回 null,表示取不到有效值。 注意:此字段可能返回 null,表示取不到有效值。 */ PostTime: number; /** * 对应输入参数,AccountType 是 QQ 或微信开放账号时,用于标识 QQ 或微信用户登录 后关联业务自身的账号 ID。 注意:此字段可能返回 null,表示取不到有效值。 注意:此字段可能返回 null,表示取不到有效值。 */ AssociateAccount: string; /** * 业务详情。 注意:此字段可能返回 null,表示取不到有效值。 注意:此字段可能返回 null,表示取不到有效值。 */ UserIp: string; /** * 风险值 pass : 无恶意 review:需要人工审核 reject:拒绝,高风险恶意 注意:此字段可能返回 null,表示取不到有效值。 注意:此字段可能返回 null,表示取不到有效值。 */ RiskLevel: string; /** * 风险类型,请查看下面详细说明 注意:此字段可能返回 null,表示取不到有效值。 账号风险 账号信用低 1 账号近期存在因恶意被处罚历史,网络低活跃,被举报等因素 疑似 低活跃账号 11 账号活跃度与正常用户有差异 垃圾账号 2 疑似批量注册小号,近期存在严重违规或大量举报 疑似小号 21 账号有疑似线上养号,小号等行为 疑似 违规账号 22 账号曾有违规行为、曾被举报过、曾因违规被处罚过等 无效账号 3 送检账号参数无法成功解析,请检查微信 openid 是否有 黑名单 4 该账号在业务侧有过拉黑记录 白名单 5 业务自行有添加过白名单记录 行为风险 批量操作 101 存在 ip/设备/环境等因素的聚集性异常 疑似 IP 属性聚集 1011 出现 IP 聚集 疑似 设备属性聚集 1012 出现设备聚集 自动机 103 疑似自动机批量请求 微信登录态无效 104 检查 wxtoken 参数,是否已经失效 环境风险 环境异常 201 操作 ip/设备/环境存在异常。当前 ip 为非常用 ip 或恶意 ip 段 疑似 非常用IP请求 2011 当前请求 IP 非该账号常用 IP 疑似 IP 异常 2012 使用 idc 机房 ip 或 使用代理 ip 或 使用恶意 ip 非公网有效 ip 205 传进来的 IP 地址为内网 ip 地址或者 ip 保留地 注意:此字段可能返回 null,表示取不到有效值。 */ RiskType: Array<number | bigint>; } /** * DescribeCaptchaOperData 接口 返回数据类型集合 */ export interface CaptchaOperDataRes { /** * 验证码加载耗时数据返回 注意:此字段可能返回 null,表示取不到有效值。 */ OperDataLoadTimeUnitArray: Array<CaptchaOperDataLoadTimeUnit>; /** * 验证码拦截情况数据返回 注意:此字段可能返回 null,表示取不到有效值。 */ OperDataInterceptUnitArray: Array<CaptchaOperDataInterceptUnit>; /** * 验证码尝试次数数据返回 注意:此字段可能返回 null,表示取不到有效值。 */ OperDataTryTimesUnitArray: Array<CaptchaOperDataTryTimesUnit>; /** * 验证码尝试次数分布数据返回 注意:此字段可能返回 null,表示取不到有效值。 */ OperDataTryTimesDistributeUnitArray: Array<CaptchaOperDataTryTimesDistributeUnit>; } /** * GetTicketStatistics请求参数结构体 */ export interface GetTicketStatisticsRequest { /** * 验证码AppId */ CaptchaAppId: string; /** * 开始时间字符串 */ StartTimeStr: string; /** * 结束时间字符串 */ EndTimeStr: string; /** * 查询粒度 */ Dimension: string; } /** * DescribeCaptchaTicketData 返回的数据结构 */ export interface TicketInterceptUnit { /** * 时间 */ DateKey: string; /** * 票据验证拦截量 */ Intercept: number; } /** * DescribeCaptchaUserAllAppId请求参数结构体 */ export declare type DescribeCaptchaUserAllAppIdRequest = null; /** * GetTotalTicketStatistics返回参数结构体 */ export interface GetTotalTicketStatisticsResponse { /** * 返回数据 注意:此字段可能返回 null,表示取不到有效值。 */ Data: CaptchaStatisticObj; /** * 返回码 */ CaptchaCode: number; /** * 返回信息 */ CaptchaMsg: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 验证码票据校验趋势obj */ export interface TicketCheckTrendObj { /** * 时间参数 */ Ftime: string; /** * 票据校验量 */ TicketCount: number; /** * 票据通过量 */ TicketThroughput: number; /** * 票据拦截量 */ TicketIntercept: number; } /** * DescribeCaptchaMiniData返回参数结构体 */ export interface DescribeCaptchaMiniDataResponse { /** * 返回码 0 成功 其它失败 */ CaptchaCode: number; /** * 数据数组 注意:此字段可能返回 null,表示取不到有效值。 */ Data: Array<CaptchaQueryData>; /** * 返回信息描述 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 拦截率趋势obj */ export interface InterceptPerTrendObj { /** * 时间参数 */ Ftime: string; /** * 拦截率 */ RequestInterceptPer: number; /** * 答案拦截率 */ AnswerInterceptPer: number; /** * 策略拦截率 */ PolicyInterceptPer: number; } /** * DescribeCaptchaMiniRiskResult请求参数结构体 */ export interface DescribeCaptchaMiniRiskResultRequest { /** * 固定填值:9(滑块验证码) */ CaptchaType: number; /** * 验证码返回给用户的票据 */ Ticket: string; /** * 业务侧获取到的验证码使用者的外网IP */ UserIp: string; /** * 验证码应用APPID */ CaptchaAppId: number; /** * 用于服务器端校验验证码票据的验证密钥,请妥善保密,请勿泄露给第三方 */ AppSecretKey: string; /** * 业务 ID,网站或应用在多个业务中使用此服务,通过此 ID 区分统计数据 */ BusinessId?: number; /** * 场景 ID,网站或应用的业务下有多个场景使用此服务,通过此 ID 区分统计数据 */ SceneId?: number; /** * mac 地址或设备唯一标识 */ MacAddress?: string; /** * 手机设备号 */ Imei?: string; /** * 验证场景:1 活动防刷场景,2 登录保护场景,3 注册保护场景。根据需求选择场景参数。 */ SceneCode?: number; /** * 用户操作来源的微信开放账号 */ WeChatOpenId?: string; } /** * UpdateCaptchaAppIdInfo返回参数结构体 */ export interface UpdateCaptchaAppIdInfoResponse { /** * 返回码 0 成功,其它失败 */ CaptchaCode?: number; /** * 返回操作信息 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 用户注册的APPID和应用名称对象 */ export interface CaptchaUserAllAppId { /** * 验证码应用ID */ CaptchaAppId: number; /** * 注册应用名称 */ AppName: string; /** * 腾讯云APPID */ TcAppId: number; /** * 渠道信息 */ ChannelInfo: string; } /** * DescribeCaptchaDataSum返回参数结构体 */ export interface DescribeCaptchaDataSumResponse { /** * 请求总量 */ GetSum: number; /** * 请求验证成功量 */ VfySuccSum: number; /** * 请求验证量 */ VfySum: number; /** * 拦截攻击量 */ AttackSum: number; /** * 返回信息 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg: string; /** * 成功返回0 其它失败 */ CaptchaCode: number; /** * 票据校验总量 */ CheckTicketSum: number; /** * 票据验证通过量 */ TicketThroughputSum: number; /** * 票据验证拦截量 */ TicketInterceptSum: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCaptchaTicketData 返回的数据结构 */ export interface TicketThroughUnit { /** * 时间 */ DateKey: string; /** * 票据验证的通过量 */ Through: number; } /** * DescribeCaptchaTicketData请求参数结构体 */ export interface DescribeCaptchaTicketDataRequest { /** * 验证码应用ID */ CaptchaAppId: number; /** * 查询开始时间 例如:20200909 */ Start: number; /** * 查询结束时间 例如:20220314 */ End?: number; } /** * DescribeCaptchaResult返回参数结构体 */ export interface DescribeCaptchaResultResponse { /** * 1 OK 验证通过 7 captcha no match 传入的Randstr不合法,请检查Randstr是否与前端返回的Randstr一致 8 ticket expired 传入的Ticket已过期(Ticket有效期5分钟),请重新生成Ticket、Randstr进行校验 9 ticket reused 传入的Ticket被重复使用,请重新生成Ticket、Randstr进行校验 15 decrypt fail 传入的Ticket不合法,请检查Ticket是否与前端返回的Ticket一致 16 appid-ticket mismatch 传入的CaptchaAppId错误,请检查CaptchaAppId是否与前端传入的CaptchaAppId一致,并且保障CaptchaAppId是从验证码控制台【验证管理】->【基础配置】中获取 21 diff 票据校验异常,可能的原因是(1)若Ticket包含terror前缀,一般是由于用户网络较差,导致前端自动容灾,而生成了容灾票据,业务侧可根据需要进行跳过或二次处理。(2)若Ticket不包含terror前缀,则是由于验证码风控系统发现请求有安全风险,业务侧可根据需要进行拦截。 100 appid-secretkey-ticket mismatch 参数校验错误,(1)请检查CaptchaAppId与AppSecretKey是否正确,CaptchaAppId、AppSecretKey需要在验证码控制台【验证管理】>【基础配置】中获取(2)请检查传入的Ticket是否由传入的CaptchaAppId生成 */ CaptchaCode?: number; /** * 状态描述及验证错误信息 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg?: string; /** * 无感验证模式下,该参数返回验证结果: EvilLevel=0 请求无恶意 EvilLevel=100 请求有恶意 注意:此字段可能返回 null,表示取不到有效值。 */ EvilLevel?: number; /** * 前端获取验证码时间,时间戳格式 注意:此字段可能返回 null,表示取不到有效值。 */ GetCaptchaTime?: number; /** * 拦截类型 注意:此字段可能返回 null,表示取不到有效值。 */ EvilBitmap?: number; /** * 提交验证码时间 */ SubmitCaptchaTime?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCaptchaMiniDataSum请求参数结构体 */ export interface DescribeCaptchaMiniDataSumRequest { /** * 验证码应用ID */ CaptchaAppId: number; /** * 查询开始时间 */ Start: number; /** * 查询结束时间 */ End: number; } /** * DescribeCaptchaOperData操作数据查询尝试次数 type = 3 */ export interface CaptchaOperDataTryTimesUnit { /** * 时间 */ DateKey: string; /** * 平均尝试次数 */ CntPerPass: Array<number>; /** * market平均尝试次数 */ MarketCntPerPass: number; } /** * DescribeCaptchaOperData请求参数结构体 */ export interface DescribeCaptchaOperDataRequest { /** * 验证码应用ID */ CaptchaAppId: number; /** * 查询开始时间 */ Start: number; /** * 查询类型 */ Type: number; /** * 查询结束时间 */ End?: number; } /** * DescribeCaptchaDataSum请求参数结构体 */ export interface DescribeCaptchaDataSumRequest { /** * 验证码应用ID */ CaptchaAppId: number; /** * 查询开始时间 */ Start: number; /** * 查询结束时间 */ End: number; } /** * DescribeCaptchaMiniRiskResult返回参数结构体 */ export interface DescribeCaptchaMiniRiskResultResponse { /** * 1 ticket verification succeeded 票据验证成功 7 CaptchaAppId does not match 票据与验证码应用APPID不匹配 8 ticket expired 票据超时 10 ticket format error 票据格式不正确 15 ticket decryption failed 票据解密失败 16 CaptchaAppId wrong format 检查验证码应用APPID错误 21 ticket error 票据验证错误 25 bad visitor 策略拦截 26 system internal error 系统内部错误 100 param err 参数校验错误 */ CaptchaCode: number; /** * 状态描述及验证错误信息 注意:此字段可能返回 null,表示取不到有效值。 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg: string; /** * 拦截策略返回信息 注意:此字段可能返回 null,表示取不到有效值。 注意:此字段可能返回 null,表示取不到有效值。 */ ManageMarketingRiskValue: OutputManageMarketingRiskValue; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * GetTicketStatistics返回参数结构体 */ export interface GetTicketStatisticsResponse { /** * 查询后数据块 注意:此字段可能返回 null,表示取不到有效值。 */ Data: CaptchaStatisticObj; /** * 验证码返回码 */ CaptchaCode: number; /** * 验证码返回信息 */ CaptchaMsg: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * GetTotalRequestStatistics请求参数结构体 */ export interface GetTotalRequestStatisticsRequest { /** * 开始时间字符串 */ StartTimeStr: string; /** * 结束时间字符串 */ EndTimeStr: string; /** * 查询粒度 */ Dimension: string; } /** * DescribeCaptchaTicketData 返回的数据结构 */ export interface TicketAmountUnit { /** * 时间 */ DateKey: string; /** * 票据验证总量 */ Amount: number; } /** * GetTotalRequestStatistics返回参数结构体 */ export interface GetTotalRequestStatisticsResponse { /** * 查询后数据块 注意:此字段可能返回 null,表示取不到有效值。 */ Data?: CaptchaStatisticObj; /** * 验证码返回码 */ CaptchaCode?: number; /** * 验证码返回信息 */ CaptchaMsg?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 该类型为DescribeCaptchaData 方法返回数据类型 */ export interface CaptchaQueryData { /** * 数量 */ Cnt: number; /** * 时间 */ Date: string; } /** * 验证码请求趋势图obj */ export interface RequestTrendObj { /** * 时间参数 */ Ftime: string; /** * 请求量 */ RequestAction: number; /** * 验证量 */ RequestVerify: number; /** * 通过量 */ RequestThroughput: number; /** * 拦截量 */ RequestIntercept: number; } /** * DescribeCaptchaData返回参数结构体 */ export interface DescribeCaptchaDataResponse { /** * 返回码 0 成功 其它失败 */ CaptchaCode?: number; /** * 数据数组 注意:此字段可能返回 null,表示取不到有效值。 */ Data?: Array<CaptchaQueryData>; /** * 返回信息描述 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCaptchaResult请求参数结构体 */ export interface DescribeCaptchaResultRequest { /** * 固定填值:9。可在控制台配置不同验证码类型。 */ CaptchaType: number; /** * 前端回调函数返回的用户验证票据 */ Ticket: string; /** * 业务侧获取到的验证码使用者的外网IP */ UserIp: string; /** * 前端回调函数返回的随机字符串 */ Randstr: string; /** * 验证码应用ID。登录 [验证码控制台](https://console.cloud.tencent.com/captcha/graphical),在验证列表的【密钥】列,即可查看到CaptchaAppId。 */ CaptchaAppId: number; /** * 验证码应用密钥。登录 [验证码控制台](https://console.cloud.tencent.com/captcha/graphical),在验证列表的【密钥】列,即可查看到AppSecretKey。AppSecretKey属于服务器端校验验证码票据的密钥,请妥善保密,请勿泄露给第三方。 */ AppSecretKey: string; /** * 预留字段 */ BusinessId?: number; /** * 预留字段 */ SceneId?: number; /** * mac 地址或设备唯一标识 */ MacAddress?: string; /** * 手机设备号 */ Imei?: string; /** * 是否返回前端获取验证码时间,取值1:需要返回 */ NeedGetCaptchaTime?: number; } /** * 验证码统计图Obj */ export interface CaptchaStatisticObj { /** * 请求总量 */ ActionTotal: number; /** * 验证总量 */ VerifyTotal: number; /** * 验证通过总量 */ VerifyThroughTotal: number; /** * 验证拦截总量 */ VerifyInterceptTotal: number; /** * 票据校验总量 */ TicketTotal: number; /** * 票据通过总量 */ TicketThroughTotal: number; /** * 票据拦截总量 */ TicketInterceptTotal: number; /** * 请求趋势图 注意:此字段可能返回 null,表示取不到有效值。 */ RequestTrend: Array<RequestTrendObj>; /** * 拦截率趋势图 注意:此字段可能返回 null,表示取不到有效值。 */ InterceptPerTrend: Array<InterceptPerTrendObj>; /** * 票据校验趋势图 注意:此字段可能返回 null,表示取不到有效值。 */ TicketCheckTrend: Array<TicketCheckTrendObj>; } /** * UpdateCaptchaAppIdInfo请求参数结构体 */ export interface UpdateCaptchaAppIdInfoRequest { /** * 验证码应用ID */ CaptchaAppId: number; /** * 应用名 */ AppName: string; /** * 域名限制 */ DomainLimit: string; /** * 场景类型 */ SceneType: number; /** * 验证码类型 */ CapType: number; /** * 风险级别 */ EvilInterceptGrade: number; /** * 智能检测 */ SmartVerify: number; /** * 开启智能引擎 */ SmartEngine: number; /** * web风格 */ SchemeColor: string; /** * 语言 */ CaptchaLanguage: number; /** * 告警邮箱 */ MailAlarm: string; /** * 是否全屏 */ TopFullScreen: number; /** * 流量限制 */ TrafficThreshold: number; } /** * 操作数据查询方法DescribeCaptchaOperData 的返回结果,安全验证码加载耗时type = 1 */ export interface CaptchaOperDataLoadTimeUnit { /** * 时间 */ DateKey: string; /** * Market加载时间 */ MarketLoadTime: number; /** * AppId加载时间 */ AppIdLoadTime: number; } /** * DescribeCaptchaMiniOperData请求参数结构体 */ export interface DescribeCaptchaMiniOperDataRequest { /** * 验证码应用ID */ CaptchaAppId: number; /** * 查询开始时间 */ Start: number; /** * 查询类型 */ Type: number; /** * 查询结束时间 */ End?: number; } /** * DescribeCaptchaAppIdInfo请求参数结构体 */ export interface DescribeCaptchaAppIdInfoRequest { /** * 验证码应用注册APPID */ CaptchaAppId: number; } /** * DescribeCaptchaAppIdInfo返回参数结构体 */ export interface DescribeCaptchaAppIdInfoResponse { /** * 界面风格 */ SchemeColor?: string; /** * 语言 */ Language?: number; /** * 场景 */ SceneType?: number; /** * 防控风险等级 */ EvilInterceptGrade?: number; /** * 智能验证 */ SmartVerify?: number; /** * 智能引擎 */ SmartEngine?: number; /** * 验证码类型 */ CapType?: number; /** * 应用名称 */ AppName?: string; /** * 域名限制 */ DomainLimit?: string; /** * 邮件告警 注意:此字段可能返回 null,表示取不到有效值。 */ MailAlarm?: Array<string>; /** * 流量控制 */ TrafficThreshold?: number; /** * 加密key */ EncryptKey?: string; /** * 是否全屏 */ TopFullScreen?: number; /** * 成功返回0 其它失败 */ CaptchaCode?: number; /** * 返回操作信息 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCaptchaUserAllAppId返回参数结构体 */ export interface DescribeCaptchaUserAllAppIdResponse { /** * 用户注册的所有Appid和应用名称 注意:此字段可能返回 null,表示取不到有效值。 */ Data?: Array<CaptchaUserAllAppId>; /** * 成功返回 0 其它失败 */ CaptchaCode?: number; /** * 返回操作信息 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCaptchaData请求参数结构体 */ export interface DescribeCaptchaDataRequest { /** * 验证码应用ID */ CaptchaAppId: number; /** * 查询开始时间 */ Start: number; /** * 查询结束时间 */ End: number; /** * 查询类型 */ Type: number; } /** * DescribeCaptchaMiniResult请求参数结构体 */ export interface DescribeCaptchaMiniResultRequest { /** * 固定填值:9(滑块验证码) */ CaptchaType: number; /** * 验证码返回给用户的票据 */ Ticket: string; /** * 业务侧获取到的验证码使用者的外网IP */ UserIp: string; /** * 验证码应用ID。登录 [验证码控制台](https://console.cloud.tencent.com/captcha/graphical),在验证列表的【密钥】列,即可查看到CaptchaAppId。 */ CaptchaAppId: number; /** * 验证码应用密钥。登录 [验证码控制台](https://console.cloud.tencent.com/captcha/graphical),在验证列表的【密钥】列,即可查看到AppSecretKey。AppSecretKey属于服务器端校验验证码票据的密钥,请妥善保密,请勿泄露给第三方。 */ AppSecretKey: string; /** * 业务 ID,网站或应用在多个业务中使用此服务,通过此 ID 区分统计数据 */ BusinessId?: number; /** * 场景 ID,网站或应用的业务下有多个场景使用此服务,通过此 ID 区分统计数据 */ SceneId?: number; /** * mac 地址或设备唯一标识 */ MacAddress?: string; /** * 手机设备号 */ Imei?: string; } /** * DescribeCaptchaTicketData返回参数结构体 */ export interface DescribeCaptchaTicketDataResponse { /** * 成功返回 0 其它失败 */ CaptchaCode: number; /** * 返回信息 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg: string; /** * 验证码票据信息 注意:此字段可能返回 null,表示取不到有效值。 */ Data: CaptchaTicketDataRes; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCaptchaTicketData 接口 返回数据类型集合 */ export interface CaptchaTicketDataRes { /** * 票据验证总量返回 */ TicketAmountArray: Array<TicketAmountUnit>; /** * 票据验证通过量返回 */ TicketThroughArray: Array<TicketThroughUnit>; /** * 票据验证拦截量返回 */ TicketInterceptArray: Array<TicketInterceptUnit>; } /** * DescribeCaptchaMiniResult返回参数结构体 */ export interface DescribeCaptchaMiniResultResponse { /** * 1 ticket verification succeeded 票据验证成功 7 CaptchaAppId does not match 票据与验证码应用APPID不匹配 8 ticket expired 票据超时 10 ticket format error 票据格式不正确 15 ticket decryption failed 票据解密失败 16 CaptchaAppId wrong format 检查验证码应用APPID错误 21 (1)ticket error 票据验证错误 (2)diff 一般是由于用户网络较差,导致前端自动容灾,而生成了容灾票据,业务侧可根据需要进行跳过或二次处理 25 invalid ticket 无效票据 26 system internal error 系统内部错误 31 UnauthorizedOperation.Unauthorized 无有效套餐包/账户已欠费 100 param err 参数校验错误 */ CaptchaCode?: number; /** * 状态描述及验证错误信息 注意:此字段可能返回 null,表示取不到有效值。 */ CaptchaMsg?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCaptchaMiniData请求参数结构体 */ export interface DescribeCaptchaMiniDataRequest { /** * 验证码应用ID */ CaptchaAppId: number; /** * 查询开始时间 例如:2019112900 */ Start: number; /** * 查询结束时间 例如:2019112902 */ End: number; /** * 查询类型 安全验证码小程序插件分类查询数据接口,请求量type=0、通过量type=1、验证量type=2、拦截量type=3 小时级查询(五小时左右延迟) */ Type: number; }
d7726ecc04171568fbafe07df336cd9f8d3a2315
TypeScript
vladimirlojanica/a12n-server
/src/privilege/formats/hal.ts
2.640625
3
import { Privilege } from '../types'; export function collection(privileges: Privilege[]) { const hal: any = { _links: { self: { href: '/privilege' }, item: [], }, }; for (const privilege of privileges) { hal._links.item.push({ href: '/privilege/' + privilege.privilege, title: privilege.description }); } return hal; } export function item(privilege: Privilege) { const hal: any = { _links: { self: {href: '/privilege/' + privilege.privilege}, collection: {href: '/privilege', title: 'Privilege Collection'} }, privilege: privilege.privilege, description: privilege.description }; return hal; }
2f3e5265e40444a2a05edbcac5cd920fd4d40129
TypeScript
csgpro/csgpro.com
/server/views/helpers/formatDate.ts
2.625
3
'use strict'; import * as moment from 'moment'; function formatDate(date: string | Date, format = 'MM/DD/YYYY'): string { if (arguments.length <= 2) { date = new Date(); if (typeof arguments[0] === 'string') { format = arguments[0]; } } return moment(date).format(format); } export = formatDate;
aee8fa3e1c2f84f62a9a6c63965a588aeeecb221
TypeScript
SomosCodear/checkout-api
/src/resources/ticket/processor.ts
2.5625
3
import { KnexProcessor, Operation, ResourceRelationship, JsonApiErrors } from "@joelalejandro/jsonapi-ts"; import Errors from "../../errors"; import Ticket from "./resource"; export default class TicketProcessor extends KnexProcessor<Ticket> { public resourceClass = Ticket; public async getById(id: string): Promise<Ticket> { const ticket = await this.knex("Tickets") .where({ id }) .first(); if (!ticket) { return {} as Ticket; } return Promise.resolve(this.asResource(ticket)); } public async markAsOwned(id: string): Promise<Ticket> { const ticket = await this.knex("Tickets") .update({ status: "owned" }) .where({ id }); return this.asResource(ticket); } public async get(op: Operation): Promise<Ticket[]> { return (await super.get(op)).map(this.asResource.bind(this)); } public async markForSale(id: string): Promise<void> { await this.knex("Tickets") .update({ status: "forSale", customerId: null }) .where({ id }); } public async add(op: Operation): Promise<Ticket> { const ticket = op.data; if (!ticket.relationships.customer) { throw Errors.DataRequired("relationships.customer"); } ticket.attributes.customerId = (ticket.relationships.customer .data as ResourceRelationship).id as string; ticket.attributes.status = "booked"; ticket.attributes.dateBooked = new Date().toJSON(); ticket.relationships = {}; const assignedTicketId = await this.getFirstSellableTicketId(); ticket.attributes.price = Number( await this.getTicketPrice(assignedTicketId) ); const updatedTicket = await super.update({ ...op, data: ticket, ref: { type: "Ticket", id: assignedTicketId } } as Operation); updatedTicket.relationships = { event: { data: { id: updatedTicket.attributes.eventId as string, type: "event" } }, ticketType: { data: { id: updatedTicket.attributes.ticketTypeId as string, type: "ticketType" } }, customer: { data: { id: updatedTicket.attributes.customerId as string, type: "customer" } } }; delete updatedTicket.attributes.customerId; delete updatedTicket.attributes.eventId; delete updatedTicket.attributes.ticketTypeId; delete updatedTicket.attributes.purchaseId; return updatedTicket; } public async delete() { throw JsonApiErrors.AccessDenied(); } private async getFirstSellableTicketId(): Promise<string> { const [{ id }] = await this.knex("Tickets") .select("id") .where({ ticketTypeId: "attendee", eventId: 1, status: "forSale" }) .limit(1); return id; } private async getTicketPrice(ticketId: string): Promise<number> { const [{ ticketTypeId, eventId }] = await this.knex("Tickets") .select("ticketTypeId", "eventId") .where({ id: ticketId }) .limit(1); const [{ defaultPrice }] = await this.knex("TicketTypes") .select("defaultPrice") .where({ id: ticketTypeId, eventId, canBePurchased: true }) .limit(1); return Number(defaultPrice); } private asResource(ticketObject): Ticket { const ticket = { ...ticketObject }; delete ticket.id; const result = { id: ticketObject.id, type: "ticket", attributes: ticket.attributes ? ticket.attributes : ticket, relationships: { event: { data: { id: (ticket.attributes || ticket).eventId as string, type: "event" } }, ticketType: { data: { id: (ticket.attributes || ticket).ticketTypeId as string, type: "ticketType" } }, customer: { data: { id: (ticket.attributes || ticket).customerId as string, type: "customer" } }, purchase: { data: { id: (ticket.attributes || ticket).purchaseId as string, type: "purchase" } } } }; delete result.attributes.eventId; delete result.attributes.customerId; delete result.attributes.ticketTypeId; delete result.attributes.purchaseId; return result as Ticket; } }
591ef2dc66b9917a21ae07162d547e9159e49eec
TypeScript
kasuparu/knowledge-brushup
/src/spec/bubble.spec.ts
2.90625
3
import { sort } from '../bubble'; const array = [4, 6, 1, 3, 8, 7, 2]; const sortedArray = array.slice().sort(); describe('bubble', () => { it('sorts', () => { const arrayCopy = array.slice(); sort(arrayCopy); expect(arrayCopy).toEqual(sortedArray); }); });
31119539caa7edb8f453e760b1a4342ef01ca8f3
TypeScript
josseas/ngrx-ie
/src/app/ingreso-egreso/ingreso-egreso.reducer.ts
2.734375
3
import { IngresoEgreso } from './ingreso-egreso.model'; import { Acciones, SET_ITEMS, UNSET_ITEMS } from './ingreso-egreso-actions'; import { AppState } from '../app.reducer'; export interface IeState { items: Array<IngresoEgreso>; } export interface AppState extends AppState { ie: IeState; } const estadoInicial: IeState = { items: [] } export function ieReducer(state = estadoInicial, action: Acciones) : IeState { switch(action.type) { case SET_ITEMS: return { items: [...action.items] }; // return { items: [...action.items.map(item => { return { ...item }; } )] }; case UNSET_ITEMS: return { items: [] }; default: return state; } }
de0bb2637c138e6d81cd0bf7def85fba3076096f
TypeScript
dividab/abstract-visuals
/packages/abstract-document/src/abstract-document/atoms/text-field.ts
2.96875
3
import * as TextStyle from "../styles/text-style"; export type FieldType = "Date" | "PageNumber" | "TotalPages" | "PageNumberOf"; export interface TextField { readonly type: "TextField"; readonly styleName: string; readonly fieldType: FieldType; readonly style: TextStyle.TextStyle; readonly target: string; readonly text: string; } export interface TextFieldProps { readonly styleName?: string; readonly fieldType: FieldType; readonly style?: TextStyle.TextStyle; readonly target?: string; } export function create(props: TextFieldProps): TextField { const { styleName = "", fieldType, style = TextStyle.create(), target = "" } = props; return { type: "TextField", styleName, fieldType, style, target, text: "" }; }
1eb1c3544b0f1633223ddd12e0fac3e703d8b7a5
TypeScript
RamiroPastor/portfolio_shopeame
/src/app/pipes/filter-names.pipe.ts
2.65625
3
import { Pipe, PipeTransform } from '@angular/core'; import { Product } from './../shared/models/Product'; @Pipe({ name: 'filterNames' }) export class FilterNamesPipe implements PipeTransform { transform(productList: Product[], filterText: string): Product[] { const filterT: string = filterText.toLowerCase().trim(); const filtered = productList.filter((p) => {return p.name.toLowerCase().includes(filterT)}); return filtered } }
9627b76f8bc6b20e37eeaab13e040bd7c4a311c1
TypeScript
Gerasik/NETFLIX-roulette
/src/models/MoviesResponse.ts
2.515625
3
import Immutable from 'immutable'; import { Movie, MovieMap } from './Movie'; export type MoviesData = Movie[]; export type MoviesDataMap = Immutable.List<MovieMap>; export type MoviesResponse = { data: MoviesData; total: number; offset: number; limit: number; }; export type MoviesResponseMap = Immutable.Record< Omit<MoviesResponse, 'data'> & { data: MoviesDataMap } >;
8196b69ddafca251dbf20e791172e2b503b6369b
TypeScript
TIBCOSoftware/TCSTK-Angular
/projects/tibco-tcstk/tc-core-lib/src/lib/common/tc-core-common-functions.ts
2.703125
3
import {HashLocationStrategy, Location} from '@angular/common'; import {TcComponent} from '../models/tc-component'; // @dynamic export class TcCoreCommonFunctions { public static escapeString(text) { return text.replace(/"/g, '\"'); } public static fileSizeToHuman(size) { const e = (Math.log(size) / Math.log(1e3)) | 0; return +(size / Math.pow(1e3, e)).toFixed(2) + ' ' + ('kMGTPEZY'[e - 1] || '') + 'B'; } public static camelCaseToWords(str) { const re = str.replace(/([a-z])([A-Z])/g, '$1 $2') .replace(/([A-Z])([a-z])/g, ' $1$2') .replace(/\ +/g, ' '); return re; } public static convertToJSON(array) { const objArray = []; for (let i = 1; i < array.length; i++) { objArray[i - 1] = {}; for (let k = 0; k < array[0].length && k < array[i].length; k++) { const key = array[0][k]; objArray[i - 1][key] = array[i][k]; } } return objArray; } public static transposeArray(array, arrayLength) { // console.log('transposing array) arrayLength: ' + arrayLength ); const newArray = []; for (let i = 0; i < arrayLength; i++) { newArray.push([]); } for (let i = 0; i < array.length; i++) { for (let j = 0; j < arrayLength; j++) { newArray[j].push(array[i][j]); } } return newArray; } public static camelize = (str: string): string => { let newStr = ''; let newArr = []; if (str.indexOf('-') !== -1) { newArr = str.split('-'); for (let i = 0; i < newArr.length; i++) { newArr[i] = newArr[i].charAt(0).toUpperCase() + newArr[i].substr(1); } newStr = newArr.join(' '); } return newStr; } public static prepareUrlForNonStaticResource = (location: Location, str: string): string => { // @ts-ignore if (location._platformStrategy instanceof HashLocationStrategy) { return str; } else { return str; } } public static prepareUrlForStaticResource = (location: Location, str: string): string => { // @ts-ignore if (location._platformStrategy instanceof HashLocationStrategy) { return str; } else { return location.prepareExternalUrl(str); } } public static calcSummaryCardPct = (width: TcComponent) => { if (width.gtLg) { return 20; } else if (width.gtMd) { return 25; } else if (width.gtSm) { return 33; } else if (width.gtXs) { return 50; } else { return 100; } } public static formLayoutToJson = (formLayout: any): string => { const replacer = (key, value) => { // if we get a function, give us the code for that function if (typeof value === 'function') { return value.toString(); } return value; }; const serialized = JSON.stringify(formLayout, replacer, 2); return serialized; } public static parseLayoutString = (layoutString: string): any => { let newFormObject: any = null; try { // tslint:disable-next-line:no-eval eval('newFormObject = ' + layoutString); } catch (error) { console.log('eval failed, ', error); } return newFormObject; } public static formLayoutJsonToObject = (formLayoutJSON: string): any => { const reviver = (key, value) => { if (typeof value === 'string' && value.indexOf('function ') === 0) { const functionTemplate = `(${value})`; // tslint:disable-next-line:no-eval return eval(functionTemplate); } return value; }; // const parsedObject = JSON.parse(formLayoutJSON); // formLayoutJSON = TcCoreCommonFunctions.escapeString(formLayoutJSON); const parsedObject = JSON.parse(formLayoutJSON, reviver); return parsedObject; } }
0896364086e6b83c3ef1b4dafc63123059540a62
TypeScript
ULL-ESIT-INF-DSI-2021/ull-esit-inf-dsi-20-21-prct07-menu-datamodel-grupo-a
/src/food.ts
3.40625
3
import { macroType, locationType, Printable, Identifiable} from './helpers'; /** * @description Class that handles Food, that implements Printable and * Identifiable interfaces. */ export abstract class Food implements Printable, Identifiable { /** * @description Food class constructor * @param name Consists of a string * @param origin Consists of a locationType * @param macros Consists of a macroType * @param weight Consists of a number * @param kcalPer100gr Consists of a number * @param pricePerKg Consists of a number */ constructor(private name: string, private origin: locationType, private macros: macroType, private weight: number, private kcalPer100gr: number, private pricePerKg: number) { } /** * @description Getter for the name * @returns Returns a string */ getName(): string { return this.name; } /** * @description Getter for the origin * @returns Returns a locationType */ getOrigin(): locationType { return this.origin; } /** * @description Getter for the macros * @returns Returns macroType */ getMacros(): macroType { return this.macros; } /** * @description Getter for the weight * @returns Returns a number */ getWeight(): number { return this.weight; } /** * @description Getter for the kcal per 100 gr * @returns Returns a number */ getKcalPer100gr(): number { return this.kcalPer100gr; } /** * @description Getter for the price per kg * @returns Returns a number */ getPricePerKg(): number { return this.pricePerKg; } /** * @description Setter for the name * @param name Consists of a string */ setName(name: string) { this.name = name; } /** * @description Setter for the origin * @param origin Consists of a locationType */ setOrigin(origin: locationType) { this.origin = origin; } /** * @description Setter for the macros * @param macros Consists of a macroType */ setMacros(macros: macroType) { this.macros = macros; } /** * @description Setter for the weight * @param weight Consists of a number */ setWeight(weight: number) { this.weight = weight; } /** * @description Setter for the kcal per 100gr * @param kcal Consists of a number */ setKcalPer100gr(kcal: number) { this.kcalPer100gr = kcal; } /** * @description Setter for the price per kg * @param price Consists of a number */ setPricePerKg(price: number) { this.pricePerKg = price; } /** * @description Method that calculates the price per weight * @returns Returns a number */ calcPricePerWeigth(): number { // Assuming that the weight is setted as grams, 1kg equals 1000gr return (this.getWeight() / 1000) * this.getPricePerKg(); } /** * @description Function that calculates the total kcal of the food * @returns Returns a number */ calcKcal(): number { // Assuming that we got the kcals per 100g return (this.getWeight() * this.getKcalPer100gr()) / 100; } /** * @description Method that prints all the food information * @returns Returns a string */ print() { return 'Class: ' + this.getClassName() + '\nName: ' + this.getName() + '\nOrigin: ' + '[Country: ' + this.getOrigin().country + ', City: ' + this.getOrigin().city + ']' + '\nMacros: ' + '[Carbs: ' + this.getMacros().carbs + ', Proteins: ' + this.getMacros().proteins + ', Lipids: ' + this.getMacros().lipids + ']' + '\nKcal per 100 gr: ' + this.getKcalPer100gr() + '\nPrice per kg: ' + this.getPricePerKg(); } /** * @description Getter for the class name * @returns Returns a string */ getClassName(): string { return this.constructor.name; } }
92e82e3c04339e8ee78c9f1378d7488e988ab842
TypeScript
iceboss3d/finloan
/src/guarantor/guarantor.entity.ts
2.515625
3
import { ApplicationEntity } from "src/application/application.entity"; import { Column, CreateDateColumn, Entity, OneToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm"; @Entity('guarantor') export class GuarantorEntity { @PrimaryGeneratedColumn('uuid') id!: string; @CreateDateColumn() created: Date; @UpdateDateColumn() updated: Date; @Column() firstName: string; @Column() lastName: string; @Column() placeOfWork: string; @Column() designation: string; @Column() phoneNumber: string; @Column() address: string; @OneToOne(type => ApplicationEntity, application => application.guarantor) application: ApplicationEntity; }
dd931e8359ab4e6820a6a43d2bcad99dca4937ea
TypeScript
rokicki/kpuzzle.js
/src/parser.ts
2.6875
3
import {KPuzzleDefinition} from "./kpuzzle" import {parse as jison_parse} from "./jison_parser"; function FixMoves(def: KPuzzleDefinition) { for (var moveName in def.moves) { var move = def.moves[moveName] ; for (var orbitName in def.orbits) { var moveOrbit = move[orbitName] ; var oldOrientation = moveOrbit.orientation ; var perm = moveOrbit.permutation ; var newOrientation = new Array(oldOrientation.length) ; for (var i=0; i<perm.length; i++) newOrientation[i] = oldOrientation[perm[i]-1] ; moveOrbit.orientation = newOrientation ; } } return def ; } export function parse(s: string): KPuzzleDefinition { return FixMoves(<KPuzzleDefinition>jison_parse(s)); }
61174c2e9db5599da8adbefe117e545745011359
TypeScript
ronitsingh2001/ERP-client
/src/app/services/department.service.ts
2.515625
3
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { map, take, tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class DepartmentService { url = `http://localhost:8080/` _fields = new BehaviorSubject<FieldInterface[]>([]) _departments = new BehaviorSubject<DepartmentInterface[]>([]) constructor(private http: HttpClient) { } public get fields() { return this._fields.asObservable() } public get departments() { return this._departments.asObservable() } fetchFields() { return this.http.get<{ fields: FieldInterface[] }>(this.url + 'get-fields') .pipe( map(res => { let loadedFields = [] res.fields.forEach(field => { loadedFields.push(field) }) return loadedFields }), take(1), tap(fields => { this._fields.next(fields) }) ) } fetchDepartments() { return this.http.get<{ departments: DepartmentInterface[] }>(this.url + 'get-departments') .pipe( map(res => { let loadedDepartments = [] res.departments.forEach(dept => { if(!dept){ return [] } loadedDepartments.push(dept) }) return loadedDepartments }), take(1), tap(departments => { this._departments.next(departments) }) ) } addField(field: Object) { return this.http.post(this.url + `add-field`, field) } addDepartment(department: Object) { return this.http.post(this.url + `add-department`, department) } } export interface DepartmentInterface { name: String field: String | Object semester: String | Object } export interface FieldInterface { name: String _id: String }
c99c4107d180bee88d3e631d7854302872a4c460
TypeScript
vsaase/cornerstoneTools
/types/store/modules/segmentationModule/getSegmentsOnPixeldata.d.ts
2.75
3
/** * Returns an array of the segment indicies present on the `pixelData`. * @param {UInt16Array|Float32Array} pixelData The pixel data array. */ export default function getSegmentsOnPixelData(pixelData: any | Float32Array): any[];
5817c7877a83608143792d5c166155b86ff5e7be
TypeScript
tesla-1st-code/socpred
/helpers/data.ts
2.65625
3
import { readFileSync } from "fs"; const seasons = ['1718', '1819']; export class DataHelper { static getSeasonData(prefix) { let data = []; for (let j=0; j<seasons.length; j++) { let seasonData = JSON.parse(readFileSync('../data/' + prefix + seasons[j] + '.json').toString()); data = data.concat(seasonData); } return data; } static getFixtures(prefix) { return JSON.parse(readFileSync('../data/' + prefix + '-fixtures.json').toString()); } }
d978346617736485b7fcacf18548c926b358208d
TypeScript
screenleon/javascript
/angular/itHelp/Angular30Days/Angular30DaysECApplication/src/app/checkout/receipt-info/receipt-info.component.ts
2.578125
3
import { Component, OnInit } from '@angular/core'; import { appPath } from '../../app-path.const'; import { SendType } from './send-type.enum'; @Component({ selector: 'app-receipt-info', templateUrl: './receipt-info.component.html', styleUrls: ['./receipt-info.component.css'] }) export class ReceiptInfoComponent implements OnInit { /** * 給 Template 用的路由定義 * * @memberof ReceiptInfoComponent */ public path = appPath; /** * 給 Template 用的寄送方式列舉 * * @memberof ReceiptInfoComponent */ sendType = SendType; /** * 當前的寄送類型,預設使用 Email * * @memberof ReceiptInfoComponent */ selectedType = SendType.EMAIL; constructor() { } ngOnInit() { } /** * 切換寄送類型 * * @param {SendType} type - 欲切換的寄送類型 * @memberof ReceiptInfoComponent */ switch(type: SendType): void { this.selectedType = type; } /** * 傳入的寄送類型是否為當前所選擇的寄送類型 * * @param {SendType} type - 欲判斷的寄送類型 * @returns {boolean} * @memberof ReceiptInfoComponent */ didSelected(type: SendType): boolean { return this.selectedType === type; } }
81aef5e669737e3873fff598cc91d175a8ff0fd6
TypeScript
magauran/forteen
/src/utils/Keyboard.ts
2.53125
3
/* eslint-disable */ export const KEYBOARD_DID_OPEN = 'keyboardDidShow' export const KEYBOARD_DID_CLOSE = 'keyboardDidHide' const KEYBOARD_THRESHOLD = 150 let previousVisualViewport: any = {} let currentVisualViewport: any = {} let previousLayoutViewport: any = {} let currentLayoutViewport: any = {} let keyboardOpen = false export const startKeyboardAssist = (win: Window) => { if (!win.visualViewport) { return } currentVisualViewport = copyVisualViewport(win).visualViewport currentLayoutViewport = copyLayoutViewport(win) win.visualViewport.onresize = () => { trackViewportChanges(win) if (keyboardDidOpen() || keyboardDidResize(win)) { setKeyboardOpen(win) } else if (keyboardDidClose(win)) { setKeyboardClose(win) } } } export const setKeyboardOpen = (win: Window, ev?: any) => { fireKeyboardOpenEvent(win, ev) keyboardOpen = true } export const setKeyboardClose = (win: Window) => { fireKeyboardCloseEvent(win) keyboardOpen = false } export const keyboardDidOpen = (): boolean => { const scaledHeightDifference = (previousVisualViewport.height - currentVisualViewport.height) * currentVisualViewport.scale return ( !keyboardOpen && previousVisualViewport.width === currentVisualViewport.width && scaledHeightDifference > KEYBOARD_THRESHOLD ) } export const keyboardDidResize = (win: Window): boolean => { return keyboardOpen && !keyboardDidClose(win) } export const keyboardDidClose = (win: Window): boolean => { return keyboardOpen && currentVisualViewport.height === win.innerHeight } const fireKeyboardOpenEvent = (win: Window, nativeEv?: any): void => { const keyboardHeight: number = nativeEv ? nativeEv.keyboardHeight : win.innerHeight - currentVisualViewport.height const ev = new CustomEvent(KEYBOARD_DID_OPEN, { detail: keyboardHeight }) win.dispatchEvent(ev) } const fireKeyboardCloseEvent = (win: Window): void => { const ev = new CustomEvent(KEYBOARD_DID_CLOSE) win.dispatchEvent(ev) } export const trackViewportChanges = (win: Window) => { previousVisualViewport = { ...currentVisualViewport } currentVisualViewport = copyVisualViewport(win.visualViewport) previousLayoutViewport = { ...currentLayoutViewport } currentLayoutViewport = copyLayoutViewport(win) } export const copyVisualViewport = (visualViewport: any): any => { return { width: Math.round(visualViewport.width), height: Math.round(visualViewport.height), offsetTop: visualViewport.offsetTop, offsetLeft: visualViewport.offsetLeft, pageTop: visualViewport.pageTop, pageLeft: visualViewport.pageLeft, scale: visualViewport.scale } } export const copyLayoutViewport = (win: Window): any => { return { width: win.innerWidth, height: win.innerHeight } }
391fcc221d0dcba9c25f01df352098c4f0561990
TypeScript
PatrykPasterny/BertTest
/BertoniTest/Scripts/Repositories/CommentRepository.ts
2.59375
3
import { HttpHelper } from "../Helpers/HttpHelper.js"; import { Comment } from "../Models/Comment.js"; export class CommentRepository extends HttpHelper { constructor() { super(); let self = this; self.baseUrl += "api/photo" } async getAllPhotos(): Promise<Comment[]> { let self = this; const response = await self.http<Comment[]>(self.baseUrl + "/Get"); return response.parsedBody; } async getAllPhotosForAlbum(photoId: number): Promise<Comment[]> { let self = this; const response = await self.http<Comment[]>(self.baseUrl + "/GetAllCommentsForPhoto?photoId=" + photoId); return response.parsedBody; } }
66af833d2e71d33be30d0d0b8549c6ef2b5c20e6
TypeScript
infojunkie/quizzical
/src/entity/Question.ts
3.125
3
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn, TableInheritance } from 'typeorm'; import {Skill} from './Skill'; import {Helpers} from '../Helpers'; export class AnswerEvaluation { // Automatic constructor arguments // https://www.stevefenton.co.uk/2013/04/Stop-Manually-Assigning-TypeScript-Constructor-Parameters/ constructor(public correct: boolean, public best: any) {} } @Entity() @TableInheritance({ column: { type: "varchar", name: "type" } }) export class Question { @PrimaryGeneratedColumn() id: number; @ManyToOne(type => Skill, skill => skill.questions) skill: Skill; @Column() level: number; @Column() difficulty: number; @Column("simple-json") config: any; /** * Overridable function to evaluate an answer. * Most question types store the correct answer as plain text in `config.answer`. */ evaluate(answer: any): AnswerEvaluation { return new AnswerEvaluation( Helpers.normalize(this.config.answer) === Helpers.normalize(answer), this.config.answer ); } }
b584f07c28297b63ed329026598091676ca46a37
TypeScript
nkleemann/p5-tone-starter
/src/mover.ts
3.140625
3
import * as p5 from "p5"; export class Mover { p: p5; mass: number; position: p5.Vector; velocity: p5.Vector; acceleration: p5.Vector; color: p5.Color; constructor(p: p5, _x: number, _y: number, _m: number) { this.p = p; this.mass = _m; this.position = p.createVector(_x, _y); this.velocity = p.createVector(1, 0); this.acceleration = p.createVector(0.0, 0.0); this.color = p.color(p.random(100, 255), p.random(100, 255), p.random(100, 255)); } update() { this.velocity.add(this.acceleration); this.position.add(this.velocity); // Reset acceleration in order to prevent incrementing forever this.acceleration.mult(0); } display() { this.p.stroke(0); this.p.strokeWeight(1); this.p.fill(this.color); this.p.ellipse(this.position.x, this.position.y, this.mass*8, this.mass*8); } applyForce(forceVec: p5.Vector) { // preserve the original force vector // Newtons second law (a = F/m) let forceVecCopy = p5.Vector.div(forceVec, this.mass); this.acceleration.add(forceVecCopy); } }
cf843cf200ad5f38c8fd07723dae6c96a7b775d9
TypeScript
keilaloia/helpDesk
/src/Components/_tools/fetchPUT.ts
2.6875
3
import { async } from "q"; // var data : any; //use a T template class so that we can pass in any json object being sent from the server! export const httpPUT = <T> (url: string, data: any): Promise<T> => { return new Promise(resolve => { fetch(url, { method: 'PUT', body: JSON.stringify(data), headers:{ 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then(response => response.json()) .catch((err) => { console.log(err); }); }); }; // return fetch('/api/update', { // method: 'put', // body: JSON.stringify(data), // headers: { // 'Accept': 'application/json', // 'Content-Type': 'application/json' // } // }) // .then(checkStatus) // .then(()=>console.log('updated!!!')) // }
7c65e2620c01700bc709de1629517bfcfaa72ff7
TypeScript
gocd/gocd
/server/src/main/webapp/WEB-INF/rails/webpack/models/mixins/errors.ts
2.53125
3
/* * Copyright 2023 Thoughtworks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {mixins as s} from "helpers/string-plus"; import _ from "lodash"; import {EventAware} from "models/mixins/event_aware"; export interface ErrorsJSON { [key: string]: string[]; } export class Errors { private _errors: ErrorsJSON; constructor(errors: ErrorsJSON = {}) { this._errors = errors; EventAware.call(this); } clone() { return new Errors(_.clone(this._errors)); } add(attrName: string, message: string) { if (!this._errors[attrName]) { this._errors[attrName] = []; } this._errors[attrName].push(message); this.notify("error:change"); } addIfDoesNotExists(attrName: string, message: string) { if (!this.hasError(attrName, message)) { this.add(attrName, message); } } clear(attrName?: string) { "undefined" !== typeof attrName ? delete this._errors[attrName] : this._errors = {}; this.notify("error:change"); } clearError(attrName: string, message: string) { const errors = this._errors[attrName]; _.remove(errors, (err) => err === message); this._errors[attrName] = errors; } errors(attrName?: string) { return attrName ? this._errors[attrName] : this._errors; } hasErrors(attrName?: string) { return attrName ? !_.isEmpty(this._errors[attrName]) : !this._isEmpty(); } hasError(attrName: string, message: string) { const errors = this._errors[attrName] || []; return !!_.find(errors, (err) => err === message); } errorsForDisplay(attrName: string) { return _.uniq(_.map(this._errors[attrName] || [], s.terminateWithPeriod)).join(" "); } allErrorsForDisplay(): string[] { return _.uniq(_.map(this.keys(), (key) => this.errorsForDisplay(key))); } count() { return _.size(this._errors); } keys() { return Object.keys(this._errors); } toJSON() { return JSON.parse(JSON.stringify(this._errors)); // deep copy of internal state } private _isEmpty() { return _.every(this._errors, (errs, attr) => _.isEmpty(errs)); } } // tslint:disable-next-line no-empty-interface export interface Errors extends EventAware {}
23da5ff8dcadd741250d387b231cf78213977ac2
TypeScript
temple-deng/dsa
/js2/leetcode/236.ts
3.875
4
/** * @file 236. 二叉树的最近公共祖先 * @link https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/ */ class TreeNode { val: number left: TreeNode | null right: TreeNode | null constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { this.val = (val===undefined ? 0 : val) this.left = (left===undefined ? null : left) this.right = (right===undefined ? null : right) } } export function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null { // 想要在这个树中找公共节点,根据之前的经验,只要一个节点在左侧,一个节点在右侧,这就是一个公共节点 // 所以我想的是先在当前左子树中找两个点 if (root === null || p === null || q === null) { return null; } if (root.val === p.val || root.val === q.val) { return root; } const pInLeft = findNode(root.left, p); const qInRight = findNode(root.right, q); // const pInRight = findNode(root.right, p); // const qInLeft = findNode(root.left, q); if (pInLeft && qInRight) { return root; } else if (pInLeft && !qInRight) { return lowestCommonAncestor(root.left, p, q); } else if (!pInLeft && qInRight) { return lowestCommonAncestor(root.right, p, q); } else { return root; } }; function findNode(node: TreeNode | null, p: TreeNode | null): boolean { if (node === null || p === null) { return false; } if (node.val === p.val) { return true; } return findNode(node.left, p) || findNode(node.right, p); }
836e376d3a3853731b703865be79384bcb1228cf
TypeScript
lukecaptaincode/SuperTodoWorld
/src/app/services/super-todo.service.ts
3.140625
3
import { Injectable } from '@angular/core'; import { TodoItem } from '../classes/todo-item'; import { Storage } from '@ionic/storage'; @Injectable({ providedIn: 'root' }) /** * @class SuperTodoService - Service class that manages all the todo list interactions */ export class SuperTodoService { todoItems: TodoItem[]; constructor(private storage: Storage) { this.getItemsFromStorage(); } /** * Completes the tasks * @param todoItem: the item to complete */ public completeTask(todoItem: TodoItem) { todoItem.endDate = new Date(); // Get now as a date; // Get the duration of the task by subtracting the start time from the end time todoItem.duration = this.msToTime( todoItem.endDate.getTime() - todoItem.startDate.getTime() ); todoItem.isDone = true; // Set to done this.updateTodoList(todoItem); // Update the todo list } /** * Deletes the item from the todo list * @param todoItem the todo item to delete */ public deleteTask(todoItem: TodoItem) { this.updateTodoList(todoItem, true); // Update the todo list with the isDelete flag } /** * Adds a new todo item to the the list of todo items * @param text the text of the item * @param score the score of the item */ public newTodoItem( text: string, score: number) { // Generate random id for item const itemId = Math.random() .toString(36) .substr(2, 9); // Create a new item object const todoItem = new TodoItem(itemId, text, score, new Date()); // If the array is empty initialize it if (this.todoItems == null) { this.todoItems = []; } // Add it to the items array this.todoItems.push(todoItem); // Save the array to storage this.saveItemToStorage(); } /** * Returns the list of todo items */ public getTodoItems(): TodoItem[] { return this.todoItems; } /** * Gets the list of todo items from storage */ public getItemsFromStorage() { return new Promise(response => { // Returning it in a promise for reasons this.storage .get('todoItems') .then(items => { // console.log('Loaded items from storage: '); // console.log(items); response(items); this.todoItems = items; }) .catch(err => { console.log('Error loading items from storage: ' + err); }); }); } /** * Updates the todo list either by updating the specific passed item or deleting it * @param todoItem the item to update or delete * @param isDeleteAction sets if the item should be deleted */ private updateTodoList(todoItem: TodoItem, isDeleteAction = false) { // loop of the array for (let i = 0; i < this.todoItems.length; i++) { if (this.todoItems[i].itemID === todoItem.itemID) { // Find the match using the unique id if (!isDeleteAction) { // if not delete, update the entry this.todoItems[i] = todoItem; } else { this.todoItems.splice(i, 1); // OR delete the entry } } } this.saveItemToStorage(); // Save the updated array to storage } /** * Saves the todo items to storage */ private saveItemToStorage() { this.storage.set('todoItems', this.todoItems); // Savse the todo list item to storage } /** * Converts milliseconds to a human readable string * @param ms the milliseconds to be converted */ private msToTime(ms: number): string { const hours = Math.floor(ms / 3600000); // 1 Hour = 36000 Milliseconds const minutes = Math.floor((ms % 3600000) / 60000); // 1 Minutes = 60000 Milliseconds return hours + ':' + minutes; } }
e30136cd86c58a9203b8ff86045c17e8082a98ee
TypeScript
Softeq/angular-libs
/projects/angular-mls-ri-lib/src/lib/utils.ts
2.546875
3
// Developed by Softeq Development Corporation // http://www.softeq.com import { Hash, Maybe } from '@softeq/types'; import isEmpty from 'lodash/isEmpty'; export interface RiMlsRecordNormalized { key: string; params?: Hash<any>; } export type RiMlsRecord = RiMlsRecordNormalized | string; export function normalizeTranslationRecord(record: RiMlsRecord): RiMlsRecordNormalized { return typeof record === 'string' ? { key: record } : record; } export function mlsRecord(key: string, params: Hash<any>): RiMlsRecord { return { key, params }; } export function getMlsRecordKey(record: RiMlsRecord): string { return typeof record === 'string' ? record : record.key; } export function getMlsRecordParams(record: RiMlsRecord): Maybe<Hash<any>> { return typeof record === 'string' ? void 0 : record.params; } export function setMlsRecordKey(record: RiMlsRecord, key: string): RiMlsRecord { return { key, params: getMlsRecordParams(record) }; } export function setMlsRecordParams(record: RiMlsRecord, params: Hash<any>): RiMlsRecord { return { key: getMlsRecordKey(record), params }; } export function mergeMlsRecordParams(record: RiMlsRecord, params: Hash<any>): RiMlsRecord { const normalized = normalizeTranslationRecord(record); return { key: normalized.key, params: isEmpty(normalized.params) && isEmpty(params) ? void 0 : { ...normalized.params, ...params } }; }
6de25624b3b88a0362c441872efb8ddd2d03fad2
TypeScript
Zuodion/HammingEncoder
/EncoderDecoder.ts
2.953125
3
class EncoderDecoder { private _matrix: Array<number>; private _converterFromBinary: ConverterFromBinary; private _logger: Logger; private _introduceError: boolean = false; private _introduceDoubleError: boolean = false; private _errorData: string = ''; constructor(matrix: Matrix, converterFromBinary: ConverterFromBinary, logger: Logger) { this._matrix = matrix.defineMatrix() this._converterFromBinary = converterFromBinary this._logger = logger } public defineIntroduceError (introduceError: boolean, introduceDoubleError: boolean, errorData: string): void { this._introduceError = introduceError; this._introduceDoubleError = introduceDoubleError; this._errorData = errorData; } public encoder (binaryCode: string): void { let fourBitsArray: any = binaryCode.match(/.{1,4}/g) this._logger.notice(`Далі данні діляться на чотирьох бітові символи ${fourBitsArray}`) let encodedBitsArray: Array<string> = []; for (let quadIndex = 0; quadIndex < fourBitsArray.length; quadIndex++) { let newElement: Array<string> = fourBitsArray[quadIndex].split('') newElement.splice(0, 0, '0') newElement.splice(1, 0, '0') newElement.splice(3, 0, '0') let sevenBitsString: any = newElement.join('') let sevenBitsArray: Array<string> = sevenBitsString.split('') for (let matrixRow = 0; matrixRow < this._matrix.length; matrixRow++) { let resultMode2: string = (Number('0b' + sevenBitsString.toString(2)) & Number('0b' + this._matrix[matrixRow].toString(2))).toString(2) let hvArray: Array<string> = resultMode2.split('') let rowSum: number = 0; for (let i = 0; i < hvArray.length; i++) { if (hvArray[i] === '1') rowSum++ } if (rowSum % 2 === 1) { switch (matrixRow) { case 0: sevenBitsArray.splice(3, 1, '1') break; case 1: sevenBitsArray.splice(1, 1, '1') break; case 2: sevenBitsArray.splice(0, 1, '1') break; } } } encodedBitsArray.push(sevenBitsArray.join('')) } this._logger.notice(`Числа кодуються кодом Хемінга ${encodedBitsArray}`) if (this._introduceError && !this._introduceDoubleError) { this.errorIntroducer(encodedBitsArray) } else if (!this._introduceError && this._introduceDoubleError) { this.errorDoubleIntroducer(encodedBitsArray) } else if (this._introduceError && this._introduceDoubleError) { this.errorMixedIntroducer(encodedBitsArray) } else if (this._errorData !== '') { this.errorDeterminedIntroducer(encodedBitsArray) } else this.decoder(encodedBitsArray) } private randomInteger (min: number, max: number): number { let randomInt: number = (min - 0.5 + Math.random() * (max - min + 1)) randomInt = Math.round(randomInt); return randomInt; } private errorIntroducer (encodedCode: any): void { let encodedCorruptedCode: Array<string> = []; let htmlArray: Array<string> = [] for (let index = 0; index < encodedCode.length; index++) { let encodedCodeArray: Array<string> = encodedCode[index].split('') let randomIndex: number = (this.randomInteger(1, 7) - 1) encodedCodeArray[randomIndex] = String(Number(!Number(encodedCodeArray[randomIndex]))); encodedCorruptedCode.push(encodedCodeArray.join('')) let htmlElement: string = this._logger.colorizeElement(encodedCodeArray, randomIndex, 'red') htmlArray.push(htmlElement) } this._logger.notice(`Випадковим чином вводяться однобітові помилки: ${htmlArray}`) this.decoder(encodedCorruptedCode) } private errorDoubleIntroducer (encodedCode: any): void { let encodedCorruptedCode: Array<string> = []; let htmlArray: Array<string> = [] for (let index = 0; index < encodedCode.length; index++) { let encodedCodeArray: Array<string> = encodedCode[index].split('') let firstIndex: number = (this.randomInteger(1, 7) - 1) encodedCodeArray[firstIndex] = String(Number(!Number(encodedCodeArray[firstIndex]))); let secondIndex: number = (this.randomInteger(1, 7) - 1) while (firstIndex === secondIndex) { secondIndex = (this.randomInteger(1, 7) - 1) } encodedCodeArray[secondIndex] = String(Number(!Number(encodedCodeArray[secondIndex]))); encodedCorruptedCode.push(encodedCodeArray.join('')) let htmlElement: string = this._logger.colorizeElement(encodedCodeArray, firstIndex, 'red') htmlElement = this._logger.colorizeElement(encodedCodeArray, secondIndex, 'red') htmlArray.push(htmlElement) } this._logger.notice(`Випадковим чином вводяться двобітові помилки: ${htmlArray}`) this.decoder(encodedCorruptedCode) } private errorMixedIntroducer (encodedCode: any): void { let encodedCorruptedCode: Array<string> = []; let htmlArray: Array<string> = [] for (let index = 0; index < encodedCode.length; index++) { if (this.randomInteger(1, 2) - 1) { let encodedCodeArray: Array<string> = encodedCode[index].split('') let firstIndex: number = (this.randomInteger(1, 7) - 1) encodedCodeArray[firstIndex] = String(Number(!Number(encodedCodeArray[firstIndex]))); let secondIndex: number = (this.randomInteger(1, 7) - 1) while (firstIndex === secondIndex) { secondIndex = (this.randomInteger(1, 7) - 1) } encodedCodeArray[secondIndex] = String(Number(!Number(encodedCodeArray[secondIndex]))); encodedCorruptedCode.push(encodedCodeArray.join('')) let htmlElement: string = this._logger.colorizeElement(encodedCodeArray, firstIndex, 'red') htmlElement = this._logger.colorizeElement(encodedCodeArray, secondIndex, 'red') htmlArray.push(htmlElement) } else { let encodedCodeArray: Array<string> = encodedCode[index].split('') let randomIndex: number = (this.randomInteger(1, 7) - 1) encodedCodeArray[randomIndex] = String(Number(!Number(encodedCodeArray[randomIndex]))); encodedCorruptedCode.push(encodedCodeArray.join('')) let htmlElement: string = this._logger.colorizeElement(encodedCodeArray, randomIndex, 'red') htmlArray.push(htmlElement) } } this._logger.notice(`Випадковим чином вводяться однократні і двократні помилки: ${htmlArray}`) this.decoder(encodedCorruptedCode) } private errorDeterminedIntroducer (encodedCode: any): void { let encodedCorruptedCode: Array<string> = []; let htmlArray: Array<string> = []; for (let codeIndex = 0; codeIndex < encodedCode.length; codeIndex++) { let encodedCodeArray: Array<string> = encodedCode[codeIndex].split('') for (let index = 0; index < this._errorData.length; index++) { let errorIndex: any = this._errorData[index]; encodedCodeArray[errorIndex-1] = String(Number(!Number(encodedCodeArray[errorIndex-1]))) } encodedCorruptedCode.push(encodedCodeArray.join('')) // Colorizer let htmlElement = ''; for (let index = 0; index < this._errorData.length; index++) { let errorIndex: any = this._errorData[index]; htmlElement = this._logger.colorizeElement(encodedCodeArray, errorIndex-1, 'red') } htmlArray.push(htmlElement) } this._logger.notice(`Виставляються помилки вибраним чином: ${htmlArray}`) this.decoder(encodedCorruptedCode) } public decoder (encodedCode: Array<string>): void { let htmlArray: Array<string> = [] let decodedCode: Array<string> = []; for (let codeIndex = 0; codeIndex < encodedCode.length; codeIndex++) { let sevenBitsCode: any = encodedCode[codeIndex] let errorIndex: number = 0; // Block correction error if (this._introduceError || this._introduceDoubleError || this._errorData) { for (let matrixRow = 0; matrixRow < this._matrix.length; matrixRow++) { let resultMode2: string = (Number('0b' + sevenBitsCode.toString(2)) & Number('0b' + this._matrix[matrixRow].toString(2))).toString(2) let hvArray: Array<string> = resultMode2.split('') let rowSum: number = 0; for (let i = 0; i < hvArray.length; i++) { if (hvArray[i] === '1') rowSum++ } if (rowSum % 2 === 1) { switch (matrixRow) { case 0: errorIndex += 4 break; case 1: errorIndex += 2 break; case 2: errorIndex += 1 break; } } } } let fixedCode: Array<string> = sevenBitsCode.split('') if (fixedCode[errorIndex - 1]) { fixedCode[errorIndex - 1] = String(Number(!Number(fixedCode[errorIndex - 1]))) } decodedCode.push(fixedCode.join('')) let htmlElement: string = this._logger.colorizeElement(fixedCode, errorIndex - 1, 'aqua') htmlArray.push(htmlElement) } if (this._introduceError || this._introduceDoubleError || this._errorData) { this._logger.notice(`За допомогою декодування знаходяться помилки і виправляються: ${htmlArray}`) } let fourBitsArray: Array<string> = []; for (let decodedCodeIndex = 0; decodedCodeIndex < decodedCode.length; decodedCodeIndex++) { let fourBits: Array<string> = decodedCode[decodedCodeIndex].split('') fourBits.splice(0, 1); fourBits.splice(0, 1); fourBits.splice(1, 1); fourBitsArray.push(fourBits.join('')) } this._logger.notice(`Забирається перевірочна частина ${fourBitsArray}`) this._converterFromBinary.convertToOriginalData(fourBitsArray) } }
0f551d1c585761539c748657571cb63359e3264a
TypeScript
morerokk/vgwdb-client
/src/app/models/weapon.model.ts
2.9375
3
import { Model } from './model.interface'; export class Weapon implements Model { private _id: number; private _name: string; private _description: string; private _imagePath: string; private _designed: string; private _manufacturer; private _games; constructor(values: Object = {}) { Object.assign(this, values); } //Return object with current values, for use in json.stringify() for example public toObject() { return { id: this.id, name: this.name, description: this.description, imagePath: this.imagePath, designed: this.designed, manufacturer: this.manufacturer, games: this.games }; } public get id(): number { return this._id; } public set id(i: number) { this._id = i; } public get name(): string { return this._name; } public set name(n: string) { this._name = n; } public get description(): string { return this._description; } public set description(d: string) { this._description = d; } public get imagePath(): string { return this._imagePath; } public set imagePath(i: string) { this._imagePath = i; } public get designed(): string { return this._designed; } public set designed(d: string) { this._designed = d; } public get manufacturer() { return this._manufacturer; } public set manufacturer(m) { this._manufacturer = m; } public get games() { return this._games; } public set games(g) { this._games = g; } }
ce3d4f829d5c63660ef44608701c91ab6f896c15
TypeScript
VinayaSathyanarayana/cube.js
/packages/cubejs-query-orchestrator/src/orchestrator/LocalCacheDriver.ts
2.859375
3
import { CacheDriverInterface } from './cache-driver.interface'; const store = {}; export class LocalCacheDriver implements CacheDriverInterface { protected readonly store: Record<string, any>; public constructor() { this.store = store; } public async get(key: string) { if (this.store[key] && this.store[key].exp < new Date().getTime()) { delete this.store[key]; } return this.store[key] && this.store[key].value; } public async set(key: string, value, expiration) { this.store[key] = { value, exp: new Date().getTime() + expiration * 1000 }; } public async remove(key: string) { delete this.store[key]; } public async keysStartingWith(prefix: string) { return Object.keys(this.store) .filter(k => k.indexOf(prefix) === 0 && this.store[k].exp > new Date().getTime()); } public async cleanup(): Promise<void> { // Nothing to do } public async testConnection(): Promise<void> { // Nothing to do } }
a9feb2f462f7b6d6b683539ee8ab8df32d616ab8
TypeScript
mikepuerto/orderbook-analysis
/src/univariate/univariate.ts
2.90625
3
// Univariate Analysis import { median, quantileSorted, variance, sampleVariance, linearRegression, sampleSkewness, sampleKurtosis, } from 'simple-statistics'; import { OrderBookExtended, Order, linearRegressionResult } from '../types'; export const Univariate = { medianByAsksPrice: (Orderbook: OrderBookExtended): number => { return median([...Orderbook.asks.map((order: Order) => order.price)]); }, medianByBidsPrice: (Orderbook: OrderBookExtended): number => { return median([...Orderbook.bids.map((order: Order) => order.price)]); }, medianByAllPrice: (Orderbook: OrderBookExtended): number => { return median([...Orderbook.all.map((order: Order) => order.price)]); }, medianByAsksTotal: (Orderbook: OrderBookExtended): number => { return median([...Orderbook.asks.map((order: Order) => order.total)]); }, medianByBidsTotal: (Orderbook: OrderBookExtended): number => { return median([...Orderbook.bids.map((order: Order) => order.total)]); }, medianByAllTotal: (Orderbook: OrderBookExtended): number => { return median([...Orderbook.all.map((order: Order) => order.total)]); }, _quartilesBy: (values: number[]): any => { // min, 25%, 50%, 75%, max return { 0: values[0], 25: quantileSorted(values, 0.25), 50: quantileSorted(values, 0.5), 75: quantileSorted(values, 0.75), 100: values[values.length - 1], IQR: quantileSorted(values, 0.75) - quantileSorted(values, 0.25), }; }, quartilesByAsksPrice: (Orderbook: OrderBookExtended): number[] => { return Univariate._quartilesBy([...Orderbook.asks.map((order: Order) => order.price)]); }, quartilesByBidsPrice: (Orderbook: OrderBookExtended): number[] => { return Univariate._quartilesBy([...Orderbook.bids.map((order: Order) => order.price)]); }, quartilesByAllPrice: (Orderbook: OrderBookExtended): number[] => { return Univariate._quartilesBy([...Orderbook.all.map((order: Order) => order.price)]); }, _varianceBy(values: number[]): number { if (values.length > 2) { return sampleVariance(values); } return variance(values); }, varianceByAllPrice: (Orderbook: OrderBookExtended): number => { return Univariate._varianceBy([...Orderbook.all.map((order: Order) => order.price)]); }, varianceByAsksPrice: (Orderbook: OrderBookExtended): number => { return Univariate._varianceBy([...Orderbook.asks.map((order: Order) => order.price)]); }, varianceByBidsPrice: (Orderbook: OrderBookExtended): number => { return Univariate._varianceBy([...Orderbook.bids.map((order: Order) => order.price)]); }, _linearRegressionByPriceAndTotal: (data: number[][]): linearRegressionResult => { return linearRegression(data); }, linearRegressionByAll: (Orderbook: OrderBookExtended): linearRegressionResult => { return Univariate._linearRegressionByPriceAndTotal([ ...Orderbook.all.map((order: Order) => [order.price, order.total]), ]); }, linearRegressionByAsks: (Orderbook: OrderBookExtended): linearRegressionResult => { return Univariate._linearRegressionByPriceAndTotal([ ...Orderbook.asks.map((order: Order) => [order.price, order.total]), ]); }, linearRegressionByBids: (Orderbook: OrderBookExtended): linearRegressionResult => { return Univariate._linearRegressionByPriceAndTotal([ ...Orderbook.bids.map((order: Order) => [order.price, order.total]), ]); }, skewnessByAsksPrice: (Orderbook: OrderBookExtended): number => { return sampleSkewness([...Orderbook.asks.map((order: Order) => order.price)]); }, skewnessByBidsPrice: (Orderbook: OrderBookExtended): number => { return sampleSkewness([...Orderbook.bids.map((order: Order) => order.price)]); }, skewnessByAllPrice: (Orderbook: OrderBookExtended): number => { return sampleSkewness([...Orderbook.all.map((order: Order) => order.price)]); }, kurtosisByAsksPrice: (Orderbook: OrderBookExtended): number => { return sampleKurtosis([...Orderbook.asks.map((order: Order) => order.price)]); }, kurtosisByBidsPrice: (Orderbook: OrderBookExtended): number => { return sampleKurtosis([...Orderbook.bids.map((order: Order) => order.price)]); }, kurtosisByAllPrice: (Orderbook: OrderBookExtended): number => { return sampleKurtosis([...Orderbook.all.map((order: Order) => order.price)]); }, };
72a54231b66c1c8eb2c96379560a2d2c68a37230
TypeScript
RyenToretto/blossom
/src/models/hsv/transform.ts
3.5
4
import { round } from "@util/helpers"; import type { ColorHSV, ColorRGB, ColorHSL } from "../../types"; /** * Convert HSV color object to RGB. */ export function hsv2rgb(color: ColorHSV): ColorRGB { const h = (color.h / 360) * 6; const s = color.s / 100; const v = color.v / 100; const a = color?.a ?? 1; const hh = Math.floor(h); const b = v * (1 - s); const c = v * (1 - (h - hh) * s); const d = v * (1 - (1 - h + hh) * s); const module = hh % 6; return { r: [v, c, b, b, d, v][module] * 255, g: [d, v, v, c, b, b][module] * 255, b: [b, b, d, v, v, c][module] * 255, a: a, }; } /** * Convert HSV color object to HSL. */ export function hsv2hsl(color: ColorHSV): ColorHSL { const h = color.h; const sv = color.s / 100; const v = color.v / 100; const a = color.a ? round(color.a, 2) : 1; const l = v * (1 - sv / 2); const sl = (l === 0 || l === 1) ? 0 : (v - l) / (Math.min(l, 1 - l)); return { h, s: round(sl * 100), l: round(l * 100), a }; }
e80cbb7ea469a90d42698055ecca0121c245e255
TypeScript
neefrehman/generative
/src/sketches/utils/shaders/types.ts
3.140625
3
import type { Vector } from "Utils/math/types"; export type UniformDimensions = "1" | "2" | "3" | "4"; export type UniformValueType = "f" | "i" | "fv" | "iv"; export type UniformType = `${UniformDimensions}${UniformValueType}`; export type UniformValue = number | Vector | Float32List | Int32List; /** * A uniform value to interface with shaders */ export interface Uniform<T extends UniformType> { value: any; // UniformValue // TODO: type guards for accessing these with safety in sketches type?: T; } /** * A dictionary of uniforms */ export interface UniformDict { [uniformName: string]: Uniform<UniformType>; }
f7b5c19ff30c2c6a2496e0f90505614d12015443
TypeScript
kraftwerk28/blcklstbot
/lib/fetch.ts
2.8125
3
import { request, RequestOptions } from "https"; import qs from "querystring"; type RestMethod = | "GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "DELETE" | "PATCH"; export function rest<T>( url: string, method: RestMethod, headers: Record<string, string> = {}, query?: Record<string, any>, body?: Record<string, any>, options: RequestOptions = {}, ): Promise<T> { const callback = (resolve: any, reject: any) => { const fullUrl = new URL(url); const opts: RequestOptions = { method, headers: { "content-type": "application/json", ...headers }, ...options, }; if (query) { fullUrl.search = qs.stringify(query); } if (method === "POST") { opts.headers!["content-type"] = "application/json"; } const req = request(fullUrl, opts, (response) => { if (response.statusCode!.toString()[0] !== "2") { console.info(`${method} ${fullUrl.pathname} -> ${response.statusCode}`); reject( "Bad Blocklist API response:" + `${response.statusCode} ${response.statusMessage}`, ); return; } console.info(`${method} ${fullUrl.pathname} -> ${response.statusCode}`); const data = [] as any[]; response .on("data", (ch) => data.push(ch)) .on("end", () => { const d = Buffer.concat(data).toString(); if (response.headers["content-type"] === "application/json") { resolve(JSON.parse(d)); } resolve(d); }) .on("error", reject); }); if (body) { req.write(JSON.stringify(body)); } req.end(); }; return new Promise(callback); }
0ce273584d1effc320aa930982ddefb40870eed7
TypeScript
green-fox-academy/Kifrido
/week-02/day-3/starry-night-ts.ts
3.21875
3
'use strict'; const canvas = document.querySelector('.main-canvas') as HTMLCanvasElement; const ctx = canvas.getContext('2d'); // DO NOT TOUCH THE CODE ABOVE THIS LINE // Draw the night sky: // - The background should be black // - The stars should be small squares // - The stars should have random positions on the canvas // - The stars should have random color (some shade of grey) ctx.fillRect(0, 0, canvas.width, canvas.height); function starryNight(position1: number, position2: number, colors: string){ ctx.fillStyle = colors; ctx.fillRect(position1, position2, 5, 5); } for(let i: number = 0; i < Math.random() * 200; i++){ let colors: number = Math.floor(Math.random() * 255); starryNight(Math.random() * canvas.width, Math.random() * canvas.height, `rgb(${colors},${colors},${colors})`); }
1fd1a920a0eb6d6c31c0925d343335f62ae6efba
TypeScript
hemant-batra/kiteAdminUI
/src/app/kitecash/services/common/data.service.ts
2.546875
3
import {Injectable} from '@angular/core'; @Injectable() export class DataService { private userRole: string = null; private userName: string = null; private fullName: string = null; private mobileNumber: string = null; private message: string = null; public getUserRole() { return this.userRole; } public setUserRole(userRole: string) { this.userRole = userRole; } public getUserName() { return this.userName; } public setUserName(userName: string) { this.userName = userName; } public getFullName() { return this.fullName; } public setFullName(fullName: string) { this.fullName = fullName; } public getMobileNumber() { return this.mobileNumber; } public setMobileNumber(mobileNumber: string) { this.mobileNumber = mobileNumber; } public getMessage() { return this.message; } public setMessage(message: string) { this.message = message; } }
d5cb41740d677c9ca745e3f311020198565071fe
TypeScript
robsonmvieira/book-store-api
/src/modules/roles/roles.service.ts
2.546875
3
import {BaseService} from '../../infra/BaseService.service' import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Role } from './entities/role.entity'; import { CreateRoleDto } from './dto/create-role.dto'; import { Permission } from '../permissions/entities/permission.entity' @Injectable() export class RolesService extends BaseService<Role> { constructor(@InjectRepository(Role) protected resource: Repository<Role>, @InjectRepository(Permission) protected permissionRepository: Repository<Permission>) { super(resource) } async create(data: CreateRoleDto): Promise<Role> { const { permissions } = data const newRole = { name: data.name, description: data.description, slug: data.slug, permissions: [] } for (const perm of permissions) { const tmp = await this.permissionRepository.findOne(perm) newRole.permissions.push(tmp) } return this.resource.save(newRole) } }
a78b40aeed548d5a846128741050ebae21fb0af2
TypeScript
entropitor/ddd-course
/typescript/index.spec.ts
3.109375
3
// Scenario: Online Reservation // The system lists movies available with given time interval, title and screening times and prices. // The user chooses a particular screening. // The system gives information regarding screening room and available seats. // The user chooses seats, and gives the name of the person doing the reservation (name and surname). // The system gives back the total amount to pay and reservation expiration time. // After 12 minutes, the reservatrion should be cancelled import uuid from "uuid/v4"; namespace Domain { export type Seat = `${1 | 2}${"a" | "b" | "c"}`; export type Time = { minutes: number }; export const Screening = (publish: Infrastructure.Publish) => { let reservedSeats = new Set(); return { apply(event: Events.Event) { switch (event.type) { case "ScreeningPlanned": reservedSeats = new Set(); break; case "SeatsReserved": event.seats.forEach((seat) => reservedSeats.add(seat)); } }, reserveSeat(command: ReturnType<typeof Commands.ReserveSeat>) { const alreadyReservedSeats = command.seats.filter((seat) => reservedSeats.has(seat) ); if (alreadyReservedSeats.length > 0) { publish( Events.SeatsAlreadyReserved(command.title, alreadyReservedSeats) ); } else { publish( Events.SeatsReserved( command.reservationId, command.title, command.seats ) ); } }, }; }; export const AvailableSeats = () => { let availableSeats: Set<Seat> = new Set(); return { project(event: Events.Event) { switch (event.type) { case "ScreeningPlanned": availableSeats = new Set(event.allSeats); break; case "SeatsReserved": event.seats.forEach((seat) => availableSeats.delete(seat)); break; } }, availableSeats(query: ReturnType<typeof Queries.AvailableSeats>) { return { title: query.title, availableSeats: [...availableSeats], }; }, }; }; } namespace Events { export const ScreeningPlanned = (title: string, allSeats: Domain.Seat[]) => ({ title, allSeats, type: "ScreeningPlanned", } as const); export const SeatsReserved = ( reservationId: string, title: string, seats: Domain.Seat[] ) => ({ seats, title, reservationId, type: "SeatsReserved", } as const); export const SeatsAlreadyReserved = ( title: string, alreadyReservedSeats: Domain.Seat[] ) => ({ alreadyReservedSeats, title, type: "SeatsAlreadyReserved", } as const); export type Event = | ReturnType<typeof ScreeningPlanned> | ReturnType<typeof SeatsReserved> | ReturnType<typeof SeatsAlreadyReserved>; } namespace Commands { export const ReserveSeat = (title: string, seats: Domain.Seat[]) => ({ seats, title, reservationId: uuid(), type: "ReserveSeat", } as const); export const StartReservationTimer = (time: Domain.Time) => ({ time, type: "ReserveSeat", } as const); export type Command = | ReturnType<typeof ReserveSeat> | ReturnType<typeof StartReservationTimer>; } namespace Queries { export const AvailableSeats = (title: string) => ({ title, type: "AvailableSeats", } as const); export type Query = ReturnType<typeof AvailableSeats>; } namespace Infrastructure { export const unreachable = (_value: never) => { throw new Error("should be unreachable"); }; export type Publish = (event: Events.Event) => void; export const CommandHandler = (history: any[], publish: Publish) => { return { handleCommand(command: any) { const screening = Domain.Screening(publish); history.forEach((event) => screening.apply(event)); if (command.type === "ReserveSeat") { screening.reserveSeat(command); } }, }; }; export const QueryHandler = (history: Events.Event[]) => { return { handleQuery(query: any) { const readModel = Domain.AvailableSeats(); history.forEach((event) => readModel.project(event)); if (query.type === "AvailableSeats") { return readModel.availableSeats(query); } }, }; }; } namespace TestingFramework { export const createTest = () => { const generatedEvents: any[] = []; let history: any[] = []; let generatedResponse: any = null; return { given(...events: any[]) { history = events; }, then(...expectedEvents: any[]) { expect(generatedEvents).toEqual(expectedEvents); }, then_result(expectedResult: any) { expect(generatedResponse).toEqual(expectedResult); }, then_expected_command(_command: Commands.Command) { // TODO }, when(command: Commands.Command) { const commandHandler = Infrastructure.CommandHandler( history, (event) => { generatedEvents.push(event); } ); commandHandler.handleCommand(command); }, when_event(event: Events.Event) { // TODO }, when_query(query: Queries.Query) { generatedResponse = Infrastructure.QueryHandler(history).handleQuery( query ); }, }; }; } const allSeats = [ "1a" as const, "1b" as const, "1c" as const, "2a" as const, "2b" as const, "2c" as const, ]; describe("Commands", () => { it("Reserve Seat successfull test", () => { const { given, then, when } = TestingFramework.createTest(); given(Events.ScreeningPlanned("Movie 42", allSeats)); when(Commands.ReserveSeat("Movie 42", ["1b", "1c"])); then(Events.SeatsReserved(expect.any(String), "Movie 42", ["1b", "1c"])); }); it("Reserve Seat failed test", () => { const { given, then, when } = TestingFramework.createTest(); given( Events.ScreeningPlanned("Movie 42", allSeats), Events.SeatsReserved(uuid(), "Movie 42", ["1a", "1b"]) ); when(Commands.ReserveSeat("Movie 42", ["1b", "1c"])); then(Events.SeatsAlreadyReserved("Movie 42", ["1b"])); }); }); // it("Reserve Seat failed test because reserving seat that does not exist", () => { // const { given, then, when } = TestingFramework.createTest(); // given(Events.ScreeningPlanned("Movie 42", allSeats)); // when(Commands.ReserveSeat("Movie 42", ["3b", "3c"])); // then(Events.SeatsNotExisting("Movie 42", ["3b", "3c"])); // }); describe("Projection", () => { it("Available seats", () => { const { given, then_result, when_query } = TestingFramework.createTest(); given(Events.ScreeningPlanned("Movie 42", allSeats)); when_query(Queries.AvailableSeats("Movie 42")); then_result({ availableSeats: allSeats, title: "Movie 42", }); }); it("Available seats after reservation", () => { const { given, then_result, when_query } = TestingFramework.createTest(); given( Events.ScreeningPlanned("Movie 42", allSeats), Events.SeatsReserved(uuid(), "Movie 42", ["2a", "2b"]) ); when_query(Queries.AvailableSeats("Movie 42")); then_result({ availableSeats: ["1a", "1b", "1c", "2c"], title: "Movie 42", }); }); }); describe("Policies", () => { it("...", () => { const { given, then_expected_command, when_event, } = TestingFramework.createTest(); given(Events.ScreeningPlanned("Movie 42", allSeats)); when_event(Events.SeatsReserved(uuid(), "Movie 42", ["2a", "2b"])); then_expected_command(Commands.StartReservationTimer({ minutes: 10 })); }); });
2bb9e53e1599d1ca57aa8bb13fa2fe62e89b70bb
TypeScript
scottbenton/Pomodoro
/src/store/pomodoro-settings.store.ts
2.625
3
import { produce } from "immer"; import { create } from "zustand"; import { persist } from "zustand/middleware"; export enum CYCLES { WORK = "work", BREAK = "break", LONG_BREAK = "long-break", } export interface IPomodoroSettingsStore { playAudioOnCycleEnd: boolean; togglePlayAudioOnCycleEnd: (shouldPlayAudio: boolean) => void; keepScreenOnDuringCycles: boolean; toggleKeepScreenOnDuringCycles: (shouldKeepScreenOn: boolean) => void; autoStartCycles: boolean; toggleAutoStartCycles: (autoStartCycles: boolean) => void; [CYCLES.WORK]: { length: number; }; [CYCLES.BREAK]: { length: number; }; [CYCLES.LONG_BREAK]: { enabled: boolean; length: number; cyclesBeforeLongBreak: number; }; setCycleLength: (cycle: CYCLES, length: number) => void; setLongBreakEnabled: (enabled: boolean) => void; setCyclesBeforeLongBreak: (cyclesBeforeLongBreak: number) => void; } export const usePomodoroSettings = create<IPomodoroSettingsStore>()( persist( (set) => ({ playAudioOnCycleEnd: true, togglePlayAudioOnCycleEnd: (shouldPlayAudio) => set( produce((state: IPomodoroSettingsStore) => { state.playAudioOnCycleEnd = shouldPlayAudio; }) ), keepScreenOnDuringCycles: false, toggleKeepScreenOnDuringCycles: (keepScreenOnDuringCycles) => set( produce((state: IPomodoroSettingsStore) => { state.keepScreenOnDuringCycles = keepScreenOnDuringCycles; }) ), autoStartCycles: true, toggleAutoStartCycles: (autoStartCycles) => set( produce((state: IPomodoroSettingsStore) => { state.autoStartCycles = autoStartCycles; }) ), [CYCLES.WORK]: { length: 25, }, [CYCLES.BREAK]: { length: 5, }, [CYCLES.LONG_BREAK]: { enabled: true, length: 15, cyclesBeforeLongBreak: 4, }, setCycleLength: (cycle, length) => set( produce((state: IPomodoroSettingsStore) => { state[cycle].length = length; }) ), setLongBreakEnabled: (enabled) => set( produce((state: IPomodoroSettingsStore) => { state[CYCLES.LONG_BREAK].enabled = enabled; }) ), setCyclesBeforeLongBreak: (cyclesBeforeLongBreak) => set( produce((state: IPomodoroSettingsStore) => { state[CYCLES.LONG_BREAK].cyclesBeforeLongBreak = cyclesBeforeLongBreak; }) ), }), { name: "pomodoro-timer-settings", } ) );
3a43cb5f64d9ab173e59fc60fe7f4a2455f3594d
TypeScript
sanathyadav/linked_list
/src/list.ts
3.734375
4
class Item<T> { value: T; next: Item<T> | null; constructor(value: T) { this.value = value; this.next = null; } } export default class List<T> { private head: Item<T>; private size: number; constructor(item: T) { this.head = new Item(item); this.size = 1; } private getHead() { return this.head; } private getItem(index: number) { if (index == 0) { return this.head; } let current: Item<T> | null = this.head.next; for (let i = 0; i < this.len(); i++) { if (i + 1 == index) { return current; } current = current && current.next; } return null; } get(index: number) { return this.getItem(index)?.value; } private getTail() { return this.getItem(this.len() - 1)!; } add(item: T) { this.getTail().next = new Item(item); this.size += 1; } len() { return this.size; } }