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
a0b5bf2f00aef614af26747a99e89ec9b97b86a5
TypeScript
lucsbasto/paint-calculator
/src/wall/schemas/wall.schema.ts
2.578125
3
import { Document } from 'mongoose'; import ObjectID from 'bson-objectid' import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; export interface PaintCans { '0.5L': number, '2.5L': number, '3.6L': number, '18L': number } @Schema({ timestamps: true }) export class Wall { @Prop({ type: Number, required: true }) height: number; @Prop({ type: Number, required: true }) width: number; @Prop({ type: Number, required: true }) windows: number; @Prop({ type: Number, required: true }) doors: number; @Prop({ type: Number, required: true }) number: number; @Prop({type: String, default: new ObjectID()}) room: string @Prop({type: Object }) paintCans: PaintCans } export const WallSchema = SchemaFactory .createForClass(Wall); export type WallDocument = Wall & Document;
8ab093d061c7b14ff3ed9204cf5d991ee0058c71
TypeScript
LaghzaliTaha/insiders
/app/shared/forms/services/form.service.ts
2.703125
3
import { Injectable } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { InputBase } from '../models/input-base'; @Injectable() export class FormService { constructor() { } toFormGroup(inputs: InputBase<any>[] ) { let group: any = {}; inputs.forEach(input => { switch (input.key) { case 'nom': case 'prenom': case'condition': case 'entite' : group[input.key] = new FormControl(input.value || '', Validators.required); input.errMessage = 'Ce champs doit contenir au moin un caractère'; break; case 'adresseMail' : group[input.key] = new FormControl(input.value || '', Validators.compose([ Validators.required, Validators.email, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')])); input.errMessage = 'Le format de l\'email n\'est pas valide'; break; case 'numeroMobile' : group[input.key] = new FormControl(input.value || '', [ Validators.required, Validators.pattern('^(\\+33)+[0-9]{9}$') ]); input.errMessage = 'Le numéro de Tél doit commencer par +33 et doit contenir 11 chiffres'; break; // case 'fonction' : // group[input.key] = new FormControl(input.value || '', Validators.compose([Validators.required, Validators.minLength(4)])); // input.errMessage = 'La fonction doit contenir au moin 4 caractères'; // break; default: group[input.key] = new FormControl(input.value || ''); break; } }); return new FormGroup(group); } }
6d009e251c7dd97385cbf8937fa6488da3e14bdd
TypeScript
dingchaolin/ts-demo-3
/class/class_static.ts
3.8125
4
/** * Created by chaolinding on 2017/10/19. */ // x** 表示x的平方 class Gird{ static origin = {x:0, y:0}; Distance(point:{x:number, y:number}){ let xDist = point.x - Gird.origin.x; let yDist = point.y - Gird.origin.y; return Math.sqrt( xDist** 2 + yDist** 2); } } let g = new Gird(); console.log( g.Distance({x: 3, y: 4}));//5 Gird.origin = {x:6, y:8}; console.log( Gird.origin )
a26a72c9c69e6b7f7319d722c6c0fe55be8b2b26
TypeScript
RickMu/single-page-shop
/src/common/extensions/utils/linkedlist.ts
3.375
3
import LinkedNode from "../LinkedNode"; export function constructLinkedList<T>(items: T[]): LinkedNode<T> { const head: LinkedNode<T> = { item: items[0], next: undefined, prev: undefined }; const remainedItems = items.slice(1); remainedItems.reduce((prevValue: LinkedNode<T>, currentValue: T) => { const newNode: LinkedNode<T> = { item: currentValue, next: undefined, prev: prevValue }; prevValue.next = newNode; return newNode; }, head); return head; } export function constructLinkedListArray<T>(items: T[]): Array<LinkedNode<T>> { const head = constructLinkedList(items); const linkedListArray: Array<LinkedNode<T>> = [head]; let pointer = head; while (pointer.next) { linkedListArray.push(pointer.next); pointer = pointer.next; } return linkedListArray; }
578c9b49f03ce198016a643dd78423e7bda67d2e
TypeScript
michaelrondon27/curso_angular_sockets
/03-socket-server-multi/classes/ticket-control.ts
2.84375
3
import { Ticket } from './ticket'; export class TicketControl { private hoy: any = new Date().getDate(); private tickets: Ticket[] = []; private ultimo: number = 0; private ultimos4: Ticket[] = []; constructor() { if (new Date().getDate() !== this.hoy) { this.reiniciarConteo(); } } atenderTicket( escritorio: any ) { if (this.tickets.length === 0) { return { data: { numero: 0, escritorio: null } }; } let numeroTicket = this.tickets[0].numero; this.tickets.shift(); let atenderTicket = new Ticket(numeroTicket, escritorio); this.ultimos4.unshift(atenderTicket); if (this.ultimos4.length > 4) { this.ultimos4.splice(-1, 1); // borra el último } return { data: { numero: atenderTicket.numero, escritorio: atenderTicket.escritorio, } }; } generarNuevoTicket() { this.ultimo += 1; let ticket = new Ticket(this.ultimo, null); this.tickets.push(ticket); } getUltimosCuatro() { return { data: this.ultimos4 }; } getUltimoTicket() { return { data: { ultimoTicket: this.ultimo } }; } reiniciarConteo() { this.tickets = []; this.ultimo = 0; this.ultimos4 = []; } }
411da47fea5399c0852a86ee9e9cafc9c4868540
TypeScript
future4code/Gabriel-Mina
/semana18/semana18-projeto/src/endpoints/anotherUserProfile.ts
2.515625
3
import { Request, Response } from "express" import connection from "../connection" import { generateToken, getTokenData } from "../services/authenticator" import { compare } from "../services/hashManager" // id fo francis 15495c8f-7442-43d6-86df-c0078cb187d4 export default async function anotherUserProfile( req: Request, res: Response ): Promise<void> { try { const tokenData = req.headers.authorization as string; const id = req.params.id as string; const resultToken = getTokenData(tokenData) if(!resultToken){ throw new Error("O usuário deste token não está cadastrado") } if (!tokenData) { res.statusCode = 401; throw new Error() } const [user] = await connection("usuarioCokenu") .where({id}); if(!user){ throw new Error("Usuário não encontrado") } res.status(200).send({ id: user.id, name: user.nome, email:user.email }) } catch (error) { res.status(400).send({ message: error.message }) } }
4f0099335f01b35f2dc0dcd72afc0da9cac9c89f
TypeScript
JohnathanMB/PruebaAccFront
/src/app/componentes/consulta/consulta.component.ts
2.625
3
import { Component, OnInit } from '@angular/core'; import { ReactiveFormsModule, FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms'; import { ConsultaService } from '../../services/consulta/consulta.service'; @Component({ selector: 'app-consulta', templateUrl: './consulta.component.html', styleUrls: ['./consulta.component.css'] }) export class ConsultaComponent implements OnInit { public formularioConsulta: FormGroup; public consultaRealizada = false; public boolMonto = false; public aprobada ; public monto; public mensaje; constructor(private formBuider: FormBuilder, private clienteConsulta: ConsultaService) { } ngOnInit() { this.buildForm(); } private buildForm() { const dateLength = 10; const today = new Date().toISOString().substring(0, dateLength); this.formularioConsulta = this.formBuider.group({ empresa: [], nit: ['', [Validators.required, this.esEntero, this.formatoNit]], salario: ['', [Validators.required, Validators.max(100000000), Validators.min(0), this.esEntero]], fecha_inicio: [today, [Validators.required, this.esPasado]] }); } public consultar(){ const consulta = this.formularioConsulta.value; this.postConsulta(consulta); } postConsulta(consulta: any) { this.clienteConsulta.postConsulta(consulta).subscribe(resultado=>{ console.log(resultado); console.log(resultado.aprobado); this.consultaRealizada = true; if(resultado.aprobado){ this.aprobada = 'Felicitaciones!\nSu credito a sido aprobado'; this.boolMonto = true; this.monto = resultado.credito; }else{ this.aprobada = 'Lo sentimos\nsu credito a sido rechazado'; this.boolMonto = false; } this.mensaje = resultado.mensaje; }, error=>{ console.log(error); }); } private esEntero(control: AbstractControl){ let error = null; var datoEntero = control.value; if(!Number.isInteger(datoEntero)){ error = { ...error, tipo_entero: 'Se requiere valor entero' }; } return error; } private formatoNit(control: AbstractControl){ let error = null; var nit = control.value; var cadenaNit = nit.toString(); if(cadenaNit.length != 10){ // error = { ...error, formato_nit: 'El nit ingresado no cumple con el formato XXXXXXXXXY' }; error = { ...error, formato_nit: 'El nit ingresado no cumple con el formato, Debe tener 10 digitos' }; } return error; } private esPasado(control: AbstractControl){ let error = null; var fecha_inicio = control.value; const today = new Date().toISOString().substring(0, 10); if(today <= fecha_inicio){ error = { ...error, ingreso: 'La fecha de ingreso debe ser posterior al dia de hoy' }; } return error; } public getError(controlName: string): string { let error = ''; const control = this.formularioConsulta.get(controlName); if (control.touched && control.errors != null) { console.log(control.errors); if (control.errors.required) { error = 'Campo requerido'; } else if (control.errors.ingreso) { error = control.errors.ingreso; } else if (control.errors.max) { error = 'El salario debe ser menor a 100.000.000'; } else if (control.errors.min) { error = 'El salario debe ser un valor positivo'; } else if (control.errors.tipo_entero) { error = control.errors.tipo_entero; } else if (control.errors.formato_nit) { error = control.errors.formato_nit; } else { error = error + 'error sin conocer'; } } return error; } private convertirStringAArreglo(cadena: string){ var digito = new Array(cadena.length); for(var i=0; i<cadena.length; i++){ digito[i] = cadena.charAt(i); } return digito; } }
c50dcdfafb45e8024303aea9ff7e84015c9d41cf
TypeScript
Ch4mpl00/typescript-and-express
/src/app/user/useCases/authorizeUserByEmailAndPasswordUserCase.ts
2.53125
3
import { Left, Right } from "monet" import { User } from "~/app/user/domain/entity/User" import { EmailAndPasswordDoNotMatch } from "~/app/user/domain/errors/emailAndPasswordDoNotMatch" import UserNotFoundError from "~/app/user/domain/errors/userNotFoundError" import Email from "~/app/user/domain/values/Email" import { userToView } from "~/app/user/infra/mapping/userToApiView" import { IUserRepository } from "~/app/user/infra/storage/types" import { ProceedWithResult } from "~/core/infra/types" export default ( userRepository: IUserRepository, checkPassword: (password: string) => (hash: string) => boolean, makeToken: (data: object) => string ) => (data: { email?: string, password?: string }) => (next: ProceedWithResult) => { const email = new Email(data.email ?? "") const tryLogin = (user: User) => (password: string) => (hash: string) => checkPassword(password)(hash) ? next(Right(userToView(user, makeToken(userToView(user))))) : next(Left(new EmailAndPasswordDoNotMatch())) email .map(email => userRepository.findOne({ email })) .map(async u => (await u) .map(user => { tryLogin(user)(data.password ?? "")(user.password.unsafeGetValue()) return user }) .orElseRun(() => next(Left(new UserNotFoundError()))) ) .leftMap(err => next(Left(err))) }
cf123b8d830779de929cb7b0a93613a1d62a879e
TypeScript
arzamax/json-editor-service
/client/lib/hooks/use-click-outside.ts
2.671875
3
import React, { useEffect, useRef } from 'react'; type CbType = () => void; export const useOnClickOutside = (refs: Array<React.RefObject<HTMLElement>>, cb: CbType) => { useEffect(() => { if (refs && Array.isArray(refs) && cb) { const handleMouseDown = (e: any) => { let isTarget = false; for (const ref of refs) { if (ref.current && ref.current.contains(e.target)) { isTarget = true; break; } } if (!isTarget) { cb(); } }; document.addEventListener('mousedown', handleMouseDown); return () => { document.removeEventListener('mousedown', handleMouseDown); }; } }, []); };
049eb6266d84ecd971e8121ce4b9bc56aca6f952
TypeScript
tiagolascasas/FEUP-ASSO
/src/view/renderer_svg.ts
2.796875
3
'use strict' import { Renderer } from './renderer' import { Shape, Rectangle, Circle, Triangle } from '../model/shape' export class SVGRenderer extends Renderer { objs = new Array<Shape>() factory = new SVGShapeRendererFactory() constructor(elementID: string) { super(elementID) this.element = <HTMLElement>document.getElementById(elementID) } drawObjects(): void { for (const layer of this.currLayers) { for (const shape of this.currObjects.get(layer)) { let renderableObject = this.factory.make(shape) switch (this.mode) { case 'Color': renderableObject = new SVGColorDecorator(renderableObject) break case 'Wireframe': renderableObject = new SVGWireframeDecorator(renderableObject) break case 'Gradient': renderableObject = new SVGGradientDecorator(renderableObject) break case 'None': default: break } const e = renderableObject.render() this.element.appendChild(e) } } } drawLine(x1: number, y1: number, x2: number, y2: number) { let newLine = document.createElementNS('http://www.w3.org/2000/svg', 'line') newLine.setAttribute('x1', x1.toString()) newLine.setAttribute('y1', y1.toString()) newLine.setAttribute('x2', x2.toString()) newLine.setAttribute('y2', y2.toString()) newLine.setAttribute('stroke', this.GRID_COLOR) this.element.appendChild(newLine) } clearCanvas(): void { this.element.innerHTML = '' } init(): void { const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs') const gradient = <SVGLinearGradientElement>( document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient') ) const stop1 = <SVGStopElement>document.createElementNS('http://www.w3.org/2000/svg', 'stop') const stop2 = <SVGStopElement>document.createElementNS('http://www.w3.org/2000/svg', 'stop') stop1.setAttribute('offset', '0%') stop1.setAttribute('stop-color', '#000000') stop1.setAttribute('stop-opacity', '1') stop2.setAttribute('offset', '100%') stop2.setAttribute('stop-color', '#FFFFFF') stop2.setAttribute('stop-opacity', '1') gradient.appendChild(stop1) gradient.appendChild(stop2) gradient.setAttribute('id', 'linear') gradient.setAttribute('x1', '0%') gradient.setAttribute('y1', '50%') gradient.setAttribute('x2', '100%') gradient.setAttribute('y2', '50%') defs.appendChild(gradient) this.element.appendChild(defs) } applyZoom(): void { const zoomX = Number(this.element.getAttribute("width")) * (1 / this.zoom) const zoomY = Number(this.element.getAttribute("height")) * (1 / this.zoom) const viewBox = "0 0 " + zoomX + " " + zoomY this.element.setAttribute("viewBox", viewBox) } finish(): void {} } abstract class SVGShapeRenderer { constructor(public shape: Shape) {} abstract render(): SVGElement } class SVGShapeRendererFactory { make(shape: Shape): SVGShapeRenderer { if (shape instanceof Rectangle) return new SVGRectangleRenderer(shape) if (shape instanceof Circle) return new SVGCircleRenderer(shape) if (shape instanceof Triangle) return new SVGTriangleRenderer(shape) else return new SVGNullRenderer(shape) } } class SVGNullRenderer extends SVGShapeRenderer { constructor(shape: Shape) { super(shape) } render(): SVGElement { return document.createElementNS('http://www.w3.org/2000/svg', 'g') } } class SVGColorDecorator extends SVGShapeRenderer { constructor(public obj: SVGShapeRenderer) { super(obj.shape) } render(): SVGElement { let e = this.obj.render() if (e.tagName == 'g') { let realElement = <SVGElement>e.firstElementChild realElement.setAttribute('style', `stroke: black; fill: ${this.shape.color}`) realElement.setAttribute('fill-opacity', '1.0') } else { e.setAttribute('style', `stroke: black; fill: ${this.shape.color}`) e.setAttribute('fill-opacity', '1.0') } return e } } class SVGWireframeDecorator extends SVGShapeRenderer { constructor(public obj: SVGShapeRenderer) { super(obj.shape) } render(): SVGElement { let e = this.obj.render() if (e.tagName == 'g') { let realElement = <SVGElement>e.firstElementChild e.setAttribute('style', `stroke: black; fill: #FFFFFF`) realElement.setAttribute('fill-opacity', '0.0') } else { e.setAttribute('style', `stroke: black; fill: #FFFFFF`) e.setAttribute('fill-opacity', '0.0') } return e } } class SVGGradientDecorator extends SVGShapeRenderer { constructor(public obj: SVGShapeRenderer) { super(obj.shape) } render(): SVGElement { let e = this.obj.render() if (e.tagName == 'g') { let realElement = <SVGElement>e.firstElementChild realElement.setAttribute('style', `stroke: black; fill: url(#linear)`) e.setAttribute('fill-opacity', '1.0') } else { e.setAttribute('style', `stroke: black; fill: url(#linear)`) e.setAttribute('fill-opacity', '1.0') } return e } } class SVGRectangleRenderer extends SVGShapeRenderer { constructor(shape: Shape) { super(shape) } render(): SVGElement { const e = document.createElementNS('http://www.w3.org/2000/svg', 'rect') const g = document.createElementNS('http://www.w3.org/2000/svg', 'g') const shape = <Rectangle>this.shape g.setAttribute( 'transform', `translate(${shape.center.x}, ${shape.center.y}) rotate(${shape.angle})` ) e.setAttribute('width', shape.width.toString()) e.setAttribute('height', shape.height.toString()) e.setAttribute('x', (-shape.width / 2).toString()) e.setAttribute('y', (-shape.height / 2).toString()) g.appendChild(e) return g } } class SVGCircleRenderer extends SVGShapeRenderer { constructor(shape: Shape) { super(shape) } render(): SVGElement { const e = document.createElementNS('http://www.w3.org/2000/svg', 'ellipse') const g = document.createElementNS('http://www.w3.org/2000/svg', 'g') const shape = <Circle>this.shape g.setAttribute( 'transform', `translate(${shape.center.x}, ${shape.center.y}) rotate(${shape.angle})` ) e.setAttribute('cx', '0') e.setAttribute('cy', '0') e.setAttribute('rx', shape.rx.toString()) e.setAttribute('ry', shape.ry.toString()) g.appendChild(e) return g } } class SVGTriangleRenderer extends SVGShapeRenderer { render(): SVGElement { const e = document.createElementNS('http://www.w3.org/2000/svg', 'polygon') const g = document.createElementNS('http://www.w3.org/2000/svg', 'g') const shape = <Triangle>this.shape g.setAttribute( 'transform', `translate(${shape.center.x}, ${shape.center.y}) rotate(${shape.angle})` ) e.setAttribute( 'points', (shape.p0.x - shape.center.x)+ ',' + (shape.p0.y - shape.center.y) + ' ' + (shape.p1.x - shape.center.x)+ ',' + (shape.p1.y - shape.center.y) + ' ' + (shape.p2.x - shape.center.x)+ ',' + (shape.p2.y - shape.center.y) ) g.appendChild(e) return g } }
6cc99b785dc7cefdbb35a6bf0938bad9d9c50332
TypeScript
artnez/jsxstyle
/tests/meta.spec.ts
2.53125
3
import { getPackages } from '@lerna/project'; import fs = require('fs'); import packlist = require('npm-packlist'); import path = require('path'); // NOTE: this interface is incomplete // See: @lerna/package interface Package { name: string; location: string; private: boolean; toJSON: () => string; } const JSXSTYLE_ROOT = path.resolve(__dirname, '..'); describe('npm publish', () => { it('only publishes the intended files', async () => { const packages: Package[] = await getPackages(JSXSTYLE_ROOT); const packagePromises = packages // exclude private packages .filter(pkg => !pkg.private) .sort((a, b) => a.name.localeCompare(b.name)) .map(pkg => // fetch file list and format it into something packlist({ path: pkg.location }).then( fileList => ` ${pkg.name} ${pkg.name.replace(/./g, '=')} ${fileList.map(f => `- ${f}`).join('\n')} ` ) ); await expect(Promise.all(packagePromises)).resolves.toMatchSnapshot(); }); }); describe('yarn.lock', () => { it('does not contain Twitter-internal URLs', async () => { const lockfileContents = fs.readFileSync('../yarn.lock', 'utf8'); expect(lockfileContents.includes('twitter.biz')).toEqual(false); }); });
8a1e37459f86c81d678078f79e5cc7532aacc1dc
TypeScript
RoxnnyABarriosC/node-experience
/src/Shared/Presentation/Requests/Filter.ts
2.90625
3
import IFilter from './IFilter'; import { ParsedQs } from 'qs'; abstract class Filter implements IFilter { private readonly filters: Map<string, any>; constructor(query: ParsedQs) { this.filters = new Map<string, any>(); const queryFilters: any = query.filter ?? []; const defaultFilters: any = this.getDefaultFilters(); const keys = this.getFields(); defaultFilters.forEach((defaultFilter: any) => { const defaultKey: string = Object.keys(defaultFilter)[0]; const defaultValue: string = defaultFilter[defaultKey]; this.filters.set(defaultKey, defaultValue); }); const newFilters = Object.keys(queryFilters).map((key: string) => { const filter: Record<string, any> = query.filter as Record<string, any>; return { [key]: filter[key] }; }).filter((value => { const key = Object.keys(value)[0]; return keys.includes(key) ? value : false; })); newFilters.forEach((newFilter: any) => { const defaultKey: string = Object.keys(newFilter)[0]; const defaultValue: string = newFilter[defaultKey]; this.filters.set(defaultKey, defaultValue); }); } get(key: string): string { return this.filters.has(key) ? this.filters.get(key) : ''; } getArray(): any { return this.filters.entries(); } has(key: string): boolean { return this.filters.has(key); } isEmpty(): boolean { return this.filters.size === 0; } values(): Map<string, any> { return this.filters; } abstract getFields(): string[]; abstract getDefaultFilters(): any[]; } export default Filter;
c7eabdfecb750f130e7b9f73191bd6f637d8bf1a
TypeScript
sheetaljadam/UserManagement
/src/app/core/services/validation.service.ts
2.625
3
import {Injectable } from '@angular/core' import { FormGroup, FormControl } from '@angular/forms'; @Injectable() export class ValidationService { //Email validation validateEmail(c: FormControl){ let EMAIL_REGEXP = /^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i; return EMAIL_REGEXP.test(c.value) ? null : { validateEmail: { valid: false } }; } }
947d5473a3369b763f42f49003ce28ee5d8fdd68
TypeScript
ImranOpenFin/layouts-service
/src/client/tabbing.ts
2.765625
3
/** * @module Tabbing */ import {Identity} from 'hadouken-js-adapter'; import {tryServiceDispatch} from './connection'; import {AddTabPayload, getId, parseIdentity, SetTabstripPayload, TabAPI, UpdateTabPropertiesPayload} from './internal'; import {ApplicationUIConfig, TabAddedPayload, TabGroupEventPayload, TabProperties, TabPropertiesUpdatedPayload, WindowIdentity} from './types'; /** * Fired when a window has had its tab properties updated. See {@link addEventListener}. */ export interface TabPropertiesUpdatedEvent extends CustomEvent<TabPropertiesUpdatedPayload> { type: 'tab-properties-updated'; } /** * Fired when the window has become the active tab in a tabstrip. See {@link addEventListener}. */ export interface TabActivatedEvent extends CustomEvent<TabGroupEventPayload> { type: 'tab-activated'; } /** * Fired when the window has been removed from its tabstrip. See {@link addEventListener}. */ export interface TabRemovedEvent extends CustomEvent<TabGroupEventPayload> { type: 'tab-removed'; } /** * Fired when the window has been added to a tabstrip. See {@link addEventListener}. */ export interface TabAddedEvent extends CustomEvent<TabAddedPayload> { type: 'tab-added'; } /** * @hidden */ export interface EventMap { 'tab-added': TabAddedEvent; 'tab-removed': TabRemovedEvent; 'tab-activated': TabActivatedEvent; 'tab-properties-updated': TabPropertiesUpdatedEvent; } /** * Event fired whenever the current window is tabbed. This event is used when adding windows to both new and existing * tabsets. * * To find out which other windows are in the tabset, use the `getTabs()` method. * * ```ts * import {tabbing} from 'openfin-layouts'; * * tabbing.addEventListener('tab-added', async (event: TabAddedEvent) => { * console.log("Window added to tab group: ", event.detail.identity); * console.log("Windows in current group: ", await tabbing.getTabs()); * }); * ``` * * If a window is moved from one tab group to another, this will be messaged as a `tab-removed` event, followed by a `tab-added`. * * @type tab-added * @event */ export async function addEventListener(eventType: 'tab-added', listener: (event: TabAddedEvent) => void): Promise<void>; /** * Event fired whenever the current window is removed from it's previous tabset. * * To find out which other windows are in the tabset, use the `getTabs()` method. * * ```ts * import {tabbing} from 'openfin-layouts'; * * tabbing.addEventListener('tab-removed', async (event: TabRemovedEvent) => { * console.log("Window removed from tab group"); * }); * ``` * * If a window is moved from one tab group to another, this will be messaged as a `tab-removed` event, followed by a `tab-added`. * * @type tab-removed * @event */ export async function addEventListener(eventType: 'tab-removed', listener: (event: TabRemovedEvent) => void): Promise<void>; /** * Event fired whenever the active tab within a tab group is changed. * * ```ts * import {tabbing} from 'openfin-layouts'; * * tabbing.addEventListener('tab-activated', (event: TabActivatedEvent) => { * const activeTab = event.detail.tabID; * console.log("Active tab:", activeTab.uuid, activeTab.name); * }); * ``` * * @type tab-activated * @event */ export async function addEventListener(eventType: 'tab-activated', listener: (event: TabActivatedEvent) => void): Promise<void>; /** * Event fired whenever a windows tab properties are {@link updateTabProperties|updated}. * * The event will always contain the full properties of the tab, even if only a subset of them were updated. * * ```ts * import {tabbing} from 'openfin-layouts'; * * tabbing.addEventListener('tab-properties-updated', (event: TabPropertiesUpdatedEvent) => { * const tabID = event.detail.identity; * const properties = event.detail.properties; * console.log(`Properties for ${tabID.uuid}/${tabID.name} are:`, properties); * }); * ``` * * @type tab-properties-updated * @event */ export async function addEventListener(eventType: 'tab-properties-updated', listener: (event: TabPropertiesUpdatedEvent) => void): Promise<void>; export async function addEventListener<K extends keyof EventMap>(eventType: K, listener: (event: EventMap[K]) => void): Promise<void> { if (typeof fin === 'undefined') { throw new Error('fin is not defined. The openfin-layouts module is only intended for use in an OpenFin application.'); } // Use native js event system to pass internal events around. // Without this we would need to handle multiple registration ourselves. window.addEventListener(eventType, listener as EventListener); } /** * Returns array of window identity references for tabs belonging to the tab group of the provided window context. * * If no `Identity` is provided as an argument, the current window context will be used. * * If there is no tab group associated with the window context, will resolve to null. * ```ts * import {tabbing} from 'openfin-layouts'; * * // Gets all tabs for the current window context. * tabbing.getTabs(); * * // Get all tabs for another window context. * tabbing.getTabs({uuid: "sample-window-uuid", name: "sample-window-name"}); * ``` * * @param identity The window context, defaults to the current window. * @throws `Promise.reject`: If `identity` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. */ export async function getTabs(identity: Identity = getId()): Promise<WindowIdentity[]|null> { return tryServiceDispatch<Identity, WindowIdentity[]|null>(TabAPI.GETTABS, {name: identity.name, uuid: identity.uuid}); } /** * Creates the custom tabstrip + configuration for the entire application. An application cannot have different windows using different tabstrip UIs. * * ```ts * import {tabbing} from 'openfin-layouts'; * * tabbing.setTabstrip({url: 'https://localhost/customTabstrip.html', height: 60}); * ``` * * @param config The {@link ApplicationUIConfig| Application UI Configuration} object. * @throws `Promise.reject`: If `config` is not a valid {@link ApplicationUIConfig} * @throws `Promise.reject`: If `config.url` is not a valid URL/URI. */ export async function setTabstrip(config: ApplicationUIConfig): Promise<void> { if (!config || isNaN(config.height) || !config.url.length) { return Promise.reject('Invalid config provided'); } try { // tslint:disable-next-line:no-unused-expression We're only checking a valid URL was provided. No need to assign the resulting object. new URL(config.url); } catch (e) { return Promise.reject(e); } return tryServiceDispatch<SetTabstripPayload, void>(TabAPI.SETTABSTRIP, {id: getId(), config}); } /** * Given a set of windows, will create a tab group construct and UI around them. The bounds and positioning of the first (applicable) window in the set will be * * used as the seed for the tab UI properties. * * ```ts * import {tabbing} from 'openfin-layouts'; * * tabbing.createTabGroup([{uuid: "App1", name: "App1"}, {uuid: "App2", name: "App2"}, {uuid: "App3", name: "App3"}]); * ``` * * @param windows Array of windows which will be added to the new tab group. * @throws `Promise.reject`: If no windows is not an array or less than 2 windows were provided. */ export async function createTabGroup(windows: Identity[]): Promise<void> { return tryServiceDispatch<Identity[], void>(TabAPI.CREATETABGROUP, windows); } /** * Adds current window context (or window specified in second arg) to the tab group of the target window (first arg). * * The added tab will be brought into focus. * * ```ts * import {tabbing} from 'openfin-layouts'; * * // Tab self to App1. * tabbing.addTab({uuid: 'App1', name: 'App1'}); * * // Tab App2 to App1. * tabbing.addTab({uuid: 'App1', name: 'App1'}. {uuid: 'App2', name: 'App2'}); * ``` * * @param targetWindow The identity of the window to create a tab group on. * @param windowToAdd The identity of the window to add to the tab group. If no `Identity` is provided as an argument the current window context will be used. * @throws `Promise.reject`: If the {@link ApplicationUIConfig| App Config} does not match between the target and window to add. * @throws `Promise.reject`: If the `targetWindow` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. * @throws `Promise.reject`: If the `windowToAdd` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. * @throws `Promise.reject`: If `identity` is not an existing tab in a tabstrip. */ export async function addTab(targetWindow: Identity, windowToAdd: Identity = getId()): Promise<void> { return tryServiceDispatch<AddTabPayload, void>(TabAPI.ADDTAB, {targetWindow: parseIdentity(targetWindow), windowToAdd: parseIdentity(windowToAdd)}); } /** * Removes the specified window context from its tab group. * * ```ts * import {tabbing} from 'openfin-layouts'; * * // Remove the current context from its tab group. * tabbing.removeTab(); * * // Remove another window from its tab group. * tabbing.removeTab({uuid: 'App1', name: 'App1'}); * ``` * * @param identity Identity of the window context to remove. If no `Identity` is provided as an argument, the current window context will be used. * @throws `Promise.reject`: If `identity` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. * @throws `Promise.reject`: If `identity` is not an existing tab in a tabstrip. */ export async function removeTab(identity: Identity = getId()): Promise<void> { return tryServiceDispatch<Identity, void>(TabAPI.REMOVETAB, parseIdentity(identity)); } /** * Sets the window context as the active tab in its tab group. Active tabs are brought to the front of the tab group and shown. * * ```ts * import {tabbing} from 'openfin-layouts' * * // Sets the current window as active in the tab group. * tabbing.setActiveTab() * * // Sets another window context as the active tab. * tabbing.setActiveTab({uuid: 'App1', name: 'App1'}); * ``` * * @param identity Identity of the window context to set as active. If no `Identity` is provided as an argument the current window context will be used. * @throws `Promise.reject`: If `identity` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. * @throws `Promise.reject`: If `identity` is not an existing tab in a tabstrip. */ export async function setActiveTab(identity: Identity = getId()): Promise<void> { return tryServiceDispatch<Identity, void>(TabAPI.SETACTIVETAB, parseIdentity(identity)); } /** * Closes the tab for the window context and removes it from its associated tab group. * * ```ts * import {tabbing} from 'openfin-layouts'; * * // Closes the current window context tab. * tabbing.closeTab(); * * // Closes another windows context tab. * tabbing.closeTab({uuid: 'App1', name: 'App1'}); * ``` * * @param identity Identity of the window context to close. If no `Identity` is provided as an argument the current window context will be used. * @throws `Promise.reject`: If `identity` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. * @throws `Promise.reject`: If `identity` is not an existing tab in a tabstrip. */ export async function closeTab(identity: Identity = getId()): Promise<void> { return tryServiceDispatch<Identity, void>(TabAPI.CLOSETAB, parseIdentity(identity)); } /** * Minimizes the tab group for the window context. * * ```ts * import {tabbing} from 'openfin-layouts'; * * // Minimizes the tab group for the current window context. * tabbing.minimizeTabGroup(); * * // Minimizes the tab group for another windows context. * tabbing.minimizeTabGroup({uuid: 'App1', name: 'App1'}); * ``` * * @param identity Identity of the window context to minimize the tab group for. If no `Identity` is provided as an argument the current window context will be * used. * @throws `Promise.reject`: If `identity` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. * @throws `Promise.reject`: If `identity` is not an existing tab in a tabstrip. */ export async function minimizeTabGroup(identity: Identity = getId()): Promise<void> { return tryServiceDispatch<Identity, void>(TabAPI.MINIMIZETABGROUP, parseIdentity(identity)); } /** * Maximizes the tab group for the window context. * * ```ts * import {tabbing} from 'openfin-layouts'; * * // Minimizes the tab group for the current window context. * tabbing.maxmimizeTabGroup(); * * // Minimizes the tab group for another windows context. * tabbing.maximizeTabGroup({uuid: 'App1', name: 'App1'}); * ``` * * @param identity Identity of the window context to maximize the tab group for. If no `Identity` is provided as an argument the current window context will be * used. * @throws `Promise.reject`: If `identity` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. * @throws `Promise.reject`: If `identity` is not an existing tab in a tabstrip. */ export async function maximizeTabGroup(identity: Identity = getId()): Promise<void> { return tryServiceDispatch<Identity, void>(TabAPI.MAXIMIZETABGROUP, parseIdentity(identity)); } /** * Closes the tab group for the window context. * * ```ts * import {tabbing} from 'openfin-layouts'; * * // Closes the tab group for the current window context. * tabbing.closeTabGroup(); * * // Closes the tab group for another windows context. * tabbing.closeTabGroup({uuid: 'App1', name: 'App1'}); * ``` * * @param identity Identity of the window context to close the tab group for. If no `Identity` is provided as an argument the current window context will be * used. * @throws `Promise.reject`: If `identity` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. * @throws `Promise.reject`: If `identity` is not an existing tab in a tabstrip. */ export async function closeTabGroup(identity: Identity = getId()): Promise<void> { return tryServiceDispatch<Identity, void>(TabAPI.CLOSETABGROUP, parseIdentity(identity)); } /** * Restores the tab group for the window context to its normal state. * * ```ts * import {tabbing} from 'openfin-layouts'; * * // Restores the tab group for the current window context. * tabbing.restoreTabGroup(); * * // Restores the tab group for another windows context. * tabbing.restoreTabGroup({uuid: 'App1', name: 'App1'}); * ``` * * @param identity Identity of the window context to restore the tab group for. If no `Identity` is provided as an argument the current window context will be * used. * @throws `Promise.reject`: If `identity` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. * @throws `Promise.reject`: If `identity` is not an existing tab in a tabstrip. */ export async function restoreTabGroup(identity: Identity = getId()): Promise<void> { return tryServiceDispatch<Identity, void>(TabAPI.RESTORETABGROUP, parseIdentity(identity)); } /** * Updates a tab's Properties on the Tab strip. This includes the tabs title and icon. * * ```ts * import {tabbing} from 'openfin-layouts'; * * // Updating only some properties for the current window context. * tabbing.updateTabProperties({title: 'An Awesome Tab!'}); * * // Update all properties for the current window context. * tabbing.updateTabProperties({title: 'An Awesome Tab!', icon: 'http://openfin.co/favicon.ico'}); * * // Update properties for another windows context. * tabbing.updateTabProperties({title: 'An Awesome Tab'}, {uuid: 'App1', name: 'App1'}); * ``` * @param properties Properties object for the tab to consume. * @param identity Identity of the window context set the properties on. If no `Identity` is provided as an argument the current window context will be used. * @throws `Promise.reject`: If `identity` is not a valid {@link https://developer.openfin.co/docs/javascript/stable/global.html#Identity | Identity}. */ export async function updateTabProperties(properties: Partial<TabProperties>, identity: Identity = getId()): Promise<void> { return tryServiceDispatch<UpdateTabPropertiesPayload, void>(TabAPI.UPDATETABPROPERTIES, {window: parseIdentity(identity), properties}); }
8e08aa8e3868274118844e1c8b2821e7d8421a60
TypeScript
omeralper/sdnproject
/client/src/app/swagger/AAAPROTOCOL.ts
2.53125
3
//imports start AAAPROTOCOL import {IModelDef} from "./IModelDef"; //imports end 'use strict'; /** * AAA Sunucuları tarafından desteklenen protokol tipini belirten ENUM değeri.\nDeğerler şunlardır;\n\n| Adı | Açıklama |\n|:---------|:-------------------|\n| RADIUS | RADIUS Protokolü |\n| LDAP | LDAP Protokolü | */ export enum AAAPROTOCOL { RADIUS = <any>'RADIUS', LDAP = <any>'LDAP' } export var AAAPROTOCOLDef:IModelDef = { meta: { className: 'AAAPROTOCOL', isObject: false, isEnum: true, }, map: { RADIUS : 1, LDAP : 2 }, toString:()=>{ return 'AAAPROTOCOL'; } }
3078aa9f760520c190938b543439246637d2cf6e
TypeScript
celo-tipbot/celo-github-bot
/test/parse.test.ts
2.515625
3
import { parseGitHubComment } from '../src/parse' describe('Command parser', () => { test('parses a correct TIP command', () => { const comment = { user: { login: 'Alice123' }, body: '@celo-tipbot TIP @Bob456 10' } // @ts-ignore const command = parseGitHubComment(comment) expect(command).toEqual({ ok: true, result: { type: 'tip', sender: 'Alice123', receiver: 'Bob456', value: '10' } }) }) test('Fails on a TIP without username', () => { const comment = { user: { login: 'Alice123' }, body: '@celo-tipbot TIP 10' } // @ts-ignore const command = parseGitHubComment(comment) expect(command.ok).toBeFalsy() }) test('Fails on a TIP without value', () => { const comment = { user: { login: 'Alice123' }, body: '@celo-tipbot TIP @Bob456' } // @ts-ignore const command = parseGitHubComment(comment) expect(command.ok).toBeFalsy() }) test('parses a correct REGISTER command', () => { const comment = { user: { login: 'Alice123' }, body: '@celo-tipbot REGISTER 0x5234ae9f990acc920b9209867189eaaee78baf78' } // @ts-ignore const command = parseGitHubComment(comment) expect(command).toEqual({ ok: true, result: { type: 'register', sender: 'Alice123', address: '0x5234ae9f990acc920b9209867189eaaee78baf78' } }) }) test('fails on a REGISTER with malformed address', () => { const comment = { user: { login: 'Alice123' }, body: '@celo-tipbot REGISTER 0x5234ae9f990cc920b9209867189eaaee78baf78' } // @ts-ignore const command = parseGitHubComment(comment) expect(command.ok).toBeFalsy() }) test('Fails on an unknown command', () => { const comment = { user: { login: 'Alice123' }, body: '@celo-tipbot DOTHINGS 123' } // @ts-ignore const command = parseGitHubComment(comment) expect(command.ok).toBeFalsy() }) })
a133a53178896830b0ef5d6573c3a0d584640ff5
TypeScript
ucdavis/uccsc-mobile-functions
/functions/src/models/venue.ts
2.515625
3
export function mapVenueFromJsonApi(data) { if (!data) { return null; } const result = { title: data.title, building: data.field_venue_name, room: data.field_room_number_name, address: { street: '', city: '', state: '', postalCode: '', }, location: { lat: 0, lng: 0 } }; if (data.field_address) { result.address = { street: `${data.field_address.address_line1} ${data.field_address.address_line1}`.trim(), city: data.field_address.locality, state: data.field_address.administrative_area, postalCode: data.field_address.postal_code, }; } if (data.field_location) { result.location = { lat: data.field_location.lat, lng: data.field_location.lng, }; } return result; };
0bc9ac1e0deab9b814af9c2ee82186c08abb5701
TypeScript
RenateBrokelmann/b2c-api-react-example
/src/helpers/common/salutation.ts
2.640625
3
import { TSalutationVariant } from '@interfaces/customer'; import { salutationVariants } from '@constants/customer'; export const getSalutationToShow = (salutation: string): JSX.Element | string => { const salutationVariantData = salutationVariants.filter((item: TSalutationVariant) => (item.value === salutation)); return (salutationVariantData && salutationVariantData[0]) ? salutationVariantData[0].name : salutation; };
7f41dffdd929802613badfd4d967a5a1a0c04b1f
TypeScript
sanketughade/sankets-libraray-management-app
/src/app/books/books.service.ts
2.71875
3
import { EventEmitter,Injectable } from '@angular/core'; import { Book } from './books.model'; @Injectable() export class BooksService{ private books:Book[]= [ new Book(1,'Book 1','Author 1',100,'Publisher 1'), new Book(2,'Book 2','Author 2',200,'Publisher 2'), new Book(3,'Book 3','Author 3',300,'Publisher 3'), new Book(4,'Book 4','Author 4',400,'Publisher 4'), new Book(5,'Book 5','Author 5',500,'Publisher 5') ] arrayIndex!:number; bookAdded= new EventEmitter<Book[]>(); bookUpdate = new EventEmitter<Book>(); isBookUpdatedSuccessfully= new EventEmitter<boolean>(); areDeleteAndUpdateIconsDisabled= new EventEmitter<boolean>(); getBooks(){ return this.books.slice(); } deleteBook(id: number){ //index = a.findIndex(x => x.prop2 ==="yutu"); this.arrayIndex=this.books.findIndex(element => element.id === id); this.books.splice(this.arrayIndex,1); } addNewBook(book: Book){ this.books.push(book); } getSingleBook(id: number){ this.arrayIndex=this.books.findIndex(element => element.id === id); return this.books[this.arrayIndex]; } updateExistingBook(book: Book){ this.arrayIndex=this.books.findIndex(element => element.id === book.id); this.books[this.arrayIndex]=book; } }
c23773489cce1741abf860327e82ac16ac589c40
TypeScript
Eveble/typend
/src/validators/collection-including-validator.ts
2.984375
3
import { isPlainObject, get, isEmpty } from 'lodash'; import { diff } from 'deep-diff'; import { PatternValidator } from '../pattern-validator'; import { InvalidTypeError } from '../errors'; import { getResolvablePath } from '../helpers'; import { types } from '../types'; import { CollectionIncluding } from '../patterns/collection-including'; export class CollectionIncludingValidator extends PatternValidator implements types.PatternValidator { /** * Evaluates if validator can handle provided explicit pattern or implicit expectation. * @param expectation - Evaluated explicit `Pattern` instance or implicit expectation. * @returns Returns `true` if pattern is instance of `CollectionIncluding` or is plain `Object` validated in loose mode, else `false`. */ public canValidate( expectation: types.Expectation, isStrict?: boolean ): boolean { return ( expectation instanceof CollectionIncluding || (!isStrict && isPlainObject(expectation)) ); } /** * Validates if value matches an `Object` with expected keys and values matching * the given expectations. * The value may also contain other keys with arbitrary values not defined in * pattern(equivalent of Meteor's `Match.ObjectIncluding`). * @param value - Value that is validated against expectation. * @param collIncOrExpect - Explicit pattern as `CollectionIncluding` instance or implicit expectation as plain `Object` against which value is validated. * @param validator - Validator matching `Validator` interface. * @returns Returns `true` if value is matching explicit `CollectionIncluding` pattern or implicit expectation as plain object even with arbitrary keys, else throws. * @throws {InvalidTypeError} * Thrown if the value is not an object. * @throws {ValidationError} * Thrown if the value does not match properties. */ public validate( value: any, collIncOrExpect: CollectionIncluding | Record<keyof any, any>, validator: types.Validator ): boolean { if (!isPlainObject(value)) { throw new InvalidTypeError( 'Expected %s to be an Object', this.describe(value) ); } const differences = diff(collIncOrExpect, value); if (differences === undefined || isEmpty(differences)) { return true; } for (const difference of differences) { if ( difference === undefined || // Omit new entries, interfaces should allow arbitrary values difference.kind === 'N' || difference.path === undefined ) { continue; } // Ensure that each difference in object is validated against expectation from same path const diffPath = difference.path.join('.'); const key = getResolvablePath(diffPath, collIncOrExpect); const valueFromPath = get(value, key); const expectationFromPath = get(collIncOrExpect, key); try { validator.validate(valueFromPath, expectationFromPath); } catch (err) { const stringifiedValue = this.describe(value); if ( err.message.includes('Unexpected key') || err.message.includes('to be a undefined') ) { continue; } else { throw new err.constructor( `(Key '${key}': ${err.message} in ${stringifiedValue})` ); } } } return true; } }
bc2640a625b3c368412f233a2d1b86990ab0b435
TypeScript
Amolmore456/reactive-ng
/src/app/products/store/reducers/card.reducer.ts
2.671875
3
import * as fromCardAction from '../action/card.action'; import { Card } from '../../models/card.model'; import { reduce } from 'rxjs/operators'; export interface CardState { entities:{[id:number]:Card}, loading:boolean, loaded:boolean } export const initialState:CardState = { entities:{}, loaded:false, loading:false } export function reducer(state = initialState, action:fromCardAction.CardAction) { switch(action.type) { case fromCardAction.ADD_CARD: { return { ...state, loading:true } } case fromCardAction.ADD_CARD_SUCCESS: { console.log(action.payload) return { ...state, loaded:true, loading:false } } case fromCardAction.ADD_CARD_FAIL: { console.log(action.payload) return { ...state, loaded:false, loading:false} } default: { return state } } } export const getCardDetails = (state:CardState) => state.entities; export const getCardLoading = (state:CardState) => state.loading; export const getCardLoaded = (state:CardState) => state.loaded;
478dcbaa9dfa1f7a946fc592bb58b7a1526c6122
TypeScript
gzuidhof/zarr.js
/src/nestedArray/ops.ts
3.234375
3
import { ArraySelection, SliceIndices } from '../core/types'; import { ValueError } from '../errors'; import { TypedArray, TypedArrayConstructor, NestedArrayData, NDNestedArrayData } from './types'; import { normalizeArraySelection, selectionToSliceIndices } from '../core/indexing'; /** * Digs down into the dimensions of given array to find the TypedArray and returns its constructor. * Better to use sparingly. */ export function getNestedArrayConstructor<T extends TypedArray>(arr: any): TypedArrayConstructor<T> { // TODO fix typing // tslint:disable-next-line: strict-type-predicates if ((arr as TypedArray).byteLength !== undefined) { return (arr).constructor; } return getNestedArrayConstructor(arr[0]); } /** * Returns both the slice result and new output shape * @param arr NestedArray to slice * @param shape The shape of the NestedArray * @param selection */ export function sliceNestedArray(arr: NestedArrayData, shape: number[], selection: number | ArraySelection): [NestedArrayData | number, number[]] { // This translates "...", ":", null into a list of slices or integer selections const normalizedSelection = normalizeArraySelection(selection, shape); const [sliceIndices, outShape] = selectionToSliceIndices(normalizedSelection, shape); const outArray = _sliceNestedArray(arr, shape, sliceIndices); return [outArray, outShape]; } function _sliceNestedArray<T extends TypedArray>(arr: NestedArrayData, shape: number[], selection: (SliceIndices | number)[]): NestedArrayData | number { const currentSlice = selection[0]; // Is this necessary? // // This is possible when a slice list is passed shorter than the amount of dimensions // // tslint:disable-next-line: strict-type-predicates // if (currentSlice === undefined) { // return arr.slice(); // } // When a number is passed that dimension is squeezed if (typeof currentSlice === "number") { // Assume already normalized integer selection here. if (shape.length === 1) { return arr[currentSlice]; } else { return _sliceNestedArray(arr[currentSlice] as NestedArrayData, shape.slice(1), selection.slice(1)); } } const [from, to, step, outputSize] = currentSlice; if (outputSize === 0) { return new (getNestedArrayConstructor(arr))(0); } if (shape.length === 1) { if (step === 1) { return (arr as TypedArray).slice(from, to); } const newArrData = new (arr.constructor as TypedArrayConstructor<T>)(outputSize); for (let i = 0; i < outputSize; i++) { newArrData[i] = (arr as TypedArray)[from + i * step]; } return newArrData; } let newArr = new Array(outputSize); for (let i = 0; i < outputSize; i++) { newArr[i] = _sliceNestedArray(arr[from + i * step] as NestedArrayData, shape.slice(1), selection.slice(1)); } // This is necessary to ensure that the return value is a NestedArray if the last dimension is squeezed // e.g. shape [2,1] with slice [:, 0] would otherwise result in a list of numbers instead of a valid NestedArray if (outputSize > 0 && typeof newArr[0] === "number") { const typedArrayConstructor = (arr[0] as TypedArray).constructor; newArr = (typedArrayConstructor as any).from(newArr); } return newArr; } export function setNestedArrayToScalar(dstArr: NestedArrayData, value: number, destShape: number[], selection: number | ArraySelection) { // This translates "...", ":", null, etc into a list of slices. const normalizedSelection = normalizeArraySelection(selection, destShape, true); // Above we force the results to be SliceIndicesIndices only, without integer selections making this cast is safe. const [sliceIndices, _outShape] = selectionToSliceIndices(normalizedSelection, destShape) as [SliceIndices[], number[]]; _setNestedArrayToScalar(dstArr, value, destShape, sliceIndices); } export function setNestedArray(dstArr: NestedArrayData, sourceArr: NestedArrayData, destShape: number[], sourceShape: number[], selection: number | ArraySelection) { // This translates "...", ":", null, etc into a list of slices. const normalizedSelection = normalizeArraySelection(selection, destShape, false); const [sliceIndices, outShape] = selectionToSliceIndices(normalizedSelection, destShape); // TODO: replace with non stringify equality check if (JSON.stringify(outShape) !== JSON.stringify(sourceShape)) { throw new ValueError(`Shape mismatch in target and source NestedArray: ${outShape} and ${sourceShape}`); } _setNestedArray(dstArr, sourceArr, destShape, sliceIndices); } function _setNestedArray(dstArr: NestedArrayData, sourceArr: NestedArrayData | number, shape: number[], selection: (SliceIndices | number)[]) { const currentSlice = selection[0]; if (typeof sourceArr === "number") { _setNestedArrayToScalar(dstArr, sourceArr, shape, selection.map(x => typeof x === "number" ? [x, x + 1, 1, 1] : x)); return; } // This dimension is squeezed. if (typeof currentSlice === "number") { _setNestedArray((dstArr as NDNestedArrayData)[currentSlice], sourceArr, shape.slice(1), selection.slice(1)); return; } const [from, _to, step, outputSize] = currentSlice; if (shape.length === 1) { if (step === 1) { (dstArr as TypedArray).set(sourceArr as TypedArray, from); } else { for (let i = 0; i < outputSize; i++) { dstArr[from + i * step] = (sourceArr)[i]; } } return; } for (let i = 0; i < outputSize; i++) { _setNestedArray((dstArr as NDNestedArrayData)[from + i * step], (sourceArr as NDNestedArrayData)[i], shape.slice(1), selection.slice(1)); } } function _setNestedArrayToScalar(dstArr: NestedArrayData, value: number, shape: number[], selection: SliceIndices[]) { const currentSlice = selection[0]; const [from, to, step, outputSize] = currentSlice; if (shape.length === 1) { if (step === 1) { (dstArr as TypedArray).fill(value, from, to); } else { for (let i = 0; i < outputSize; i++) { dstArr[from + i * step] = value; } } return; } for (let i = 0; i < outputSize; i++) { _setNestedArrayToScalar((dstArr as NDNestedArrayData)[from + i * step], value, shape.slice(1), selection.slice(1)); } } export function flattenNestedArray(arr: NestedArrayData, shape: number[], constr?: TypedArrayConstructor<TypedArray>): TypedArray { if (constr === undefined) { constr = getNestedArrayConstructor(arr); } const size = shape.reduce((x, y) => x * y, 1); const outArr = new constr(size); _flattenNestedArray(arr, shape, outArr, 0); return outArr; } function _flattenNestedArray(arr: NestedArrayData, shape: number[], outArr: TypedArray, offset: number) { if (shape.length === 1) { // This is only ever reached if called with rank 1 shape, never reached through recursion. // We just slice set the array directly from one level above to save some function calls. outArr.set((arr as TypedArray), offset); return; } if (shape.length === 2) { for (let i = 0; i < shape[0]; i++) { outArr.set((arr as TypedArray[])[i], offset + shape[1] * i); } return arr; } const nextShape = shape.slice(1); // Small optimization possible here: this can be precomputed for different levels of depth and passed on. const mult = nextShape.reduce((x, y) => x * y, 1); for (let i = 0; i < shape[0]; i++) { _flattenNestedArray((arr as NDNestedArrayData)[i], nextShape, outArr, offset + mult * i); } return arr; }
4a9ab65b4c2b3dc065f7ae44038008d223199341
TypeScript
exaptis/ngrx-rest-app
/client/src/models/FacetModel.ts
3.015625
3
export interface IFacetModel { id: number; name: string; } export default class FacetModel implements IFacetModel { id: number; name: string; constructor(name: string) { this.id = Math.ceil(Math.random() * 100); this.name = name; } getReadableText(): string { return `${this.id} - ${this.name}`; } }
95e63bb14b54887f8898bd50236db5b3b4ed3866
TypeScript
tswordyao/babel-plugin-define-wrap-imports
/source/index.ts
2.6875
3
import * as babel from 'babel-core'; import * as t from 'babel-types'; import { NodePath,default as traverse,} from 'babel-traverse'; const nejDefineMark = '_nej_defined_'; function addNejDefineMarkOnlyOnce(identifier){ if(!identifier.name.includes(nejDefineMark)){ identifier.name += nejDefineMark } } function isNejDefineCalleeExp(expression) { var callee; if( t.isCallExpression(expression) ){ callee = expression.callee; } return t.isMemberExpression(callee) && // 对象是标识符 t.isIdentifier(callee.object) && // 标识符是NEJ callee.object.name === 'NEJ' && // 对象属性也是标识符 t.isIdentifier(callee.property) && // 标识符是define callee.property.name === 'define'; } export default function (): babel.PluginObj { var programPath: NodePath; return { visitor: { // 获取下路径 Program(path: NodePath) { programPath = path; }, // 编译前整个代码是一个top立即执行函数 CallExpression:{ enter(path){ // 节点 const node = path.node as t.CallExpression; // 函数调用 let callee = node.callee; let isIIFE = t.isFunctionExpression(callee); let importsCodes:t.Statement[];//, importsCodesDecs,defineCodes,defineCodesDecs; let defineCalleeExp; // 第一个IIFE if(isIIFE){ importsCodes = []; callee = callee as t.FunctionExpression; //获取代码 let codes = callee.body.body; codes.forEach((it:t.Statement)=>{ if (t.isExpressionStatement(it) && isNejDefineCalleeExp(it.expression)) { defineCalleeExp = it.expression; } else{ importsCodes.push(it) } }); if(!defineCalleeExp){ return console.log('no defineCallee'); } let defineDps = defineCalleeExp.arguments[0]; let defineCb:t.FunctionExpression = defineCalleeExp.arguments[1]; let defineParams = defineCb.params.map((it:t.Identifier)=>it.name); // let defineCodes = defineCb.body.body; let declaresInNej = []; // 先把声明的标识符登记好 traverse(defineCb.body,{ // 避免变量声明重复 VariableDeclarator:(varPath:NodePath)=>{ var varDec = varPath.node as t.VariableDeclarator; var identifier = varDec.id as t.Identifier; declaresInNej.push(identifier.name); }, // 避免函数声明重复 FunctionDeclaration:(funcPath:NodePath)=>{ var funDec = funcPath.node as t.FunctionDeclaration; var identifier = funDec.id as t.Identifier declaresInNej.push(identifier.name); }, },path.scope,path); // importCodes中变量可能会被define中用到, 而define中变量不会被importCodes用到 // 将nej.define参数和内部变量rename为uid或打上token traverse(defineCb.body,{ //作为[属性调用的第一个标识符] MemberExpression: function(mPath){ var memberExp = mPath.node; if(t.isIdentifier(memberExp.object)){ let identifier = memberExp.object as t.Identifier; if(defineParams.includes(identifier.name) || declaresInNej.includes(identifier.name)){ addNejDefineMarkOnlyOnce(identifier); } } }, // 作为[独立标识符]使用的 Identifier: function (iPath) { var identifier = iPath.node; if(defineParams.includes(identifier.name) || declaresInNej.includes(identifier.name)){ let isInMember = t.isMemberExpression(iPath.parent); // a.b.c let isInObjectProp = t.isObjectProperty(iPath.parentPath.node); // obj = {a:c, b:d} if(!isInMember){ addNejDefineMarkOnlyOnce(identifier); } // 直接标识符 if (!isInMember && !isInObjectProp) { addNejDefineMarkOnlyOnce(identifier); } // 对象中的属性标识符(作为属性key是不转的, 作为属性value是要转的) if(isInObjectProp && (iPath.parentPath.node as t.ObjectProperty).key != identifier){ addNejDefineMarkOnlyOnce(identifier); } } } },path.scope,path); // 作为形参定义的 defineParams.forEach((name:string,i:number)=>{ // if(path.scope.hasBinding(name)){ (defineCb.params[i] as t.Identifier).name += nejDefineMark; // } }); let newMemberExpression = { type:'MemberExpression', object:{ type:'Identifier', name:'NEJ' }, property:{ type:'Identifier', name:'define' } }; let newBlockStatement = t.blockStatement([ ...importsCodes, ...defineCb.body.body ]); let _arguments:Array<t.Expression|t.SpreadElement>= [ defineDps, t.functionExpression( null, defineCb.params as t.LVal[], newBlockStatement ) ]; let newCallExpression = t.callExpression( newMemberExpression as t.MemberExpression, _arguments ) let newAst = t.program([ t.expressionStatement(newCallExpression) ]); // 替换为新的ast programPath.replaceWith(newAst); // 终止 path.stop(); } } } } }; }
1cf42376d39b16d557f8fe4a7299ae1f4e4dcbfb
TypeScript
vercel-support/dokkie
/src/utils/assets.ts
2.515625
3
import { ISettings, IFile } from "../types"; const { readFile, writeFile, mkdir, stat } = require("fs").promises; import { join, basename, dirname } from "path"; import { download, createFolder, asyncForEach } from "./"; import * as log from "cli-block"; const downloadImage = async ( image: string, settings: ISettings ): Promise<void> => { try { let imageFile = ""; const filePath = join( process.cwd(), settings.output, "img", basename(image) ); await createFolder(dirname(filePath)); if (image.includes("http")) { await download(image, filePath).then(async () => { if (settings.logging.includes("debug")) { const stats = await stat(filePath); log.BLOCK_SETTINGS(stats); } }); } else { imageFile = await readFile(image).then((r: any): string => r.toString()); await writeFile(filePath, imageFile).then(async () => { if (settings.logging.includes("debug")) { const stats = await stat(filePath); log.BLOCK_SETTINGS(stats); } }); } } catch (err) { throw Error(err); } }; export const downloadAssets = async ( settings: ISettings ): Promise<ISettings> => { // Get images from content const contentImages = []; const imageRegex = new RegExp('<img src="(.*?)"[^>]+>'); if (!settings.skip.includes("download")) try { settings.files.forEach((file: IFile, index: number) => { const images = file.html.match(imageRegex); if (images) images.forEach((img) => { if (!img.includes("<img")) contentImages.push({ fileIdx: index, image: img, }); }); }); } catch (err) { throw Error(err); } // If there arent any image. Do nothing. if (!settings.assets && contentImages.length < 1) return settings; !settings.logging.includes("silent") && log.BLOCK_MID("Assets"); await createFolder(join(settings.output, "/img")); // Process Assets if (settings.assets?.logo) try { await downloadImage(settings.assets.logo, settings).then(() => { const filename = "/img/" + basename(settings.assets.logo); settings.assets.logo = filename; !settings.logging.includes("silent") && log.BLOCK_LINE_SUCCESS(filename); }); } catch (err) { throw Error(err); } // Process Content images function filenameFromUrl(str: string): string { return str.split("/")[str.split("/").length - 1]; } if (contentImages && !settings.skip.includes("download")) try { await asyncForEach(contentImages, async (img) => { await downloadImage(img.image, settings).then(() => { const filename = `${settings.url}/img/${filenameFromUrl(img.image)}`; settings.files[img.fileIdx].html = settings.files[ img.fileIdx ].html.replace(img.image, filename); !settings.logging.includes("silent") && log.BLOCK_LINE_SUCCESS(filename); }); }); } catch (err) { !settings.logging.includes("silent") && log.BLOCK_LINE_ERROR( `Couldn\'t download ${err.message.match(/'([^']+)'/)[1]}` ); } return settings; };
d8fb94c4adb1707404d6ba8000fc40d1bdccf1cb
TypeScript
sangonz193/openfing-web
/src/hooks/useObservableStates.ts
2.734375
3
import { useObservableState } from "observable-hooks" import React from "react" import type { Observable } from "rxjs" export const useObservableStates = <TStore extends {}, TKeys extends keyof TStore>( store: TStore, keys: TKeys[] ): { [K in TKeys]: TStore[K] extends Observable<infer TValue> ? TValue : never } => { const result: { [K in keyof typeof store]: (typeof store)[K] extends Observable<infer TValue> ? TValue : never } = {} as any const values = keys.map((key) => { const observable = store[key] const value = useObservableState(observable as any, (observable as any).getValue()) result[key] = value as any return value }) return React.useMemo(() => result, values) }
fb5e46b1d6cf98d4fd53c8b1fbae0b143b5a2ea6
TypeScript
bescione/jhipster-angular-typescript
/src/main/webapp/ts-app/app/commons/subscriptions.service.ts
2.578125
3
/** * Created by mmasuyama on 10/22/2015. */ module Onesnap { export interface IStreamService { setStream(streamKey: string, stream: any) getStream(streamKey: string) getStreams() } export class StreamsService implements IStreamService{ private streams = {}; private generalListeners = []; /** @ngInject */ constructor() {} public defaultEvents = {'COLLECTION_LOADED' : 'cloaded', 'COLLECTION_OBJECT_REMOVED': 'coremoved', 'OBJECT_CREATE' : 'ocreated', 'OBJECT_LOAD': 'oloaded', 'OBJECT_UPDATE': 'oupdated', 'OBJECT_DELETE': 'odeleted'}; setStream (streamKey: string, stream: any) { if(!this.streams[streamKey]) { this.streams[streamKey] = stream; this.generalListeners.forEach(function(listener) { listener.onNext(stream); }); } } setGeneralListener(thread: any) { this.generalListeners.push(thread); } getGeneralListener () { } getStream (streamKey: string) { if(!this.streams[streamKey]) { this.setStream(streamKey, new Rx.Subject<{}>()) }; return this.streams[streamKey] } getStreams() { return this.streams; } } angular.module('springTestApp') .service('StreamsService', StreamsService) }
27a7f74433e1f4194f3f7474912c9f59c8616a07
TypeScript
Zackwn/clean-architecture-api
/src/repositories/external/mongodb/user/mongodb-user-repository.ts
2.765625
3
import { UserData } from "../../../../entities/user/user-data"; import { Either, left, right } from "../../../../shared/either"; import { UpdateUserData, UserRepository } from "../../../../usecases/ports/user-repository"; import { UserAlredyExistsError } from "../../../errors/user/user-alredy-exists"; import { UserDoNotExistsError } from "../../../errors/user/user-do-not-exists"; import { MongoHelper } from "../helpers/mongo-helper"; export class MongoDBUserRepository implements UserRepository { public constructor() { } public async findByEmail(email: string): Promise<Either<UserDoNotExistsError, UserData>> { const userCollection = MongoHelper.getCollection('user') const result = await userCollection.findOne({ email }) if (!result) { return left(new UserDoNotExistsError(email)) } return right(result as UserData) } public async findById(id: string): Promise<Either<UserDoNotExistsError, UserData>> { const userCollection = MongoHelper.getCollection('user') const result = await userCollection.findOne({ id }) if (!result) { return left(new UserDoNotExistsError(id)) } return right(result as UserData) } public async exists(email: string): Promise<boolean> { return (await this.findByEmail(email)).isRight() } public async updateUser(id: string, updatedUserData: UpdateUserData): Promise<Either<UserDoNotExistsError, UserData>> { const userOrError = await this.findById(id) if (userOrError.isLeft()) { return left(userOrError.value) } const userCollection = MongoHelper.getCollection('user') const result = await userCollection.findOneAndUpdate({ id }, { $set: updatedUserData }, { returnOriginal: false }) return right(result.value as UserData) } public async save(userData: UserData): Promise<Either<UserAlredyExistsError, UserData>> { if (await this.exists(userData.email)) { return left(new UserAlredyExistsError(userData.email)) } const userCollection = MongoHelper.getCollection('user') await userCollection.insertOne(userData) return right(userData) } }
900233add14785c4baeb76fb36f765baeb9ed987
TypeScript
FrederikKristensen/3Website
/src/js/index.ts
2.734375
3
import axios, { AxiosResponse, AxiosError } from "../../node_modules/axios/index" interface ICoronaTest { testId: number machineName: string temperature: number location: string date: string time: string } let baseUrl: string = "https://coronatest.azurewebsites.net/api/CoronaTests" new Vue({ // TypeScript compiler complains about Vue because the CDN link to Vue is in the html file. // Before the application runs this TypeScript file will be compiled into bundle.js // which is included at the bottom of the html file. el: "#app", data: { tests: [], idToGetBy: 1, singleTest: null, temp: [], highTemp: [] }, methods: { getAllTests() { this.helperGetAndShow(baseUrl, "all") }, // helperGetAndSho(url: string) { // axios.get<ICoronaTest[]>(url) // .then((response: AxiosResponse<ICoronaTest[]>) => { // this.tests = response.data // }) // .catch((error: AxiosError) => { // //this.message = error.message // alert(error.message) // https://www.w3schools.com/js/js_popup.asp // }) // }, helperGetAndShow(url: string, type: string) { axios.get<ICoronaTest[]>(url) .then((response: AxiosResponse<ICoronaTest[]>) => { if (type == "all") this.tests = response.data else this.highTemp = response.data }) .catch((error: AxiosError) => { //this.message = error.message alert(error.message) }) }, getById(id: number) { let url: string = baseUrl + "/" + id axios.get<ICoronaTest>(url) .then((response: AxiosResponse<ICoronaTest>) => { this.singleTest = response.data }) .catch((error: AxiosError) => { //this.message = error.message alert(error.message) // https://www.w3schools.com/js/js_popup.asp }) }, getAllWithHighTemperature() { let url = baseUrl + "/temperature" this.helperGetAndShow(url) } } })
752e49f0b1d9db2472ab0b35f6fbd7e852585678
TypeScript
lcolyott/react-hocs
/src/api/index.ts
2.90625
3
/** * Mocks an async call to inject a script * @returns string */ async function fetchScriptsAsync(): Promise<string | undefined> { var scriptToInject: string | undefined = "InjectedScript"; let promise = new Promise<string | undefined>((resolve, reject) => { setTimeout(() => { resolve(scriptToInject); }, 5000); }); return await promise; }; export { fetchScriptsAsync };
e9faeda26344d006baede343ad07a8aa53307fe3
TypeScript
origin1tech/colurs
/dist/interfaces.d.ts
2.734375
3
export interface IColursChain extends IColursStyle { (): boolean; (str: any, ...args: any[]): any; } export interface IColursStyle { reset?: IColursChain; bold?: IColursChain; dim?: IColursChain; italic?: IColursChain; underline?: IColursChain; inverse?: IColursChain; hidden?: IColursChain; strikethrough?: IColursChain; black?: IColursChain; red?: IColursChain; green?: IColursChain; yellow?: IColursChain; blue?: IColursChain; magenta?: IColursChain; cyan?: IColursChain; white?: IColursChain; gray?: IColursChain; grey?: IColursChain; bgBlack?: IColursChain; bgRed?: IColursChain; bgGreen?: IColursChain; bgYellow?: IColursChain; bgBlue?: IColursChain; bgMagenta?: IColursChain; bgCyan?: IColursChain; bgWhite?: IColursChain; bgGray?: IColursChain; bgGrey?: IColursChain; blackBright?: IColursChain; redBright?: IColursChain; greenBright?: IColursChain; yellowBright?: IColursChain; blueBright?: IColursChain; magentaBright?: IColursChain; cyanBright?: IColursChain; whiteBright?: IColursChain; bgBlackBright?: IColursChain; bgRedBright?: IColursChain; bgGreenBright?: IColursChain; bgYellowBright?: IColursChain; bgBlueBright?: IColursChain; bgMagentaBright?: IColursChain; bgCyanBright?: IColursChain; bgWhiteBright?: IColursChain; } export declare type AnsiTuple = number[]; export interface IAnsiStyles { reset?: AnsiTuple; bold?: AnsiTuple; italic?: AnsiTuple; underline?: AnsiTuple; inverse?: AnsiTuple; dim?: AnsiTuple; hidden?: AnsiTuple; strikethrough?: AnsiTuple; black?: AnsiTuple; red?: AnsiTuple; green?: AnsiTuple; yellow?: AnsiTuple; blue?: AnsiTuple; magenta?: AnsiTuple; cyan?: AnsiTuple; white?: AnsiTuple; grey?: AnsiTuple; gray?: AnsiTuple; bgBlack?: AnsiTuple; bgRed?: AnsiTuple; bgGreen?: AnsiTuple; bgYellow?: AnsiTuple; bgBlue?: AnsiTuple; bgMagenta?: AnsiTuple; bgCyan?: AnsiTuple; bgWhite?: AnsiTuple; bgGray?: AnsiTuple; bgGrey?: AnsiTuple; redBright: AnsiTuple; greenBright: AnsiTuple; yellowBright: AnsiTuple; blueBright: AnsiTuple; magentaBright: AnsiTuple; cyanBright: AnsiTuple; whiteBright: AnsiTuple; bgBlackBright?: AnsiTuple; bgRedBright?: AnsiTuple; bgGreenBright?: AnsiTuple; bgYellowBright?: AnsiTuple; bgBlueBright?: AnsiTuple; bgMagentaBright?: AnsiTuple; bgCyanBright?: AnsiTuple; bgWhiteBright?: AnsiTuple; } export interface ICssStyles { bold?: string; italic?: string; underline?: string; dim?: string; hidden?: string; strikethrough?: string; black?: string; red?: string; green?: string; yellow?: string; blue?: string; magenta?: string; cyan?: string; white?: string; grey?: string; gray?: string; bgBlack?: string; bgRed?: string; bgGreen?: string; bgYellow?: string; bgBlue?: string; bgMagenta?: string; bgCyan?: string; bgWhite?: string; bgGray?: string; bgGrey?: string; blackBright: string; redBright: string; greenBright: string; yellowBright: string; blueBright: string; magentaBright: string; cyanBright: string; whiteBright: string; bgBlackBright?: string; bgRedBright?: string; bgGreenBright?: string; bgYellowBright?: string; bgBlueBright?: string; bgMagentaBright?: string; bgCyanBright?: string; bgWhiteBright?: string; } export interface IColurOptions { enabled?: boolean; browser?: boolean; ansiStyles?: IAnsiStyles; cssStyles?: ICssStyles; } export interface IColursInstance { new (options?: IColurOptions): IColurs; } export interface IColurs extends IColursStyle { /** * Colurs options. */ options?: IColurOptions; /** * Enables setting options after init. * * @param key the key to set or object. * @param val the value to set if key is not an object. */ setOption?(key: any, val: any): void; /** * Strips ansi styles from value. * * @param val the value to strip ansi styling from. */ strip?(val: any): any; /** * Checks if value has any ansi styling. * * @param val the value to inspect. */ hasAnsi?(val: any): boolean; /** * Apply ansi styling to value. * * @example .applyAnsi('foo', 'red'); * * @param str the value to be styled. * @param style the style to be applied. */ applyAnsi?(str: string, style: any): string; /** * Apply ansi styling to value. * * @example .applyAnsi('foo', ['red', 'bold']); * * @param str the value to be styled. * @param styles the styles to be applied. */ applyAnsi?(str: string, styles: any[]): string; /** * Apply ansi styling to value. * * @example .applyAnsi('foo', 'red', true); * * @param str the value to be styled. * @param style the style to be applied. * @param isBrowser allows override to style for browser. */ applyAnsi?(str: string, style: any, isBrowser: boolean): any[]; /** * Apply ansi styling to value. * * @example .applyAnsi('foo', ['red', 'bold'], true); * * @param str the value to be styled. * @param styles the styles to be applied. * @param isBrowser allows override to style for browser. */ applyAnsi?(str: string, styles: any[], isBrowser: boolean): any[]; applyAnsi?(str: string, style: any | any[], isBrowser?: boolean): string | any[]; /** * Applies styling for html output. * * @param str the value to apply html styles to. * @param style the style or styles to be applied. */ applyHtml?(str: any, style: any | any[]): string; /** * Converts to html styling from ansi, simply a * convenience wrapper to ansi-html module. * * @param str the value to convert. */ toHtml?(str: string): string; /** * Applies styling for css. * * @param str the value to apply css styling to. * @param style the style or styles to apply. */ applyCss?(str: string, style: string | string[]): any[]; /** * Toggles enable/disable of browser mode. * * @param state when true using browser mode. */ browser?(state?: boolean): boolean; /** * Toggles state when false colorizing is disabled. * * @param state toggles the enabled state. */ enabled?(state?: boolean): boolean; }
1a6d0a8e190a7c79ddbf2301b34a88456069aaab
TypeScript
runictree/chronos
/src/Record.ts
2.703125
3
export interface Record { /** * Internal ID * * In some devices, it is Record ID, but some devices it is internal user ID * * For reliable user ID, use UserId instead */ id: number, /** * User ID * * Input via Add User in the device menu */ userId?: string, /** * Verification Method */ verifyMethod: number, /** * Attendance Record timestamp */ timestamp: string, /** * Verification State */ verifyState: number } export const VerificationMethods = Object.freeze({ password: 0, fingerprint: 1, rfidCard: 2 }) export const VerificationStates = Object.freeze({ checkIn: 0, checkOut: 1, breakOut: 2, breakIn: 3, otIn: 4, otOut: 5 })
c9684e267ac057aa3024d1e332754bfbd8031642
TypeScript
codehub0x/TypeScript-DeFi
/src/gambling-strategies/low-brainers/momentum-trader.ts
2.53125
3
import { BinanceConnector } from "../../binance/binance-connector" import { Player } from "../utilities/player" import { PortfolioProvider } from "../utilities/portfolio-provider" export class MomentumTrader { private binanceConnector: BinanceConnector private historicData: any[] = [] private portfolioProvider: PortfolioProvider private tradingUnit: number private pair: string private previousPNL: number = 0 private limit: number = 0 public constructor(apiKey: string, apiSecret: string, tradingUnit: number, pair: string, limit: number) { this.binanceConnector = new BinanceConnector(apiKey, apiSecret) this.portfolioProvider = new PortfolioProvider() this.tradingUnit = tradingUnit this.pair = pair this.limit = limit } public async investWisely(): Promise<void> { const currentPrices = await this.binanceConnector.getCurrentPrices() const currentPrice = this.portfolioProvider.getCurrentXPrice(currentPrices, this.pair) const accountData = await this.binanceConnector.getFuturesAccountData() const position = accountData.positions.filter((entry: any) => entry.symbol === this.pair)[0] // console.log(`currentPrice: ${currentPrice}`) if (this.historicData.length === 500000) { this.historicData.splice(this.historicData.length - 1, 1) } this.historicData.unshift(currentPrice) const delta = this.historicData[1] - currentPrice const x = Math.abs(Number(((delta * 100) / this.historicData[1]).toFixed(2))) if (Number(accountData.totalWalletBalance) < 5) { await this.binanceConnector.transferFromSpotAccountToUSDTFutures(5) } else if (accountData.totalWalletBalance > 55) { await this.binanceConnector.transferFromUSDTFuturesToSpotAccount(5) } // console.log(x) if (x > this.limit) { let theFactor = Number((x * 10).toFixed(0)) theFactor = (theFactor > 7) ? 7 : theFactor console.log(`theFactor: ${theFactor}`) if (delta > 0) { console.log(`the price decreased significantly by ${x} Percent`) await this.binanceConnector.sellFuture(pair, this.tradingUnit * theFactor) } else if (delta < 0) { console.log(`the price increased significantly by ${x} Percent`) await this.binanceConnector.buyFuture(pair, this.tradingUnit * theFactor) } } else if (Number(position.unrealizedProfit) > 1) { await this.binanceConnector.transferFromUSDTFuturesToSpotAccount(1) } else if (Number(position.unrealizedProfit) < -0.2) { console.log(`I should get out of that shit as the PNL is ${position.unrealizedProfit}`) if (Number(position.positionAmt) > 0) { const r = await this.binanceConnector.sellFuture(this.pair, Number(position.positionAmt)) console.log(r) } else if (Number(position.positionAmt) < 0) { const r = await this.binanceConnector.buyFuture(this.pair, Number(position.positionAmt) * -1) console.log(r) } } else if (this.previousPNL > Math.abs(Number(position.unrealizedProfit)) * 2) { console.log(`the previous PNL ${this.previousPNL} was much better than the current ${position.unrealizedProfit}`) if (position.positionAmt > 0) { await this.binanceConnector.sellFuture(this.pair, position.positionAmt) } else if (position.positionAmt < 0) { await this.binanceConnector.buyFuture(this.pair, Number(position.positionAmt) * -1) } } else { console.log(`boring times (${x} is below ${limit}) - avB: ${accountData.availableBalance}`) } this.previousPNL = Number(position.unrealizedProfit) } } const binanceApiKey = process.argv[2] // check your profile on binance.com --> API Management const binanceApiSecret = process.argv[3] // check your profile on binance.com --> API Management const limit = Number(process.argv[4]) // e.g. 0.4 const pair = 'DOGEUSDT' const tradingUnit = 100 const momentumTrader = new MomentumTrader(binanceApiKey, binanceApiSecret, tradingUnit, pair, limit) setInterval(async () => { momentumTrader.investWisely() }, 11 * 1000)
3c471985ba75274120524da591e089fba59d04fa
TypeScript
saumyasinghal747/pixel-editor
/src/store/index.ts
2.71875
3
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) function makeArray(x: number,y: number,d: any) : Array<object> { return JSON.parse(JSON.stringify((new Array(y)).fill((new Array(x)).fill(d)))); } interface Cell { people: Array<any>, type: string } // @ts-ignore export default new Vuex.Store({ state: { grid: makeArray(100,70,{people:[],type:'road'}), focusedColor:"road", availableColors: ["road","grass","parking","concrete","library","jade","water","history","cefg","gunn","science","language","other","util","computers","brick"] }, mutations: { changeFColor(state,newColor){ state.focusedColor = newColor }, // @ts-ignore changeCellColor(state,payload){ // @ts-ignore //console.log(state.grid[20]); state.grid[payload.y][payload.x].type=state.focusedColor }, setGrid(state,grid){ for (var y in grid){ //console.log(y); for (var x in grid[y]){ // @ts-ignore //console.log(grid[y][x]); state.grid[y][x].type = grid[y][x].type //console.log(state.grid[y][x]) } } } }, actions: { }, modules: { } })
d11d457fe12b37bb41833c4a479c7a009fbf1bcf
TypeScript
romusulin/js-challenger
/src/middleware/verify-token.ts
2.59375
3
import { NextFunction, Request, Response } from 'express'; import { HTTP_CODES } from '../app'; import { AUTHORIZATION_SCHEMA } from '../security/auth-utils'; import { verifyToken } from '../security/auth-utils'; import { ResponseWithLocals } from './custom-response'; export function verifyAuthorizationTokenMiddleware(req: Request, res: ResponseWithLocals, next: NextFunction) { const authorizationHeader = req.header('Authorization'); if (!authorizationHeader) { return res.status(HTTP_CODES.HTTP_BAD_REQUEST).json('Verification requires the authorization header to be set'); } const [ schema, encodedToken ] = authorizationHeader.split(' '); if (schema !== AUTHORIZATION_SCHEMA) { return res.status(HTTP_CODES.HTTP_BAD_REQUEST).json('Incorrect authorization schema'); } const verificationResult = verifyToken(encodedToken); if (!verificationResult.success) { return res.status(HTTP_CODES.HTTP_BAD_REQUEST).json(`Token verification failed: ${verificationResult.error}`); } res.locals.token = verificationResult.token; next(); }
5d8d7addd3e3cd60546e44320965a6d6af514772
TypeScript
devpt-org/estirador
/client-side/web-app/src/components/ui-kit/core/utils/camel-case-to-css-property-name.ts
2.734375
3
export function camelCaseToCSSPropertyName(camelCasedName: string) { return camelCasedName.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`); }
ec188d773b20d811a87e8328042e6e32f1c83561
TypeScript
gadget2015/gamble
/noteservice/src/noteservice.ts
2.765625
3
import {Request, Response} from 'express'; import * as db from 'mysql'; import myprops = require('properties-reader'); import {Logger} from 'winston'; /** * The Note service, that handles CRUD operations. * */ export class Noteservice { logger: Logger; constructor(logger : Logger) { this.logger = logger; } getNote(req: Request, res: Response) { const id = parseInt(req.params.id, 10); this.logger.debug('Search for note with id = ' + id); const con = this.connectToDb(); const sql = 'select * from noterepo.note where id = ' + id + ';'; let sqlpromise = new Promise((resolve, reject) => { con.query(sql, this.createReadCallbackFunction(resolve, reject, this.logger)); con.end(); }); return sqlpromise; } async createNote(req: Request, res: Response) { const text = req.body['TEXT']; this.logger.debug('Create a new note with TEXT = ' + text); const con = this.connectToDb(); // Calculate the next sequnece ID used in the sql insert into statement. const sqlLastID = 'SELECT ID FROM noterepo.note ORDER BY ID DESC LIMIT 1;'; let sqlpromise = new Promise((resolve, reject) => { con.query(sqlLastID, this.createReadCallbackFunction(resolve, reject, this.logger)); }); let result = await sqlpromise; const id = parseInt(result['queryResult'][0]["ID"], 10); const nextId = id + 1; // Insert new Note in database. const sqlInsert = 'insert into noterepo.note (ID, ADMINUSERID, PRIVATEACCESS, TEXT, LASTSAVED) VALUES (' + nextId + ',\'\', 0, \'' + text + '\', CURRENT_TIMESTAMP);'; sqlpromise = new Promise((resolve, reject) => { con.query(sqlInsert, this.createInsertCallbackFunction(resolve, reject, this.logger)); con.end(); }); const returnPromise = new Promise(async (reslove, reject) => { const result = await sqlpromise; const affectedRows = result['affectedRows']; if (affectedRows === 1 ){ reslove(nextId); } else { reject('Error while inserting Note.'); } }); return returnPromise; } /** * Create a database connection that can be used to query data/write data. */ connectToDb(): db.Connection { let properties = myprops('database.properties'); let dbHost = properties.get('database.host'); let dbUser = properties.get('database.user'); let dbPassword = properties.get('database.password'); let con = db.createConnection({ host: dbHost, user: dbUser, password: dbPassword }); con.connect(); return con; } /** * Params are case sensitive. */ updateNote(req: Request, res: Response) { const text = req.body['text']; const id = parseInt(req.body['id'], 10); this.logger.debug('Update note with id = ' + id + ', and text = ' + text); const con = this.connectToDb(); const sql = 'update noterepo.note set TEXT = ' + con.escape(text) + ', LASTSAVED = CURRENT_TIMESTAMP where id = ' + id + ';'; let sqlpromise = new Promise((resolve, reject) => { con.query(sql, this.createReadCallbackFunction(resolve, reject, this.logger)); con.end(); }); return sqlpromise; } createReadCallbackFunction(resolve, reject, logger) { return function(err, result) { if (err) { logger.error('Error while updating a Note: ' + err); reject('SQLerror'); } resolve({queryResult: result}); } } createInsertCallbackFunction(resolve, reject, logger) { return function (err, result) { if (err) { this.logger.error('Error while finding last ID: ' + err); reject(err); } resolve(result); } } }
d2504e859bf6899239796c2c708155f86343dd00
TypeScript
tadayosi/hawtio-next
/packages/hawtio/src/plugins/camel/camel-preferences-service.ts
2.828125
3
export interface ICamelPreferencesService { loadCamelPreferences(): CamelOptions saveCamelPreferences(newValues: Partial<CamelOptions>): void } export type CamelOptions = { isHideOptionDocumentation: boolean isHideDefaultOptionValues: boolean isHideUnusedOptionValues: boolean isIncludeTraceDebugStreams: boolean maximumTraceDebugBodyLength: number maximumLabelWidth: number isIgnoreIDForLabel: boolean isShowInflightCounter: boolean routeMetricMaximumSeconds: number } export const CAMEL_PREFERENCES_DEFAULT_VALUES: CamelOptions = { isHideOptionDocumentation: false, isHideDefaultOptionValues: false, isHideUnusedOptionValues: false, isIncludeTraceDebugStreams: false, maximumTraceDebugBodyLength: 5000, maximumLabelWidth: 34, isIgnoreIDForLabel: false, isShowInflightCounter: true, routeMetricMaximumSeconds: 10, } as const export const STORAGE_KEY_CAMEL_PREFERENCES = 'camel.preferences' class CamelPreferencesService implements ICamelPreferencesService { loadCamelPreferences(): CamelOptions { return { ...CAMEL_PREFERENCES_DEFAULT_VALUES, ...this.loadFromStorage() } } saveCamelPreferences(newValues: Partial<CamelOptions>): void { const preferencesToSave = { ...this.loadFromStorage(), ...newValues } localStorage.setItem(STORAGE_KEY_CAMEL_PREFERENCES, JSON.stringify(preferencesToSave)) } private loadFromStorage(): Partial<CamelOptions> { const localStorageData = localStorage.getItem(STORAGE_KEY_CAMEL_PREFERENCES) return localStorageData ? JSON.parse(localStorageData) : {} } } export const camelPreferencesService = new CamelPreferencesService()
55dc73701c1674c2b949604d148484a768cd6600
TypeScript
andy0104/graphql-federation-lib
/book-service/src/services/book-factory.ts
2.671875
3
import Book from '../models/book'; import BookAuthor from "../models/book-author"; import { MutationSaveBookArgs } from '../graphql/generated'; class BookFactory { public async getAllBooks(): Promise<Book[]> { try { return await Book.findAll({ include: { model: BookAuthor, as: 'book_author' } }); } catch (error) { console.error(error); return Promise.reject(error); } } public async getBookById(bookId: string): Promise<Book|null> { try { return await Book.findOne({ where: { book_id: bookId }, include: { model: BookAuthor, as: 'book_author' } }); } catch (error) { console.error(error); return Promise.reject(error); } } public async saveBooks(params: MutationSaveBookArgs): Promise<Book|null> { try { const { id, title, genre, author } = params; let book: Book|null; if (id !== '') { // Update the book book = await Book.findOne({ where: { book_id: id } }); if (!book) return null; book.book_title = title||''; book.book_genre = genre||''; await book.save(); await this.saveBookAuthors(id, author, true); } else { // Add a new book book = await Book.build({ book_title: title, book_genre: genre }); await book.save(); await this.saveBookAuthors(book.book_id, author); } return await this.getBookById(book.book_id); } catch (error) { console.error(error); return Promise.reject(error); } } public async getBooksByGenre(genreId: string): Promise<Book[]> { try { return await Book.findAll({ where: { book_genre: genreId }, include: { model: BookAuthor, as: 'book_author' } }); } catch(error) { console.error(error); return Promise.reject(error); } } public async getBooksByAuthor(authorId: string): Promise<Book[]> { try { return await Book.findAll({ include: { model: BookAuthor, as: 'book_author', where: { author_id: authorId } } }); } catch(error) { console.error(error); return Promise.reject(error); } } private async saveBookAuthors(bookId: string, authors: string[], clearAll: boolean = false): Promise<boolean> { try { if (clearAll) { // find all book authors await BookAuthor.destroy({ where: { book_id: bookId } }); } authors.forEach(async (author) => { await BookAuthor.create({ book_id: bookId, author_id: author }); }); return Promise.resolve(true); } catch (error) { console.error(error); return Promise.reject(false); } } } export default new BookFactory();
d45afeb2335e7b8d49758f7f389155e9ce32d9cb
TypeScript
urwrstkn8mare/angularshoppinglist
/src/app/shoppinglistitems.service.ts
2.671875
3
import { Injectable } from "@angular/core"; import { ShoppingListItem } from "./shopping-list-item"; import { AngularFirestore } from "@angular/fire/firestore"; @Injectable({ providedIn: "root" }) export class ShoppinglistitemsService { collection; constructor(public db: AngularFirestore) { this.collection = this.db.collection("shoppinglist"); } convertDoc(data, id): ShoppingListItem { return new ShoppingListItem(data.name, data.quantity, data.costEach, data.bought, id); } async itemsPromise() { return await this.collection .get() .toPromise() .then(querySnapshot => { const items: ShoppingListItem[] = []; querySnapshot.forEach(doc => { items.push(this.convertDoc(doc.data(), doc.id)); }); return items; }); } async removeItem(index: number) { // return this._items.splice(index, 1)[0]; return await this.itemsPromise().then(array => { this.collection .doc(array[index].id) .delete() .then(() => { console.log(array[index].id + " successfully deleted!"); }) .catch(err => { throw err; }); }); } async addItem(item: ShoppingListItem) { // if (index) { // this._items.splice(index, 0, item); // } else { // this._items.push(item); // } // return item; return await this.collection .add({ name: item.name, quantity: item.quantity, costEach: item.costEach, bought: item.bought }) .then(docRef => { console.log("Document written with ID: ", docRef.id); return docRef.id; }) .catch(err => { throw err; }); } async clear() { let arrayAboutToBeClearedPromise: Promise<ShoppingListItem[]>; this.itemsPromise().then(array => { arrayAboutToBeClearedPromise = this.itemsPromise(); array.forEach((item, index) => { this.removeItem(index); }); }); return await arrayAboutToBeClearedPromise; } set items(value: ShoppingListItem[]) { // this._items = value; this.clear(); value.forEach(item => { this.addItem(item); }); } changeIndex(oldIndex: number, newIndex: number) { this.itemsPromise().then(array => { const arrayItem = array.splice(oldIndex, 1)[0]; array.splice(newIndex, 0, arrayItem); this.items = array; }); // const item = this._items.splice(oldIndex, 1)[0]; // this._items.splice(newIndex, 0, item); // return item; } // TODO: Fix this async getIndex(id: string) { console.log(id); return await this.itemsPromise().then(array => { const matching: number[] = []; array.forEach((item, index) => { if (item.id === id) { matching.push(index); } }); if (matching.length > 1) { throw Error("There is more than one item that matches with the name: '" + name + "'!"); } else if (matching.length === 0) { throw Error("There is no item that matches with the name: '" + name + "'!"); } else { return matching[0]; } }); // return this._items.findIndex(item => (item.name === name ? true : false)); } async replaceItem( index: number, name?: string, quantity?: number, costEach?: number, bought?: boolean ) { // const itemMemory = this.items[index]; return await this.itemsPromise().then(items => { const itemMemory = items[index]; this.collection.doc(items[index].id).set({ name: name === undefined || name === null ? itemMemory.name : name, quantity: quantity === undefined || name === null ? itemMemory.quantity : quantity, costEach: costEach === undefined || name === null ? itemMemory.costEach : costEach, bought: bought === undefined || name === null ? itemMemory.bought : bought }); }); // this.removeItem(index); // this.addItem( // new ShoppingListItem( // name === undefined || name === null ? itemMemory.name : name, // quantity === undefined || name === null ? itemMemory.quantity : quantity, // costEach === undefined || name === null ? itemMemory.costEach : costEach, // bought === undefined || name === null ? itemMemory.bought : bought // ) // ); // this.changeIndex(this.getIndex(itemMemory.name), index); } }
26d6de338be6926ca629d2d161f87680d8b7d389
TypeScript
DaeronAlagos/warcry-statshammer
/api/tests/statsController.test.ts
2.90625
3
import { StatsController } from '../controllers/statsController'; import * as t from '../controllers/statsController.types'; import Fighter from '../models/fighter'; const mockMappedResult: t.TMappedResult = { toughness: 4, results: { 'Test Fighter': { buckets: [ { damage: 0, count: 9, probability: 25 }, { damage: 1, count: 12, probability: 33.33 }, { damage: 2, count: 10, probability: 27.78 }, { damage: 3, count: 4, probability: 11.11 }, { damage: 4, count: 1, probability: 2.78 }, { damage: 5, count: 0, probability: 0 }, ], metrics: { max: 4, mean: 1.33, }, }, }, }; describe('Stats Controller', () => { test('Build Result', () => { const controller = new StatsController(); const expected: t.ICompareFightersResult = { toughness: 4, discrete: [ { damage: 0, 'Test Fighter': 25 }, { damage: 1, 'Test Fighter': 33.33 }, { damage: 2, 'Test Fighter': 27.78 }, { damage: 3, 'Test Fighter': 11.11 }, { damage: 4, 'Test Fighter': 2.78 }, { damage: 5, 'Test Fighter': 0 }, ], cumulative: [ { damage: 0, 'Test Fighter': 25 }, { damage: 1, 'Test Fighter': 58.33 }, { damage: 2, 'Test Fighter': 86.11 }, { damage: 3, 'Test Fighter': 97.22 }, { damage: 4, 'Test Fighter': 100 }, { damage: 5, 'Test Fighter': 100 }, ], metrics: { max: { 'Test Fighter': 4, }, mean: { 'Test Fighter': 1.33, }, }, }; // @ts-ignore const output = controller.buildResult(mockMappedResult); expect(output).toEqual(expected); }); describe('Get Toughness Ranges', () => { const controller = new StatsController(); const fighterList = [ new Fighter('Test 1', { attacks: 2, strength: 3, damage: { hit: 1, crit: 2 }, }), new Fighter('Test 2', { attacks: 2, strength: 4, damage: { hit: 2, crit: 4 }, }), ]; test('Auto <-> Auto', () => { // @ts-ignore expect(controller.getToughnessRanges(fighterList, { min: 'auto', max: 'auto' })).toEqual({ min: 2, max: 5, }); }); test('3 <-> Auto', () => { // @ts-ignore expect(controller.getToughnessRanges(fighterList, { min: 3, max: 'auto' })).toEqual({ min: 3, max: 5, }); }); test('Auto <-> 7', () => { // @ts-ignore expect(controller.getToughnessRanges(fighterList, { min: 'auto', max: 7 })).toEqual({ min: 2, max: 7, }); }); test('7 <-> Auto (min > max)', () => { // @ts-ignore expect(controller.getToughnessRanges(fighterList, { min: 7, max: 'auto' })).toEqual({ min: 7, max: 7, }); }); test('Auto <-> 1 (max < min)', () => { // @ts-ignore expect(controller.getToughnessRanges(fighterList, { min: 'auto', max: 1 })).toEqual({ min: 2, max: 2, }); }); test('-1 <-> -10 (negative numbers)', () => { // @ts-ignore expect(controller.getToughnessRanges(fighterList, { min: -1, max: -10 })).toEqual({ min: 1, max: 1, }); }); }); });
d37757094f3a91f56796147d4f5ae6b76b114cd3
TypeScript
Eunice17/LIM014-burger-queen-api-client
/src/app/services/products/product.service.spec.ts
2.5625
3
import { ProductService } from './product.service'; import { Product } from '../../model/product-interface'; import { defer } from 'rxjs'; import { AuthService } from '../auth/auth.service'; fdescribe('ProductService', () => { let httpClientSpy: { get: jasmine.Spy }; let authServiceSpy: { get: jasmine.Spy }; let service: ProductService; beforeEach(() => { httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']); service = new ProductService(httpClientSpy as any, authServiceSpy as any); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('GET should return expected products (HttpClient called once)', (done: DoneFn) => { const expectedProduct: Product[] = [{ _id: "D01", name: "Café americano", price: 5.0, image: "src/logo.png", type: "desayuno", dateEntry: new Date() }, { _id: "D01", name: "Café americano", price: 5.0, image: "src/logo.png", type: "desayuno", dateEntry: new Date() }]; function asyncData<Product>(data: Product) { return defer(() => Promise.resolve(data)); } httpClientSpy.get.and.returnValue(asyncData(expectedProduct)); service.getListProducts().subscribe( prod => { expect(prod).toEqual(expectedProduct, 'expected products'); done(); }, done.fail ); expect(httpClientSpy.get).toHaveBeenCalledTimes(1); }); });
975c295e08163737a3547c53bee99759f99c72cb
TypeScript
firedev/zerg
/src/LoggerModule.ts
2.765625
3
import {TLogLevel, TExtendedData, TLogFunction} from './types'; class LoggerModule { name: string; readonly __originLog: TLogFunction; constructor(name: string, logFn: TLogFunction) { this.name = name; this.__originLog = logFn; } private log(level: TLogLevel, message: string, extendedData?: TExtendedData) { this.__originLog(this.name, level, message, extendedData); } verbose(message: string, extendedData?: TExtendedData) { this.log('verbose', message, extendedData); } debug(message: string, extendedData?: TExtendedData) { this.log('debug', message, extendedData); } info(message: string, extendedData?: TExtendedData) { this.log('info', message, extendedData); } warn(message: string, extendedData?: TExtendedData) { this.log('warn', message, extendedData); } error(message: string, extendedData?: TExtendedData) { this.log('error', message, extendedData); } metric(message: string, extendedData?: TExtendedData) { this.log('metric', message, extendedData); } event(message: string, extendedData?: TExtendedData) { this.log('event', message, extendedData); } } export default LoggerModule;
e7bfe622e9275ca69cd62bf6d7a8fc7dc288a3a0
TypeScript
ThomasDupont/core
/packages/system/src/Stream/Stream/flattenTake.ts
2.59375
3
// ets_tracing: off import type * as TK from "../Take" import type { Stream } from "./definitions" import { flattenChunks } from "./flattenChunks" import { flattenExitOption } from "./flattenExitOption" /** * Unwraps `Exit` values and flatten chunks that also signify end-of-stream by failing with `None`. */ export function flattenTake<R, E, E1, O1>( self: Stream<R, E, TK.Take<E1, O1>> ): Stream<R, E | E1, O1> { return flattenChunks(flattenExitOption(self)) }
f081008bd8d8b634f177e489b5a9961f0e496478
TypeScript
defifarmer/bot
/src/commands/moderation/prune.ts
2.734375
3
import {Argument} from 'discord-akairo'; import {bold} from 'discord-md-tags'; import {Collection, Message, Permissions} from 'discord.js'; import {AkairoArgumentType, DiceCommand, DiceCommandCategories} from '../../structures/DiceCommand'; export default class PruneCommand extends DiceCommand { constructor() { super('prune', { aliases: [ 'bulk-delete-messages', 'message-prune', 'message-bulk-delete', 'delete-messages', 'messages-prune', 'messages-bulk-delete', 'bulk-delete', 'prune-messages' ], category: DiceCommandCategories.Moderation, description: { content: 'Delete several messages in bulk.', usage: '<amount>', examples: ['5', '100'] }, userPermissions: [Permissions.FLAGS.MANAGE_MESSAGES], channel: 'guild', args: [ { id: 'amount', type: Argument.range(AkairoArgumentType.Integer, 1, 100, true), prompt: { start: 'How many messages do you want to delete?', retry: `Invalid amount provided, please provide a number from 1-100` } } ] }); } async exec(message: Message, args: {amount: number}): Promise<Message | undefined> { if (message.member!.permissionsIn(message.channel).has(Permissions.FLAGS.MANAGE_MESSAGES)) { const reason = `Requested by ${message.author.tag}`; if (message.deletable) { await message.delete({reason}); } const channelMessages = await message.channel.messages.fetch({limit: args.amount}); let deletedMessages: Collection<string, Message>; try { deletedMessages = await message.channel.bulkDelete(channelMessages); } catch { // eslint-disable-next-line no-return-await return await message.util?.send('Unable to delete those messages'); } return message.util?.send(`${bold`${deletedMessages.size}`} messages were deleted`); } return message.util?.send("You don't have permissions to delete messages in this channel"); } }
ab5ac24be889d4fcd862872ad9dee0f3f9564309
TypeScript
figuevigo/angular-escalable-vitae-febrero
/libs/data/src/lib/services/validators.service.ts
2.6875
3
import { Injectable } from '@angular/core'; import { AbstractControl, FormGroup } from '@angular/forms'; @Injectable({ providedIn: 'root', }) export class ValidatorsService { getInputValueFromDate(theDate: Date) { if (typeof theDate === 'string') { theDate = new Date(theDate); } // ! hack to avoid change date when time offset is applied theDate.setHours(12); return new Date(theDate).toISOString().substring(0, 10); } getErrorMessage(form: FormGroup, controlName?: string) { const control = controlName ? form.controls[controlName] : form; if (control && control.errors && control.touched) { // ToDo: use value instead of key name if is a string... return Object.keys(control.errors).concat(); } return null; } dateBetween(min: Date, max: Date) { return function validate(control: AbstractControl) { const value = new Date(control.value); if (value < min || value > max) { return { 'date-between-invalid': true, }; } return null; }; } datesInRange(from: string, to: string) { return function validate(group: FormGroup) { const fromControl = group.controls[from]; const toControl = group.controls[to]; if (fromControl.value > toControl.value) { return { 'dates-in-range-invalid': true, }; } return null; }; } }
d695f98d0163ddbafcacee2d6c3717f81ca35f3a
TypeScript
Setheum-Labs/ethers.js
/misc/admin/src.ts/cmds/get-config.ts
2.515625
3
import { config } from "../config"; if (process.argv.length !== 3) { console.log("Usage: get-config KEY"); process.exit(1); } const key = process.argv[2]; (async function() { const value = await config.get(key); console.log(value); })().catch((error) => { console.log(`Error running ${ process.argv[0] }: ${ error.message }`); process.exit(1); });
1374c3acde37fa719347bab3bce4fe02ea3b0fd1
TypeScript
KimPalao/OverflowOnline
/overflow-backend/src/migration/1617933917033-AddNormalCards.ts
2.546875
3
import { Card, CardType } from '../entity/card.entity'; import { MigrationInterface, QueryRunner } from 'typeorm'; export class AddNormalCards1617933917033 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { const connection = await queryRunner.connection; const promises = []; for (let i = 1; i <= 4; i++) { const card = new Card(); card.name = i.toString(); card.image = 'assets/placeholder.jpg'; card.type = CardType.Normal; card.value = i; promises.push(connection.manager.save(card)); } await Promise.all(promises); } public async down(queryRunner: QueryRunner): Promise<void> { const manager = queryRunner.manager; const promises = []; for (let i = 1; i <= 4; i++) { promises.push(manager.delete(Card, { name: i.toString() })); } await Promise.all(promises); } }
1f4d005663d05182e06ccecbf94156c2e10deef6
TypeScript
jmontesv/firstproject
/src/app/tasks/form-tarea/date-validation.directive.ts
2.6875
3
import { Directive } from '@angular/core'; import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms'; @Directive({ selector: '[appDatevalidator]', providers: [ { provide: NG_VALIDATORS, useExisting: DateValidator, multi: true } ] }) export class DateValidator implements Validator { currentDate: { day: number, month: number, year: number }; constructor() { const nowDate = new Date(); this.currentDate = { day: null, month: null, year: null}; this.currentDate.day = nowDate.getDate(); this.currentDate.month = nowDate.getMonth(); this.currentDate.year = nowDate.getFullYear(); } validate(control: AbstractControl) { const inputvalue = control.value || ''; const dayC = inputvalue.split('-'); if ((parseFloat(dayC[2]) < this.currentDate.day && parseFloat(dayC[1]) <= this.currentDate.month + 1 && parseFloat(dayC[0]) <= this.currentDate.year) || (parseFloat(dayC[1]) < this.currentDate.month + 1 && parseFloat(dayC[0]) <= this.currentDate.year) || (parseFloat(dayC[0]) < this.currentDate.year || parseFloat(dayC[0]) >= this.currentDate.year + 2) ) { return { 'Datevalidator': 'Date invalid' }; } else { return null; } } }
c4d4f6c57e18dfd9cd08234e5fa318e9078c822e
TypeScript
ceottaki/graphql-api-server-boilerplate
/app/src/app.ts
2.515625
3
import GraphQLServerOptions from 'apollo-server-core/dist/graphqlOptions' import { graphiqlRestify, graphqlRestify } from 'apollo-server-restify' import { GraphQLObjectType, GraphQLSchema, GraphQLString } from 'graphql' import { GraphQLDateTime } from 'graphql-iso-date' import * as restify from 'restify' import { IQueryFieldCollection } from './types/query-field-collection' export class App { private server: restify.Server private queryGraphQLType: GraphQLObjectType private mutationGraphQLType: GraphQLObjectType public readonly port: number constructor(name: string, port: number) { this.port = port this.server = restify.createServer({ name, version: '1.0.0' }) this.queryGraphQLType = new GraphQLObjectType({ name: 'Query', fields: { heartBeat: { type: GraphQLDateTime, description: 'A simple check that returns the server date and time.', resolve: () => new Date() } } }) this.mutationGraphQLType = new GraphQLObjectType({ name: 'Mutation', fields: { noop: { type: GraphQLString, description: 'A non-operation, always returns an empty string.', resolve: () => '' } } }) } public start(): void { console.log('Configuring GraphQL server...') const schema = new GraphQLSchema({ query: this.queryGraphQLType, mutation: this.mutationGraphQLType }) const graphQLOptions: GraphQLServerOptions = { schema } this.server.use(restify.plugins.bodyParser()) this.server.use(restify.plugins.queryParser()) this.server.post('/graphql', graphqlRestify(graphQLOptions)) this.server.get('/graphql', graphqlRestify(graphQLOptions)) this.server.get('/graphiql', graphiqlRestify({ endpointURL: '/graphql' })) console.log('Application starting on port ' + this.port.toString() + '...') this.server.listen(this.port, () => { console.log(`Application started and is listening on port ${this.port}.`) console.log(`Open http://localhost:${this.port}/graphiql to start running queries`) console.log(`or use the endpoint http://localhost:${this.port}/graphql in your API.`) }) } public addQueryFieldCollection( queryFieldCollection: IQueryFieldCollection<unknown, unknown> ): void { const newConfig = this.queryGraphQLType.toConfig() newConfig.fields = { ...newConfig.fields, ...queryFieldCollection.queryFields } this.queryGraphQLType = new GraphQLObjectType(newConfig) if (queryFieldCollection.mutationFields) { const newMutationConfig = this.mutationGraphQLType.toConfig() newMutationConfig.fields = { ...newMutationConfig.fields, ...queryFieldCollection.mutationFields } this.mutationGraphQLType = new GraphQLObjectType(newMutationConfig) } } }
83d76329a8b2fa74cb426905bcbea9e09c81e745
TypeScript
alexweltman/fullstack-typescript-starter
/src/index.ts
2.515625
3
import bodyParser from 'body-parser'; import express, { Request, Response } from 'express'; import path from 'path'; const app = express(); const port = process.env.PORT || 5000; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/api/hello', (req: Request, res: Response) => { res.send({ express: 'Hello From Express' }); }); if (process.env.NODE_ENV === 'production') { console.log('we here'); // Serve any static files app.use(express.static(path.join(__dirname, 'client/build'))); // Handle React routing, return all requests to React app app.get('*', function(req, res) { res.sendFile(path.join(__dirname, 'client/build', 'index.html')); }); } app.listen(port, () => console.log(`Listening on port ${port}`));
7fd3ac1d2ca655ab532867a8a7a02181df127a09
TypeScript
yandex-cloud/nodejs-sdk
/src/generated/yandex/cloud/cdn/v1/origin_group.ts
2.65625
3
/* eslint-disable */ import { messageTypeRegistry } from "../../../../typeRegistry"; import Long from "long"; import _m0 from "protobufjs/minimal"; import { Origin } from "../../../../yandex/cloud/cdn/v1/origin"; export const protobufPackage = "yandex.cloud.cdn.v1"; /** Origin group parameters. For details about the concept, see [documentation](/docs/cdn/concepts/origins#groups). */ export interface OriginGroup { $type: "yandex.cloud.cdn.v1.OriginGroup"; /** ID of the origin group. Generated at creation time. */ id: number; /** ID of the folder that the origin group belongs to. */ folderId: string; /** Name of the origin group. */ name: string; /** * This option have two possible conditions: * true - the option is active. In case the origin responds with 4XX or 5XX codes, * use the next origin from the list. * false - the option is disabled. */ useNext: boolean; /** List of origins. */ origins: Origin[]; } const baseOriginGroup: object = { $type: "yandex.cloud.cdn.v1.OriginGroup", id: 0, folderId: "", name: "", useNext: false, }; export const OriginGroup = { $type: "yandex.cloud.cdn.v1.OriginGroup" as const, encode( message: OriginGroup, writer: _m0.Writer = _m0.Writer.create() ): _m0.Writer { if (message.id !== 0) { writer.uint32(8).int64(message.id); } if (message.folderId !== "") { writer.uint32(18).string(message.folderId); } if (message.name !== "") { writer.uint32(26).string(message.name); } if (message.useNext === true) { writer.uint32(32).bool(message.useNext); } for (const v of message.origins) { Origin.encode(v!, writer.uint32(42).fork()).ldelim(); } return writer; }, decode(input: _m0.Reader | Uint8Array, length?: number): OriginGroup { const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = { ...baseOriginGroup } as OriginGroup; message.origins = []; while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { case 1: message.id = longToNumber(reader.int64() as Long); break; case 2: message.folderId = reader.string(); break; case 3: message.name = reader.string(); break; case 4: message.useNext = reader.bool(); break; case 5: message.origins.push(Origin.decode(reader, reader.uint32())); break; default: reader.skipType(tag & 7); break; } } return message; }, fromJSON(object: any): OriginGroup { const message = { ...baseOriginGroup } as OriginGroup; message.id = object.id !== undefined && object.id !== null ? Number(object.id) : 0; message.folderId = object.folderId !== undefined && object.folderId !== null ? String(object.folderId) : ""; message.name = object.name !== undefined && object.name !== null ? String(object.name) : ""; message.useNext = object.useNext !== undefined && object.useNext !== null ? Boolean(object.useNext) : false; message.origins = (object.origins ?? []).map((e: any) => Origin.fromJSON(e) ); return message; }, toJSON(message: OriginGroup): unknown { const obj: any = {}; message.id !== undefined && (obj.id = Math.round(message.id)); message.folderId !== undefined && (obj.folderId = message.folderId); message.name !== undefined && (obj.name = message.name); message.useNext !== undefined && (obj.useNext = message.useNext); if (message.origins) { obj.origins = message.origins.map((e) => e ? Origin.toJSON(e) : undefined ); } else { obj.origins = []; } return obj; }, fromPartial<I extends Exact<DeepPartial<OriginGroup>, I>>( object: I ): OriginGroup { const message = { ...baseOriginGroup } as OriginGroup; message.id = object.id ?? 0; message.folderId = object.folderId ?? ""; message.name = object.name ?? ""; message.useNext = object.useNext ?? false; message.origins = object.origins?.map((e) => Origin.fromPartial(e)) || []; return message; }, }; messageTypeRegistry.set(OriginGroup.$type, OriginGroup); declare var self: any | undefined; declare var window: any | undefined; declare var global: any | undefined; var globalThis: any = (() => { if (typeof globalThis !== "undefined") return globalThis; if (typeof self !== "undefined") return self; if (typeof window !== "undefined") return window; if (typeof global !== "undefined") return global; throw "Unable to locate global object"; })(); type Builtin = | Date | Function | Uint8Array | string | number | boolean | undefined; export type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? { [K in Exclude<keyof T, "$type">]?: DeepPartial<T[K]> } : Partial<T>; type KeysOfUnion<T> = T extends T ? keyof T : never; export type Exact<P, I extends P> = P extends Builtin ? P : P & { [K in keyof P]: Exact<P[K], I[K]> } & Record< Exclude<keyof I, KeysOfUnion<P> | "$type">, never >; function longToNumber(long: Long): number { if (long.gt(Number.MAX_SAFE_INTEGER)) { throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER"); } return long.toNumber(); } if (_m0.util.Long !== Long) { _m0.util.Long = Long as any; _m0.configure(); }
239ae82871d6cbc212d6facd13d238ceed22615e
TypeScript
ngseke/picsee-oa
/src/composables/use-generate-history.ts
2.609375
3
import { computed } from 'vue' import { useRoute } from 'vue-router' import { useLocalStorage } from '@vueuse/core' import History from '@/interfaces/History' export default function () { const route = useRoute() /** 當前身分(來自於 URL 參數) */ const feature = computed(() => route.query.feature) /** 是否為 admin */ const isAdmin = computed(() => feature.value === 'admin') /** 上限 */ const limit = computed(() => isAdmin.value ? Infinity : 3) /** 是否未達到限制 */ const isUnderLimit = computed(() => histories.value.length < limit.value ) /** 根據當前身分得到的 localStorage 的 key,用來模擬各登入者的資料庫 */ const key = computed(() => feature.value ? `history-${feature.value}` // 有身分 : 'history' // 沒有身分(預設) ) /** 儲存在本地的轉換記錄 */ const histories = useLocalStorage<History[]>(key.value, []) /** 新增一筆紀錄 */ const pushHistory = (history: History) => { histories.value.push(history) } return { feature, isAdmin, limit, isUnderLimit, histories, pushHistory } }
68b1ab0c0f345c94b1e2fc3ca2864bf6722e791a
TypeScript
DmitrijTrifanov/TcContext
/src/tc-context.ts
2.5625
3
// tc-context.ts /** * Module containing the main TcContext Class, responsible for establishing connection over TwinCAT's ADS layer, * generating the Type and Symbol Maps for future communication. * * * Licensed under MIT License. * * Copyright (c) 2020 Dmitrij Trifanov <d.v.trifanov@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * @packageDocumentation */ //----IMPORTS... import Debug from 'debug'; import { TcCom, TcComSettings } from './tc-com'; import { TcTypeRegistry } from './tc-type-registry'; import { TcSymbolRegistry } from './tc-symbol-registry'; import * as TcEvents from './tc-event'; import { TcNamespaceSymbol } from './tc-symbol'; import { EventEmitter } from 'events'; /** * Class responsible for creating the connection, mapping the types and symbols over the TwinCAT's ADS * layer. Its purpose is to serve as the entry point for the tc-context Library. * * Creation of a context is done through the `TcContext.create()` static method, due to the asynchronous * nature of creation. * * ```js * const { TcContext } = require('tc-context'); * * TcContext.create().then(context => { * //..... * await context.kill(); * }) * ``` * */ export class TcContext extends TcEvents.TcEmitter { /** * Internal constructor, which creates and binds all the Components of `TcContext`, used by `TcContext.create()` * * @param settings - Settings used for communicating over ADS. Definition of connection settings can be found at [ads-client](https://github.com/jisotalo/ads-client) library * @param onSourceChange - Callback which is issued when Code Change is detected. If none is specified, the the `TcContext.reinitialize` function is bound to it * @param debug - If enabled, all components of `TcContext` will produce debug information */ private constructor(settings : TcComSettings, onSourceChange? : () => void, debug : boolean = false) { super(); this.__log.enabled = debug; this.__log('Creating TcContext Object...') if (!onSourceChange) { //Bind `TcContext.reinitialize()` method so its called if code changes are detected during run time this.__com = new TcCom(this, settings, this.reinitialize.bind(this), debug); } else this.__com = new TcCom(this, settings, onSourceChange, debug); this.__types = new TcTypeRegistry(this, debug); this.__symbols = new TcSymbolRegistry(this, debug); } /** * Function responsible for the creation of `TcContext`, as well as initializing all of its components * * ```js * const { TcContext } = require('tc-context'); * * TcContext.create().then(context => { * //..... * }) * ``` * @param settings - Settings used for communicating over ADS. Definition of connection settings can be found at [ads-client](https://github.com/jisotalo/ads-client) library * @param onSourceChange - Callback which is issued when Code Change is detected. If none is specified, the the `TcContext.reinitialize` function is bound to it * @param debug - If enabled, all components of `TcContext` will produce debug information * * @throws {@link TcComBusyException} - Connection is already created and `TcCom` is busy * @throws {@link TcComConnectException} - Failure establishing ADS Communication * @throws {@link TcComChangeDetectionException} - Failure enabling Code Change monitoring * @throws {@link TcComTypeQueryException} - Failure querying Type Data from TwinCAT * @throws {@link TcComSymbolQueryException} - Failure querying Symbol Data from TwinCAT * @throws {@link TcComIsInvalidException} - Attempting to use an Invalidated TcCom Object * * @return - The newly created, connected and mapped `TcContext` */ static async create(settings : TcComSettings, onSourceChange? : () => void, debug : boolean = false) { //Create the `TcContext` and initialize all the components const context = new TcContext(settings, onSourceChange, debug); return context.__initialize(); } /** * Function responsible for explicitly killing `TcContext`, rendering it unusable, unless `TcContext.reinitialize()` is called * afterwards, which will reconnect and rebuild a new `TcContext` with previously passed settings * * ```js * const { TcContext } = require('tc-context'); * * TcContext.create().then(context => { * * await context.kill() * //context is no longer usable afterwards * * }) * ``` * ***NOTE:*** Even if the function throws an exception, the context will still be rendered unusable * * @throws {@link TcComUnsubscribeException} - Failure unsubscribing from TwinCAT Symbol * @throws {@link TcComDisconnectException} - Failure disconnecting from ADS Target * * @return - The killed `TcContext`, which is no longer usable */ async kill() : Promise<TcContext> { this.__log(`kill() : Killing TcContext Object...`); await this.__types.destroy(); await this.__symbols.destroy(); await this.__com.disconnect(); this.__log(`kill() : TcContext Object was killed`); this.emit('killed', new TcEvents.TcContextKilledEvent(this)); return this; } /** * Function, which using the previously passed settings during `TcContext.create()` call, will kill the `TcContext` * and then reconnect and rebuild all the components. * * This function is automatically called, whenever the `TcCom` module detects a code change on the PLC if * no explicit callback was given during construction * * @throws {@link TcComBusyException} - Connection is already created and `TcCom` is busy * @throws {@link TcComConnectException} - Failure establishing ADS Communication * @throws {@link TcComChangeDetectionException} - Failure enabling Code Change monitoring * @throws {@link TcComTypeQueryException} - Failure querying Type Data from TwinCAT * @throws {@link TcComSymbolQueryException} - Failure querying Symbol Data from TwinCAT * @throws {@link TcComIsInvalidException} - Attempting to use an Invalidated TcCom Object * @throws {@link TcComUnsubscribeException} - Failure unsubscribing from TwinCAT Symbol * @throws {@link TcComDisconnectException} - Failure disconnecting from ADS Target * @throws {@link TcComToRawException} - Error occurred when transforming value to raw data * * @return - The reinitialized `TcContext` */ async reinitialize() : Promise<TcContext> { this.__log(`reinitialized() : Reinitializing TcContext Object...`); await this.kill(); await this.__initialize(); this.__log(`reinitialized() : TcContext Object was reinitialized...`); this.emit('reinitialized', new TcEvents.TcContextReinitializedEvent(this)); return this; } /** * Access to the ADS Communication Module, through which all ADS Actions are made */ get COM() : TcCom { return this.__com; } /** * Access to the Registry, which stores all the TwinCAT Type Data, pulled from the PLC, and which * is used for Symbol generation */ get types() : TcTypeRegistry { return this.__types; } /** * Access to the Registry, which stores the Symbol Map, generated based on the TwinCAT PLC Data and the * Type data gathered by the `TcContext.types` Component */ get symbols() : TcSymbolRegistry { return this.__symbols; } /** * Shortcut operator of `TcContext.symbols.namespaces`, for quickly accessing the created `TcNamespaces` */ get $() : { [ key : string ] : TcNamespaceSymbol } { return this.__symbols.namespaces }; //----EVENTS... /** * Emitted when `TcContext` is killed and is no longer usable * @event killed */ on(event : 'killed', listener : (e : TcEvents.TcContextKilledEvent) => void) : any; /** * Emitted when `TcContext` is reinitialized * @event reinitialized */ on(event : 'reinitialized', listener : (e : TcEvents.TcContextReinitializedEvent) => void) : any; /** * Emitted from {@link TcCom} when it establishes a connection to the PLC * @event connected */ on(event : 'connected', listener : (e : TcEvents.TcComConnectedEvent) => void) : any; /** * Emitted from {@link TcCom} when it disconnects from the PLC * @event disconnected */ on(event : 'disconnected', listener : (e : TcEvents.TcComDisconnectedEvent) => void) : any; /** * Emitted from {@link TcCom} when it detect Code Changes in the PLC * @event sourceChanged */ on(event : 'sourceChanged', listener : (e : TcEvents.TcComSourceChangedEvent) => void) : any; /** * Emitted from {@link TcSymbolRegistry} when it creates the Symbol Map * @event created */ on(event : 'created', listener : (e : TcEvents.TcSymbolRegistryCreatedEvent) => void) : any; /** * Emitted from {@link TcSymbolRegistry} when it destroys the Symbol Map * @event destroyed */ on(event : 'destroyed', listener : (e : TcEvents.TcSymbolRegistryDestroyedEvent) => void) : any; /** * Emitted from {@link TcTypeRegistry} when it creates the Type Map * @event created */ on(event : 'created', listener : (e : TcEvents.TcTypeRegistryCreatedEvent) => void) : any; /** * Emitted from {@link TcTypeRegistry} when it destroys the Types Map * @event destroyed */ on(event : 'destroyed', listener : (e : TcEvents.TcTypeRegistryDestroyedEvent) => void) : any; /** * Emitted from {@link TcBinding} of a {@link TcSymbol} when `TcSymbol.$set()` has completed * @event set */ on(event : 'set', listener : (e : TcEvents.TcSymbolSetEvent) => void) : any; /** * Emitted from {@link TcBinding} of a {@link TcSymbol} when `TcSymbol.$get` has completed * @event get */ on(event : 'get', listener : (e : TcEvents.TcSymbolGetEvent) => void) : any; /** * Emitted from {@link TcBinding} of a {@link TcSymbol} when `TcSymbol.$clear()` has completed * @event cleared */ on(event : 'cleared', listener : (e : TcEvents.TcSymbolClearedEvent) => void) : any; /** * Emitted from {@link TcBinding} of a {@link TcSymbol} when `TcSymbol` detects a change in the PLC Symbol * @event changed */ on(event : 'changed', listener : (e : TcEvents.TcSymbolChangedEvent) => void) : any; on(eventName : string | symbol, listener : (e : any) => void) : any { super.on(eventName, listener); return this; } /** * Internal function used by `TcContext.create()` static method, to initialize all the Components of the `TcContext` Object * * @throws {@link TcComBusyException} - Connection is already created and `TcCom` is busy * @throws {@link TcComConnectException} - Failure establishing ADS Communication * @throws {@link TcComChangeDetectionException} - Failure enabling Code Change monitoring * @throws {@link TcComTypeQueryException} - Failure querying Type Data from TwinCAT * @throws {@link TcComSymbolQueryException} - Failure querying Symbol Data from TwinCAT * @throws {@link TcComIsInvalidException} - Attempting to use an Invalidated TcCom Object * @throws {@link TcComToRawException} - Error occurred when transforming value to raw data * * @return - The newly created, connected and mapped `TcContext` * */ private async __initialize() : Promise<TcContext> { this.__log(`initialize() : Initializing TcContext Object...`); await this.__com.initialize() try { await this.__types.create() await this.__symbols.create(); } catch (err) { await this.__com.disconnect(); throw(err) } this.__log(`initialize() : TcContext Object was initialized...`); return this; } /** * ADS Communication Module * @internal */ private __com : TcCom; /** * Will register all the TwinCAT Types, which will be used by `TcSymbolRegistry` to create Symbol Map * @internal */ private __types : TcTypeRegistry; /** * Will created and store the TwinCAT Symbol Map * @internal */ private __symbols : TcSymbolRegistry; /** * @internal */ private __log : debug.Debugger = Debug(`TcContext::TcContext`); }
e8ff88d34e2bda247fcc28652c826722d2f09ff2
TypeScript
Brocco/stencil
/src/mock-doc/test/event.spec.ts
2.71875
3
import { MockWindow } from '../window'; describe('event', () => { let win: MockWindow; beforeEach(() => { win = new MockWindow(); }); it('Event() requires type', () => { expect(() => { new win.Event(); }).toThrow(); }); it('Event(type)', () => { const ev = new win.Event('click') as Event; expect(ev.bubbles).toBe(false); expect(ev.cancelBubble).toBe(false); expect(ev.cancelable).toBe(false); expect(ev.composed).toBe(false); expect(ev.currentTarget).toBe(null); expect(ev.defaultPrevented).toBe(false); expect(ev.srcElement).toBe(null); expect(ev.target).toBe(null); expect(typeof ev.timeStamp).toBe('number'); expect(ev.type).toBe('click'); }); it('Event(type, eventInitDict)', () => { const eventInitDict = { bubbles: true, composed: true }; const ev = new win.Event('click', eventInitDict) as Event; expect(ev.bubbles).toBe(true); expect(ev.cancelBubble).toBe(false); expect(ev.cancelable).toBe(false); expect(ev.composed).toBe(true); expect(ev.currentTarget).toBe(null); expect(ev.defaultPrevented).toBe(false); expect(ev.srcElement).toBe(null); expect(ev.target).toBe(null); expect(typeof ev.timeStamp).toBe('number'); expect(ev.type).toBe('click'); }); it('CustomEvent() requires type', () => { expect(() => { new win.CustomEvent(); }).toThrow(); }); it('CustomEvent(type)', () => { const ev = new win.CustomEvent('click') as CustomEvent; expect(ev.bubbles).toBe(false); expect(ev.cancelBubble).toBe(false); expect(ev.cancelable).toBe(false); expect(ev.composed).toBe(false); expect(ev.currentTarget).toBe(null); expect(ev.defaultPrevented).toBe(false); expect(ev.srcElement).toBe(null); expect(ev.target).toBe(null); expect(typeof ev.timeStamp).toBe('number'); expect(ev.type).toBe('click'); expect(ev.detail).toBe(null); }); it('CustomEvent(type, eventInitDict)', () => { const eventInitDict = { bubbles: true, composed: true, detail: 88 }; const ev = new win.CustomEvent('click', eventInitDict) as CustomEvent; expect(ev.bubbles).toBe(true); expect(ev.cancelBubble).toBe(false); expect(ev.cancelable).toBe(false); expect(ev.composed).toBe(true); expect(ev.currentTarget).toBe(null); expect(ev.defaultPrevented).toBe(false); expect(ev.srcElement).toBe(null); expect(ev.target).toBe(null); expect(typeof ev.timeStamp).toBe('number'); expect(ev.type).toBe('click'); expect(ev.detail).toBe(88); }); it('KeyboardEvent() requires type', () => { expect(() => { new win.KeyboardEvent(); }).toThrow(); }); it('KeyboardEvent(type)', () => { const ev = new win.KeyboardEvent('keyup') as KeyboardEvent; expect(ev.bubbles).toBe(false); expect(ev.cancelBubble).toBe(false); expect(ev.cancelable).toBe(false); expect(ev.composed).toBe(false); expect(ev.currentTarget).toBe(null); expect(ev.defaultPrevented).toBe(false); expect(ev.srcElement).toBe(null); expect(ev.target).toBe(null); expect(typeof ev.timeStamp).toBe('number'); expect(ev.type).toBe('keyup'); expect(ev.code).toBe(''); expect(ev.key).toBe(''); expect(ev.altKey).toBe(false); expect(ev.ctrlKey).toBe(false); expect(ev.metaKey).toBe(false); expect(ev.shiftKey).toBe(false); expect(ev.location).toBe(0); expect(ev.repeat).toBe(false); }); it('KeyboardEvent(type, eventInitDict)', () => { const eventInitDict = { bubbles: true, composed: true, code: 'KeyA', key: 'A', altKey: false, ctrlKey: false, metaKey: false, shiftKey: true, location: 0, repeat: true }; const ev = new win.KeyboardEvent('keyup', eventInitDict) as KeyboardEvent; expect(ev.bubbles).toBe(true); expect(ev.cancelBubble).toBe(false); expect(ev.cancelable).toBe(false); expect(ev.composed).toBe(true); expect(ev.currentTarget).toBe(null); expect(ev.defaultPrevented).toBe(false); expect(ev.srcElement).toBe(null); expect(ev.target).toBe(null); expect(typeof ev.timeStamp).toBe('number'); expect(ev.type).toBe('keyup'); expect(ev.code).toBe('KeyA'); expect(ev.key).toBe('A'); expect(ev.altKey).toBe(false); expect(ev.ctrlKey).toBe(false); expect(ev.metaKey).toBe(false); expect(ev.shiftKey).toBe(true); expect(ev.location).toBe(0); expect(ev.repeat).toBe(true); }); });
f2092460940edcc50db89cc3cea67d27c82f7491
TypeScript
guardaco/javascript-sdk
/__tests__/decoder.test.ts
2.515625
3
import * as amino from "../src/amino" import { unMarshalBinaryLengthPrefixed } from "../src/amino" import { AminoPrefix, StdTx, SendMsg } from "../src/types/" class Msg { constructor(opts) { opts = opts || {} this.string = opts.address || "" this.buf = opts.buf || Buffer.alloc(0) this.price = opts.price || 0 this.bool = opts.timeinforce || false this.quantity = opts.quantity || 0 this.coin = [] } } Msg.prototype.msgType = AminoPrefix.NewOrderMsg describe("decoder", () => { it("decode type", () => { const opt = { address: "tbnb1l6vgk5yyxcalm06gdsg55ay4pjkfueazkvwh58", buf: Buffer.from("1213"), price: 100000000, timeinforce: true, quantity: 0, coins: [ { denom: "BNB", amount: 1000000000, }, ], aminoPrefix: AminoPrefix.NewOrderMsg, } const msgObj = new Msg(opt) const result = new Msg() let bytes = amino.marshalBinary(msgObj) bytes = Buffer.from(bytes, "hex") amino.unMarshalBinaryLengthPrefixed(bytes, result) expect(JSON.stringify(result)).toBe(JSON.stringify(msgObj)) }) })
37a3ab088086fa8a408e89438b2d333c663315b4
TypeScript
newfangledman/typedown
/src/classes/handlers.ts
2.671875
3
import { ParseElement } from "./parser"; import { IMarkdownVisitable, IMarkdownDocument, IMarkdownVisitor } from "./types/interfaces"; import {MarkdownVisitable} from "./visitors" abstract class Handler<T>{ protected next: Handler<T> | null = null; public setNext(next: Handler<T>): void{ this.next = next } public handleRequest(request: T){ if(!this.canHandle(request)){ if(this.next){ this.next.handleRequest(request) } return; } } protected abstract canHandle(request: T): boolean } export class ParseChainHandler extends Handler<ParseElement>{ private readonly visitable: IMarkdownVisitable = new MarkdownVisitable(); constructor(private readonly document: IMarkdownDocument, private readonly tagType: string, private readonly visitor: IMarkdownVisitor){ super() } } export class HtmlHandler { public textChangeHandler() : void { } }
b30ec087282ca691ce536c3dd92bb1e350507c25
TypeScript
Yota-K/apollo-server-sample
/src/index.ts
2.671875
3
import { ApolloServer, gql } from 'apollo-server'; import { Resolvers } from './generated/graphql'; const typeDefs = gql` type Query { hello: String } `; // MEMO: リゾルバの型を指定。 // 以下のように記述することで、スキーマとリゾルバの型が一致しない時はTSのコンパイルが通らなくなる const resolvers: Resolvers = { Query: { hello: () => 'world', }, }; const server = new ApolloServer({ typeDefs, resolvers, }) server.listen().then(({ url }) => { console.log(`server start ${url}`); });
66cac1c4cc7d81b6a49c8ba91992ec2da8f59c94
TypeScript
type-challenges/type-challenges
/questions/09160-hard-assign/test-cases.ts
3
3
import type { Equal, Expect } from '@type-challenges/utils' // case1 type Case1Target = {} type Case1Origin1 = { a: 'a' } type Case1Origin2 = { b: 'b' } type Case1Origin3 = { c: 'c' } type Case1Answer = { a: 'a' b: 'b' c: 'c' } // case2 type Case2Target = { a: [1, 2, 3] } type Case2Origin1 = { a: { a1: 'a1' } } type Case2Origin2 = { b: [2, 3, 3] } type Case2Answer = { a: { a1: 'a1' } b: [2, 3, 3] } // case3 type Case3Target = { a: 1 b: ['b'] } type Case3Origin1 = { a: 2 b: { b: 'b' } c: 'c1' } type Case3Origin2 = { a: 3 c: 'c2' d: true } type Case3Answer = { a: 3 b: { b: 'b' } c: 'c2' d: true } // case 4 type Case4Target = { a: 1 b: ['b'] } type Case4Answer = { a: 1 b: ['b'] } type cases = [ Expect<Equal<Assign<Case1Target, [Case1Origin1, Case1Origin2, Case1Origin3]>, Case1Answer>>, Expect<Equal<Assign<Case2Target, [Case2Origin1, Case2Origin2]>, Case2Answer>>, Expect<Equal<Assign<Case3Target, [Case3Origin1, Case3Origin2]>, Case3Answer>>, Expect<Equal<Assign<Case4Target, ['', 0]>, Case4Answer>>, ]
fd0862d7ca5809449ef5965183f9c452fa60dca5
TypeScript
mediasourcery/cross-blockchain-doc-uploader
/src/apis/capabilities/createCapabilityApi.ts
2.65625
3
import axios from 'axios'; export interface ICreateCapabilityApi { (request: ICreateCapabilityApiRequest): Promise<ICreateCapabilityApiResponse>; } export interface ICreateCapabilityApiRequest { owner: string; name: string; target: string; } export interface ICreateCapabilityApiResponse { success: boolean; data: ICreateCapabilityApiResponseData; errors: { code: string; category: string; message: string; data: any[]; }[]; } export interface ICreateCapabilityApiResponseData { owner: string; capability: { name: string; target: string; }; } export const createCapabilityApi: ICreateCapabilityApi = async request => { const params: { owner?: string; name?: string; target?: string; } = {}; if (request.name) { params.name = request.name; } if (request.owner) { params.owner = request.owner; } if (request.target) { params.target = request.target; } const response = await axios({ headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` }, params, method: 'POST', url: `${process.env.AUTH_API_URL}/api/capabilities` }); return response.data; };
1cc324fd2f5e566ce3d67044d5fa3a6da997bcc6
TypeScript
kozlov-victor/vEngine2
/demo/dataTexture/pbmReader.ts
3.03125
3
import {DebugError} from "@engine/debug/debugError"; import {Game} from "@engine/core/game"; import {DataTexture} from "@engine/renderer/webGl/base/dataTexture"; import {ITexture} from "@engine/renderer/common/texture"; export class PbmReader { constructor(private game:Game,buff:ArrayBuffer){ this.file = new Int8Array(buff); } private currentPos:number = 0; private readonly file:Int8Array; private static charAsBits(char:string):number[]{ const code:number = char.charCodeAt(0); const arr:number[] = []; for (let i:number=7;i>=0;i--){ const powOfTwo:number = Math.pow(2,i); arr.push((code & powOfTwo)>0?1:0); } return arr; } public createTexture():ITexture{ const {width,height} = this.readHead(); const t:DataTexture = new DataTexture(this.game,width,height); const bitmap = this.read(width,height); t.setNewData(new Uint8Array(bitmap)); return t; } private isEOF():boolean{ return this.currentPos===this.file.length; } private getNextByte():number{ if (this.isEOF()) throw new DebugError('unexpected and of file'); return this.file[this.currentPos++]; } private getNextChar():string{ return String.fromCharCode(this.getNextByte()); } private skipNextChar(charAs:string):void{ const char:string = this.getNextChar(); if (char!==charAs) throw new DebugError(`unexpected char ${char}, expected ${charAs}`); } private skipNewLine():void{ this.skipNextChar('\n'); } private showNextChar():string{ const char:string = this.getNextChar(); this.currentPos--; return char; } private readNextString(l:number):string { let res:string = ''; for (let i:number=0;i<l;i++){ res+=this.getNextChar(); } return res; } private readNextLine():string{ return this.readNextStringUntil(['\n']); } private readNextStringUntil(charsUntil:string[]):string{ let res:string = ''; for (;;){ const char:string = this.getNextChar(); if (charsUntil.indexOf(char)>-1) break; res+=char; } return res; } private readNextIntUntil(charsUntil:string[]):number{ const str:string = this.readNextStringUntil(charsUntil); const num:number = parseInt(str,10); if (isNaN(num)) throw new DebugError(`can not read number: wrong character sequence '${str}'`); return num; } private readHead():{width:number,height:number}{ const header:string = this.readNextString(2); if (header!=='P4') throw new DebugError('only P4 headers are supported'); this.skipNewLine(); if (this.showNextChar()==='#') { this.readNextLine(); } const width:number = this.readNextIntUntil([' ']); const height:number = this.readNextIntUntil([' ','\n']); return {width,height}; } private read(width:number,height:number):number[]{ const desiredSize:number = width*height*4; const data:number[] = new Array(desiredSize); data.fill(255); let i:number = 0; while (!this.isEOF()) { const char:string = this.getNextChar(); const bits:number[] = PbmReader.charAsBits(char); for (const bit of bits) { if (bit===0) { data[i++]=100; data[i++]=255; data[i++]=255; data[i++]=255; } else { data[i++]=0; data[i++]=33; data[i++]=0; data[i++]=255; } } } return data; } }
abff64087d82e6697480f686966e0af2873e508e
TypeScript
by1773/MT-Data
/src/utils/common.ts
2.875
3
/* * @Descripttion: * @version: * @Author: by1773 * @Date: 2019-09-17 13:54:16 * @LastEditors: by1773 * @LastEditTime: 2019-09-24 08:42:51 */ /** * 共用函数 */ import Taro,{ Component } from "@tarojs/taro"; export const repeat = (str = '0', times) => (new Array(times + 1)).join(str); // 时间前面 +0 export const pad = (num, maxLength = 2) => repeat('0', maxLength - num.toString().length) + num; // 全局的公共变量 export let globalData: any = { } // 时间格式装换函数 export const formatTime = time => { `${pad(time.getHours())}:${pad(time.getMinutes())}:${pad(time.getSeconds())}.${pad(time.getMilliseconds(), 3)}` } export const DateFormat = (date) =>{ if(!date) return null let [ week,year,mouth,weekAlias,toDay] = ['', 0, '','',0]; let dates = new Date(date.replace(/-/g, "/")) const day=dates.getDay(); toDay = dates.getDate() year = dates.getFullYear() ; if(dates.getMonth() +1 < 10){ mouth = `0${dates.getMonth() +1}`; }else{ mouth = `${dates.getMonth() +1}`; } if(day==0){ week="星期日"; weekAlias='SUN' } else if(day==1){ week="星期一"; weekAlias='MON' } else if (day == 2) { week = "星期二"; weekAlias='TUE' } else if (day == 3) { week = "星期三"; weekAlias='WED' } else if (day == 4) { week = "星期四"; weekAlias='THU' } else if (day == 5) { week = "星期五"; weekAlias='FRI' } else if (day == 6) { week = "星期六"; weekAlias='STA' } return { week,year,mouth,weekAlias,toDay,fullDay:`${mouth}/${toDay}` } } /** * @name: by1773 * @test: 小数转百度数 * @msg: * @param {type} * @return: */ export const toPercent=(point)=>{ // console.log(point) if(!point) return `--%` var str=Number(point*100).toFixed(1); str+="%"; return str; }
7dd5ac819962622e99d1769308242922d7764b66
TypeScript
mickmister/live-to-jam-app
/src/types/model-interfaces.ts
3.0625
3
export interface Note { number: number // i.e. 84 name: string // i.e. "C" octave: number // i.e. 5 } export interface Chord { name: string notes: Note[] midiNotes: MidiNote[] } export interface Scale { root: Note quality: string } export interface Progression { chords: Chord[] } export interface NoteCollection { notes: Note[] } export type MidiNumber = number export type MidiNumberMod = number export const noteToMidiNumber = (note: Note) => { return note.number } export enum Quality { MAJOR = 'Major', MINOR = 'Minor', }; export type MidiNote = { note: number; velocity: number; } export interface MidiIO { onMidiIn(callback: (note: MidiNote) => void): void; sendMidi(midiNotes: MidiNote[]): void; } export interface Logger { log(message: string): void; }
426d585ef330d6569307fb26947bbced0444ba3e
TypeScript
AndriiChernyshov/angular-shop
/src/app/app.component.ts
2.515625
3
import { Component, OnInit } from '@angular/core'; import { Cart } from './components/cart/models/cart.model'; import { Product } from './components/product/models/product.model'; import { ProductService } from './components/product/product.service' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [ProductService] }) export class AppComponent implements OnInit{ constructor(private productService: ProductService) { } title = 'app'; name = "Angular Shop site"; description = "Angular Test project"; price:number = 10; category: CategoryTypes = CategoryTypes.Good; isAvailable:boolean = true; equivalents: number[] = [41,42,43,46]; ingredients: Array<string> = ["Not bad", "Good", "Wwwweee"]; cart: Cart = { productIds: [], totalPrice: 0, discount: 0 }; products: Product[]; selectedProduct: Product; listProduct(): void{ this.products = this.productService.listProduct(); } onSelect(product:Product){ console.log(product.name); this.selectedProduct = product; } onAddProductToCartClcik(product:Product){ this.cart.totalPrice = this.cart.totalPrice + product.price; } onClearCartClcik(){ this.cart.totalPrice = 0; } ngOnInit() : void{ this.listProduct(); } } enum CategoryTypes{ Good = 1, Bad, Ugly }
ae6b98ecddeac5520259a12d44e681de832be7de
TypeScript
svirmi/stream-charts
/src/app/charts/utils.ts
3.1875
3
import {Dimensions, Margin} from "./margins" import * as d3 from "d3"; import {Selection, ZoomTransform} from "d3"; import {calculateZoomFor, ContinuousNumericAxis} from "./axes"; import {ContinuousAxisRange} from "./continuousAxisRangeFor"; /** * No operation function for use when a default function is needed */ export const noop = () => { } /** * Calculates whether the mouse is in the plot-area * @param x The x-coordinate of the mouse's position * @param y The y-coordinate of the mouse's position * @param margin The plot margins * @param dimensions The the overall dimensions (plot dimensions plus margin) * @return `true` if the mouse is in the plot area; `false` if the mouse is not in the plot area */ export const mouseInPlotAreaFor = (x: number, y: number, margin: Margin, dimensions: Dimensions): boolean => x > margin.left && x < dimensions.width - margin.right && y > margin.top && y < dimensions.height - margin.bottom /** * Calculates the width of an SVG text element, based on its bounding box * @param elem The SVG text element * @return The width in pixels, or 0 if SVG text element has not children */ export const textWidthOf = (elem: Selection<SVGTextElement, any, HTMLElement, any>) => elem.node()?.getBBox()?.width || 0 /** * The object returned by the zoom */ export interface Zoom { zoomFactor: number, timeRange: ContinuousAxisRange, } /** * Called when the user uses the scroll wheel (or scroll gesture) to zoom in or out. Zooms in/out * at the location of the mouse when the scroll wheel or gesture was applied. * @param transform The d3 zoom transformation information * @param x The x-position of the mouse when the scroll wheel or gesture is used * @param plotDimensions The current dimensions of the plot * @param containerWidth The container width * @param margin The plot margins * @param xAxis The linear x-axis * @param timeRange The time-range of the current x-axis * @return The zoom factor and updated time-range */ export function handleZoom( transform: ZoomTransform, x: number, plotDimensions: Dimensions, containerWidth: number, margin: Margin, xAxis: ContinuousNumericAxis, timeRange: ContinuousAxisRange, ): Zoom | undefined { if (x > 0 && x < containerWidth - margin.right) { const {range, zoomFactor} = calculateZoomFor(transform, x, plotDimensions, xAxis, timeRange) return {zoomFactor, timeRange: range} } } export function formatNumber(value: number, format: string): string { return isNaN(value) ? '---' : d3.format(format)(value) } export function formatTime(value: number): string { return formatNumber(value, " ,.0f") } export function formatValue(value: number): string { return formatNumber(value, " ,.3f") } export function formatChange(v1: number, v2: number, format: string): string { return isNaN(v1) || isNaN(v2) ? '---' : d3.format(format)(v2 - v1) } export function formatTimeChange(v1: number, v2: number): string { return formatChange(v1, v2, " ,.0f") } export function formatValueChange(v1: number, v2: number): string { return formatChange(v1, v2, " ,.3f") } /** * Calculates the (min, max) of all the values (from the accessor) in the data matrix, clamped by the global * (currentMin, currentMax). * * Curried function that accepts an accessor used to grab the value from the data point, and array of (x, y) values * (each (x, y) value is represented as [number, number] tuple), and a global, current min and max values. The * global, current min and max clamp the calculated min and max values. * @param accessor Access function that accepts a datum and returns the value which to use in the min-max calc * @return A function that accepts data (represented as a matrix of (x, y) pairs, where each row is a data series), * a global currentMin and currentMax, which clamp the calculated results. The function return a tuple holding the * min as the first value and the max as the second value. * @example * // function that calculates the min-max of the y-values generated by calling the minMaxOf and handing it the * // accessor function that grabs the y-value from the datum * const minMaxTimeSeriesY: (data: Array<TimeSeries>, currentMinMax: [number, number]) => [number, number] = minMaxOf((datum: [number, number]): number => datum[1]) */ export const minMaxOf = <T>(accessor: (v: T) => number) => (data: Array<Array<T>>, currentMinMax: [number, number]): [number, number] => [ Math.min(d3.min(data, series => d3.min(series, datum => accessor(datum))) || 0, currentMinMax[0]), Math.max(d3.max(data, series => d3.max(series, datum => accessor(datum))) || 1, currentMinMax[1]) ] /** * Sets up the min-max function to extract the y-value of the time-series. * * Defines a function that accepts an array of time-series (matrixish) and returns the min and max * y-value for all the values in all the series. * @see minMaxOf */ export const minMaxYFor = minMaxOf((datum: [number, number]): number => datum[1])
44405f7598035c2c1721ec470a761eb2ce57d17e
TypeScript
AhmadKabakibi/checkout-cart
/src/app/modules/collection/collection.module.ts
2.703125
3
export class Collection { public id: string; public price: number; public name: string; public description: string; public photo: string; public updateFrom(src: Collection): void { this.id = src.id; this.price = src.price; this.name = src.name; this.description = src.description; this.photo = src.photo; } }
8253edee6f638b92c36fce47db537931d984e37d
TypeScript
dex-it/react-native-template-dex
/template/src/core/BaseComponent.ts
2.640625
3
import React from "react"; export abstract class BaseReduxComponent<TSP, TDP, TS= {}, TOwnProps = {}> extends React.Component<IReduxProps<TSP, TDP, TOwnProps>, TS> { get dispatchProps(): TDP { return (this.props as any).dispatchProps; } get stateProps(): TSP { return (this.props as any).stateProps; } } export type IReduxProps<TStateProps, TDispatchProps, TOwnProps = {}> = { [key in keyof TOwnProps] : TOwnProps[key] } & { readonly stateProps?: TStateProps; readonly dispatchProps?: TDispatchProps; };
9e13e5804b91a3c7d2a59040960cd4c19a8f6670
TypeScript
PrayaAmadigaPitasa/react-native-design-kit
/src/types/chip/ChipType.ts
2.828125
3
export type ChipActionType = 'chip' | 'radio' | 'checkbox'; export type ChipIcon = (info: ChipInfo) => JSX.Element; export type ChipIconAction = ( id: string, isSelected: boolean, ) => 'delete' | 'check' | (() => void); export interface ChipInfo { id: string; isSelected: boolean; }
238d8b1a7e2eb2c40e675893cf03425447f8a4fe
TypeScript
AndreiShybin/Authenticator
/src/ui/qr.ts
2.515625
3
import * as QRGen from 'qrcode-generator'; import {OTPType, UIConfig} from '../models/interface'; import {OTPEntry} from '../models/otp'; import {UI} from './ui'; async function getQrUrl(entry: OTPEntry) { return new Promise( (resolve: (value: string) => void, reject: (reason: Error) => void) => { const label = entry.issuer ? (entry.issuer + ':' + entry.account) : entry.account; const type = entry.type === OTPType.hex ? OTPType[OTPType.totp] : (entry.type === OTPType.hhex ? OTPType[OTPType.hotp] : OTPType[entry.type]); const otpauth = 'otpauth://' + type + '/' + label + '?secret=' + entry.secret + (entry.issuer ? ('&issuer=' + entry.issuer.split('::')[0]) : '') + ((entry.type === OTPType.hotp || entry.type === OTPType.hhex) ? ('&counter=' + entry.counter) : '') + (entry.type === OTPType.totp && entry.period ? ('&period=' + entry.period) : ''); const qr = QRGen(0, 'L'); qr.addData(otpauth); qr.make(); resolve(qr.createDataURL(5)); return; }); } export async function qr(_ui: UI) { const ui: UIConfig = { data: {qr: ''}, methods: { shouldShowQrIcon: (entry: OTPEntry) => { return entry.secret !== 'Encrypted' && entry.type !== OTPType.battle && entry.type !== OTPType.steam; }, showQr: async (entry: OTPEntry) => { const qrUrl = await getQrUrl(entry); _ui.instance.qr = `url(${qrUrl})`; _ui.instance.currentClass.qrfadein = true; _ui.instance.currentClass.qrfadeout = false; return; }, hideQr: () => { _ui.instance.currentClass.qrfadein = false; _ui.instance.currentClass.qrfadeout = true; setTimeout(() => { _ui.instance.currentClass.qrfadeout = false; }, 200); return; } } }; _ui.update(ui); }
64ca8a8f4e3c424d413023698baaa1ff1e8c914d
TypeScript
nicx519y/H5Game-Fish
/src/water.ts
2.578125
3
// import { AssetsLoader } from './assetsLoader'; // import { WaterMask } from './waterMask'; export class Water extends createjs.Container { private box; //水的mask,负责水浮动动画 private width: number = 0; private height: number = 0; private duration: number = 0; private color: string = '#000000'; /** * * @param width 水的宽度,一般设置为和屏幕宽度相等 * @param height 水的波浪高度 * @param y 水的背景图片纵坐标 * @param framerate 水波横向移动速度,数值越大越慢 */ render(colors: Array<string>, radios: Array<number>, width: number = 640, height: number = 10, duration: number = 100) { this.width = width; this.height = height; this.duration = duration; // 添加渐变色 this.box = new createjs.Shape(); this.box.graphics.beginLinearGradientFill( colors, radios, 0, 0, 0, 2000 ) .moveTo(0, 0) .bezierCurveTo(width / 3, height, width * 2 / 3, height, width, 0) .bezierCurveTo(width * 4 / 3, - height, width * 5 / 3, - height, width * 2, 0) .bezierCurveTo(width * 7 / 3, height, width * 8 / 3, height, width * 3, 0) .lineTo(width * 3, 1000) .lineTo(0, 1000) .lineTo(0, 0) .closePath() .endFill(); // this.box.cache(0,y - this.height, width * 3, 1000); this.box.cache(0, -height, width * 3, 1000); this.addChild(this.box); createjs.Tween.get(this.box, { override: true, loop: true }) .to({ x: -2*width }, duration); } }
19c1d4654007a017a021a7d4ef68a127ff32598c
TypeScript
G-Rath/terra
/src/utils/assertDefined.ts
2.71875
3
export function assertDefined(val: unknown, message?: string): asserts val { if (val === undefined) { throw new Error(message ?? `Unexpected undefined value`); } }
6369933e0259da7201a1ea7705a5194715a54618
TypeScript
chunkitmax/node-decorators
/di/src/container.ts
2.890625
3
import { InjectableId, Provider, StoreProvider, ClassProvider, FactoryProvider, ValueProvider, Dependency, Injectable, Factory } from './types'; import { Store } from './store'; import { MissingProviderError, RecursiveProviderError } from './errors'; export class Container { /** * Register new or replace providers * * @static * @param {Provider[]} providers */ public static provide(providers: Provider[]) { providers .filter((_provider: ClassProvider) => _provider.useClass) .forEach((_provider: ClassProvider) => this.registerClassProvider(_provider)); providers .filter((_provider: FactoryProvider) => _provider.useFactory) .forEach((_provider: FactoryProvider) => this.registerFactoryProvider(_provider)); providers .filter((_provider: ValueProvider) => _provider.useValue) .forEach((_provider: ValueProvider) => this.registerValueProvider(_provider)); } /** * Get instance of injectable * * @template T * @param {Injectable} injectable * @returns {T} */ public static get<T>(injectable: Injectable): T { const provider: StoreProvider = Store.findProvider(injectable); if (provider === undefined) { throw new MissingProviderError(injectable); } return this.resolveProvider(provider) } /** * Resolve provider * * @private * @param {StoreProvider} provider * @param {StoreProvider[]} [requesters = []] provider, that initiated di * @returns {*} */ private static resolveProvider(provider: StoreProvider, requesters: StoreProvider[] = []): any { if (provider.value) { return provider.value; } const _requesters = requesters.concat([provider]); const deps = provider .deps.map((dep: Dependency) => { const requesterProvider: StoreProvider = _requesters.find((requester: StoreProvider) => requester.id === dep.id); if (requesterProvider) { throw new RecursiveProviderError(_requesters, requesterProvider); } const depService: StoreProvider = Store.findProvider(dep.id); if (!depService && !dep.optional) { throw new MissingProviderError(provider, dep); } if (!depService && dep.optional) { return null; } return this.resolveProvider(depService, _requesters); }); provider.value = provider.factory ? provider.factory(...deps) : new provider.type(...deps); return provider.value; } /** * Register class provider * * @private * @static * @param {ClassProvider} provider */ private static registerClassProvider(provider: ClassProvider): void { const id: InjectableId = Store.providerId(provider.provide); const classProvider: StoreProvider = Store.findProvider(provider.useClass); const deps: Dependency[] = classProvider ? classProvider.deps : (provider.deps || []) .map((dep: Injectable) => ({ id: Store.providerId(dep) })); Store.replaceProvider(provider.provide, { id, deps, type: provider.useClass }); } /** * Register factory provider * * @private * @static * @param {FactoryProvider} provider */ private static registerFactoryProvider(provider: FactoryProvider): void { const id: InjectableId = Store.providerId(provider.provide); const factory: Factory = provider.useFactory; const deps: Dependency[] = (provider.deps || []) .map((dep: Injectable) => ({ id: Store.providerId(dep) })); Store.replaceProvider(provider.provide, { id, factory, deps }) } /** * Register value provider * * @private * @static * @param {ValueProvider} provider * @memberof Container */ private static registerValueProvider(provider: ValueProvider): void { const id: InjectableId = Store.providerId(provider.provide); const value: any = provider.useValue; Store.replaceProvider(provider.provide, { id, value }); } }
795f9f840ad8ccc25fa68cc10901666e1565e0a5
TypeScript
BrooklinJazz/dragon-chess
/src/gamelogic/Piece.ts
2.84375
3
import { positionNumbers, positions as allPositions } from "../constants/positions"; import { IPiece } from "../constants/pieces"; import { Position } from "./Position"; import { Player } from "../redux/types"; import { PieceFactory } from "./PieceFactory"; import { pipe } from "../helpers.ts/pipe"; export class Piece { public position: Position; constructor( public piece: IPiece, public pieces: IPiece[] ) { this.position = new Position(piece.position, piece.player); } player = () => this.piece.player; isBlack = () => this.player() === Player.black isWhite = () => this.player() === Player.white isFirstMove = () => !this.piece.hasMoved public allTakenPositions = this.pieces.map(each => each.position) public whitePieces = this.pieces.filter(each => each.player === Player.white) public blackPieces = this.pieces.filter(each => each.player === Player.black) public blackPositions = this.blackPieces.map(each => each.position) public whitePositions = this.whitePieces.map(each => each.position) public friendlyPieces = this.isWhite() ? this.whitePieces : this.blackPieces public opponentPieces = this.isWhite() ? this.blackPieces : this.whitePieces public friendlyPositions = this.friendlyPieces.map(each => each.position) public opponentPositions = this.opponentPieces.map(each => each.position) filterOutUndefined = (positions: (string | undefined)[]): string[] => positions.filter(each => each) as string[]; filterInsideBoard = (positions: string[]) => positions.filter(position => allPositions.some(each => each === position)); filterOutFriendlyPositions = (positions: string[]) => positions.reduce((total: string[], each) => { return this.friendlyPositions.includes(each) ? total : total.concat(each); }, []); up = () => this.position.up(); down = () => this.position.down(); right = () => this.position.right(); left = () => this.position.left(); upLeft = () => this.up().left(); upRight = () => this.up().right(); downRight = () => this.down().right(); downLeft = () => this.down().left(); takeablePositions(): string[] { // this avoids max call stack but is likely incorrect for validMovePositions. return this.movePositionsAfterUniqueFilters(); } validMovePositions(): string[] { return pipe( this.filterOutLosingPositions )(this.movePositionsAfterUniqueFilters()) } movePositionsAfterUniqueFilters(): string[] { throw new Error("NYI movePositionsAfterUniqueFilters"); } baseMovePositions(): (string | undefined)[] { throw new Error("NYI movePositions"); } all = (fn: () => Position, total: string[] = []): string[] => { const position = fn(); const returnVal = position.tempValue(); if (!returnVal || this.friendlyPositions.some(each => each === returnVal)) { position.revert(); return total; } if (this.opponentPositions.some(each => each === returnVal)) { position.revert(); return total.concat(returnVal); } return this.all(fn, total.concat(returnVal)); }; filterOutLosingPositions = (positions: string[]) => { return positions.filter(each => { const king = this.piece.type === "king" ? { ...this.piece, position: each } : this.friendlyPieces.find(each => each.type === "king") || {position: undefined} const opponentMoves = this.possibleOpponentMoves(each) const moveKillsKing = opponentMoves.some(each => each === king.position) return !moveKillsKing }); }; possibleOpponentMoves = (move: string): string[] => { if (!move) { return []; } const newPiece = { ...this.piece, position: move }; const newPieces = this.pieces.map(each => each.id === newPiece.id ? newPiece : each) return this.opponentPieces.filter(each => each.position !== move).reduce( (total: string[], opponentPiece) => { return [ ...total, ...PieceFactory.fromPiece( opponentPiece, newPieces ).takeablePositions() ]; }, [] ); } }
29c8c792f8ec96df2f14014df41a44acb79e54de
TypeScript
akulaarora/fancystack
/packages/web/src/lib/helpers.ts
2.796875
3
import { ManualFieldError } from "react-hook-form" import dayjs, { Dayjs } from "dayjs" export const snakeToCamel = (value: string) => value.replace(/_(\w)/g, m => m[1].toUpperCase()) export const capitalize = (str: string) => { return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase() } export const round = (value: number, places = 2) => { const exp = Math.pow(10, places) return Math.round(value * exp) / exp } export const sleep = (delay: number) => { return new Promise(resolve => { setTimeout(() => resolve(), delay) }) } export const decimalCount = (value: number) => { if (value % 1 !== 0) return value.toString().split(".")[1].length return 0 } export const getDays = (startDate: Dayjs, daysCount: number) => { return Array(daysCount) .fill(null) .map((_, v) => startDate.add(v, "day")) } export const isToday = (day: Dayjs) => { return dayjs(day).isSame(dayjs(), "day") } export const getMonths = (startDate: Dayjs, daysCount: number) => { // Include year to cater for scrolling further than 12 const monthsByDay = Array(daysCount) .fill(null) .map( (_, v) => startDate.add(v, "day").month() + "/" + startDate.add(v, "day").year(), ) const uniqueMonths = monthsByDay.filter(function(value, index, array) { return array.indexOf(value) === index }) return uniqueMonths.map(month => ({ month: Number(month.split("/", 2)[0]), year: Number(month.split("/", 2)[1]), })) } export const formatTime = (time: number) => { if (time !== 0) { let formatted if (Math.floor(time / 60)) { formatted = Math.floor(time / 60) + "h " if (Math.floor(time % 60)) { formatted = formatted + Math.floor(time % 60) + "m" } } else if (Math.floor(time % 60)) { formatted = Math.floor(time % 60) + "m" } return formatted } else { return false } } export const hoursInMins = (estimatedTime?: string | null) => { if (estimatedTime) { const split = estimatedTime.split(":") const minutes = parseInt(split[0]) * 60 return minutes + parseInt(split[1]) } else { return 0 } } // DAYJS set month is broken!! export const monthNames = [ "jan.", "feb.", "mar.", "apr.", "may.", "jun.", "jul.", "aug.", "sept.", "oct.", "nov.", "dec.", ] export const isMobileDevice = () => { return ( typeof window.orientation !== "undefined" || navigator.userAgent.indexOf("IEMobile") !== -1 ) } export interface ValidationError { property: string constraints: { [key: string]: string } } export function formatValidations( errors: ValidationError[], ): ManualFieldError<any>[] { return errors.map(error => ({ name: error.property, type: error.property, types: error.constraints, })) } export const formatFileName = (filename: string) => { const cleanFileName = filename.toLowerCase().replace(/[^a-z0-9]/g, "-") return cleanFileName }
d02c4aa1340f8c1f1298d31703ff722d25d4cda8
TypeScript
meghoshpritam/mail-send
/src/entities/Register.ts
2.625
3
import { Schema, model, Document } from 'mongoose'; export interface Register extends Document { name: string; email: string; status: boolean; } const registers = new Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, status: { type: Boolean, default: false }, }); const Registers = model<Register>('Exams', registers); export default Registers;
4459a97c2f1a46192c7adb138d79e25aac036a87
TypeScript
LoicMahieu/yup-locales
/src/locales/he.ts
2.9375
3
/*eslint-disable no-template-curly-in-string*/ import printValue from '../util/printValue'; import { LocaleObject } from 'yup'; // Based on https://github.com/jquense/yup/blob/2973d0a/src/locale.js export const mixed: LocaleObject['mixed'] = { default: '${path} לא קיים או לא תקין', required: '${path} הינו שדה חובה', oneOf: 'על ${path} להיות מהערכים הבאים: ${values}', notOneOf: 'אסור ${path} להיות מהערכים הבאים: ${values}', notType: ({ path, type, value, originalValue }) => { let isCast = originalValue != null && originalValue !== value; let msg = `${path} חייב להיות מסוג \`${type}\`, ` + `אבל התקבל: \`${printValue(value, true)}\`` + (isCast ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : '.'); if (value === null) { msg += `\n If "null" is intended as an empty value be sure to mark the schema as \`.nullable()\``; } return msg; }, }; export const string: LocaleObject['string'] = { length: '${path} חייב להכיל ${length} תווים בדיוק', min: '${path} חייב להכיל לפחות ${min} תווים', max: '${path} חייב להכיל פחות מ${max} תווים', matches: '${path} חייב להיות זהה ל: "${regex}"', email: '${path} צריך להיות מייל חוקי', url: '${path} צריך להיות כתובת חוקית', trim: '${path} must be a trimmed string', lowercase: '${path} must be a lowercase string', uppercase: '${path} must be a upper case string', }; export const number: LocaleObject['number'] = { min: '${path} חייב להיות גדול או שווה ל ${min}', max: '${path}חייב להיות קטן או שווה ל ${max}', lessThan: '${path} חייב להיות קטן מ ${less}', moreThan: '${path} חייב להיות גדול מ ${more}', positive: '${path} מוכרח להיות חיובי', negative: '${path} מוכרח להיות שלילי', integer: '${path} חייב להיות מספר שלם', }; export const date: LocaleObject['date'] = { min: '${path} צריך להיות אחרי ${min}', max: '${path} צריך להיות לפני ${max}', }; export const boolean: LocaleObject['boolean'] = {}; export const object: LocaleObject['object'] = { noUnknown: '${path} חייב להכיל את התבנית הספציפית של אובייקט התבנית', }; export const array: LocaleObject['array'] = { min: '${path} צריך להכיל לפחות ${min} פריטים', max: '${path} צריך להכיל פחות מ ${max} פריטים', };
8d35e7beb0af25d9a76c3f53b520bd289354db9f
TypeScript
CodeguruEdison/leetcode-typescript-solutions
/problems/207-Course-Schedule.ts
3.390625
3
// TS // Runtime: 84 ms, faster than 95.45% of TypeScript online submissions for Course Schedule. // Memory Usage: 41.1 MB, less than 77.27% of TypeScript online submissions for Course Schedule. function canFinish(numCourses: number, prerequisites: number[][]): boolean { const graph: number[][] = Array.from(Array(numCourses), () => []); const ranks: number[] = Array(numCourses).fill(0); prerequisites.forEach(([u, v]) => { graph[v].push(u); ranks[u]++; }); const queue: number[] = []; ranks.forEach((r, i) => { if (!r) queue.push(i); }); while (queue.length) { const f = queue.shift(); numCourses--; graph[f as number].forEach((neigh) => { ranks[neigh]--; if (!ranks[neigh]) queue.push(neigh); }); } return !numCourses; } // JS // Runtime: 76 ms, faster than 99.42% of JavaScript online submissions for Course Schedule. // Memory Usage: 41.2 MB, less than 63.39% of JavaScript online submissions for Course Schedule. // var canFinish = function (numCourses, prerequisites) { // const graph = Array.from(Array(numCourses), () => []); // const ranks = Array(numCourses).fill(0); // prerequisites.forEach(([u, v]) => { // graph[v].push(u); // ranks[u]++; // }); // const queue = []; // ranks.forEach((r, i) => { // if (!r) queue.push(i); // }); // while (queue.length) { // const f = queue.shift(); // numCourses--; // graph[f].forEach((neigh) => { // ranks[neigh]--; // if (!ranks[neigh]) queue.push(neigh); // }); // } // return !numCourses; // };
97e723a80214db7f69a3e10fc4c2b8373a45bd9e
TypeScript
AlexandreKimura/sixth-challenge-ignite-nodejs
/src/modules/statements/useCases/getStatementOperation/GetStatementOperationUseCase.spec.ts
2.6875
3
import { InMemoryStatementsRepository } from "@modules/statements/repositories/in-memory/InMemoryStatementsRepository" import { InMemoryUsersRepository } from "@modules/users/repositories/in-memory/InMemoryUsersRepository" import { CreateUserUseCase } from "@modules/users/useCases/createUser/CreateUserUseCase" import { ICreateUserDTO } from "@modules/users/useCases/createUser/ICreateUserDTO" import { AppError } from "@shared/errors/AppError" import { CreateStatementUseCase } from "../createStatement/CreateStatementUseCase" import { GetStatementOperationUseCase } from "./GetStatementOperationUseCase" let getStatementOperationUseCase: GetStatementOperationUseCase let statementRepositoryInMemory: InMemoryStatementsRepository let usersRepositoryInMemory: InMemoryUsersRepository let createUserUseCase: CreateUserUseCase let createStatementUseCase: CreateStatementUseCase enum OperationType { DEPOSIT = 'deposit', WITHDRAW = 'withdraw', TRANSFERS = 'transfers', } describe("List a operation", () => { beforeAll(() => { statementRepositoryInMemory = new InMemoryStatementsRepository(); usersRepositoryInMemory = new InMemoryUsersRepository(); getStatementOperationUseCase = new GetStatementOperationUseCase(usersRepositoryInMemory, statementRepositoryInMemory); createUserUseCase = new CreateUserUseCase(usersRepositoryInMemory); createStatementUseCase = new CreateStatementUseCase(usersRepositoryInMemory, statementRepositoryInMemory); }) it("Should not be able to create a statement with incorrect ID" , async () => { expect(async () => { const user: ICreateUserDTO = { name: "Alexandre", email: "Alexandre@teste.com", password: "123456", }; await createUserUseCase.execute(user); await getStatementOperationUseCase.execute({ user_id: "fail", statement_id: '100', }); }).rejects.toBeInstanceOf(AppError); }); it("Should be able to list a operation by statement ID", async () => { const user: ICreateUserDTO = { name: "Alexandre", email: "Alexandre@teste.com", password: "123456", }; const userCreated = await createUserUseCase.execute(user); const deposit = await createStatementUseCase.execute({ user_id: userCreated.id, amount: 100, description: "deposit", type: OperationType.DEPOSIT }); const statementOperation = await getStatementOperationUseCase.execute({ user_id: userCreated.id, statement_id: deposit.id, }); expect(statementOperation).toHaveProperty("id"); }); it("Should not be to list a operation by incorrect statement ID", async () => { expect(async () => { const user: ICreateUserDTO = { name: "Alexandre1", email: "Alexandre1@teste.com", password: "123456", }; const userCreated = await createUserUseCase.execute(user); await createStatementUseCase.execute({ user_id: userCreated.id, amount: 100, description: "deposit", type: OperationType.DEPOSIT }); await getStatementOperationUseCase.execute({ user_id: userCreated.id, statement_id: 'fakeStatement', }); }).rejects.toBeInstanceOf(AppError); }); })
13385abacdfc2103eddb68802952c4b252c2edf1
TypeScript
larongbingo/AZGH-College-Public-Portal
/src/shared/database/models/Room.entity.ts
2.59375
3
import { AllowNull, Column, DataType, Model, Table, } from "sequelize-typescript"; import { IRoom } from "../../interfaces/models/IRoom"; @Table({ tableName: "rooms", paranoid: true, }) export class Room extends Model<Room> implements IRoom { @AllowNull(false) @Column(DataType.STRING) public roomCode: string; @AllowNull(true) @Column(DataType.STRING) public description: string; }
22149ea12e3f9c0a1f544c8baef07e306b8c750a
TypeScript
VanSan888/thinknario
/src/providers/bibliothek/bibliothek.ts
2.53125
3
import { Injectable } from '@angular/core'; import firebase from 'firebase'; @Injectable() export class BibliothekProvider { constructor() { } // Funktion, um alle erstellten Szenarien auf ein Array zu schreiben getSzenarioList(): Promise<any> { return new Promise( (resolve, reject) => { firebase.database().ref("szenarioData") .on('value', snapshot => { //Deklarierung des Arrays let rawList = []; snapshot.forEach( snap => { //Hier wird mittels einer Firebase-Abfrage geschaut, ob schon ein Average für das Szenario //verfügbar ist. Sehr ähnlich zu szenarioProvider.checkPath, siehe Erklärung dort. //Wenn kein Average angegeben ist, der User also sein eigenes Szenario //noch nicht bewertet hat und es somit noch nicht vollständig ist, //Wird es auch nicht auf der HomePage (in der Bibliothek) angezeigt //Abzufragender Pfad: firebase.database().ref('/szenarioData') .child(snap.key).child("average") .on('value', data => { //Wenn ein Wert existiert, dann... if(data.exists()){ //Beschreibe das Arrays rawList.push({ //Es werden nur der .key, der username, der Average und die Problemdefintion für die //Darstellung auf bibliothekpage.html benötigt id: snap.key, username: snap.val().userName.userName, problemdefinition: snap.val().problemdefinition.problemdefinition, average: snap.val().average.average, }); } }); //Damit der .forEach "snap" => void einen wert returned und damit assignable to type // datasnapshot => boolean wird return false }); resolve(rawList); }); }); } //Funktion um mit Hilfe der (szenarioId) den Pfad zu bestimmen, aus den die Daten gelesen werden sollen //(szenarioId) legt fest, welche Szenariodaten gelesen und zurückgegeben werden sollen. //szenarioId wird je nach dem festgelegt, welche ion-card auf bibliothekpage.html angeklickt wird getSzenarioDetail(szenarioId): Promise<any> { return new Promise( (resolve, reject) => { firebase.database().ref("szenarioData/") .child(szenarioId).on('value', snapshot => { resolve({ //Beschreiben der Properties mit den Daten aus den jeweiligen Szenarien id: snapshot.key, username: snapshot.val().userName.userName, problemdefinition: snapshot.val().problemdefinition.problemdefinition, schluesselfaktor1: snapshot.val().schluesselfaktoren.schluesselfaktor1, schluesselfaktor2: snapshot.val().schluesselfaktoren.schluesselfaktor2, schluesselfaktor3: snapshot.val().schluesselfaktoren.schluesselfaktor3, schluesselfaktor4: snapshot.val().schluesselfaktoren.schluesselfaktor4, schluesselfaktor5: snapshot.val().schluesselfaktoren.schluesselfaktor5, schluesselfaktor6: snapshot.val().schluesselfaktoren.schluesselfaktor6, annahme1: snapshot.val().annahmen.annahme1.annahme, annahme2: snapshot.val().annahmen.annahme2.annahme, annahme3: snapshot.val().annahmen.annahme3.annahme, annahme4: snapshot.val().annahmen.annahme4.annahme, annahmebegruendung1: snapshot.val().annahmen.annahme1.begruendung, annahmebegruendung2: snapshot.val().annahmen.annahme2.begruendung, annahmebegruendung3: snapshot.val().annahmen.annahme3.begruendung, annahmebegruendung4: snapshot.val().annahmen.annahme4.begruendung, randbedingung1: snapshot.val().randbedingungen.randbedingung1.randbedingung, randbedingung2: snapshot.val().randbedingungen.randbedingung2.randbedingung, randbedingung3: snapshot.val().randbedingungen.randbedingung3.randbedingung, randbedingung4: snapshot.val().randbedingungen.randbedingung4.randbedingung, randbedingungbegruendung1: snapshot.val().randbedingungen.randbedingung1.begruendung, randbedingungbegruendung2: snapshot.val().randbedingungen.randbedingung2.begruendung, randbedingungbegruendung3: snapshot.val().randbedingungen.randbedingung3.begruendung, randbedingungbegruendung4: snapshot.val().randbedingungen.randbedingung4.begruendung, ereignis1: snapshot.val().ereignisse.ereignis1.ereignis, ereignis2: snapshot.val().ereignisse.ereignis2.ereignis, ereignis3: snapshot.val().ereignisse.ereignis3.ereignis, ereignis4: snapshot.val().ereignisse.ereignis4.ereignis, ereignisbegruendung1: snapshot.val().ereignisse.ereignis1.begruendung, ereignisbegruendung2: snapshot.val().ereignisse.ereignis2.begruendung, ereignisbegruendung3: snapshot.val().ereignisse.ereignis3.begruendung, ereignisbegruendung4: snapshot.val().ereignisse.ereignis4.begruendung, szenariotext: snapshot.val().szenariotext.ausgangslage, ausgangslage: snapshot.val().szenariotext.ausgangslage, entwicklung: snapshot.val().szenariotext.entwicklung, endzustand: snapshot.val().szenariotext.endzustand, hilfe: snapshot.val().szenariotext.hilfe, average: snapshot.val().average.average, }); }); }); } getRatedList(): Promise<any> { return new Promise( (resolve, reject) => { firebase.database().ref("ratingData").child(firebase.auth().currentUser.uid) .child("erstellteBewertungen").on('value', snapshot => { //Deklarierung des Arrays let rawList = []; snapshot.forEach( snap => { //Beschreiben des Arrays rawList.push({ //Es werden nur der .key, der username und die Problemdefintion für die //Darstellung auf bibliothekpage.html benötigt //Später soll auch die Anzahl der Kommentare //Auf das Array geschrieben werden und in bibliothekpage.html angezeigt werden. id: snap.key, username: snap.val().userName, problemdefinition: snap.val().problemdefinition, average: snap.val().average.average, }); return false }); resolve(rawList); }); }); } //Hier wird ein Array mit den UIDs beschrieben, von denen man eine Bewertung erhalten hat //In den updateUsername() updateAverage() und updateProblemdefinition() Funktionen wird dieses //Array benutzt, um auch in "ratingData/currentUser/erstellteBewertungen" den usernamen, den Average //und die Problemdefintion zu aktualisieren //--> Noch NICHT Einsatzbereit getErhalteneBewertungenList(): Promise<any> { return new Promise( (resolve, reject) => { firebase.database().ref("ratingData").child(firebase.auth().currentUser.uid) .child("erhalteneBewertungen").on('value', snapshot => { //Deklarierung des Arrays let rawList = []; snapshot.forEach( snap => { //Beschreiben des Arrays rawList.push({ //Es werden nur der .key, benötigt id: snap.key }); return false }); resolve(rawList); }); }); } /* Diese Funktion später nach dem Vorbild von getSzenariolist gestalten. Es soll dabei allerdings nach den meisten Kommentaren und/oder den besten Bewertungen durch .orderByChild() usw. gefiltert werden. getShortSzenarioList(): Promise<any> { return new Promise( (resolve, reject) => { firebase.database().ref("szenarioData").orderByChild().endAt(2) .on('value', snapshot => { let rawList = []; snapshot.forEach( snap => { rawList.push({ id: snap.key, username: snap.val().userName, problemdefinition: snap.val().problemdefinition, }); return false }); resolve(rawList); }); }); } */ }
e0b114f8596c8f2a8840f2ac3a63e5ef4ea16332
TypeScript
pinkfish/teamsfuse
/firebase/functions/ts/util/updateusers.ts
2.78125
3
import * as admin from 'firebase-admin'; import { DocumentSnapshot } from '@google-cloud/firestore'; const FieldValue = admin.firestore.FieldValue; const db = admin.firestore(); interface UsersAndPlayers { users: Record<string, any>; players: Record<string, any>; } // Updates the usersAndPlayers with exciting data when created or updated. export async function updateUsersAndPlayers( players: Record<string, any>, users: Record<string, any>, force: boolean, ): Promise<UsersAndPlayers> { const retUser: Record<string, any> = {}; const retPlayer: Record<string, any> = {}; const playerSet: Set<string> = new Set<string>(); // Go through the users and make sure there is still a a player for each one. for (const idx in users) { const user = users[idx]; let found = false; for (const player in user) { if (player !== 'added') { found = true; playerSet.add(player); } } if (!found) { retUser[user] = FieldValue.delete(); } } // go through the players and make sure we have a corresponding user. for (let idx in players) { idx = idx.trim(); if (!playerSet.has(idx) || force) { // Load the user details from the player and update. const playerData = await db.collection('Players').doc(idx).get(); const playerDataInner = playerData.data(); if (playerDataInner !== null && playerDataInner !== undefined) { for (const newIdx in playerDataInner.user) { if (!(newIdx in retUser)) { if (users === null || users === undefined || !(newIdx in users)) { retUser['users.' + newIdx + '.added'] = true; } } retUser['users.' + newIdx + '.' + idx] = true; } } } } return { users: retUser, players: retPlayer }; } export function updateUsers(data: Record<string, any>): Record<string, any> { const ret: Record<string, any> = {}; // Go through the users and make sure there is still a a player for each one. for (const idx in data) { const user = data[idx]; let found = false; for (const player in user) { if (player !== 'added') { found = true; } } if (!found) { ret[user] = FieldValue.delete(); } } return ret; } export function updateAdmins(doc: DocumentSnapshot, admins: Set<string>, oldAdmins: Set<string>): Record<string, any> { const ret: Record<string, any> = {}; for (const idx in admins) { // Update the seasons with the admins bits. ret['users.' + idx + '.admin'] = true; ret['users.' + idx + '.added'] = true; } if (oldAdmins) { const difference = new Set([...oldAdmins].filter((x) => !admins.has(x))); for (const toRemove in difference) { ret['users.' + toRemove + '.admin'] = FieldValue.delete(); fixEmptyUser(doc, ret, toRemove, 'admin', false); } } return ret; } // CLeanup the user section if a user is completely removed. export function fixEmptyUser( doc: DocumentSnapshot, updateData: Record<string, any>, user: string, specialUser: string, updateAdmin: boolean, ): void { const docData = doc.data(); if (docData && docData.users) { const users = { ...docData.users }; if (users) { const checkUser = users[user]; if (checkUser) { delete checkUser[specialUser]; delete checkUser['added']; if (Object.keys(checkUser).length === 0) { // Remove the user from the team altogether. updateData['users.' + user] = admin.firestore.FieldValue.delete(); delete updateData['users.' + user + '.' + specialUser]; } } } } // See if we should delete the admin too. if (updateAdmin) { if (docData && docData.admins) { const admins = { ...docData.admins }; if (admins) { const checkAdmin = admins[user]; if (checkAdmin) { delete checkAdmin[specialUser]; delete checkAdmin['added']; if (Object.keys(checkAdmin).length === 0) { // Remove the user from the team altogether. updateData['admins.' + user] = admin.firestore.FieldValue.delete(); delete updateData['admins.' + user + '.' + specialUser]; } } } } } return; }
acde142a207cf990f5a769e6fe3ad120550efae9
TypeScript
ag-grid/ag-grid
/grid-packages/ag-grid-docs/documentation/doc-pages/integrated-charts-api-cross-filter-chart/examples/sales-dashboard2/data.ts
2.90625
3
var numRows = 500; var names = [ 'Aden Moreno', 'Alton Watson', 'Caleb Scott', 'Cathy Wilkins', 'Charlie Dodd', 'Jermaine Price', 'Reis Vasquez', ]; var phones = [ { handset: 'Huawei P40', price: 599 }, { handset: 'Google Pixel 5', price: 589 }, { handset: 'Apple iPhone 12', price: 849 }, { handset: 'Samsung Galaxy S10', price: 499 }, { handset: 'Motorola Edge', price: 549 }, { handset: 'Sony Xperia', price: 279 }, ]; export function getData(): any[] { var data: any[] = []; for (var i = 0; i < numRows; i++) { var phone = phones[getRandomNumber(0, phones.length)]; var saleDate = randomDate(new Date(2020, 0, 1), new Date(2020, 11, 31)); var quarter = 'Q' + Math.floor((saleDate.getMonth() + 3) / 3); data.push({ salesRep: names[getRandomNumber(0, names.length)], handset: phone.handset, sale: phone.price, saleDate: saleDate, quarter: quarter, }); } data.sort(function (a, b) { return a.saleDate.getTime() - b.saleDate.getTime(); }); data.forEach(function (d) { d.saleDate = d.saleDate.toISOString().substring(0, 10); }); return data; } function getRandomNumber(min: number, max: number) { return Math.floor(Math.random() * (max - min) + min); } function randomDate(start: Date, end: Date) { return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); }
fbfb34fe12883de39f32d7efa1fdd02eca7f99b1
TypeScript
hisoftking/algorithm
/algorithm/HashTable/0219_contains_duplicate_ii.ts
3.421875
3
/** * @author lizhi.guo@foxmail.com * @source https://leetcode-cn.com/problems/count-primes/ * @time 2019-11-13 * * Time Complexity: O(n) * Space Complexity: O(n) */ function containsNearbyDuplicate (nums: number[], k: number) { let map = new Map(); for (let i = 0; i < nums.length; i++) { if (map.has(nums[i]) && i - map.get(nums[i]) <= k) { return true } else { map.set(nums[i], i) } } return false }
fde761e1310ed5829532b21cca48605c24ce3214
TypeScript
Kotpes/monthly-wages
/tests/helpers.test.ts
2.75
3
import {currencyFormatter, getOvertimeWageRate, calculateDailyWage, handleData} from '../src/utils/helpers' describe('currency formatter', () => { const formattedCurrency = currencyFormatter('en-US', 'USD').format(110.34) test('should not be undefined', () => { expect(formattedCurrency).toBeDefined() }) test('should return correctly formatted currency', () => { expect(formattedCurrency).toMatch('$110.34') }) }) describe('overtime wage rage', () => { const overtimeHours = 7.5 const baseRate = 23.4 test('should not be undefined', () => { expect(getOvertimeWageRate(overtimeHours, baseRate)).toBeDefined() }) test('should it should return correct rate', () => { expect(getOvertimeWageRate(overtimeHours, baseRate)).toEqual(310.05) }) }) describe('calculate daily wage', () => { const endDateTime = '2014-03-04T08:30' const startDayTime = '2014-03-04T23:30' const hoursWorked = 15 test('should not be undefined', () => { expect(calculateDailyWage(endDateTime, startDayTime, hoursWorked)).toBeDefined() }) test('should return correct object', () => { expect(calculateDailyWage(endDateTime, startDayTime, hoursWorked)).toEqual({compensationForTheShift: 285.02, overtimeHours: 7}) }) }) describe('handleData', () => { const shifts = [ { 'Person Name': 'Scott Scala', 'Person ID': '2', Date: '2.3.2014', Start: '6:00', End: '14:00' }, { 'Person Name': 'Janet Java', 'Person ID': '1', Date: '3.3.2014', Start: '9:30', End: '17:00' }, { 'Person Name': 'Scott Scala', 'Person ID': '2', Date: '3.3.2014', Start: '8:15', End: '16:00' } ] const expectedData = [ { employeeId: '1', employeeName: 'Janet Java', monthlyHours: 7.5, monthlyOvertime: 0, monthlyWage: '$31.88' }, { employeeId: '2', employeeName: 'Scott Scala', monthlyHours: 15.75, monthlyOvertime: 0, monthlyWage: '$66.94' } ] test('should not be undefined', () => { expect(handleData(shifts)).toBeDefined() }) test('should return correct data', () => { expect(handleData(shifts)).toEqual(expectedData) }) })
64db63316bd6ef72c5d14d57de1c296ef34cd6e7
TypeScript
JunkProvider/ng-tracks
/src/app/common/components/text-input/text-input.ts
2.734375
3
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; export interface SuggestionProvider { provide(value: string): Promise<string[]>; } interface Word { index: number; text: string; } @Component({ selector: 'app-text-input', templateUrl: './text-input.html', styleUrls: ['./text-input.css'] }) export class TextInput implements OnInit { @Output() readonly input = new EventEmitter<string>(); @Output() readonly cleared = new EventEmitter<string>(); @Input() value: string = null; @Input() disabled = false; @Input() readonly = false; @Input() placeholder = ''; @Input() suggestionProvider: SuggestionProvider = { provide: () => Promise.resolve([]) }; suggestionsDisplayed = false; suggestions: string[] = []; selectedSuggestionIndex = -1; constructor() { } ngOnInit() { } onInput(value: string) { this.value = value; const lastWord = this.findLastWord(value); if (lastWord) { this.updateSuggestions(lastWord).then(() => this.showSuggestions()); } else { this.hideSuggestions(); } this.input.next(value); } onBlur() { this.suggestions = []; this.hideSuggestions(); } onKeyDown(event: KeyboardEvent) { if (event.keyCode === 32 && event.ctrlKey) { this.updateSuggestions(this.findLastWord(this.value)).then(() => this.showSuggestions()); } if (!this.suggestionsDisplayed) { return; } if (event.keyCode === 40) { this.selectNextSuggestion(); } if (event.keyCode === 38) { this.selectPreviousSuggestion(); } if (event.keyCode === 13) { /*if (event.ctrlKey) { this.applySelectedSuggestion(); } else { this.hideSuggestions(); }*/ this.applySelectedSuggestion(); } if (event.keyCode === 27) { this.hideSuggestions(); } } onSuggestionClick(index: number) { this.selectedSuggestionIndex = index; this.applySelectedSuggestion(); } selectPreviousSuggestion() { this.selectedSuggestionIndex = this.selectedSuggestionIndex === 0 ? this.suggestions.length - 1 : this.selectedSuggestionIndex - 1; } selectNextSuggestion() { this.selectedSuggestionIndex = this.selectedSuggestionIndex === this.suggestions.length - 1 ? 0 : this.selectedSuggestionIndex + 1; } applySelectedSuggestion() { const suggestion = this.suggestions[this.selectedSuggestionIndex]; if (!suggestion) { return; } const lastWord = this.findLastWord(this.value); if (lastWord) { this.value = this.value.substring(0, lastWord.index) + suggestion; } else { this.value += suggestion; } this.hideSuggestions(); this.input.next(this.value); } clear() { this.value = ''; this.input.next(this.value); this.cleared.next(this.value); } private updateSuggestions(lastWord: Word) { return this.suggestionProvider.provide(lastWord ? lastWord.text : '').then(suggestions => { this.suggestions = suggestions; if (this.selectedSuggestionIndex >= this.suggestions.length) { this.selectedSuggestionIndex = 0; } }); } private findLastWord(value: string): Word { if (value.trim().length === 0 || value.endsWith(' ')) { return null; } let wordStart = value.lastIndexOf(' '); if (wordStart === -1) { wordStart = 0; } else { wordStart++; } return { index: wordStart, text: value.substring(wordStart, value.length) }; } private showSuggestions() { if (this.suggestionsDisplayed) { return; } this.selectedSuggestionIndex = 0; this.suggestionsDisplayed = true; } private hideSuggestions() { if (!this.suggestionsDisplayed) { return; } this.selectedSuggestionIndex = -1; this.suggestionsDisplayed = false; } }
dfec0c4c4f8c180d31891f09f6d3e1bdbe853d68
TypeScript
tusbar/vscode-linter-xo
/server/src/buffered-message-queue.ts
2.578125
3
// Copied from https://github.com/Microsoft/vscode-eslint/blob/ad394e3eabfa89c78c38904d71d9aebf64b7edfa/server/src/server.ts import { CancellationToken, RequestHandler, NotificationHandler, IConnection, RequestType, NotificationType, ResponseError, ErrorCodes } from 'vscode-languageserver'; interface Request<P, R> { method: string; params: P; documentVersion: number | undefined; resolve(value: R | Thenable<R>): void | undefined; reject(error: any): void | undefined; token: CancellationToken | undefined; } namespace Request { export function is(value: any): value is Request<any, any> { const candidate: Request<any, any> = value; return candidate && !!candidate.token && !!candidate.resolve && !!candidate.reject; } } interface Notifcation<P> { method: string; params: P; documentVersion: number; } type Message<P, R> = Notifcation<P> | Request<P, R>; type VersionProvider<P> = (params: P) => number; namespace Thenable { export function is<T>(value: any): value is Thenable<T> { const candidate: Thenable<T> = value; return candidate && typeof candidate.then === 'function'; } } export default class BufferedMessageQueue { private readonly queue: Message<any, any>[]; private readonly requestHandlers: Map<string, {handler: RequestHandler<any, any, any>; versionProvider?: VersionProvider<any>}>; private readonly notificationHandlers: Map<string, {handler: NotificationHandler<any>; versionProvider?: VersionProvider<any>}>; private timer: NodeJS.Timer | undefined; constructor(private readonly connection: IConnection) { this.queue = []; this.requestHandlers = new Map(); this.notificationHandlers = new Map(); } public registerRequest<P, R, E, RO>(type: RequestType<P, R, E, RO>, handler: RequestHandler<P, R, E>, versionProvider?: VersionProvider<P>): void { this.connection.onRequest(type, async (params, token) => { return new Promise<R>((resolve, reject) => { this.queue.push({ method: type.method, params, documentVersion: versionProvider ? versionProvider(params) : undefined, resolve, reject, token }); this.trigger(); }); }); this.requestHandlers.set(type.method, {handler, versionProvider}); } public registerNotification<P, RO>(type: NotificationType<P, RO>, handler: NotificationHandler<P>, versionProvider?: (params: P) => number): void { this.connection.onNotification(type, params => { this.queue.push({ method: type.method, params, documentVersion: versionProvider ? versionProvider(params) : undefined, }); this.trigger(); }); this.notificationHandlers.set(type.method, {handler, versionProvider}); } public addNotificationMessage<P, RO>(type: NotificationType<P, RO>, params: P, version: number) { this.queue.push({ method: type.method, params, documentVersion: version }); this.trigger(); } public onNotification<P, RO>(type: NotificationType<P, RO>, handler: NotificationHandler<P>, versionProvider?: (params: P) => number): void { this.notificationHandlers.set(type.method, {handler, versionProvider}); } private trigger(): void { if (this.timer || this.queue.length === 0) { return; } this.timer = setImmediate(() => { this.timer = undefined; this.processQueue(); }); } private processQueue(): void { const message = this.queue.shift(); if (!message) { return; } if (Request.is(message)) { const requestMessage = message; if (requestMessage.token.isCancellationRequested) { requestMessage.reject(new ResponseError(ErrorCodes.RequestCancelled, 'Request got cancelled')); return; } const elem = this.requestHandlers.get(requestMessage.method); if (elem.versionProvider && requestMessage.documentVersion !== void 0 && requestMessage.documentVersion !== elem.versionProvider(requestMessage.params)) { requestMessage.reject(new ResponseError(ErrorCodes.RequestCancelled, 'Request got cancelled')); return; } const result = elem.handler(requestMessage.params, requestMessage.token); if (Thenable.is(result)) { result.then(value => { requestMessage.resolve(value); }, error => { requestMessage.reject(error); }); } else { requestMessage.resolve(result); } } else { const notificationMessage = message; const elem = this.notificationHandlers.get(notificationMessage.method); if (elem.versionProvider && notificationMessage.documentVersion !== void 0 && notificationMessage.documentVersion !== elem.versionProvider(notificationMessage.params)) { return; } elem.handler(notificationMessage.params); } this.trigger(); } }
490a56d8cc5e9aa4bbeda06dad46024eda7ce97c
TypeScript
shanehickeylk/angular-libraries
/projects/pipes/src/lib/string/remove_html_tags.ts
2.609375
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'removeHtmlTags' }) export class RemoveHtmlTagsPipe implements PipeTransform { // This pipe removes all HTML tags from a text string // Used for sanitizing input so that html tags are not shown transform(value: string): string { return value.replace(/<\/?[^>]+>/gi, ''); } }
f5b72dde6cd99ca2857a694eb1ac400acadb9387
TypeScript
craigmichaelmartin/pure-orm
/test-utils/thirteen/models/member.ts
2.53125
3
import { IModel, ICollection, IColumns } from '../../../src/index'; export const tableName: string = 'member'; export const columns: IColumns = ['id']; export class Member implements IModel { id: number; constructor(props: any) { this.id = props.id; } } export class Members implements ICollection<Member> { models: Array<Member>; constructor({ models }: any) { this.models = models; } } export const memberEntity = { tableName, columns, Model: Member, Collection: Members };
2963d980d842f08e5a92f7aaeab53bcf4e525241
TypeScript
rapharw/beauty-az-cli
/src/app/wizards/az-cli/operations/shared/subscription-question-select.ts
2.578125
3
import Choice from "../../../../../lib/inquirer/choice"; import Question from "../../../../question"; import QuestionSelect from "../../../../question-select"; import Account from "../az-account/account"; import Subscription from "../az-login/subscription"; /** * Know how to get the question(s) */ export default (): Promise<Question> => { const choices: Choice[] = []; const account = new Account(); return new Promise((resolve, reject) => { account.getSubscriptions().then((subscriptions: Subscription[]) => { for(let subscription of subscriptions){ choices.push(new Choice(subscription.name, subscription.name, subscription.name)); } resolve(new QuestionSelect("subscription", "Select a subscription", choices)); }) .catch((err) => { console.log(err); reject(new Error("Error on Subscription-Question-Select")) }); }); }
e62cc506b03f88e4a7bfd5e6bce5513153db37d6
TypeScript
fork-from-others-coder/QinScript
/src/Parser/DataStruct/HashFile.ts
2.515625
3
export class HashFile{ //hash文件的数据结构 hashValue:number;//grammar文件内容的hash值 hashDate:number;//grammar文件的修改日期hash值 constructor(hashValue: number, hashDate: number) { this.hashValue = hashValue; this.hashDate = hashDate; } }
bb412e298c4b8c5ff7e45285aab7d511a07e3156
TypeScript
FrederikBolding/tournament-brackets
/hooks/useBracket.ts
2.953125
3
import { useState } from "react"; import { Game, Round } from "../types"; import { BracketGenerationOptions, generateBracket } from "../utils/bracket"; export const useBracket = (teams: string[], options?: BracketGenerationOptions) => { const [rounds, setRounds] = useState(generateBracket(teams, options)); const getRoundByGame = (id: number) => { const round = rounds.find((r) => r.games.find((g) => g.id === id)); const game = round.games.find((g) => g.id === id); return { round, game }; }; const updateWinners = (rounds: Round[]) => { return rounds.map((round, _, roundArr) => ({ ...round, games: round.games.reduce((acc, cur) => { const prevRound = roundArr.find((r) => r.games.find((g) => g.next === cur.id) ); const prevGames = prevRound && prevRound.games.filter((g) => g.next === cur.id); if (!prevGames || prevGames.length === 0) { return [...acc, cur]; } const team1 = prevGames[0].winner ?? cur.team1; const team2 = prevGames[1].winner ?? cur.team2; const updatedGame = { ...cur, team1, team2 }; const winner = calculateWinner(updatedGame) return [...acc, { ...updatedGame, winner }]; }, []), })); }; const updateGame = (updatedGame: Game) => { const id = updatedGame.id; const { round, game } = getRoundByGame(id); const winner = calculateWinner(updatedGame) const winnerChange = game.winner !== winner; const updatedGames = [ ...round.games.filter((g) => g.id !== id), { ...updatedGame, winner }, ].sort((a, b) => a.id - b.id); const updatedRound = { ...round, games: updatedGames }; const updatedRounds = [ ...rounds.filter((r) => r.round !== round.round), updatedRound, ].sort((a, b) => a.round - b.round); setRounds(winnerChange ? updateWinners(updatedRounds) : updatedRounds); }; const updateTeamName = (id: number, team: number, newName: string) => { const { game } = getRoundByGame(id); const update = team === 1 ? { team1: newName } : { team2: newName }; updateGame({ ...game, ...update }); }; const calculateWinner = (game: Game) => { if (game.score1 > game.score2) { return game.team1; } else if (game.score1 < game.score2) { return game.team2; } return undefined; }; const updateTeamScore = (id: number, team: number, newScore: string) => { const { game } = getRoundByGame(id); const update = team === 1 ? { score1: parseInt(newScore) } : { score2: parseInt(newScore) }; updateGame({ ...game, ...update }); }; return { rounds, updateTeamName, updateTeamScore }; };
29e18237cedda22913f7c53e2d8a64fde9cdd1f9
TypeScript
majo44/redux-tx
/lib/utils/optimisticMerge.ts
2.859375
3
export function optimisticMerge(outisde: any, before: any, after: any, path: Array<string> = []) { if (!isObject(outisde, before, after)) { throw 'Transaction commit failed. The state should bean an plain object.'; } let target: any = {}; uniq(Object.keys(after) .concat(Object.keys(before)) .concat(Object.keys(outisde))) .forEach((key: string) => { if (key !== '$$transactions') { if (after[key] === before[key]) { if (typeof outisde[key] !== 'undefined') { target[key] = outisde[key]; } } else if (before[key] === outisde[key]) { if (typeof after[key] !== 'undefined') { target[key] = after[key]; } } else { if (isObject(outisde[key], before[key], after[key])) { target[key] = optimisticMerge(outisde[key], before[key], after[key], [...path, key]); } else { throw `The race detected. Property ${path.join('.')}.${key}` + `of state updated during the transaction. Transactions trays` + ` to commit new value to this same property.`; } } } }); return target; } function isObject(outisde: any, before: any, after: any) { return typeof outisde === typeof before && typeof before === typeof after && typeof after === 'object' && !Array.isArray(after); } function uniq(a: Array<any>): Array<any> { let seen: any = {}; let out = []; let len = a.length; let j = 0; for (let i = 0; i < len; i++) { let item = a[i]; if (seen[item] !== 1) { seen[item] = 1; out[j++] = item; } } return out; }
6a2e850db07ea65e20efe6454c60eeb659636b6b
TypeScript
jbrowneuk/jblog
/apps/jblog/src/app/services/rest.service.ts
2.6875
3
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; export type Headers = { [key: string]: string }; @Injectable({ providedIn: 'root' }) export class RestService { constructor(private http: HttpClient) {} /** * Gets a resource from a server * * @param url url to GET * @param headers (option) HTTP request headers */ public get<T>(url: string, headers?: Headers): Observable<T> { const options = { headers }; return this.http.get<T>(url, options); } public post( url: string, body: { [key: string]: any }, headers?: Headers ): Observable<any> { // TODO: remove responseType once API returns JSON // https://stackoverflow.com/a/54383818 const responseType = 'text' as any; const options = { headers: headers ? headers : undefined, responseType }; return this.http.post(url, body, options); } }
b4690e4a321394db0ba8882c377c908e2f3fb6e2
TypeScript
jbhouse/automation
/utilities/models/supplement.ts
2.671875
3
import { Language } from './language.enum'; export class Supplement { name: string; language: Language; code: string; notes: string; constructor(name: string = '', language: Language = Language.TEXT, code: string = '', notes: string = '') { this.name = name; this.language = language; this.code = code; this.notes = notes; } }
5db2f87981fb82fea985b52442e2e0212d1f71c3
TypeScript
xyz252631m/web
/js/tool/tree.ts
2.890625
3
class Tree { //转为tree型 list convertTreeData(list) { let repMap = {}; let temList = []; //去除重复 list.forEach(d => { if (!repMap[d.id]) { repMap[d.id] = d; temList.push({...d, isOpen: false, children: []}) } }); let map = {}, treeData = []; temList.forEach(d => { map[d.id] = d; }); temList.forEach(d => { if (d.pid) { if (map[d.pid]) { map[d.pid].children.push(d); } } }); for (let key in map) { if (!map[key].pid) { treeData.push(map[key]); } } return treeData; } //转为tree型 list convertTreeData2(list) { let map = {}, treeData = []; list.forEach(d => { if (map[d.id]) { console.error("tree id 重复," + d.id); } map[d.id] = { key: d.id, title: d.name, children: [], isLeaf: d.type === 'page', data: d }; }); list.forEach(d => { if (d.pid) { if (map[d.pid]) { map[d.pid].children.push(map[d.id]); } } else { treeData.push(map[d.id]); } }); return treeData; } //转为tree型 list convertTreeData3(list) { let map = {}, treeData = [], temList = []; list.forEach(d => { if (map[d.id]) { console.error("tree id 重复," + d.id); } map[d.id] = { key: d.id, title: d.name, children: [], isLeaf: d.type === 'page', data: d }; if (d.pid) { if (map[d.pid]) { map[d.pid].children.push(map[d.id]); } else { temList.push(d); } } else { treeData.push(map[d.id]); } console.log("count") }); temList.forEach(d => { if (map[d.pid]) { map[d.pid].children.push(map[d.id]); } console.log("count") }); return treeData; } }
3853f5cfb7e8ea88be808300107c3ab0ff10d8c0
TypeScript
LucasSimpson/js_web_graphics
/webGL/framework.ts
3.203125
3
/** * Created by lucas on 08/07/17. */ class PolygonData { protected vertices: Array<number> = []; protected colors: Array<number> = []; protected indices: Array<number> = []; public getColors() { return this.colors; } public getVertices() { return this.vertices; } public getIndices() { return this.indices; } public mergeWith(other: PolygonData) { this.vertices = this.vertices.concat(other.vertices); this.colors = this.colors.concat(other.colors); this.indices = this.indices.concat(other.indices); } } class SceneManager extends PolygonData { } class Cube extends PolygonData { // private vertices: Array<number> = []; // private colors: Array<number> = []; // private indices: Array<number> = []; constructor(x, y, z, sx, sy, sz: number) { super(); this.vertices = [ // Front face -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, // Back face -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, // Top face -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, // Bottom face -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, // Right face 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, // Left face -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0 ]; // build colors let colors: Array<Array<number>> = [ [1.0, 1.0, 1.0, 1.0], // Front face: white [1.0, 0.0, 0.0, 1.0], // Back face: red [0.0, 1.0, 0.0, 1.0], // Top face: green [0.0, 0.0, 1.0, 1.0], // Bottom face: blue [1.0, 1.0, 0.0, 1.0], // Right face: yellow [1.0, 0.0, 1.0, 1.0] // Left face: purple ]; // Convert the array of colors into a table for all the vertices. this.colors = []; for (let j = 0; j < 6; j++) { let c = colors[j]; // Repeat each color four times for the four vertices of the face for (let i = 0; i < 4; i++) { this.colors = this.colors.concat(c); } } // link vertices together into triangles. Polygon color // specified by color in similar index this.indices = [ 0, 1, 2, 0, 2, 3, // front 4, 5, 6, 4, 6, 7, // back 8, 9, 10, 8, 10, 11, // top 12, 13, 14, 12, 14, 15, // bottom 16, 17, 18, 16, 18, 19, // right 20, 21, 22, 20, 22, 23 // left ]; } } let cube:Cube = new Cube(1, 1, 1, 1, 1, 1); polys = { vertices: cube.getVertices(), colors: cube.getColors(), indices: cube.getIndices() };
2c3bb7ebd89169e4c747963d61ef78da973a91a3
TypeScript
sketch7/ssv-au-core
/src/logging/logging.model.ts
2.640625
3
export interface ILog { debug(method: string, message?: string, data?: any): void; info(method: string, message?: string, data?: any): void; warn(method: string, message?: string, data?: any): void; error(method: string, message?: string, data?: any): void; }
69258bf1f5cc5f8fb7d1e450d204f64ce42ee5e6
TypeScript
microsoft/fluentui
/tools/workspace-plugin/src/generators/migrate-converged-pkg/lib/utils.ts
2.6875
3
import { logger } from '@nx/devkit'; import ejs from 'ejs'; import fs from 'fs'; /** * Similar to @nx/devkit#generateFiles function but for getting content only * * @param src - the source folder of files (absolute path) * @param substitutions - an object of key-value pairs * @returns */ export function getTemplate(src: string, substitutions: Record<string, unknown>) { if (!fs.existsSync(src)) { throw new Error(`${src} doesn't exists`); } const template = fs.readFileSync(src, 'utf8').trim(); if (!substitutions) { return template; } try { const content = ejs.render(template, substitutions, {}); return content; } catch (err) { logger.error(`Error in ${src}:`); throw err; } } export function uniqueArray<T extends unknown>(value: T[]) { return Array.from(new Set(value)); }
570fa3729b1f68e7f3b48edc122a9aeabd5c8c12
TypeScript
hiephn/hoctypescript
/lession18.ts
3.140625
3
class Person{ constructor (name){ this.name = name; console.log('Xin chao ' + this.name); } static talk(){ console.log('Talk'); } run(){ console.log('Run'); } } var p1 = new Person('hiep'); Person.talk();
9fbb407aa45f9e1bd38c38a695077d37a8279678
TypeScript
mrWh1te/gardn
/libs/data/src/lib/event/types.ts
2.828125
3
import { Event, EventData } from './../generated' /** * Just like the Event type, generated, except more relaxed aka "loose" in typing via Partials */ export type LooseEvent = Omit<Partial<Event>, 'data'> & { data: Partial<EventData> // don't require 'dateCreated' }