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
38db2c74e5966bb5cbb20abf304c1807612850b5
TypeScript
mrdulin/react-examples
/ts-example/src/actions/promise-all.ts
2.546875
3
import { createAction } from 'redux-actions'; import * as t from '../actionTypes'; import * as fetch from 'isomorphic-fetch'; const request = (status: boolean) => { return new Promise((resolve, reject) => { setTimeout(() => { if (status) { resolve('success'); } else { reject('failed'); } }, 2000); }); }; const req1 = createAction( t.REQUEST_ONE, async (status: boolean) => { try { return await request(status); } catch (err) { throw err; } } ); const req2 = createAction( t.REQUEST_TWO, async (status: boolean) => { try { return await request(status); } catch (err) { throw err; } } ); const req2Fallback = createAction(t.REQUEST_TWO_FALLBACK, (value: string) => Promise.resolve(value)); export { req1, req2, req2Fallback };
192cecef7ab04d6d5f762709d9bc832ee0ef604b
TypeScript
marcello3d/jsondiffpatch-flatten
/src/deltaTypes.ts
2.953125
3
import { AddDelta, AnyDelta, ArrayDelta, ArrayMoveDelta, DeleteDelta, ObjectDelta, ReplaceDelta, UnidiffDelta, } from './jsondiffpatch-types'; export type AddDeltaType = { type: 'add'; delta: AddDelta; newValue: unknown; }; export type ReplaceDeltaType = { type: 'replace'; delta: ReplaceDelta; oldValue: unknown; newValue: unknown; }; export type DeleteDeltaType = { type: 'delete'; delta: DeleteDelta; oldValue: unknown; }; export type UnidiffDeltaType = { type: 'unidiff'; delta: UnidiffDelta; unidiff: string; }; export type ObjectDeltaType = { type: 'object'; delta: ObjectDelta }; export type ArrayDeltaType = { type: 'array'; delta: ArrayDelta }; export type ModifyDeltaType = | ArrayDeltaType | ObjectDeltaType | ReplaceDeltaType | UnidiffDeltaType; export type MoveDeltaType = { type: 'array-move'; delta: ArrayMoveDelta; newIndex: number; }; export type DeltaType = | AddDeltaType | ReplaceDeltaType | DeleteDeltaType | UnidiffDeltaType | ObjectDeltaType | MoveDeltaType | ArrayDeltaType; export function getDeltaType(delta: AnyDelta): DeltaType { if (Array.isArray(delta)) { if ((delta.length as number) === 0 || delta.length > 3) { throw new Error('invalid delta'); } if (delta.length === 1) { return { type: 'add', delta, newValue: delta[0], }; } if (delta.length === 2) { return { type: 'replace', delta, oldValue: delta[0], newValue: delta[1], }; } switch (delta[2]) { case 0: return { type: 'delete', delta, oldValue: delta[0], }; case 2: return { type: 'unidiff', delta, unidiff: delta[0], }; case 3: return { type: 'array-move', delta, newIndex: delta[1], }; default: throw new Error('invalid delta'); } } if (delta._t === 'a') { return { type: 'array', delta: delta as ArrayDelta }; } return { type: 'object', delta: delta as ObjectDelta }; }
1edf6062bf6c5c521977e6ea45b65e93471d7985
TypeScript
blakeembrey/back-row
/app/stores/session.ts
2.75
3
import { Store } from 'marty' import extend = require('xtend') import SessionConstants from '../constants/session' export interface SessionState { connection?: any sessions?: { [sessionId: string]: Session } } export interface Session { id: string state: SessionStateState options: SessionStateOptions } interface SessionStateOptions { imdbId: string quality: string } interface SessionStateState { time: number play: boolean updating: boolean ready: string waiting: number timestamp: number from: string peers: string[] } export default class SessionStore extends Store<SessionState> { state: SessionState = { sessions: {} } handlers = { setConnection: SessionConstants.CREATE_CONNECTION, joinedSession: [SessionConstants.JOIN_SESSION, SessionConstants.CREATE_SESSION], leftSession: SessionConstants.LEAVE_SESSION, updateSessionState: SessionConstants.UPDATE_SESSION_STATE } getConnection () { return this.fetch({ id: 'connection', locally: () => { return this.state.connection }, remotely: () => { return this.app.sessionActionCreators.connect() } }) } setConnection (connection: any) { this.setState({ connection }) } joinedSession (sessionId: string, data: Session) { this.state.sessions[sessionId] = <Session> extend({ id: sessionId }, data) this.hasChanged() } getSession (sessionId: string) { return this.fetch({ id: sessionId, locally: () => { return this.state.sessions[sessionId] }, remotely: () => { return this.app.sessionActionCreators.join(sessionId) }, dependsOn: [this.getConnection()] }) } leftSession (sessionId: string) { delete this.state.connection delete this.state.sessions[sessionId] this.hasChanged() } updateSessionState (sessionId: string, newState: SessionStateState) { const currentSession = this.state.sessions[sessionId] const state = extend(currentSession.state, newState) this.state.sessions[sessionId] = <Session> extend(currentSession, { state }) this.hasChanged() } }
5a7f321dac3a357981ec8806a24662087be0aecc
TypeScript
Rodrigobanselmo/video-plataform
/src/types.ts
3.4375
3
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/ban-types */ /* eslint-disable no-shadow */ /* eslint-disable @typescript-eslint/no-unused-vars */ export interface IInterface { author: { name: string | number; avatar: string[]; }; content: object; isAnswered: boolean; isHighlighted: boolean; } export type FQ = Record<string, IInterface>; // const obj: { // 'uuid1': IInterface, // 'uuid2': IInterface // ... // } export type FQAny = Record<string, any>; // const obj: { // 'a': string, // 'string': number, // 'string2': any, // } type IL = Record<'a' | 'b' | 'c', string>; // const obj: IListTest = { // a: '10', // b: '10', // c: '10', // }; type IL1 = Record<'a' | 'b' | 'c', string>; type IL2 = Record<string, any>; type IL3 = IL1 & IL2; // interface IL3 extends IL1, IL2 {} // const obj: IL3 = { // a: '10', // IL1 // b: '10', // IL1 // c: '10', // IL1 // // d: '10', // IL2 // ... // IL2 // }; interface Box<T> { contents: T; } // const boxA: Box<string> = { // contents: 'string text', // }; type Box1<T> = Array<T>; // const objBase: Box1<number> = [1, 2, 3]; type IObject<T> = T; interface ISimple { id: string; name: string; } const x: ISimple = { id: '1', name: 'Rodrigo', }; // const obj: IObject<typeof x> = { // id: '10', // name: '10', // }
24307bd88340acddb002c06a518b0b44f57fca9c
TypeScript
Jacks128/tytusx
/20211SVAC/G35/codigof/src/ejecucion/Expresion/Simbolo.ts
3.359375
3
import { TIPO_DATO } from './Tipo'; export class Simbolo { identificador: string; tipo: TIPO_DATO; valor: any; constructor({identificador_,tipo_,valor_}:{identificador_:string, tipo_: any, valor_: any}) { this.identificador=identificador_; this.tipo=tipo_; this.valor=valor_; } recorrer(){ return `ID: ${this.identificador} - TIPO: ${this.tipoString(this.tipo)} - VALOR: ${this.valor}\n`; } tipoString(i:number){ switch(i){ case 0: return " ERROR " case 1: return " NUMBER " case 2: return " STRING " case 3: return " BOOLEAN " case 4: return " ETIQUETA " case 5: return " FUNCION " case 6: return " ARREGLO " } //ERROR,NUMBER,STRING, BOOLEAN, ETIQUETA, FUNCION, ARREGLO return ""; } }
62baf99010b8ab0e9e8b815db3dd9e1f35384f29
TypeScript
tyblue/blog
/code/accumulate/design-pattern/template.ts
3.6875
4
abstract class AbstractClass { public TemplateMethod() { this.SpecificMethod(); this.abstractMethod1(); this.abstractMethod2(); } public SpecificMethod() { console.log("抽象类中的具体方法被调用..."); } public abstract abstractMethod1(); //抽象方法1 public abstract abstractMethod2(); //抽象方法2 } class ConcreteClass extends AbstractClass { public abstractMethod1() { console.log("抽象方法1的实现被调用..."); } public abstractMethod2() { console.log("抽象方法2的实现被调用..."); } } const tm = new ConcreteClass(); tm.TemplateMethod(); // 步骤的顺序是确定,只是某些步骤的实现可能不同
6be9531c7a2dfc3b4f448879ebaf64b9e36fbd88
TypeScript
juesvema/SQLlite-Android
/Frontend/src/app/student/services/dialog/dialog.service.ts
2.53125
3
import { WeekInformationComponent } from './../../week-information/week-information.component'; import { Injectable } from '@angular/core'; import { MdDialog, MdDialogConfig } from '@angular/material'; @Injectable() export class DialogService { /** * * @param dialog MdDialog to open components in dialog */ constructor(public dialog: MdDialog) { } /** * * @param week * open dialog with week number */ openDialog(week: number) { let configuration: MdDialogConfig = this.getDefaultMdDialogConfig( week ); this.dialog.open(WeekInformationComponent, configuration); } /** * * @param week * set default configuration of MdDialogConfig */ getDefaultMdDialogConfig( week: number ) { let configuration: MdDialogConfig = new MdDialogConfig; configuration.width = '800px'; configuration.data = week; return configuration; } }
54b1728461629c929dbd3a12e2eceb3ee73b327d
TypeScript
vermicida/kc-angular-altran
/src/app/datos-contacto.pipe.ts
3.140625
3
import { Pipe, PipeTransform } from '@angular/core'; import { Contacto } from './contacto'; // Los Pipes son clases decoradas con el decorador '@Pipe'. Es necesario // indicar el metadato 'name'; en él establecemos el nombre del Pipe, que // será el que usemos en un template para aplicarlo. // También, un Pipe debe implementar la interfaz 'PipeTransform' y, por ende, // la función 'tranform()'. Este función espera al menos un parámetro: el // dato que va a transformarse. Podemos indicar otros argumentos más para // configurar o modificar el proceso de transformación. @Pipe({ name: 'DatosContacto' }) export class DatosContactoPipe implements PipeTransform { transform(contacto: Contacto): string { let datos: string; // Si tenemos los dos datos (teléfono y email), debemos retornar 'teléfono || email'. if (contacto.telefono && contacto.email) { datos = `${contacto.telefono} || ${contacto.email}`; } // Si solo tenemos uno de los datos, lo retornamos tal cual. else if (contacto.telefono) { datos = contacto.telefono; } else if (contacto.email) { datos = contacto.email; } // Por último, si no tenemos ninguno, retornamos una cadena de texto vacía. else { datos = ''; } return datos; } }
753d057bbbaa5931f7458180b2750bb204a2aa22
TypeScript
qetr1ck-op/nodejs-patterns
/src/6.design-patterns/1.factory/2.game/characters-mixins.ts
3.546875
4
import { pipe } from 'rambda' interface ICharacter { health: number name: string } //🍿 type Constructor<T = {}> = new (...args: any[]) => T class Character implements ICharacter { health = 100 constructor(public name: string) {} } //🍿 const Mover = <TBase extends Constructor<ICharacter>>(Base: TBase) => class extends Base { constructor(...args: any[]) { super(...args) } x = 0 y = 0 move(x: number, y: number) { this.x = x this.y = y console.log(`${this.name} move x: ${x}, move y: ${y}`) } } //🍿 const Slasher = <TBase extends Constructor<ICharacter>>(Base: TBase) => class extends Base { slash(direction: string) { console.log(`${this.name} slash: ${direction}`) } } //🍿 const Shooter = <TBase extends Constructor<ICharacter>>(Base: TBase) => class extends Base { private bullets = 6 shoot(direction: string) { if (this.bullets > 0) { --this.bullets console.log(`${this.name} shoot: ${direction}`) } } } // 💩 const Samurai = Slasher(Mover(Character)) const Sniper = Shooter(Character) const Gunslinger = Shooter(Mover(Character)) const WersternSamurai = Slasher(Gunslinger) const gojiro = new WersternSamurai('Gojiro Kiryu') gojiro.move(1, 0) gojiro.slash('left') gojiro.shoot('right')
bee0eabfc7b16a799ba3aeb84c3cc2a63096a4cd
TypeScript
SayMeowArtem/Diplomafrontend
/src/store/ducks/subscribes/actionCreators.ts
2.546875
3
import { AddSubscribeActionInterface, DeleteSubscribesActionInterface, FetchAddSubscribeActionInterface, FetchDeleteSubscribesActionInterface, FetchSetSubscribesActionInterface, SetSubscribesActionInterface, SubscribeActionType } from "./contracts/actionTypes"; export const AddSubscribe = (payload: any): AddSubscribeActionInterface => ({ type: SubscribeActionType.ADD_SUBSCRIBE, payload }); export const DeleteSubscribe = (payload: any): DeleteSubscribesActionInterface => ({ type: SubscribeActionType.DELETE_SUBSCRIBE, payload }) export const FetchDeleteSubscribe = (payload: any): FetchDeleteSubscribesActionInterface => ({ type: SubscribeActionType.FETCH_DELETE_SUBSCRIBES, payload }) export const FetchAddSubscribe = (payload: any): FetchAddSubscribeActionInterface => ({ type: SubscribeActionType.FETCH_ADD_SUBSCRIBE, payload }) export const SetSubsctibes = (payload: any ): SetSubscribesActionInterface => ({ type: SubscribeActionType.SET_SUBSCRIBES, payload }) export const FetchSetSubscribes = (payload: any): FetchSetSubscribesActionInterface => ({ type: SubscribeActionType.FETCH_SET_SUBSCRIBES, payload }) export type SubscribeActions = | AddSubscribeActionInterface | SetSubscribesActionInterface | DeleteSubscribesActionInterface
7132429f716d2ac18ef69572395467693d5f94c7
TypeScript
nickjmaxwell/konekuto-app
/src/app/models/user.ts
2.640625
3
import {TeamMember} from './team-member'; export class User extends TeamMember{ constructor( public id: number, public username: string, public email: string, public teams?: Array<number> ) { super(id, username); } }
0f462f4ed542be319f186843e48aa9ade8993b13
TypeScript
gao525280067/gf-ui
/src/utils/PublishSubscribe/index.ts
3.4375
3
export type PublishSubscribeCallback = (...payload: any[]) => void; const subscribe = ( type: string, cb: PublishSubscribeCallback, SubscriberMap: { [key: string]: any[] } ) => { if (SubscriberMap[type]) { if (!SubscriberMap[type].includes(cb)) { SubscriberMap[type].push(cb); } } else { SubscriberMap[type] = [cb]; } }; const unsubscribe = ( type: string, cb: PublishSubscribeCallback, SubscriberMap: { [key: string]: any[] } ) => { if (SubscriberMap[type] || SubscriberMap[type].includes(cb)) return; const index = SubscriberMap[type].indexOf(cb); SubscriberMap[type].splice(index, 1); }; const publish = (SubscriberMap: { [key: string]: any[] }, type: string, ...payload: any[]) => { if (!SubscriberMap[type]) return; SubscriberMap[type].forEach(cb => cb(...payload)); }; /** * 可使用静态方法,也可以做用实例方式 * 表态方法不能访问实例属性和方法,但实例方法可以访问静态方法。 * 这个是由于类加载静态属性和方法就可以使用了,而实例要先实例化。 * 所以静态方法无法访问未实例化的属性和方法 */ class PublishSubscribe { /** * 存储订阅 */ public static SubscriberMap: { [key: string]: any[] } = {}; private _SubscriberMap: { [key: string]: any[] } = {}; /** * 消息订阅 * @param type * @param cb */ public static subscribe(type: string, cb: PublishSubscribeCallback) { subscribe(type, cb, PublishSubscribe.SubscriberMap); } public subscribe(type: string, cb: PublishSubscribeCallback) { subscribe(type, cb, this._SubscriberMap); } /** * 消息退订 * @param type * @param cb */ public static unsubscribe(type: string, cb: PublishSubscribeCallback) { unsubscribe(type, cb, PublishSubscribe.SubscriberMap); } public unsubscribe(type: string, cb: PublishSubscribeCallback) { unsubscribe(type, cb, this._SubscriberMap); } /** * 发布消息 * @param type * @param payload */ public static publish(type: string, ...payload: any[]) { publish(PublishSubscribe.SubscriberMap, type, ...payload); } public publish(type: string, ...payload: any[]) { publish(this._SubscriberMap, type, ...payload); } } export default PublishSubscribe;
308976f64cb62065448cd69339e2b362ff3b4064
TypeScript
ignacioPastor/playing-ngrx
/src/app/task/state/reducers/task.reducer.ts
2.953125
3
import * as taskActions from './../actions/task.actions'; /** * Here we handle the actions result of the effects. * Right now just success cases, but it could handle actions in case of errors. */ export function taskReducer(state = [], action: taskActions.Action) { switch (action.type) { case taskActions.LOAD_TASKS_SUCCESS: return action.payload; case taskActions.DELETE_TASKS_SUCCESS: return state.filter(task => task.id !== action.payload); case taskActions.ADD_NEW_TASK_SUCCESS: return [...state, action.payload]; default: return state; } }
ac87e8a3c4aec4482144539ba398c963e562bd94
TypeScript
diegoherrera/Ejemplo6
/test.ts
3.1875
3
let arregloa: number[] = [1, 2, 3, 4, 5, 6]; let arreglob: Array<number> = [12, 33, 43, 54, 62]; arregloa.forEach(element => { console.log(element); }); for (let i = 0; i < arreglob.length; i++) { console.log(arreglob[i]); }
1ed6322b562aed3df32338f80c7b65d6783bca04
TypeScript
devzolo/node-sql-database
/src/driver/oracle/OracleResultSetRowList.ts
2.703125
3
import { SQLResultSetRowList } from '../../api'; //import { print } from "util"; import { OracleResultSetRow } from './OracleResultSetRow'; export class OracleResultSetRowList extends SQLResultSetRowList { private pointer = 0; private columns: any; private rows: any; constructor(rs: any) { super(); this.rows = rs.rows || []; this.length = this.rows.length; if (rs.metaData) { this.columns = {}; rs.metaData.forEach((value: any, index: number) => { this.columns[value.name.toLowerCase()] = index; }); } } item(index: number): any { return this.rows[index]; } next(value?: any): IteratorResult<any> { if (this.pointer < this.rows.length) { return { done: false, value: new OracleResultSetRow(this.rows[this.pointer++], this.columns), }; } else { return { done: true, value: null, }; } } //return?(value?: any): IteratorResult<any>; //throw?(e?: any): IteratorResult<any>; /* [Symbol.iterator]() { let pointer = 0; let rows = this.rs.rows; return { next(): IteratorResult<any> { if (pointer < rows.length) { return { done: false, value: rows[pointer++] }; } else { return { done: true, value: null }; } } }; } */ }
989595caf5d97517bea6904020abeadba871abfb
TypeScript
mass10/typescript.note
/code/generator/src/Main.ts
3.375
3
namespace Main { /** * ジェネレーターを返します。 */ function* enumUsers(): IterableIterator<string> { const users = [ "Jimi Hendrix", "Freddie Mercury", "Aretha Franklin", "Billie Holiday", "Louis Armstrong", "Sam & Dave", "Donny Hathaway", ]; for (const u of users) { yield u; } } /** * エントリーポイントです。 */ export function main() { console.log("### START ###"); const users = enumUsers(); while (true) { const user = users.next(); if (user.done) { break; } console.log(`[TRACE]`, user); } console.log("--- END ---"); } } // ここから開始 Main.main();
2081c69b452a30f68879c026d6ff22b1218c8651
TypeScript
YOU-i-Labs/react-admin
/packages/ra-core/src/form/formMiddleware.spec.ts
2.546875
3
import { LOCATION_CHANGE } from 'react-router-redux'; import { destroy } from 'redux-form'; import formMiddleware from './formMiddleware'; import { REDUX_FORM_NAME } from './constants'; import { resetForm } from '../actions/formActions'; describe('form middleware', () => { it('does not prevent actions other than LOCATION_CHANGE to be handled', () => { const next = jest.fn(); const action = { type: '@@redux-form/INITIALIZE' }; formMiddleware()(next)(action); expect(next).toHaveBeenCalledWith(action); expect(next).toHaveBeenCalledTimes(1); }); it('does not prevent LOCATION_CHANGE actions to be handled if their state contains a skipFormReset set to true', () => { const next = jest.fn(); const action = { type: LOCATION_CHANGE, payload: { state: { skipFormReset: true } }, }; formMiddleware()(next)(action); expect(next).toHaveBeenCalledWith(action); }); it('resets the record state and destroy the redux form before letting the location change to be handled', () => { const next = jest.fn(); const action = { type: LOCATION_CHANGE, payload: { pathname: '/posts/create', }, }; formMiddleware()(next)(action); expect(next).toHaveBeenCalledWith(resetForm()); expect(next).toHaveBeenCalledWith(destroy(REDUX_FORM_NAME)); expect(next).toHaveBeenCalledWith(action); expect(next).toHaveBeenCalledTimes(3); }); it('does not resets the record and form if LOCATION_CHANGE targets the same location', () => { const next = jest.fn(); const action = { type: LOCATION_CHANGE, payload: { pathname: '/posts/create', }, }; const middleware = formMiddleware()(next); middleware(action); middleware(action); expect(next).toHaveBeenCalledWith(resetForm()); expect(next).toHaveBeenCalledWith(destroy(REDUX_FORM_NAME)); expect(next).toHaveBeenCalledWith(action); expect(next).toHaveBeenCalledTimes(4); }); });
67fcdaf6b8b589661358146e1babeb741429f127
TypeScript
ganzf/notrino
/src/ui/modules/parser/Variables.ts
3.296875
3
export class Reference { } export class Variable { // Line of the definition line: number = -1; // name of the variable name: string = ''; // Label to display if nothing else is available label: string | null = null; // Variable type type: string | null = null; // Variable type params (pointer to something, options...) params: string | null = null; // Is it a pointer to something ? isReference: boolean = false; reference: Reference | null = null; getStringValue(): string { return this.label || ''; } } export class Variables { vars: { [key: string]: Variable } = {}; constructor() { } has(name: string): boolean { return Object.keys(this.vars).includes(name); } add(v: Variable) { this.vars[v.name] = v; } get(name: string): Variable { return this.vars[name]; } }
9f744b799a88bbed604c7b21cc1379e95822c316
TypeScript
J-bar123/GhostWriter
/frontend/src/app/_services/user.service.ts
2.609375
3
import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {User} from '../_models/user'; import {Observable} from "rxjs"; interface GoalSet{ minutegoal: number; caloriegoal: number; } @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http: HttpClient) { } getAll() { return this.http.get<User[]>(`http://localhost:3030/user/allusers`); } register(user: User) { return this.http.post(`http://localhost:3030/user/register`, user); } //TODOc: add a function that will allow users to set their calorie and minute goals. // The function will communicate with the back-end. setGoals(user: User){ return this.http.post('http://localhost:3030/user/setgoals', user); } //TODOc: add a function that will allow users to get calorie and minute goals for a specific user // (this means, given a username, this function should fetch calories and minute goals for that user). // The function will communicate with the back-end. getGoals(name: User): Observable<User[]>{ return this.http.get<User[]>('http://localhost:3030/user/getgoals/' + name.username); } }
60ab1455d77cdc9d2736b452fda68e0591b9c03a
TypeScript
TheCodingWaffle/super-spork
/src/user/user.service.ts
2.65625
3
import { Injectable } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './user.entity'; @Injectable() export class UserService { constructor( @InjectRepository(User) private readonly userRepository: Repository<User>, private readonly jwtService: JwtService, ) {} async findAll(): Promise<User[]> { return await this.userRepository.find(); } async createUser(newUser: User): Promise<User> { return await this.userRepository.save(newUser); } async updateUser(updatedUser: User): Promise<boolean> { let result = false; let existingUser = await this.userRepository.findOne({ where: { id: updatedUser.id }, }); if (existingUser) { result = (await this.userRepository.save(updatedUser)) !== null; } return result; } async getUserById(userId: number): Promise<User | undefined> { return await this.userRepository.findOne({ where: { id: userId } }); } async validateUser(emailAddress: string, pass: string): Promise<any> { const user = await this.userRepository.findOne({ where: { email: emailAddress }, }); // prod wont store a password in plain text if (user && user.password === pass) { return user; } return null; } public createJwtToken(user: any): User { const payload = { email: user.email, id: user.id }; const token = this.jwtService.sign(payload); user.Token = token; return user; } }
fb9579f0118706daac1b32c1ee482c14381f5dc5
TypeScript
nilshohmann/restype
/src/authentication/RestAuthentication.ts
2.640625
3
import { AuthConfig } from '../core/HttpConfig'; import { HttpReqest } from '../core/HttpRequest'; import { logger } from '../core/Logging'; import { Authenticator } from './Authenticator'; import { BasicAuthenticator } from './BasicAuthenticator'; import { ChallengeAuthentication } from './ChallengeAuthentication'; import { JWTAuthenticator } from './JWTAuthenticator'; export type AuthenticationType = 'basic' | 'jwt'; export class RestAuthentication { public readonly challenge: ChallengeAuthentication; private config: AuthConfig; private readonly authenticators: { [type: string]: Authenticator } = {}; constructor(config: AuthConfig) { this.config = config || {}; this.challenge = new ChallengeAuthentication(config); if (typeof this.config.basicAuthentication === 'function') { this.authenticators['basic'] = new BasicAuthenticator(this.config.basicAuthentication); } if (typeof this.config.jwtAuthentication === 'function') { this.authenticators['jwt'] = new JWTAuthenticator(this.config.jwtAuthentication, this.config.jwtSecret); } } public authenticate = async <User>(authenticationType: AuthenticationType, req: HttpReqest): Promise<User> => { const authenticator = this.authenticators[authenticationType]; if (!authenticator) { logger.warn(`No authentication for type '${authenticationType}' found.`); return null; } return authenticator.authenticate<User>(req); }; public createJWT = <Payload>(payload: Payload): string => { return JWTAuthenticator.createJWT(payload, this.config.jwtSecret); }; }
bbc55b4c743426cd0560c223569db631cecc54b0
TypeScript
sarahatwork/swagger-mock-validator
/lib/swagger-mock-validator/transform-string-to-object.ts
2.515625
3
import * as yaml from 'js-yaml'; import {SwaggerMockValidatorErrorImpl} from './swagger-mock-validator-error-impl'; const parseJson = <T>(pathOrUrl: string, rawString: string): T => { try { return JSON.parse(rawString); } catch (error) { throw new SwaggerMockValidatorErrorImpl( 'SWAGGER_MOCK_VALIDATOR_PARSE_ERROR', `Unable to parse "${pathOrUrl}"`, error ); } }; const parseYaml = <T>(pathOrUrl: string, rawString: string): T => { let parsedYaml; try { parsedYaml = yaml.safeLoad(rawString); } catch (error) { throw new SwaggerMockValidatorErrorImpl( 'SWAGGER_MOCK_VALIDATOR_PARSE_ERROR', `Unable to parse "${pathOrUrl}"`, error ); } if (!parsedYaml) { throw new SwaggerMockValidatorErrorImpl('SWAGGER_MOCK_VALIDATOR_PARSE_ERROR', `Unable to parse "${pathOrUrl}"`); } return parsedYaml; }; export function transformStringToObject<T>(rawString: string, pathOrUrl: string): T { try { return parseJson<T>(pathOrUrl, rawString); } catch (parseJsonError) { try { return parseYaml<T>(pathOrUrl, rawString); } catch (parseYamlError) { throw parseJsonError; } } }
67c8a6a1b10574cb247bd4f29998398ee588a653
TypeScript
beau6183/ts-open-graph-scraper
/src/media.ts
2.515625
3
import _ from 'lodash' import fields from './fields' import { OGData, OGDataRaw, OGImage, OGMedia, OGMusicSong, OGOptions, OGVideo, OGTwitterPlayer, OGTwitterImage, } from './types' /* * media setup * @param string ogObject - return open open graph info * @param string options - options the user has set * @param function callback */ export function mediaSetup(ogObjectRaw: OGDataRaw, options: OGOptions) { /* Combine image/width/height/type and sort for priority */ if (ogObjectRaw.ogImage || ogObjectRaw.ogImageWidth || ogObjectRaw.twitterImageHeight || ogObjectRaw.ogImageType) { ogObjectRaw.ogImage = ogObjectRaw.ogImage ?? [] ogObjectRaw.ogImageWidth = ogObjectRaw.ogImageWidth ?? [] ogObjectRaw.ogImageHeight = ogObjectRaw.ogImageHeight ?? [] ogObjectRaw.ogImageType = ogObjectRaw.ogImageType ?? [] } const ogImages = _.zip(ogObjectRaw.ogImage, ogObjectRaw.ogImageWidth, ogObjectRaw.ogImageHeight, ogObjectRaw.ogImageType) .map(mediaMapper).sort(mediaSorter) /* Combine video/width/height/type and sort for priority */ if (ogObjectRaw.ogVideo || ogObjectRaw.ogVideoWidth || ogObjectRaw.ogVideoHeight || ogObjectRaw.ogVideoType) { ogObjectRaw.ogVideo = ogObjectRaw.ogVideo ?? [] ogObjectRaw.ogVideoWidth = ogObjectRaw.ogVideoWidth ?? [] ogObjectRaw.ogVideoHeight = ogObjectRaw.ogVideoHeight ?? [] ogObjectRaw.ogVideoType = ogObjectRaw.ogVideoType ?? [] } const ogVideos = _.zip(ogObjectRaw.ogVideo, ogObjectRaw.ogVideoWidth, ogObjectRaw.ogVideoHeight, ogObjectRaw.ogVideoType) .map(mediaMapper).sort(mediaSorter) /* Combine twitter image/width/height/alt and sort for priority */ if (ogObjectRaw.twitterImageSrc || ogObjectRaw.twitterImage || ogObjectRaw.twitterImageWidth || ogObjectRaw.twitterImageHeight || ogObjectRaw.twitterImageAlt) { // if twitterImage isn't there, try twitterImageSrc ogObjectRaw.twitterImage = ogObjectRaw.twitterImage ?? ogObjectRaw.twitterImageSrc ?? [] ogObjectRaw.twitterImageWidth = ogObjectRaw.twitterImageWidth ?? [] ogObjectRaw.twitterImageHeight = ogObjectRaw.twitterImageHeight ?? [] ogObjectRaw.twitterImageAlt = ogObjectRaw.twitterImageAlt ?? [] } const twitterImages = _.zip(ogObjectRaw.twitterImage, ogObjectRaw.twitterImageWidth, ogObjectRaw.twitterImageHeight, ogObjectRaw.twitterImageAlt) .map(mediaMapperTwitterImage).sort(mediaSorter) /* Combine twitter player/width/height/stream and sort for priority */ if (ogObjectRaw.twitterPlayer || ogObjectRaw.twitterPlayerWidth || ogObjectRaw.twitterPlayerHeight || ogObjectRaw.twitterPlayerStream) { ogObjectRaw.twitterPlayer = ogObjectRaw.twitterPlayer ?? [] ogObjectRaw.twitterPlayerWidth = ogObjectRaw.twitterPlayerWidth ?? [] ogObjectRaw.twitterPlayerHeight = ogObjectRaw.twitterPlayerHeight ?? [] ogObjectRaw.twitterPlayerStream = ogObjectRaw.twitterPlayerStream ?? [] } const twitterPlayers = _.zip(ogObjectRaw.twitterPlayer, ogObjectRaw.twitterPlayerWidth, ogObjectRaw.twitterPlayerHeight, ogObjectRaw.twitterPlayerStream) .map(mediaMapperTwitterPlayer).sort(mediaSorter) /* Combine music:song url, track, disk and sort in the right album order */ if (ogObjectRaw.musicSong || ogObjectRaw.musicSongTrack || ogObjectRaw.musicSongDisc) { ogObjectRaw.musicSong = ogObjectRaw.musicSong ?? [] ogObjectRaw.musicSongTrack = ogObjectRaw.musicSongTrack ?? [] ogObjectRaw.musicSongDisc = ogObjectRaw.musicSongDisc ?? [] } const musicSongs = _.zip(ogObjectRaw.musicSong, ogObjectRaw.musicSongTrack, ogObjectRaw.musicSongDisc) .map(mediaMapperMusicSong).sort(mediaSorterMusicSong) const ogObject: OGData = fields.reduce((acc, item) => { if (( item.multiple && ( item.fieldName.startsWith('ogImage') || item.fieldName.startsWith('ogVideo') || item.fieldName.startsWith('twitter') || item.fieldName.startsWith('musicSong') ) )) { return acc } else { return { ... acc, [item.fieldName]: ogObjectRaw[item.fieldName], } } }, {} as OGData) // Select the best image if (ogImages.length) { ogObject.ogImage = ogImages } // Select the best video if (ogVideos.length) { ogObject.ogVideo = ogVideos } // Select the best twitter image if (twitterImages.length) { ogObject.twitterImage = twitterImages } // Select the best player if (twitterPlayers.length) { ogObject.twitterPlayer = twitterPlayers } // Select the best music:song if (musicSongs.length) { ogObject.musicSong = musicSongs } return ogObject } function mediaMapperTwitterImage(item: (string | null | undefined)[]): OGTwitterImage { return { url: item[0]!, width: Number(item[1]), height: Number(item[2]), alt: item[3]!, } } function mediaMapperTwitterPlayer(item: (string | null | undefined)[]): OGTwitterPlayer { return { url: item[0]!, width: Number(item[1]), height: Number(item[2]), stream: item[3]!, } } function mediaMapperMusicSong(item: (string | null | undefined)[]): OGMusicSong { return { url: item[0]!, track: Number(item[1]), disc: Number(item[2]!), } } function mediaMapper(item: (string | null | undefined)[]): OGImage | OGVideo { const out = { url: item[0]!, width: Number(item[1]), height: Number(item[2]), type: item[3]!, } if (out.width === null || isNaN(out.width)) { delete out.width } if (out.height === null || isNaN(out.height)) { delete out.height } return out } function mediaSorter(a: OGMedia, b: OGMedia) { if (!(a.url && b.url)) { return 0 } const aRes = a.url.match(/\.(\w{2,5})$/) const aExt = (aRes && aRes[1].toLowerCase()) || null const bRes = b.url.match(/\.(\w{2,5})$/) const bExt = (bRes && bRes[1].toLowerCase()) || null if (aExt === 'gif' && bExt !== 'gif') { return -1 } else if (aExt !== 'gif' && bExt === 'gif') { return 1 } return Math.max(b.width, b.height) - Math.max(a.width, a.height) } function mediaSorterMusicSong(a: OGMusicSong, b: OGMusicSong) { if (!(a.track && b.track)) { return 0 } else if (a.disc > b.disc) { return 1 } else if (a.disc < b.disc) { return -1 } return a.track - b.track }
aed8129305d7c6e972d02101eacbdfa198db6473
TypeScript
sergio44444/prfinal
/src/main/webapp/app/entities/empresa/list/cliente.filtro.pipe.ts
2.5625
3
import { PipeTransform, Pipe } from '@angular/core'; import { Empresa } from '../empresa.model'; @Pipe({ name: 'empresafiltro', }) export class EmpresaFiltroPipe implements PipeTransform { transform(empresas: Empresa[], searchTerm: string, searchTerm2: string): Empresa[] { if (searchTerm !== '') { empresas = empresas.filter(empresa => empresa.numeroConvenio?.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1); } if (searchTerm2 !== '') { empresas = empresas.filter(empresa => empresa.localidad?.toLowerCase().indexOf(searchTerm2.toLowerCase()) !== -1); } return empresas; } }
15303a8022ff1bfff081c794f416f3512bc4a745
TypeScript
reginafaller/EIA2
/Endabgabe_copy/nemo.ts
2.78125
3
namespace fisch { export class Nemo { x: number; y: number; dx: number; dy: number; a: number; b: number; constructor(){ this.x = 0; this.y = Math.floor(Math.random() * crc.canvas.height); this.dx = 2; this.dy = 0; this.a = 1; } draw(): void { let bauch: Path2D = new Path2D(); bauch.moveTo(this.x, this.y); bauch.quadraticCurveTo(this.x - (15)*this.a, this.y - (20)*this.a, this.x - (40)*this.a, this.y - (6)*this.a); bauch.quadraticCurveTo(this.x - (46)*this.a, this.y - (12)*this.a, this.x - (50)*this.a, this.y - (12)*this.a); bauch.quadraticCurveTo(this.x - (55)*this.a, this.y - (9)*this.a, this.x - (50)*this.a, this.y - (6)*this.a); bauch.quadraticCurveTo(this.x - (55)*this.a, this.y - (3)*this.a, this.x - (50)*this.a, this.y); bauch.quadraticCurveTo(this.x - (55)*this.a, this.y + (3)*this.a, this.x - (50)*this.a, this.y + (6)*this.a); bauch.quadraticCurveTo(this.x - (55)*this.a, this.y + (9)*this.a, this.x - (50)*this.a, this.y + (12)*this.a); bauch.quadraticCurveTo(this.x - (46)*this.a, this.y + (12)*this.a, this.x - (40)*this.a, this.y + (6)*this.a); bauch.quadraticCurveTo(this.x - (15)*this.a, this.y + (20)*this.a, this.x, this.y); crc.fillStyle = "#FF6037"; crc.fill(bauch); crc.stroke(bauch); let auge: Path2D = new Path2D(); auge.moveTo(this.x, this.y); auge.arc(this.x - (10)*this.a, this.y - (4)*this.a, 1.5*this.a, 0, 10); crc.fillStyle = "white"; crc.fill(auge); let pupille: Path2D = new Path2D(); pupille.moveTo(this.x, this.y); pupille.arc(this.x - (10)*this.a, this.y - (4)*this.a, 1*this.a, 0, 10); crc.fillStyle = "black"; crc.fill(pupille); } update(_x: number, _y:number, _s:number): void { this.move(_x, _y); this.scale(_s) this.draw(); } move(_x: number, _y:number): void { if (this.x >= 1200) { this.x = 0; } this.x += this.dx; this.y += this.dy + _y; } scale(_s:number):void{ this.a = this.a*_s; } } }
fc9ad2de67eb09c1bb4c6a5e3cbc139c19a2fc58
TypeScript
benbotto/formn
/src/modelgenerator/model/model-column.spec.ts
3.25
3
import { ModelColumn, DefaultColumnFormatter } from '../'; describe('ModelColumn()', () => { let col: ModelColumn; beforeEach(() => col = new ModelColumn(new DefaultColumnFormatter())); describe('.getName()', () => { it('returns undefined by default.', () => { expect(col.getName()).not.toBeDefined(); }); it('returns the table name.', () => { col.setName('age'); expect(col.getName()).toBe('age'); }); }); describe('.getPropertyName()', () => { it('returns the camel case version of the name.', () => { col.setName('likes_to_eat_cake'); expect(col.getPropertyName()).toBe('likesToEatCake'); }); }); describe('.getDecoratorString()', () => { it('returns a column decorator by default.', () => { expect(col.getDecoratorString()).toBe(' @Column()'); }); it('has the name property.', () => { col.setName('likes_to_eat_cake'); expect(col.getDecoratorString()).toBe(" @Column({name: 'likes_to_eat_cake'})"); }); it('does not include the name property if the column name matches the property name.', () => { col.setName('age'); expect(col.getDecoratorString()).toBe(' @Column()'); }); it('includes the isPrimary flag when true.', () => { col.setIsPrimary(true); expect(col.getDecoratorString()).toBe(' @Column({isPrimary: true})'); }); it('includes the isGenerated flag when true.', () => { col.setIsGenerated(true); expect(col.getDecoratorString()).toBe(' @Column({isGenerated: true})'); }); it('includes the hasDefault flag when true.', () => { col.setHasDefault(true); expect(col.getDecoratorString()).toBe(' @Column({hasDefault: true})'); }); it('includes the isNullable flag when false.', () => { col.setIsNullable(false); expect(col.getDecoratorString()).toBe(' @Column({isNullable: false})'); }); it('includes the maxLength.', () => { col.setMaxLength(255); expect(col.getDecoratorString()).toBe(' @Column({maxLength: 255})'); }); it('includes the sqlDataType.', () => { col.setSQLDataType('tinyint'); expect(col.getDecoratorString()).toBe(' @Column({sqlDataType: \'tinyint\'})'); }); }); describe('.getPropertyString()', () => { it('throws an error if there is no name.', () => { expect(() => col.getPropertyString()).toThrowError('ModelColumn instance has no name.'); }); it('throws an error if there is no datatype.', () => { col.setName('name'); expect(() => col.getPropertyString()).toThrowError('ModelColumn instance has no data type.'); }); it('returns the property string.', () => { col.setName('likes_food'); col.setDataType('boolean'); expect(col.getPropertyString()).toBe(' likesFood: boolean'); }); }); describe('toString()', () => { it('returns a string representation of the column.', () => { col.setName('likes_food'); col.setDataType('boolean'); col.setHasDefault(true); expect(col.toString()) .toBe(" @Column({name: 'likes_food', hasDefault: true})\n" + " likesFood: boolean;"); }); }); });
ceb10ba918770264f2599f877c10793f3489e4cc
TypeScript
timyc/wjclient
/project/src/game/play/ai/action/AIUnitPlayAction.ts
2.53125
3
class AIUnitPlayAction extends AIUnitAction { private m_Anim: EntityClipType public constructor(anim: EntityClipType) { super() this.m_Anim = anim } OnEnter(): void { this.GetUnit().mEntity.UpdateAction(this.m_Anim, false) } public OnUpdate(delta: number): AIUnitReturn { return AIUnitReturn.NEXT } }
2aa101257fd7c53062ae1fef444b5ecd7746cdb7
TypeScript
Technopark-Altair/test1-KekW228321
/src/app/app.component.ts
2.765625
3
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css' ] }) export class AppComponent { title = 'homework2'; firstOperands: number; secondOperands: number; operator1: string; operator2: string; result: boolean; Error: string; doCalc(){ if(this.firstOperands != null && this.secondOperands != null && this.operator2 != null){ if(this.operator1!='!'){ if(this.operator2=='&&'){ this.result = Boolean(this.firstOperands && this.secondOperands) this.Error = 'Нет ошибок' }else if(this.operator2=='||'){ this.result = Boolean(this.firstOperands || this.secondOperands) this.Error = 'Нет ошибок' } }else if (this.operator1 =='!'){ if(this.operator2=='&&'){ this.result = !Boolean(this.firstOperands && this.secondOperands) this.Error = 'Нет ошибок' }else if(this.operator2=='||'){ this.result = !Boolean(this.firstOperands || this.secondOperands) this.Error = 'Нет ошибок' } } }else if(this.firstOperands==null){ this.Error='Нет первого операнда!' }else if(this.secondOperands==null){ this.Error='Нет второго операнда!' }else if(this.operator2==null){ this.Error='Нет оператора действия!' } } }
5a65d9cc002b9ae310a1bea157d599a1ee3c60ff
TypeScript
Wyden971/xrpawn
/src/core/models/BlockData.ts
2.53125
3
import {ec as EC} from "elliptic"; import SHA256 from "crypto-js/sha256"; import {v4 as uuid4} from 'uuid' import {AvailableBlockTransactionType} from "./Block"; import {Transaction} from "./Transaction"; import {Security} from "./Security"; import {Loan} from "./Loan"; import {User} from "./User"; import {Balances, Blockchain} from "./Blockchain"; export enum BlockDataType { "transaction" = "transaction", "security" = "security", "user" = "user", "loan" = "loan", } export abstract class BlockData<T> { static ec = new EC('secp256k1'); public id?: string; public abstract type: BlockDataType; public fromAddress: string; public toAddress: string; public createdAt: number; public updatedAt?: number; public deletedAt?: number; public signature?: string; public signature2?: string; public hash?: string; public previousHash?: string; constructor(fromAddress: string, toAddress: string, id: string) { this.id = id; this.fromAddress = fromAddress; this.toAddress = toAddress; this.createdAt = Math.round(Date.now() / 1000); this.updatedAt = Math.round(Date.now() / 1000); } public abstract getData(): T; public calculateHash() { return this.hashData(this.getData()); } public isValid() { if (this.fromAddress === null) return true; if (this.hash !== this.calculateHash()) { throw new Error('Invalid hash : ' + this.hash); } if (!this.signature?.length) { throw new Error('No signature for this transaction'); } const publicKey = BlockData.ec.keyFromPublic(this.fromAddress, 'hex'); if (!this.signature2?.length) { return publicKey.verify(this.hash, this.signature!); } else if (this.previousHash && this.toAddress) { const publicKey2 = BlockData.ec.keyFromPublic(this.toAddress, 'hex'); return publicKey.verify(this.previousHash, this.signature!) && publicKey2.verify(this.hash, this.signature2!); } else { return false; } } public sign(signingKey: EC.KeyPair) { const address = signingKey.getPublic('hex'); if (!address || address === this.fromAddress) { if (this.fromAddress === null) return; return this.signAsFromAddress(signingKey); } else if (address === this.toAddress) return this.signAsToAddress(signingKey); else { throw new Error('You cannot sign for other wallets'); } } private signAsFromAddress(signingKey: EC.KeyPair) { console.log('signAsFromAddress'); if (signingKey.getPublic('hex') !== this.fromAddress) { throw new Error('You cannot sign transaction for other wallets'); } this.hash = this.calculateHash(); const sig = signingKey.sign(this.hash, 'base64'); this.signature = sig.toDER('hex'); return this; } private signAsToAddress(signingKey: EC.KeyPair) { console.log('signAsToAddress'); if (!this.signature) { throw new Error('This transaction is not signed by the owner'); } if (signingKey.getPublic('hex') !== this.toAddress) { throw new Error('You cannot sign transaction for other wallets'); } this.hash = this.calculateHash(); const sig = signingKey.sign(this.hash, 'base64'); this.signature2 = sig.toDER('hex'); return this; } protected hashData(data: any) { const dataToHash = `${this.id}/${this.createdAt}/${this.fromAddress}/${this.toAddress}/${this.previousHash ?? null}/${this.deletedAt ?? null}/${JSON.stringify(data)}`; return SHA256(dataToHash).toString(); } asTransaction() { return ((this as any) as Transaction); } asLoan() { return ((this as any) as Loan); } asSecurity() { return ((this as any) as Security); } getSqlData() { const data = { id: this.id, type: this.type, fromAddress: this.fromAddress, toAddress: this.toAddress, createdAt: this.createdAt, updatedAt: this.updatedAt, signature: this.signature, signature2: this.signature2 ?? null, hash: this.hash, previousHash: this.previousHash ?? null, ...this.getData() }; return data; } getInsertSQL(table: string) { const data = this.getSqlData(); const keys = Object.keys(data).join(','); const values = Object.values(data).map((item) => item ?? null); const valuesPlace = values.map((item) => '?').join(','); return { query: `INSERT INTO \`${table}\` (${keys}) VALUES (${valuesPlace});`, variables: values }; } check(balances: Balances, inGenesisBlock: boolean = false) { const oldBalances = {...balances}; switch (this.type) { case BlockDataType.transaction: const amount = this.asTransaction().amount - (inGenesisBlock ? 0 : Blockchain.STATIC_FEE); if (!inGenesisBlock) balances[this.fromAddress] = (balances[this.fromAddress] ?? 0) - amount; balances[this.toAddress] = (balances[this.toAddress] ?? 0) + amount; break; case BlockDataType.loan: balances[this.fromAddress] = (balances[this.fromAddress] ?? 0) - Blockchain.STATIC_FEE; break; } if (!inGenesisBlock && balances[this.fromAddress] <= 0) { Object.assign(balances, oldBalances); return false; } return true; } }
718c64c9ddf3990e4ade5df23583e4754239cafb
TypeScript
JuliaGizmos/WebIO.jl
/packages/webio/src/DomNode.ts
2.96875
3
import createLogger from "debug"; const debug = createLogger("WebIO:DomNode"); import WebIONode, { WebIODomElement, WebIONodeSchema, WebIONodeContext, } from "./Node"; import {createWebIOEventListener} from "./events"; import createNode from "./createNode"; export const DOM_NODE_TYPE = "DOM"; const enum DomNamespace { // "html" should actually be "http://www.w3.org/1999/xhtml" but it's okay HTML = "html", SVG = "http://www.w3.org/2000/svg", SVG_SHORTHAND = "svg", } /** * Props associated with a WebIO DOM node serialization. */ interface DomNodeProps { /** * A map of style (CSS) attributes to the associated value. */ style?: { [attributeName: string]: string; }; /** * A map of event names to listeners (or function definitions of listeners). */ events?: { [eventName: string]: string; }; /** * A map of (DOM?) attributes to their values (or null if they should be unset). */ attributes?: { [attributeName: string]: string | null; }; /** * A map of namespaced (DOM) attributes to their values (or null if they should * be unset). * * This doesn't seem to be implemented on the Julia side of things. */ attributesNS?: { [attributeName: string]: { namespace: DomNamespace; value: string | null; } }; /** * The `innerHTML` that should be set on the node. * * @todo Is there a reason that this is `setInnerHTML` rather than just * `innerHTML`? */ setInnerHtml?: string; /** * Miscellaneous attributes that will be set on the DOM element. */ [otherProp: string]: any; } // Convenience declaration for use in methods within `WebIODomNode` type Props = Required<DomNodeProps>; /** * Data required to construct a WebIO DOM node. */ export interface DomNodeData extends WebIONodeSchema { nodeType: typeof DOM_NODE_TYPE; /** * Information about the type of DOM node (e.g. a <div /> or SVG document). */ instanceArgs: { namespace: DomNamespace; tag: string; } props: DomNodeProps; } class WebIODomNode extends WebIONode { readonly element: WebIODomElement; children: Array<WebIONode | string>; private eventListeners: {[eventType: string]: EventListener | undefined} = {}; private static createElement(data: DomNodeData) { const {namespace, tag} = data.instanceArgs; switch (namespace.toLocaleLowerCase()) { case DomNamespace.HTML: return document.createElement(tag); case DomNamespace.SVG: case DomNamespace.SVG_SHORTHAND: return document.createElementNS(DomNamespace.SVG, tag); default: throw new Error(`Unknown DOM namespace: ${namespace}.`); } } constructor(nodeData: DomNodeData, options: WebIONodeContext) { super(nodeData, options); debug("Creating WebIODomNode", {nodeData, options, node: this}); this.element = WebIODomNode.createElement(nodeData); this.applyProps(nodeData.props); // Recursively construct children. this.children = nodeData.children.map((nodeData) => { if (typeof nodeData === "string") { return nodeData; } return createNode(nodeData, {webIO: this.webIO, scope: this.scope}) }); // Append childrens' elements to this node's element. for (const child of this.children) { if (typeof child === "string") { this.element.appendChild(document.createTextNode(child)); } else { this.element.appendChild(child.element); } } } /** * Apply "props" to the underlying DOM element. * * @param props - The props to apply. */ applyProps(props: DomNodeProps) { debug("applyProps", props); const {style, events, attributes, attributesNS, setInnerHtml, ...rest} = props; style && this.applyStyles(style); events && this.applyEvents(events); attributes && this.applyAttributes(attributes); attributesNS && this.applyAttributesNS(attributesNS); setInnerHtml && this.setInnerHTML(setInnerHtml); this.applyMiscellaneousProps(rest); } /** * Apply all props that don't have special meaning. * * This should really be refactored so that all these "miscellaneous" props * are delivered in a separate object (e.g. have props.miscProps on the same * level as props.style and props.events et al.). * @param props - The object of miscellaneous props and their values. */ applyMiscellaneousProps(props: {[propName: string]: any}) { debug("applyMiscellaneousProps", props); for (const propName of Object.keys(props)) { (this.element as any)[propName] = props[propName]; } } applyStyles(styles: Props["style"]) { if (!styles) { return; } for (const attributeName of Object.keys(styles)) { this.element.style[attributeName as any] = styles[attributeName]; } } /** * Apply (add/remove) event listeners to the underlying DOM element. * * @param events - A map object from event names to event listeners. If an * event name is specified (e.g. `click`) that didn't exist before, the * associated handler (e.g. `events["click"]`) is added as a listener; if * the event name has already been specified (even if the listener function * changed!), then nothing happens; if the event name is absent (or null) in * the map, then any previously setup listeners (if any) are removed. */ applyEvents(events: Props["events"]) { debug(`applyEvents`, events); for (const eventName of Object.keys(events)) { const oldListener = this.eventListeners[eventName]; const newListenerSource = events[eventName]; const newListener = newListenerSource && createWebIOEventListener( this.element, newListenerSource, {scope: this.scope, webIO: this.webIO}, ); if (oldListener && !newListener) { // We want to just remove the old listener. this.element.removeEventListener(eventName, oldListener); delete this.eventListeners[eventName]; } else if (!oldListener && newListener) { debug(`addEventListener(${eventName}, ...)`); this.element.addEventListener(eventName, newListener); this.eventListeners[eventName] = newListener; } // If the listener is just changed, we don't really handle that. } } /** * Apply DOM attributes to the underlying DOM element. * * @param attributes - The map of attributes to apply. */ applyAttributes(attributes: Props["attributes"]) { for (const key of Object.keys(attributes)) { const value = attributes[key]; if (value === null) { this.element.removeAttribute(key); } else { this.element.setAttribute(key, value); } } } /** * Apply namespaced DOM attributes to the underlying DOM element. * * @param attributes - The `{attributeName: {namespace, value}}` map to apply. */ applyAttributesNS(attributes: Props["attributesNS"]) { for (const key of Object.keys(attributes)) { const {namespace, value} = attributes[key]; if (value === null) { this.element.removeAttributeNS(namespace, key); } else { this.element.setAttributeNS(namespace, key, value); } } } /** * Set the value associated with the node's element. * * This generally only works with `<input />` elements. * * @param value * @throws Will throw an error if the element doesn't have a `value` attribute. */ setValue(value: any) { if ("value" in this.element) { // If the value hasn't changed, don't re-set it. if (this.element.value !== value) { this.element.value = value; } } else { throw new Error("Cannot set value on an HTMLElement that doesn't support it."); } } } export default WebIODomNode;
b38b000f45c7fb39a83d489cea907bf9f4ccaba7
TypeScript
ryym/wracket
/frontend/lib/bookmark-lister.ts
2.8125
3
import {iter, Iter} from './iter'; import { Bookmark, BookmarkById, BookmarkStatus, SearchCondition, getStatusesFromFilter, } from './models'; // TODO: Use iterator more efficiently. export const selectShownIds = ( byId: BookmarkById, cdtn: SearchCondition, count: number | null = null, ): string[] => { const statuses = getStatusesFromFilter(cdtn.statusFilter); const bks = iter(Object.keys(byId)) .map(id => byId[id]!) .use(filterBookmarks(statuses)) .collect(); const sorted = sortBookmarks(bks, statuses); return (count ? sorted.slice(0, count) : sorted).map(b => b.id); }; export const filterBookmarks = (statuses: Array<BookmarkStatus>) => { const statusesSet = new Set(statuses); return (it: Iter<Bookmark>): Iter<Bookmark> => { return it.filter(b => statusesSet.has(b.status)); }; }; // in-place sort export const sortBookmarks = (bks: Bookmark[], statuses: Array<BookmarkStatus>): Bookmark[] => { if (statuses.length === 1 && statuses[0] === BookmarkStatus.Archived) { return bks.sort((b1, b2) => (b2.archivedAt || 0) - (b1.archivedAt || 0)); } return bks.sort((b1, b2) => b2.addedAt - b1.addedAt); };
f373e57b814f8596fa4967e5aac2dab27b5a66dc
TypeScript
AnkitM19/UserDetails-mysql-authentication-typeorm
/src/Service/user.service.ts
2.5625
3
/* eslint-disable @typescript-eslint/no-unused-vars */ import { Injectable, NotFoundException, UnauthorizedException, } from '@nestjs/common'; import { Users } from '../sql model/User.Entity'; import { InjectRepository } from '@nestjs/typeorm'; import { UserRepository } from '../sql model/user.repository'; import { UserDto } from 'src/dto/UserDto'; import { UpdateUserDto } from 'src/dto/updateUserDto'; import * as bcrypt from 'bcrypt'; import { LoginDto } from 'src/authentication/Auth.dto'; import { JwtService } from '@nestjs/jwt'; import { JwtPayload } from 'src/Interfaces/jwt.payload.interface'; @Injectable() export class UserService { constructor( @InjectRepository(UserRepository) private readonly userRepo: UserRepository, private jwtService: JwtService, ) {} async signUp(createUserDto: UserDto): Promise<Users> { debugger; const { Name, userName, password, phnNumber, emailId } = createUserDto; const salt = await bcrypt.genSalt(); const hashedPassword = await bcrypt.hash(password, salt); //encrypting password const user: Users = this.userRepo.create({ Name, userName, password: hashedPassword, phnNumber, emailId, }); await this.userRepo.save(user); return user; } async signIn(authDto: LoginDto): Promise<{ accessToken: string }> { const { emailId, password } = authDto; const user = await this.userRepo.findOne({ emailId }); const compare = await bcrypt.compare(password, user.password); if (user && compare) { const payload: JwtPayload = { emailId }; const accessToken: string = await this.jwtService.sign(payload); //checking user validity return { accessToken }; } else { throw new UnauthorizedException('Invalid username and password'); } } findAll(): Promise<Users[]> { if (!Users) { throw new NotFoundException('Not Found'); } else return this.userRepo.find(); } findOne(id: string): Promise<Users> { if (!id) { throw new NotFoundException('User Not Found'); } else return this.userRepo.findOne(id); } async remove(id: string): Promise<void> { await this.userRepo.delete(id); } async update(id: string, UpdateUserDto: UpdateUserDto): Promise<Users> { const userUpdate = await this.userRepo.findOne(id); if (!userUpdate) { throw new NotFoundException('User Not found'); } else { const { userName, phnNumber } = UpdateUserDto; //updating user information userUpdate.userName = userName; userUpdate.phnNumber = phnNumber; const update = await this.userRepo.save(userUpdate); return update; } } }
6fa0cf4e152e12135cf60d672c00ddbce24124eb
TypeScript
4-sight/sudoku
/src/Game/utils/solver/index.ts
2.8125
3
import { Givens } from "../../types" import Grid, { GridState } from "./Classes/Grid" import GridAreaGroup from "./Classes/GridAreaGroup" import { bifurcate } from "./strategies/" export type GridAreaGroups = [GridAreaGroup, GridAreaGroup, GridAreaGroup] export default (givens: Givens): [GridState[], boolean] => { const grid = new Grid(givens) const startTime = Date.now() const solved = grid.solve() if (!solved) { const solution = bifurcate(grid) if (solution) { console.log(`Solved in: ${Date.now() - startTime}ms`) return [solution.getHistory(), true] } } if (solved) { console.log(`Solved in: ${Date.now() - startTime}ms`) } return [grid.getHistory(), grid.unsolved.size === 0] }
68281c3e7758db95196efe3a63732aed8156264c
TypeScript
lpaladin/json-inline-doc
/src/jsonCommentWriterBase.ts
3.078125
3
import * as wrap from 'word-wrap'; import { IJSONComment, IJSONCommentConfiguration, IReplacer } from './types'; /** * Base writer to add comments to stringified JSON. * JSON stringify implementation is based on the following code: * https://github.com/douglascrockford/JSON-js/blob/2a76286e00cdc1e98fbc9e9ec6589563a3a4c3bb/json2.js * * @param CommentDataNodeType Subclasses should use this type of node to track current node and related data. */ export abstract class JSONCommentWriterBase<CommentDataNodeType> { private static readonly defaultConfiguration: IJSONCommentConfiguration = { emptyLineBeforeComments: true, spaceAroundCommentSymbol: true, styledBlockComment: true, maxLineLength: 80 }; private readonly configuration: IJSONCommentConfiguration; private indent: string = ''; private replacer: IReplacer | undefined; private path: (string | number)[] = []; /** * Construct a new JSONCommentWriter. * @param configuration Styling configuration for comments. */ public constructor(configuration?: Partial<IJSONCommentConfiguration>) { this.configuration = { ...JSONCommentWriterBase.defaultConfiguration, ...configuration }; } /** * Convert the given object to a JSON string with comments specified eariler. * @param object The root object to convert to JSON string. * @param replacer A function that alters the behavior of the stringification process, * or an array of String and Number objects that serve as a whitelist for * selecting/filtering the properties of the value object to be included in the JSON string. * * If this value is null or not provided, * all properties of the object are included in the resulting JSON string. * @param space A String or Number object that's used to insert white space into * the output JSON string for readability purposes. * * If this is a Number, it indicates the number of space characters to use as white space; * this number is capped at 10 (if it is greater, the value is just 10). * Values less than 1 indicate that no space should be used. * * If this is a String, the string is used as white space. * If this parameter is not provided (or is null), no white space is used. * * @returns The JSON string, or `undefined` if object is `undefined`. */ public stringify(object: any, replacer?: IReplacer, space?: number | string): string | undefined { this.indent = ''; if (typeof space === 'number') { for (let i: number = 0; i < space; i++) { this.indent += ' '; } } else if (typeof space === 'string') { this.indent = space; } this.replacer = replacer; if (replacer && typeof replacer !== 'function' && !Array.isArray(replacer)) { throw new Error('Argument `replacer` is expected to be a function or an array'); } this.path = []; const { comments: parts, childJSON, lineEndComment } = this.getChildJSON({ '': object }, '', '', this.root); if (childJSON === undefined) { return undefined; } parts.push(childJSON + (lineEndComment || '')); return parts.join('\n'); } protected abstract get root(): Readonly<CommentDataNodeType>; protected abstract nextNode(currentNode: Readonly<CommentDataNodeType>, key: string | number) : Readonly<CommentDataNodeType> | undefined; protected abstract getComments(currentNode: Readonly<CommentDataNodeType>): IJSONComment[]; private renderComment(gap: string, path: (string | number)[], comment: IJSONComment): string | undefined { if (typeof comment === 'string') { comment = { type: 'block', content: comment }; } let content: string | undefined = typeof comment.content === 'function' ? comment.content(path.slice(1)) : comment.content; if (content === undefined) { return undefined; } // If there's indent or is root level if (gap || this.path.length === 1) { if (this.configuration.maxLineLength > 0) { content = wrap(content, { width: this.configuration.maxLineLength, indent: '', trim: true }); } if (comment.type === 'block') { content = content.replace(/\*\//g, '*\/'); if (this.configuration.styledBlockComment) { return `/** ${gap} * ${content.replace(/\n/g, `\n${gap} * `)} ${gap} */`; } else if (this.configuration.spaceAroundCommentSymbol) { return `/* ${content.replace(/\n/g, `\n${gap}`)} */`; } else { return `/*${content.replace(/\n/g, `\n${gap}`)}*/`; } } else { if (comment.type === 'end' && content.includes('\n')) { throw new Error('Comment of type `end` is expected to be single-line'); } if (this.configuration.spaceAroundCommentSymbol) { return `// ${content.replace(/\n/g, `\n${gap}// `)}`; } else { return `//${content.replace(/\n/g, `\n${gap}//`)}`; } } } else { if (comment.type === 'block') { if (content.includes('\n')) { throw new Error('Comment is expected to be single-line when space is 0'); } content = content.replace(/\*\//g, '*\/'); if (this.configuration.spaceAroundCommentSymbol) { return `/* ${content} */`; } else { return `/*${content}*/`; } } else { return undefined; } } } private getChildJSON(value: any, nextKey: string | number, gap: string, node: CommentDataNodeType | undefined) : { comments: string[], childJSON: string | undefined, lineEndComment: string | undefined } { const nextNode: CommentDataNodeType | undefined = node && this.nextNode(node, nextKey); const parts: string[] = []; let lineEndComment: string | undefined; this.path.push(nextKey); if (nextNode) { for (const comment of this.getComments(nextNode)) { if (typeof comment === 'object' && comment.type === 'end' && lineEndComment !== undefined) { throw new Error('Comment of type `end` is expected to be unique for each field'); } const commentString: string | undefined = this.renderComment(gap, this.path, comment); if (typeof comment === 'object' && comment.type === 'end') { lineEndComment = commentString; } else if (commentString !== undefined) { parts.push(commentString); } } } const childJSON: string | undefined = this.objToJSON(nextKey, value, gap, nextNode); this.path.pop(); if (lineEndComment !== undefined && this.configuration.spaceAroundCommentSymbol) { lineEndComment = ' ' + lineEndComment; } return { comments: parts, childJSON, lineEndComment }; } /** * Convert holder[key] to JSON. * @param key The key of the item to be serialized. * Note that it accepts number to allow for JS engine optimization. * @param holder The object holding the item. * @param gap Accumulated indent. * @param nodes Selecter tree nodes matched for the item * @returns JSON representation of the item. * `undefined` if the item is `undefined`. */ // tslint:disable-next-line private objToJSON(key: string | number, holder: any, gap: string, node: CommentDataNodeType | undefined): string | undefined { let value: any = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof this.replacer === 'function') { value = this.replacer.call(holder, key, value); } if (typeof value === 'object') { if (!value) { return 'null'; } const currGap: string = gap + this.indent; const lineBreakCurrGap: string = currGap ? '\n' + currGap : ''; const lineEndComments: { [index: number]: string } = {}; const partial: string[] = []; const fnPartialToLine: (value: string, i: number) => string = (p, i) => `${p}${i < partial.length - 1 ? ',' : ''}${lineEndComments[i] || ''}`; if (Array.isArray(value)) { if (value.length === 0) { return '[]'; } for (let i: number = 0; i < value.length; i++) { const { comments: parts, childJSON, lineEndComment } = this.getChildJSON(value, i, currGap, node); if (lineEndComment !== undefined) { lineEndComments[i] = lineEndComment; } parts.push(childJSON || 'null'); const currentItemWithComments: string = parts.join(lineBreakCurrGap); if (this.configuration.emptyLineBeforeComments && i > 0 && parts.length > 1 && currGap) { // Not the first item in array && has comment && spaces != 0 // Add a empty line partial.push(lineBreakCurrGap + currentItemWithComments); } else { partial.push(currGap + currentItemWithComments); } } return currGap ? `[ ${partial.map(fnPartialToLine).join('\n')} ${gap}]` : `[${partial.join(',')}]`; } else { const keys: (string | number)[] = Array.isArray(this.replacer) ? this.replacer : Object.keys(value); if (keys.length === 0) { return '{}'; } for (const k of keys) { const { comments: parts, childJSON, lineEndComment } = this.getChildJSON(value, k, currGap, node); if (childJSON) { if (lineEndComment !== undefined) { lineEndComments[partial.length] = lineEndComment; } parts.push(JSON.stringify(k) + (currGap ? ': ' : ':') + childJSON); const currentKVPairWithComments: string = parts.join(lineBreakCurrGap); if (this.configuration.emptyLineBeforeComments && partial.length > 0 && parts.length > 1 && currGap) { // Not the first key-value pair in object && has comment && spaces != 0 // Add a empty line partial.push(lineBreakCurrGap + currentKVPairWithComments); } else { partial.push(currGap + currentKVPairWithComments); } } } return currGap ? `{ ${partial.map(fnPartialToLine).join('\n')} ${gap}}` : `{${partial.join(',')}}`; } } else { return JSON.stringify(value); } } }
e9316d92aa5c8946bb76942c5de356ec0091d498
TypeScript
PyroTechniac/Constellations
/src/lib/structures/base/Piece.ts
3.03125
3
import type { Store } from './Store'; import type { ConstellationClient } from '../../Client'; import { mergeDefault } from '../../util/Utils'; import { join } from 'path'; /** * The common class for all pieces. */ export class Piece { /** * The name of this Piece */ public name: string; /** * The file location where this Piece is stored */ public file: string[]; /** * Whether this Piece is enabled or not */ public enabled: boolean; /** * The directory this piece is held in */ public directory: string; /** * The Store that's holding this Piece */ public readonly store!: Store<this>; /** * @param store The store this Piece is for * @param file The path from the pieces folder to the Piece file * @param directory The base directory for the pieces folder * @param options The options for this piece */ public constructor(store: Store<Piece>, file: string[], directory: string, options: PieceOptions = {}) { const defaults = store.client.options.pieceDefaults[store.name]; if (defaults) options = mergeDefault(defaults, options); Object.defineProperty(this, 'store', { value: store }); this.file = file; this.name = options.name ?? file[file.length - 1].slice(0, -3); this.enabled = Boolean(options.enabled); this.directory = directory; } /** * The type of Constellation piece this is */ public get type(): string { return this.store.name.slice(0, -1); } /** * The absolute path to this piece */ public get path(): string { return join(this.directory, ...this.file); } /** * The client this Piece was instantiated with */ public get client(): ConstellationClient { return this.store.client; } /** * Reloads this Piece. */ public async reload(): Promise<this> { const piece = this.store.load(this.directory, this.file); await piece.init(); if (this.client.listenerCount('pieceReloaded')) this.client.emit('pieceReloaded', piece); return piece; } /** * Unloads this Piece. */ public unload(): boolean { if (this.client.listenerCount('pieceUnloaded')) this.client.emit('pieceUnloaded', this); return this.store.delete(this); } /** * Disables this Piece. * @chainable */ public disable(): this { if (this.client.listenerCount('pieceDisabled')) this.client.emit('pieceDisabled', this); this.enabled = false; return this; } /** * Enables this Piece. * @chainable */ public enable(): this { if (this.client.listenerCount('pieceEnabled')) this.client.emit('pieceEnabled', this); this.enabled = true; return this; } /** * The init method to be optionally overwritten in actual Pieces. * @abstract */ public async init(): Promise<any> { // Optionally defined in extension Classes } /** * Defines toString behavior for Pieces. */ public toString(): string { return this.name; } /** * Defines `JSON.stringify` behavior for Pieces. */ public toJSON(): PieceJSON { return { directory: this.directory, file: this.file, name: this.name, type: this.type, enabled: this.enabled, path: this.path }; } } export interface PieceOptions { name?: string; enabled?: boolean; } export interface PieceJSON { directory: string; file: string[]; path: string; type: string; name: string; enabled: boolean; }
30eb4958956676ef8cdaf4fa9ed1d14cb67c4030
TypeScript
PhilVargas/tetris
/src/typings/index.ts
2.734375
3
export enum CellType { E = "E", I = "I", O = "O", Z = "Z", S = "S", T = "T", J = "J", L = "L" } export type PieceType = CellType.I | CellType.O | CellType.Z | CellType.S | CellType.T | CellType.J | CellType.L export type PieceTypes = ReadonlyArray<PieceType> export interface IPieceOffset { readonly x: -1 | 0 | 1 | 2 readonly y: -1 | 0 | 1 | 2 } export type Rotation = 0 | 1 | 2 | 3 export type RotationDirection = -1 | 1 export interface ICoordinate { readonly xCoord: number readonly yCoord: number } export type PieceShape = ReadonlyArray<IPieceOffset> export type PieceRotations = ReadonlyArray<PieceShape> export type PieceMap = { [key in PieceType]: PieceRotations } export type LinesCleared = 0 | 1 | 2 | 3 | 4 export type BaseScorePerTurn = 0 | 40 | 100 | 300 | 1200 export type Level = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 export interface IScoredBoardCells { cells: BoardCells scoreThisTurn: number linesClearedThisTurn: LinesCleared } export interface IBoardSettings { height: number width: number hiddenRows: number yCoord: number xCoord: number pieceIds: Array<number> rotation: Rotation } export interface ICellSettings { edgeLength: number } export interface ICellProps { className?: string isHidden: boolean isGhost: boolean isPiece: boolean width: number height: number cellType: CellType isColorblindModeEnabled: boolean isGhostEnabled: boolean } export interface IGameSettings { hasGameBegun: boolean isPaused: boolean initialTurnDelay: number totalLinesCleared: number score: number scoreThisTurn: number minimumTurnDelay: number isGameOver: boolean isColorblindModeEnabled: boolean isGhostEnabled: boolean isQueuePieceEnabled: boolean canQueuePiece: boolean isAudioMuted: boolean } export interface ISettings { BoardSettings: IBoardSettings CellSettings: ICellSettings GameSettings: IGameSettings } export interface IBoardCell { id: number yCoord: number xCoord: number isFrozen: boolean cellType: CellType pieceType?: PieceType ghostType?: PieceType } export type BoardCells = Array<IBoardCell> export interface IBoardProps { cells: BoardCells isColorblindModeEnabled: boolean isGhostEnabled: boolean } export interface IGameState { xCoord: number yCoord: number cells: BoardCells currentPieceType: PieceType nextPieceType: PieceType queuePieceType?: PieceType pieceIds: Array<number> rotation: Rotation turnDelay: number isPaused: boolean hasGameBegun: boolean totalLinesCleared: number score: number scoreThisTurn: number isGameOver: boolean isColorblindModeEnabled: boolean isGhostEnabled: boolean isQueuePieceEnabled: boolean canQueuePiece: boolean isAudioMuted: boolean } export interface IOverlayProps { isGameOver: boolean isPaused: boolean hasGameBegun: boolean score: number isAudioMuted: boolean startGame: () => void } export interface ILegendProps { score: number scoreThisTurn: number level: Level } export interface IDisplayPieceProps { pieceType?: PieceType isEnabled: boolean isActive: boolean title: string isColorblindModeEnabled: boolean } export interface IPersistentSettings { isColorblindModeEnabled: boolean isGhostEnabled: boolean isQueuePieceEnabled: boolean isAudioMuted: boolean } export interface IDashboardProps extends IPersistentSettings { onColorblindChange: () => void onGhostChange: () => void onQueueChange: () => void onAudioChange: () => void } export interface ISwitchProps { className?: string labelText?: string isChecked: boolean onChange: () => void } export interface IThemeSongProps { isAudioMuted: boolean isPaused: boolean hasGameBegun: boolean }
a1676dbaab9dc16b0cfe35f216ab84b1a35b1a5a
TypeScript
knuhol/dkdb-fe
/src/hooks/useBooks.ts
2.65625
3
import mapKeys from 'lodash/mapKeys'; import useFetch from './useFetch'; import { GetBooksParams, getBooksUrl } from '../utils/fetchUtils'; import { BooksParams } from '../utils/urlUtils'; export type Tag = { slug: string; name: string; color: 'red' | 'orange' | 'blue' | 'green' | 'yellow' | 'purple'; }; export type Book = { slug: string; title: string; authors: Array<{ firstName: string; lastName: string; }>; yearOfIssue: number; dateOfAddition: string; imageURL: string; tags: Array<Tag>; }; type Books = { total: number; books: Book[]; }; const useBooks = (params: BooksParams, initialValue?: Books): Books | undefined => { const getBooksParams: GetBooksParams = mapKeys(params, (value, key) => { if (key === 'pageSize') { return 'size'; } return key; }); if (getBooksParams.page) { getBooksParams.page -= 1; } return useFetch({ endpoint: getBooksUrl(getBooksParams), initialValue, }); }; export default useBooks;
57ce01c3a02ec86475637e53799fd8d00178de79
TypeScript
svrakata/kegg-parser
/src/brite/human_diseases/get_human_diseases.ts
2.734375
3
import convertJSONToCSV from "../../utilities/convert_json_to_csv" import getBriteCategoryList from "../get_brite_list" import briteHumanDiseasesParser, { IBriteHumanDiseasesEntry } from "./brite_human_diseases_parser" type TOutputType = "csv" | "json" interface IGetHumanDiseasesOptions { outputType: TOutputType } type TGetHumanDiseases = (options?: IGetHumanDiseasesOptions) => Promise<IBriteHumanDiseasesEntry[] | string> const getHumanDiseases: TGetHumanDiseases = async (options = null) => { const outputType = options ? options.outputType : null const briteID = "br:br08402" const cancerogensList = await getBriteCategoryList(briteID) const humanDiseasesEntries = briteHumanDiseasesParser(cancerogensList) if (outputType === "csv") { return convertJSONToCSV( humanDiseasesEntries .sort((a: any, b) => a.name.localeCompare(b.name)), [ "name" ], ) } if (outputType === "json") { return JSON.stringify( humanDiseasesEntries.sort((a: any, b: ) => a.name.localeCompare(b.name)), ) } return humanDiseasesEntries } export default getHumanDiseases
5ff8e59bdb5f0d7ef5132669357a59d64e83cbc1
TypeScript
ciruz/Video-Hub-App
/node/main-extract.ts
2.796875
3
/** * This file contains all the logic for extracting: * first thumbnail, * full filmstrip, * the preview clip * the clip's first thumbnail * * All functions are PURE * * Huge thank you to cal2195 for the code contribution * He implemented the efficient filmstrip and clip extraction! */ // ======================================================================================== // Imports // ======================================================================================== // cool method to disable all console.log statements! // console.log('console.log disabled in main-extract.ts'); // console.log = function() {}; // const { performance } = require('perf_hooks'); // for logging time taken during debug const fs = require('fs'); import * as path from 'path'; const spawn = require('child_process').spawn; const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path.replace('app.asar', 'app.asar.unpacked'); import { GLOBALS } from './main-globals'; import { ImageElement, ScreenshotSettings } from '../interfaces/final-object.interface'; // ======================================================================================== // FFMPEG arg generating functions // ======================================================================================== /** * Generate the ffmpeg args to extract a single frame according to settings * @param pathToVideo * @param screenshotHeight * @param duration * @param savePath */ const extractSingleFrameArgs = ( pathToVideo: string, screenshotHeight: number, duration: number, savePath: string, ): string[] => { const ssWidth: number = screenshotHeight * (16 / 9); const args: string[] = [ '-ss', (duration / 10).toString(), '-i', pathToVideo, '-frames', '1', '-q:v', '2', '-vf', scaleAndPadString(ssWidth, screenshotHeight), savePath, ]; return args; }; /** * Take N screenshots of a particular file * at particular file size * save as particular fileHash * (if filmstrip not already present) * * @param pathToVideo -- full path to the video file * @param duration -- duration of clip * @param screenshotHeight -- height of screenshot in pixels * @param numberOfScreenshots -- number of screenshots to extract * @param savePath -- full path to file name and extension */ const generateScreenshotStripArgs = ( pathToVideo: string, duration: number, screenshotHeight: number, numberOfScreenshots: number, savePath: string, ): string[] => { let current = 0; const totalCount = numberOfScreenshots; const step: number = duration / (totalCount + 1); const args: string[] = []; let allFramesFiltered = ''; let outputFrames = ''; // Hardcode a specific 16:9 ratio const ssWidth: number = screenshotHeight * (16 / 9); const fancyScaleFilter: string = scaleAndPadString(ssWidth, screenshotHeight); // make the magic filter while (current < totalCount) { const time = (current + 1) * step; // +1 so we don't pick the 0th frame args.push('-ss', time.toString(), '-i', pathToVideo); allFramesFiltered += '[' + current + ':V]' + fancyScaleFilter + '[' + current + '];'; outputFrames += '[' + current + ']'; current++; } args.push( '-frames', '1', '-filter_complex', allFramesFiltered + outputFrames + 'hstack=inputs=' + totalCount, savePath ); return args; }; /** * Generate the mp4 preview clip of the video file * (if clip is not already present) * * @param pathToVideo -- full path to the video file * @param duration -- duration of the original video file * @param clipHeight -- height of clip * @param clipSnippets -- number of clip snippets to extract * @param snippetLength -- length in seconds of each snippet * @param savePath -- full path to file name and extension */ const generatePreviewClipArgs = ( pathToVideo: string, duration: number, clipHeight: number, clipSnippets: number, snippetLength: number, savePath: string, ): string[] => { let current = 1; const totalCount = clipSnippets; const step: number = duration / (totalCount + 1); const args: string[] = []; let concat = ''; // make the magic filter while (current <= totalCount) { const time = current * step; const preview_duration = snippetLength; args.push('-ss', time.toString(), '-t', preview_duration.toString(), '-i', pathToVideo); concat += '[' + (current - 1) + ':V]' + '[' + (current - 1) + ':a]'; current++; } concat += 'concat=n=' + totalCount + ':v=1:a=1[v][a];[v]scale=-2:' + clipHeight + '[v2]'; args.push('-filter_complex', concat, '-map', '[v2]', '-map', '[a]', savePath); // phfff glad that's over return args; }; /** * Extract the first frame from the preview clip * * @param pathToClip -- full path to where the .mp4 clip is located * @param fileHash -- full path to where the .jpg should be saved */ const extractFirstFrameArgs = ( pathToClip: string, pathToThumb: string ): string[] => { const args: string[] = [ '-ss', '0', '-i', pathToClip, '-frames', '1', '-f', 'image2', pathToThumb, ]; return args; }; // ======================================================================================== // Extraction engine // ======================================================================================== /** * Extract thumbnail, filmstrip, and possibly clip * * Extract following this order. Each stage returns a boolean * (^) means RESTART -- go back to (1) with the next item-to-extract on the list * * SOURCE FILE ============================ * (1) check if input file exists * T: (2) * F: (^) restart * THUMB ================================== * (2) check thumb exists * T: (4) * F: (3) * (3) extract the SINGLE screenshot * T: (4) * F: (^) restart - assume corrupt * FILMSTRIP ============================== * (4) check filmstrip exists * T: (6) * F: (5) * (5) extract the FILMSTRIP * T: (clipSnippets === 0) ? * T: nothing to do (^) restart * F: (6) * F: (^) restart - assume corrupt * CLIP =================================== * (6) check clip exists * T: (8) * F: (7) * (7) extract the CLIP * T: (8) * F: (^) restart - assume corrupt * CLIP THUMB ============================= * (8) check clip thumb exists * T: (^) restart * F: (9) * (9) extract the CLIP preview * T: (^) restart * F: (^) restart * * @param currentElement -- ImageElement to extract thumbs * @param videoFolderPath -- path to base folder where videos are * @param screenshotFolder -- path to folder where .jpg files will be saved * @param screenshotSettings -- ScreenshotSettings object * @param deepScan -- spend 50% more time trying to extracts screenshots * @param done -- execute this method when done extracting */ export function extractAll( currentElement: ImageElement, videoFolderPath: string, screenshotFolder: string, screenshotSettings: ScreenshotSettings, deepScan: boolean, done ): void { const clipHeight: number = screenshotSettings.clipHeight; // -- number in px how tall each clip should be const clipSnippets: number = screenshotSettings.clipSnippets; // -- number of clip snippets to extract; 0 == do not extract clip const screenshotHeight: number = screenshotSettings.height; // -- number in px how tall each screenshot should be const snippetLength: number = screenshotSettings.clipSnippetLength; // -- length of each snippet in the clip const pathToVideo: string = path.join(videoFolderPath, currentElement.partialPath, currentElement.fileName); const duration: number = currentElement.duration; const fileHash: string = currentElement.hash; const numOfScreens: number = currentElement.screens; const sourceHeight: number = currentElement.height; const thumbnailSavePath: string = screenshotFolder + '/thumbnails/' + fileHash + '.jpg'; const filmstripSavePath: string = screenshotFolder + '/filmstrips/' + fileHash + '.jpg'; const clipSavePath: string = screenshotFolder + '/clips/' + fileHash + '.mp4'; const clipThumbSavePath: string = screenshotFolder + '/clips/' + fileHash + '.jpg'; const maxRunTime: ExtractionDurations = setExtractionDurations( sourceHeight, numOfScreens, screenshotHeight, clipSnippets, snippetLength, clipHeight, deepScan ); checkFileExists(pathToVideo) // (1) .then((videoFileExists: boolean) => { // console.log('01 - video file live = ' + videoFileExists); if (!videoFileExists) { throw new Error('VIDEO FILE NOT PRESENT'); } else { return checkFileExists(thumbnailSavePath); // (2) } }) .then((thumbExists: boolean) => { // console.log('02 - thumbnail already present = ' + thumbExists); if (thumbExists) { return true; } else { const ffmpegArgs: string[] = extractSingleFrameArgs( pathToVideo, screenshotHeight, duration, thumbnailSavePath ); return spawn_ffmpeg_and_run(ffmpegArgs, maxRunTime.thumb, 'thumb'); // (3) } }) .then((thumbSuccess: boolean) => { // console.log('03 - single screenshot now present = ' + thumbSuccess); if (!thumbSuccess) { throw new Error('SINGLE SCREENSHOT EXTRACTION TIMED OUT - LIKELY CORRUPT'); } else { return checkFileExists(filmstripSavePath); // (4) } }) .then((filmstripExists: boolean) => { // console.log('04 - filmstrip already present = ' + filmstripExists); if (filmstripExists) { return true; } else { const ffmpegArgs: string [] = generateScreenshotStripArgs( pathToVideo, duration, screenshotHeight, numOfScreens, filmstripSavePath ); return spawn_ffmpeg_and_run(ffmpegArgs, maxRunTime.filmstrip, 'filmstrip'); // (5) } }) .then((filmstripSuccess: boolean) => { // console.log('05 - filmstrip now present = ' + filmstripSuccess); if (!filmstripSuccess) { throw new Error('FILMSTRIP GENERATION TIMED OUT - LIKELY CORRUPT'); } else if (clipSnippets === 0) { throw new Error('USER DOES NOT WANT CLIPS'); } else { return checkFileExists(clipSavePath); // (6) } }) .then((clipExists: boolean) => { // console.log('04 - preview clip already present = ' + clipExists); if (clipExists) { return true; } else { const ffmpegArgs: string[] = generatePreviewClipArgs( pathToVideo, duration, clipHeight, clipSnippets, snippetLength, clipSavePath ); return spawn_ffmpeg_and_run(ffmpegArgs, maxRunTime.clip, 'clip'); // (7) } }) .then((clipGenerationSuccess: boolean) => { // console.log('07 - preview clip now present = ' + clipGenerationSuccess); if (clipGenerationSuccess) { return checkFileExists(clipThumbSavePath); // (8) } else { throw new Error('ERROR GENERATING CLIP'); } }) .then((clipThumbExists: boolean) => { // console.log('05 - preview clip thumb already present = ' + clipThumbExists); if (clipThumbExists) { return true; } else { const ffmpegArgs: string[] = extractFirstFrameArgs(clipSavePath, clipThumbSavePath); return spawn_ffmpeg_and_run(ffmpegArgs, maxRunTime.clipThumb, 'clip thumb'); // (9) } }) .then((success: boolean) => { // console.log('09 - preview clip thumb now exists = ' + success); if (success) { // console.log('======= ALL STEPS SUCCESSFUL =========='); } done(); }) .catch((err) => { // console.log('===> ERROR - RESTARTING: ' + err); done(); }); } // ======================================================================================== // Helper methods // ======================================================================================== interface ExtractionDurations { thumb: number; filmstrip: number; clip: number; clipThumb: number; } /** * Set the ExtractionDurations - the maximum running time per extraction type * if ffmpeg takes longer, it is taken out the back and shot - killed with no mercy * * These computations are not exact, they are meant meant to give a rough timeout window * to prevent corrupt files from slowing down the extraction too much * * @param sourceHeight - height of the original video * @param numOfScreens * @param screenshotHeight * @param clipSnippets * @param snippetLength * @param clipHeight * @param deepScan -- whether to spend 50% more time extracting screenshots */ function setExtractionDurations( sourceHeight: number, numOfScreens: number, screenshotHeight: number, clipSnippets: number, snippetLength: number, clipHeight: number, deepScan: boolean ): ExtractionDurations { // screenshot heights range from 144px to 504px // we'll call 144 the baseline and increase duration based on this // number of pixels grows ~ as square of height, so we square below // this means at highest resolution we multyply by 9 the time we wait const thumbHeightRatio = screenshotHeight / 144; const thumbHeightFactor = thumbHeightRatio * thumbHeightRatio; // square of ratio // not using Math.pow(n,2) because this is apparently faster https://stackoverflow.com/a/26594370/5017391 const clipHeightRatio = clipHeight / 144; const clipHeightFactor = clipHeightRatio * clipHeightRatio; // square of ratio const sourceFactor = sourceHeight === 0 ? 1 : sourceHeight / 720; // may be better as a square rather than linear const multiplier = deepScan ? 1 : 1.5; return { // for me: thumb: 350 * multiplier * sourceFactor * thumbHeightFactor, // never above 300ms filmstrip: 350 * multiplier * sourceFactor * numOfScreens * thumbHeightFactor, // rarely above 15s, but 4K 30screens took 50s clip: 1000 * multiplier * sourceFactor * clipSnippets * snippetLength * clipHeightFactor, // barely ever above 15s clipThumb: 150 * multiplier * sourceFactor * clipHeightFactor, // never above 100ms }; } /** * Return promise for whether file exists * @param pathToFile string */ function checkFileExists(pathToFile: string): Promise<boolean> { return new Promise((resolve, reject) => { fs.access(pathToFile, fs.constants.F_OK, (err: any) => { return(resolve(!err)); }); }); } /** * Replace original file with new file * use ffmpeg to convert and letterbox to fit width and height * * @param oldFile full path to thumbnail to replace * @param newFile full path to sounce image to use as replacement * @param height */ export function replaceThumbnailWithNewImage( oldFile: string, newFile: string, height: number ): Promise<boolean> { console.log('Resizing new image and replacing old thumbnail'); const width: number = Math.floor(height * (16 / 9)); const args = [ '-y', '-i', newFile, '-vf', scaleAndPadString(width, height), oldFile, ]; return spawn_ffmpeg_and_run(args, 1000, 'replacing thumbnail'); // resizing an image file with ffmpeg should take less than 1 second } /** * Generate the correct `scale=` & `pad=` string for ffmpeg * @param width * @param height */ function scaleAndPadString(width: number, height: number): string { // sweet thanks to StackExchange! // https://superuser.com/questions/547296/resizing-videos-with-ffmpeg-avconv-to-fit-into-static-sized-player return 'scale=w=' + width + ':h=' + height + ':force_original_aspect_ratio=decrease,' + 'pad=' + width + ':' + height + ':(ow-iw)/2:(oh-ih)/2'; } /** * Spawn ffmpeg and run the appropriate arguments * Kill the process after maxRunningTime * @param args args to pass into ffmpeg * @param maxRunningTime maximum time to run ffmpeg * @param description log for console.log */ function spawn_ffmpeg_and_run( args: string[], maxRunningTime: number, description: string ): Promise<boolean> { return new Promise((resolve, reject) => { // Uncomment things in this method to check how long extraction takes // const t0: number = performance.now(); const ffmpeg_process = spawn(ffmpegPath, args); const killProcessTimeout = setTimeout(() => { if (!ffmpeg_process.killed) { ffmpeg_process.kill(); // console.log(description + ' KILLED EARLY'); return resolve(false); } }, maxRunningTime); // Note from past Cal to future Cal: // ALWAYS READ THE DATA, EVEN IF YOU DO NOTHING WITH IT ffmpeg_process.stdout.on('data', data => { if (GLOBALS.debug) { console.log(data); } }); ffmpeg_process.stderr.on('data', data => { if (GLOBALS.debug) { console.log('grep stderr: ' + data); } }); ffmpeg_process.on('exit', () => { clearTimeout(killProcessTimeout); // const t1: number = performance.now(); // console.log(description + ': ' + (t1 - t0).toString()); return resolve(true); }); }); }
d488c0b2d342e8b0c1c0978dce9e40395c2bf48a
TypeScript
MiK546/csv-arrays
/test/generateCsv.test.ts
2.5625
3
import {expect} from "chai"; import {generateCsv} from "../src/generateCsv"; import {HeaderStyle} from "../src/types"; describe("generateCsv", () => { it("should generate csv synchronously", () => { const csvResult = generateCsv([[1, 2], ["a", "b"]]); expect(csvResult).to.equal("1,a\n2,b\n"); }); it("should generate csv with all supported parameters", () => { const headers = [ "Header 1", "Header 2" ]; const csvResult = generateCsv([[1], [2]], { columnSeparator: "\t", rowSeparator: "\r\n", headerStyle: HeaderStyle.CUSTOM, customHeader: headers }); expect(csvResult).to.equal(`${headers.join("\t")}\r\n1\t2\r\n`); }); });
004d65fc197b85104340a93446f12c39679a4031
TypeScript
johanneslumpe/styled-props
/src/utils/text/overflowWrap.ts
2.765625
3
import { OverflowWrapPropertyCombined } from '@johanneslumpe/css-types'; import { style } from '../../style'; import { StyleOptions } from '../../types'; export interface OverflowWrapProps<T> { /** * The `**overflow-wrap**` CSS property applies to inline elements, setting whether the browser should insert line breaks within an otherwise unbreakable string to prevent text from overflowing its line box. * * @see https://developer.mozilla.org/docs/Web/CSS/overflow-wrap */ style$OverflowWrap: T; } export const overflowWrap = < T = OverflowWrapPropertyCombined, Theme = never, Breakpoints = never >({ themeProp, }: Partial<StyleOptions<OverflowWrapProps<T>, Theme>> = {}) => style<OverflowWrapProps<T>, Theme, Breakpoints>({ cssProp: 'overflowWrap', prop: 'style$OverflowWrap', themeProp, });
e0d10828d95414dd7bd2a45156814594169b8e01
TypeScript
cuo9958/wekf-server
/src/model/user.ts
2.515625
3
import { Model, DataTypes } from "sequelize"; import db from "../db/mysql"; class User extends Model {} User.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, nickname: { type: DataTypes.STRING(100), defaultValue: "", comment: "昵称", }, user_name: { type: DataTypes.STRING(100), unique: true, defaultValue: "", comment: "账户", }, pwd: { type: DataTypes.STRING(100), defaultValue: "", comment: "密码", }, headimg: { type: DataTypes.STRING, defaultValue: "", comment: "头像", }, role: { type: DataTypes.STRING(100), defaultValue: "", comment: "权限", }, }, { sequelize: db, freezeTableName: true, tableName: "t_user", indexes: [ { fields: ["user_name"], }, ], } ); //强制初始化数据库 // User.sync({ force: true }); export default { insert: function (model: any) { return User.create(model); }, get: function (id: number) { return User.findOne({ where: { id, }, }); }, del: function (id: number | number[]) { return User.destroy({ where: { id, }, }); }, update(data: any, id) { return User.update(data, { where: { id } }); }, getBypwd(user_name: string, pwd: string) { return User.findOne({ where: { user_name, pwd }, attributes: ["id", "nickname", "user_name", "role", "headimg", "updatedAt"], }); }, check(user_name: string, pwd: string) { return User.count({ where: { user_name, pwd }, }); }, getlist(PageIndex: number, PageSize = 20) { let where = {}; return User.findAndCountAll({ order: [["id", "desc"]], offset: PageIndex * PageSize, limit: PageSize, attributes: ["id", "nickname", "user_name", "role", "headimg", "updatedAt"], where, }); }, };
1634a2b1cdcf9ac8baad05ae6e8444f4bbf390c1
TypeScript
yuhangwang/MirrorAI
/mirror-ai/app/js/MirrorAI.ts
2.734375
3
declare function require(name:string); export function MirrorAI() { let spawn = require('child_process').spawn; let py = spawn('python', ['app/py/proxyMirrorAI.py']); let data = [1,2,3,4,5,6,7,8,9]; let dataString = ''; let d = py.stdout.on('data', function(d) { dataString += d.toString(); return d.toString(); }); py.stderr.on('data', (data) => console.log(`stderr: ${data}`)); py.stdout.on('end', function() { console.log('Sum of numbers=',dataString); }); py.stdin.write(JSON.stringify(data)); py.stdin.end(); return "hello world - " + dataString; }
f3f16e6e2d3d157b95dc3fa5ba472a7067483ee9
TypeScript
edin/VueStarterKit
/client/src/kit/Services/AuthService.ts
2.765625
3
import { ILogger, Logger } from "../Logger/Logger"; import { RestClient } from "../Rest/RestClient"; import { IAuthService, IAuthUser, ILoginResult, IResetPasswordResult, IUpdatePasswordResult, IVerifyAccountResult } from "./AuthServiceTypes"; export class AuthService implements IAuthService { static AuthInfoKey: string = "AuthInfo" private storage: Storage; private logger = Logger.getLogger("AuthService"); constructor(private client: RestClient) { this.storage = window.localStorage; } getCurrentUser(): IAuthUser|null { let result = this.storage.getItem(AuthService.AuthInfoKey); if (result) { try{ const user = JSON.parse(result); let {token, displayName } = user; if (typeof token === "string" && typeof displayName === "string") { return user; } } catch (e) { this.logger.debug("getCurrentUser", e); } } return null; } async logout(): Promise<any> { this.storage.removeItem(AuthService.AuthInfoKey); return null; } async loginWithUsernameAndPassword(username: string, password: string): Promise<ILoginResult> { const result = await this.client.post("auth/login", {username, password}); return result.data as ILoginResult; } async verifyAuthInfo(auth: IAuthUser|null = null): Promise<boolean> { let authInfo = auth; if (authInfo == null) { authInfo = await this.getCurrentUser(); } if (authInfo) { const result = await this.client.post("auth/verify-auth", {token: authInfo.token}); if (result.ok) { return true; } } return false; } async resetPassword(username: string): Promise<IResetPasswordResult> { const result = await this.client.post("auth/reset-password", {username}); return result.data as IResetPasswordResult; } async updatePassword(resetPasswordCode: string, password: string): Promise<IUpdatePasswordResult> { const result = await this.client.post("auth/update-password", { resetPasswordCode, password }); return result.data as IUpdatePasswordResult; } async verifyAccount(verificationCode: string): Promise<IVerifyAccountResult> { const result = await this.client.post("auth/verify-account", {verificationCode}); return result.data as IVerifyAccountResult; } }
139bb1ab7ed0a9a18fabf92ad6e6513d82db7fca
TypeScript
semanticlink/semantic-network
/src/representation/get.ts
2.75
3
import { LinkedRepresentation } from 'semantic-link'; import { NamedRepresentationFactory } from './namedRepresentationFactory'; import { TrackedRepresentationFactory } from './trackedRepresentationFactory'; import { ResourceQueryOptions } from '../interfaces/resourceQueryOptions'; import { ResourceLinkOptions } from '../interfaces/resourceLinkOptions'; import { HttpRequestOptions } from '../interfaces/httpRequestOptions'; import { ResourceMergeOptions } from '../interfaces/resourceAssignOptions'; import { ResourceFactoryOptions } from '../interfaces/resourceFactoryOptions'; import { ResourceFetchOptions } from '../interfaces/resourceFetchOptions'; import { RepresentationUtil } from '../utils/representationUtil'; import anylogger from 'anylogger'; import { ResourceUpdateOptions } from '../interfaces/resourceUpdateOptions'; import { instanceOfCollection } from '../utils/instanceOf/instanceOfCollection'; import { Nullable, Tracked } from '../types/types'; import { LinkRelation } from '../linkRelation'; import { LoaderJobOptions } from '../interfaces/loader'; const log = anylogger('get'); /** * A subset of the {@link ApiOptions} that are appropriate for a HTTP GET. * * @see ApiOptions */ export type ApiGetOptions = ResourceFactoryOptions & ResourceQueryOptions & ResourceLinkOptions & HttpRequestOptions & ResourceMergeOptions & ResourceFetchOptions & ResourceUpdateOptions & LoaderJobOptions; /** * Retrieve a resource based on its context and options, and its current state (ie hydrated or not) * * Note: a returned resource will not always be the same (ie self) but rather a different linked resource. * * TODO: where 'named' resources are known, return that type based on the 'rel' in options. */ export async function get<TReturn extends LinkedRepresentation, T extends LinkedRepresentation | TReturn = LinkedRepresentation, TResult extends TReturn = T extends TReturn ? T : TReturn>( resource: T | Tracked<T>, options?: ApiGetOptions): Promise<Nullable<TResult | Tracked<TResult>>> { const { rel = undefined, where = undefined, } = { ...options }; const relIsNotSelfOrEmpty = rel && rel !== LinkRelation.Self; // look at the context resource and ensure that it is first hydrated before loading sub resources if (relIsNotSelfOrEmpty) { log.debug('get context resource on \'self\''); resource = await TrackedRepresentationFactory.load(resource, { ...options, rel: LinkRelation.Self }); } // find specific item in collection if (where) { log.debug('using \'where\' to locate resource on get'); // when combined with rel, the sub resource should be the collection if (relIsNotSelfOrEmpty) { const namedSubResource = await NamedRepresentationFactory.load(resource, options); if (namedSubResource) { log.debug('named sub resource found on \'%s\'', rel); resource = namedSubResource as Tracked<T>; // now that sub resource is loaded, re-contextualise to this resource (ie will become 'self') delete options?.rel; } else { log.warn('named sub resource not found on \'%s\'', rel); } } if (instanceOfCollection(resource)) { log.debug('get collection resource (with items: %s)', options?.includeItems || false); // synchronise collection by applying all current rules (eg includeItems) const collection = await TrackedRepresentationFactory.load(resource, options); // then check for existence const item = RepresentationUtil.findInCollection(collection, options); if (item) { log.debug('item in collection found'); return await TrackedRepresentationFactory.load(item, options) as Tracked<TResult>; } else { log.debug('item in collection not found '); return undefined; } } else { log.warn('Where options cannot be used outside of a collection, skipping where'); // fall through to return context resource } } // named resources // do not add 'self' as sub resource if (relIsNotSelfOrEmpty) { log.debug('get named singleton sub resource'); return await NamedRepresentationFactory.load(resource, options); } // otherwise all resources log.debug('get resource'); return await TrackedRepresentationFactory.load(resource, options) as unknown as TResult; }
8cd1f2068a1182de503e2d72ae4d365c1ac0f6ff
TypeScript
PlayGuitar-CoderQ-Sub/design-patterns-test
/OOP/index.ts
3.375
3
interface CatProps { name: string; sex: number; age: number; weight: number; color: string; } class Cat implements CatProps { name = 'kaka'; sex = 0; age = 0; weight = 0; color = 'red'; } let res = new Cat(); console.log(res.age);
ca35ed7258a5257dea5bebd598d6e42bce8262b6
TypeScript
gksander/CIE-ColorConverter
/src/Luv.ts
2.65625
3
import { NumericTriple } from "./Matrix"; import { DEFAULT_OPTIONS, kE, kK } from "./consts"; import { ConverterOptions } from "./types"; import { getRefWhiteMtx } from "./getRefWhiteMtx"; import { XYZToLab, XYZToRGB, XYZToxyY } from "./XYZ"; import { LabToLCHab } from "./Lab"; export const LuvToLCHuv = (Luv: NumericTriple): NumericTriple => { const [L, u, v] = Luv; const H = (180 / Math.PI) * Math.atan2(v, u); return [ L, Math.sqrt(Math.pow(u, 2) + Math.pow(v, 2)), H + (H >= 0 ? 0 : 360), ]; }; export const LuvToXYZ = ( Luv: NumericTriple, { refWhite = DEFAULT_OPTIONS.REF_WHITE }: Pick<ConverterOptions, "refWhite"> = {}, ): NumericTriple => { const [L, u, v] = Luv; const Y = L > kK * kE ? Math.pow((L + 16) / 116, 3) : L / kK; const RefWhite = getRefWhiteMtx(refWhite), X_r = RefWhite[0], Y_r = RefWhite[1], Z_r = RefWhite[2], Den = X_r + 15 * Y_r + 3 * Z_r, v_0 = (9 * Y_r) / Den, u_0 = (4 * X_r) / Den, d = Y * ((39 * L) / (v + 13 * L * v_0) - 5), c = -1 / 3, b = -5 * Y, a = (1 / 3) * ((52 * L) / (u + 13 * L * u_0) - 1), X = (d - b) / (a - c), Z = X * a + b; return [X, Y, Z]; }; export const LuvToxyY = ( Luv: NumericTriple, { refWhite = DEFAULT_OPTIONS.REF_WHITE }: Pick<ConverterOptions, "refWhite"> = {}, ): NumericTriple => { return XYZToxyY(LuvToXYZ(Luv, { refWhite }), { refWhite }); }; export const LuvToLab = ( Luv: NumericTriple, { refWhite = DEFAULT_OPTIONS.REF_WHITE }: Pick<ConverterOptions, "refWhite"> = {}, ): NumericTriple => { return XYZToLab(LuvToXYZ(Luv, { refWhite }), { refWhite }); }; export const LuvToLCHab = ( Luv: NumericTriple, { refWhite = DEFAULT_OPTIONS.REF_WHITE }: Pick<ConverterOptions, "refWhite"> = {}, ): NumericTriple => { return LabToLCHab(LuvToLab(Luv, { refWhite })); }; export const LuvToRGB = ( Luv: NumericTriple, { adaptation = DEFAULT_OPTIONS.ADAPTION, refWhite = DEFAULT_OPTIONS.REF_WHITE, rgbModel = DEFAULT_OPTIONS.RGB_MODEL, gammaModel = DEFAULT_OPTIONS.GAMMA_MODEL, }: ConverterOptions = {}, ): NumericTriple => { return XYZToRGB(LuvToXYZ(Luv, { refWhite }), { adaptation, refWhite, rgbModel, gammaModel, }); };
ff735e90779b0c18dd57b613955f32a3614414d3
TypeScript
luminuszz/nlw-3-happy-backend
/src/modules/users/infra/typeorm/entities/user.entity.ts
2.5625
3
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, } from 'typeorm' @Entity('users') export class User { @PrimaryGeneratedColumn({ type: 'uuid' }) id: string @Column({ type: 'varchar', nullable: false }) name: string @Column({ type: 'varchar', nullable: false }) email: string @Column({ type: 'varchar', nullable: false }) password: string @Column({ name: 'phone_number' }) phoneNumber?: string @CreateDateColumn({ name: 'created_at' }) createdAt: Date @CreateDateColumn({ name: 'updated_at' }) updateAt: Date }
979943246f47e3eaf4906018d1522b8c3d6e3bd7
TypeScript
klasa-forks/core
/src/lib/caching/structures/messages/MessageAttachment.ts
2.703125
3
import type { APIMessageAttachmentData } from '@klasa/dapi-types'; /* eslint-disable camelcase */ /** * @see https://discord.com/developers/docs/resources/channel#attachment-object */ export class MessageAttachment implements APIMessageAttachmentData { /** * Attachment id. * @since 0.0.1 */ public readonly id: string; /** * Name of file attached. * @since 0.0.1 */ public filename: string; /** * Size of file in bytes. * @since 0.0.1 */ public size: number; /** * Source url of file. * @since 0.0.1 */ public url: string; /** * A proxied url of file. * @since 0.0.1 */ public proxy_url: string; /** * Height of file (if image). * @since 0.0.1 */ public height: number | null; /** * Width of file (if image). * @since 0.0.1 */ public width: number | null; public constructor(attachment: APIMessageAttachmentData) { this.id = attachment.id; this.filename = attachment.filename; this.size = attachment.size; this.url = attachment.url; // eslint-disable-next-line camelcase this.proxy_url = attachment.proxy_url; this.height = attachment.height || null; this.width = attachment.width || null; } } /* eslint-enable camelcase */
3c7a24251949bb37d55f37e573c7b356f21716a3
TypeScript
HaskellJacobCurry/haskell-ts
/dist/DataStructure/Clojure/LazySequence.d.ts
2.765625
3
import { Kind1, URI1 } from '../../Common/HKT'; import { Populatable1 } from '../../Typeclass/Data/Populatable'; import { Bool } from '../../Instance/Data/Bool'; import { Int } from '../../Instance/Data/Int'; import { Unit } from '../Data/Unit'; interface LazySequence<T> { value: T; done: Bool; next: () => LazySequence<T>; } export { LazySequence }; declare const URI: "LazySequence"; declare type URI = typeof URI; declare module '../../Common/HKT' { interface KindsByURI1<A> { [URI]: LazySequence<A>; } } export { URI }; declare let createLazySequence: <T>(transform: (_: T) => T) => (seed: T) => LazySequence<T>; export { createLazySequence as create }; declare let empty: <A = never>() => LazySequence<A>; export { empty }; declare let singleton: <A>(_: A) => LazySequence<A>; export { singleton }; declare let map: <A, B>(f: (_: A) => B) => (_: LazySequence<A>) => LazySequence<B>; export { map }; declare let filter: <A>(f: (_: A) => Bool) => (_: LazySequence<A>) => LazySequence<A>; export { filter }; declare let until: <A>(f: (_: A) => Bool) => (_: LazySequence<A>) => LazySequence<A>; export { until }; declare let foldl: <A, B>(f: (_: B) => (_: A) => B) => (_: B) => (_: LazySequence<A>) => B; export { foldl }; declare let evaluate: <A>(f: (_: A) => Unit) => (_: LazySequence<A>) => Unit; export { evaluate }; declare let concat_: <A>(tail: LazySequence<A>) => (front: LazySequence<A>) => LazySequence<A>; export { concat_ }; declare let concat: <A>(lazys: LazySequence<LazySequence<A>>) => LazySequence<A>; export { concat }; declare let concatMap: <A, B>(f: (_: A) => LazySequence<B>) => (_: LazySequence<A>) => LazySequence<B>; export { concatMap }; declare let toPopulatable1: <F extends URI1>(_: Populatable1<F>) => <A>(_: LazySequence<A>) => Kind1<F, A>; export { toPopulatable1 }; declare let toPopulatable: typeof toPopulatable1; export { toPopulatable }; declare let range: (min: Int, max: Int) => <F extends URI1>(_: Populatable1<F>) => Kind1<F, Int>; export { range }; declare type Constructor = typeof createLazySequence; export { Constructor }; interface HLazySequence { URI: URI; create: <T>(transform: (_: T) => T) => (seed: T) => LazySequence<T>; empty: <A = never>() => LazySequence<A>; singleton: <A>(_: A) => LazySequence<A>; map: <A, B>(f: (_: A) => B) => (_: LazySequence<A>) => LazySequence<B>; filter: <A>(f: (_: A) => Bool) => (_: LazySequence<A>) => LazySequence<A>; until: <A>(f: (_: A) => Bool) => (_: LazySequence<A>) => LazySequence<A>; take: (_: Int) => <A>(_: LazySequence<A>) => LazySequence<A>; foldl: <A, B>(f: (_: B) => (_: A) => B) => (_: B) => (_: LazySequence<A>) => B; evaluate: <A>(f: (_: A) => Unit) => (_: LazySequence<A>) => Unit; concat_: <A>(tail: LazySequence<A>) => (front: LazySequence<A>) => LazySequence<A>; concat: <A>(lazys: LazySequence<LazySequence<A>>) => LazySequence<A>; concatMap: <A, B>(f: (_: A) => LazySequence<B>) => (_: LazySequence<A>) => LazySequence<B>; toPopulatable1: <F extends URI1>(_: Populatable1<F>) => <A>(_: LazySequence<A>) => Kind1<F, A>; toPopulatable: this['toPopulatable1']; range: (min: Int, max: Int) => <F extends URI1>(_: Populatable1<F>) => Kind1<F, Int>; } export { HLazySequence }; declare let LazySequence: Constructor & HLazySequence; export default LazySequence;
1688548750766be5d2877380ed887d449e2c6e62
TypeScript
Erudition/elm-native
/src/dom/basicdom/ViewNode.ts
3.140625
3
import DocumentNode from './DocumentNode'; import { logger as log } from './Logger'; import TextNode from './TextNode'; const dashRegExp = /-/g export function normalizeElementName(elementName: string) { return `${elementName .replace(dashRegExp, '') .toLowerCase()}` } export function* elementIterator(el: ViewNode): Iterable<ViewNode> { yield el; for (let child of el.childNodes) { yield* elementIterator(child) } } export default class ViewNode { nodeType: number; _tagName: string; parentNode: ViewNode; childNodes: ViewNode[]; prevSibling: ViewNode; nextSibling: ViewNode; _ownerDocument: DocumentNode; _attributes: { [index: string]: any }; constructor() { this.nodeType = null this._tagName = null this.parentNode = null this.childNodes = [] this.prevSibling = null this.nextSibling = null this._ownerDocument = null this._attributes = {}; } hasAttribute(name: string) { return Object.keys(this._attributes).indexOf(name) > -1; } removeAttribute(name: string) { delete this._attributes[name]; } /* istanbul ignore next */ toString() { return `${this.constructor.name}(${this.tagName})` } set tagName(name) { this._tagName = normalizeElementName(name) } get tagName() { return this._tagName } get firstChild() { return this.childNodes.length ? this.childNodes[0] : null } get lastChild() { return this.childNodes.length ? this.childNodes[this.childNodes.length - 1] : null } /* istanbul ignore next */ get ownerDocument(): DocumentNode { if (this._ownerDocument) { return this._ownerDocument } let el: ViewNode = this while (el != null && el.nodeType !== 9) { el = el.parentNode } return (this._ownerDocument = el as DocumentNode) } getAttribute(key: string): any { return this._attributes[key] } /* istanbul ignore next */ setAttribute(key: string, value: any) { this._attributes[key] = value; } /* istanbul ignore next */ setText(text: string) { log.debug(() => `setText ${this} ${text}`) this.setAttribute('text', text) } updateText() { this.setText(this.childNodes.filter(x => x.nodeType === 3).map(x => (x as TextNode).text).join('')); } onInsertedChild(childNode: ViewNode, index: number) { } onRemovedChild(childNode: ViewNode) { } insertBefore(childNode: ViewNode, referenceNode: ViewNode) { log.debug(() => `insert before ${this} ${childNode} ${referenceNode}`) if (!childNode) { throw new Error(`Can't insert child.`) } // in some rare cases insertBefore is called with a null referenceNode // this makes sure that it get's appended as the last child if (!referenceNode) { return this.appendChild(childNode) } if (referenceNode.parentNode !== this) { throw new Error( `Can't insert child, because the reference node has a different parent.` ) } if (childNode.parentNode && childNode.parentNode !== this) { throw new Error( `Can't insert child, because it already has a different parent.` ) } if (childNode.parentNode === this) { // we don't need to throw an error here, because it is a valid case // for example when switching the order of elements in the tree // fixes #127 - see for more details // fixes #240 // throw new Error(`Can't insert child, because it is already a child.`) } let index = this.childNodes.indexOf(referenceNode) childNode.parentNode = this childNode.nextSibling = referenceNode childNode.prevSibling = this.childNodes[index - 1] referenceNode.prevSibling = childNode this.childNodes.splice(index, 0, childNode) this.onInsertedChild(childNode, index); } appendChild(childNode: ViewNode) { log.debug(() => `append child ${this} ${childNode}`) if (!childNode) { throw new Error(`Can't append child.`) } if (childNode.parentNode && childNode.parentNode !== this) { throw new Error( `Can't append child, because it already has a different parent.` ) } if (childNode.parentNode === this) { // we don't need to throw an error here, because it is a valid case // for example when switching the order of elements in the tree // fixes #127 - see for more details // fixes #240 // throw new Error(`Can't append child, because it is already a child.`) } childNode.parentNode = this if (this.lastChild) { childNode.prevSibling = this.lastChild this.lastChild.nextSibling = childNode } this.childNodes.push(childNode) this.onInsertedChild(childNode, this.childNodes.length - 1) } removeChild(childNode: ViewNode) { log.debug(() => `remove child ${this} ${childNode}`) if (!childNode) { throw new Error(`Can't remove child.`) } if (!childNode.parentNode) { throw new Error(`Can't remove child, because it has no parent.`) } if (childNode.parentNode !== this) { throw new Error(`Can't remove child, because it has a different parent.`) } childNode.parentNode = null if (childNode.prevSibling) { childNode.prevSibling.nextSibling = childNode.nextSibling } if (childNode.nextSibling) { childNode.nextSibling.prevSibling = childNode.prevSibling } // reset the prevSibling and nextSibling. If not, a keep-alived component will // still have a filled nextSibling attribute so vue will not // insert the node again to the parent. See #220 childNode.prevSibling = null childNode.nextSibling = null this.childNodes = this.childNodes.filter(node => node !== childNode) this.onRemovedChild(childNode); } firstElement() { for (var child of this.childNodes) { if (child.nodeType == 1) { return child; } } return null; } }
c71a274881e4642361d9d0381a99d0f3fd6f3e3d
TypeScript
VanemalP/recipe-nutrition-modelling-api
/src/data/entities/measure.entity.ts
2.703125
3
import { Entity, Column, OneToMany, PrimaryGeneratedColumn, ManyToOne } from 'typeorm'; import { Product } from './product.entity'; /** * Measure entity */ @Entity('measures') export class Measure { /** * Id of the measure */ @PrimaryGeneratedColumn('uuid') id: string; /** * Product that have this measure */ @ManyToOne(type => Product, product => product.measures) product: Promise<Product>; /** * Measure type */ @Column() measure: string; /** * Amount for the measure */ @Column() amount: number; /** * Grams per measure */ @Column() gramsPerMeasure: number; }
75040f2e3cd3fd58f1b67a8c717e6608fc0446e4
TypeScript
Azein/frontend_sim
/src/domains/tasks/logic/distribute-keys.ts
2.53125
3
import { reduce, drop, head, values, } from 'ramda' import { generateTask } from './generate-task' type KeysAndTasks = { usedKeys: string[] unusedKeys: string[] currentTasks: FormedTaskPool } type DistributeKeys = ( selectedTasks: TaskPool, keysPool: string[], ) => KeysAndTasks export const distributeKeys: DistributeKeys = (selectedTasks, keysPool) => reduce( // @ts-ignore (acc, value) => ({ currentTasks: { ...acc.currentTasks, [acc.unusedKeys[0]]: generateTask({ key: acc.unusedKeys[0], taskName: value.taskName, id: value.taskId, }), }, usedKeys: [...acc.usedKeys, head(acc.unusedKeys)], unusedKeys: drop(1, acc.unusedKeys), }), { currentTasks: {}, usedKeys: [], unusedKeys: [...keysPool], }, values(selectedTasks), )
f23393964988263c4d598d0f3edf70c831943913
TypeScript
vfcosta/angular-theme
/src/app/shared/services/events-hub.service.spec.ts
2.703125
3
import { EventsHubService } from './events-hub.service'; describe("EventsHubService", () => { let eventsHubService: EventsHubService; it("emits events for the known events", (done) => { const eventListener = () => { }; // creates the events hub service which known the event "Event1" eventsHubService = new EventsHubService(); // subscribe to the event passing the done Function as the eventListener // if the event emits works the done function is called and the // test will pass eventsHubService.subscribeToEvent<any>(eventsHubService.knownEvents.BLOCK_CHANGED, done); // emits the event eventsHubService.emitEvent(eventsHubService.knownEvents.BLOCK_CHANGED, null); }); it("throws error when trying to emit an unknow event", () => { const eventListener = () => { }; // creates the events hub service which known the event "Event1" eventsHubService = new EventsHubService(); // emits the event expect( () => { eventsHubService.emitEvent('NotKnownEvent', null); } ).toThrowError('Unknown event named NotKnownEvent'); }); it("throws error when trying to subscribe to an unknow event", () => { const eventListener = () => { }; // creates the events hub service which known the event "Event1" eventsHubService = new EventsHubService(); // emits the event expect( () => { eventsHubService.subscribeToEvent<void>('NotKnownEvent', () => {}); } ).toThrowError('Unknown event named NotKnownEvent'); }); });
3c931beea31906f5dd60632ffa87473460208c96
TypeScript
MikeWarren2014/OpenSourceRoadsSite
/src/app/services/fake-sender.service.ts
2.734375
3
import { SenderService } from "./sender.service"; import { Injectable } from "@angular/core"; import { Observable, of } from "rxjs"; import { delay } from 'rxjs/operators'; import { EmailMessage } from "../models/email-message/email-message"; @Injectable() export class FakeSenderService implements SenderService{ send(message : EmailMessage) : Observable<any> { // wait a random amount of time between .5 seconds and 5 seconds const delayTime = 500 + (Math.random() * 1000 * 4.5); // message better have a sender,subject,recipient if ((!EmailMessage.isValidEmail(message.sender.email)) || (!EmailMessage.isValidEmail(message.recipient.email)) || (!message.subject) || (!message.message)) { console.log(message.sender.email) console.log(message.recipient.email) console.log(message.subject) console.log(message.message) console.log("Sender valid? ", EmailMessage.isValidEmail(message.sender.email)) console.log("Recipient valid? ", EmailMessage.isValidEmail(message.recipient.email)) console.log(JSON.stringify(message, null, '\t')) return of(false).pipe(delay(delayTime)); } console.log("sending success message...") return of({ status: "ok", code: 200, message: "Your message has been sent! Expect a response in a week. " }).pipe(delay(delayTime)); } }
acdcbb92d8c8d1c23ca214988c17a0273e48281c
TypeScript
ngcarmelo/ProjectsPortfolio
/project-portfolio/src/app/components/login/login.component.ts
2.609375
3
import { Component, OnInit } from '@angular/core'; //to be able to access the parameters that we receive from this url and redirects: import { Router, ActivatedRoute, Params } from '@angular/router'; //Import of the user model: (Import of the user class) import { User } from '../../models/user'; //import the service, where are the methods import { UserService } from '../../services/user.service'; @Component({ selector: 'login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'], providers: [UserService] //We declare the service }) export class LoginComponent implements OnInit { public title:string; public user:User; //we have changed to 'any' to avoid user error public status: string; public identity; // will have the user's object identified public token; // will have the identification token constructor( private _route: ActivatedRoute, private _router: Router, private _userService: UserService //Variable of the UserService service ) { this.title ='Sign in'; this.user = new User("", "","","","","","ROLE_USER",""); // it is not necessary to indicate the role, the backend will be in charge } ngOnInit() { console.log('Componente de login cargado'); } onSubmit(){ //****We make 2 requests http, one to obtain the user and another to obtain the token // console.log(this.user); // alert(this.user.password); // alert(this.user.email); //Login the user and get their data this._userService.signup(this.user).subscribe( response =>{ this.identity = response.user; //will contain the logged-in user // console.log(this.identity); //user in the consola if(!this.identity || !this.identity._id){ this.status = 'error'; }else { //this.status ='success'; //Persist user data, localstorage //it is necessary to save it in the form of a string: localStorage.setItem('identity', JSON.stringify(this.identity)); //get token this.getToken(); } }, error =>{ var errorMessage = <any> error; console.log(errorMessage); if(errorMessage != null){ this.status = 'error'; } }); } getToken(){ //Login the user and get their data this._userService.signup(this.user, 'true').subscribe( response =>{ this.token = response.token; //will contain the logged-in user console.log(this.token); //token if(this.token.length <= 0){ this.status = 'error'; }else { //Persist Token, localstorage localStorage.setItem('token', this.token); this.status = 'success'; this._router.navigate(['/']); } }, error =>{ var errorMessage = <any> error; console.log(errorMessage); if(errorMessage != null){ this.status = 'error'; } }); } }
bb5627b17c0b845aced8885ae551b78f41dae693
TypeScript
whh8162880/Melon3D_ES5
/src/game/unit/actions/FollowAction.ts
2.5625
3
module rf{ export class FollowAction extends ActorAction{ static posDic:{[key:number]:number} = {}; static keyDic:{[key:number]:number} = {} constructor(){ super() this.stateID = StateDefine.FOLLOW } target:ActionActor; distance:number = 300; min_dis:number = 200 max_dis:number = 1200; check(actor:ActionActor,state:StateModel){ if(!this.target){ return false; } return super.check(actor, state) } doStart(actor:ActionActor, params?:any){ actor.on(EventT.NAVIGATION_LOC_COMPLETE, this.turnface, this) // this.follow(); time500.add(this.follow,this); } turnface(){ let{actor, target} = this; let{_x, _y} = target; if(!actor.state.isRunning(StateDefine.MOVE)){ actor.faceto(_x, _y) } } follow(){ let monster = this.actor as Monster; if(monster.state.isRunning(StateDefine.HIT) ){ return; } let{target, distance, min_dis, max_dis} = this let{_x:tx, _y:ty} = target; let{_x, _y} = monster; let dx = tx - _x; ty *= SY _y *= SY; let dy = (ty - _y); let len = Math.sqrt(dx*dx + dy*dy) if(len > max_dis){ this.actor.state.stopState(StateDefine.MOVE,this.stateID) let{_x, _y} = this.actor; // this.turnface() this.updateposDic(this.actor.guid, _x, _y) } else if(len > distance){ let dir = Math.atan2(dy ,dx); dir = dir * RADIANS_TO_DEGREES; TEMP_VECTOR3D.x = dx; TEMP_VECTOR3D.y = dy; TEMP_VECTOR3D.z = 0; TEMP_VECTOR3D.w = 0 TEMP_VECTOR3D.v3_normalize() TEMP_VECTOR3D.v3_scale(min_dis) dx = tx - TEMP_VECTOR3D.x; dy = ty - TEMP_VECTOR3D.y; let[mx, my] = this.findPointCanStand(TEMP_VECTOR3D,dx, dy, tx, ty ); mx *= 60; my *= 60; my /= SY; mx = Math.floor(mx); my = Math.floor(my); this.actor.walkPixTo(mx, my); this.updateposDic(this.actor.guid, mx, my) }else{ let{_x, _y} = this.actor; this.turnface() this.updateposDic(this.actor.guid, _x, _y) } // callLater.later(this.follow, this, 200) } findPointCanStand(dir:IVector3D, mx:number, my:number, dx:number,dy:number):number[]{ var n:number = 1; var m:number = 0; mx /= 60; my /= 60; let key = Math.round(mx) *10000 + Math.round(my); let{actor} = this; let {keyDic, posDic} = FollowAction; while(posDic[key] && posDic[key] !=actor.guid){ TEMP_MATRIX2D.m2_identity() let angle = 70/dir.v3_length TEMP_MATRIX2D.m2_rotate(angle*n); var tmp2:IVector3D = TEMP_MATRIX2D.m2_transformVector(dir); mx = (dx - tmp2.x)/60; my = (dy - tmp2.y)/60; key = Math.round(mx) *10000 + Math.round(my); n*=-1; if(n > 0){ n += 1; } if(Math.abs(n)*angle >= Math.PI/2 || Math.abs(n) > 5){ let curlen = dir.v3_length; dir.v3_normalize(); dir.v3_scale(curlen+30); n = 1; m++; } if(m > 10){ break; } } return [mx, my]; } updateposDic(guid:number, x:number, y:number):void{ let {keyDic, posDic} = FollowAction; let key:number = keyDic[guid]; if(key){ delete posDic[key] } key = Math.round((x/60)) *10000 + Math.round(y*SY/60); posDic[key] = guid; keyDic[guid] = key; } stop(activeID:number){ time500.remove(this.follow,this); } } }
ec1493fbecafb8f04106d898f0316287da661043
TypeScript
gerrysaporito/1337c0d3
/Leet 0102 - Binary Tree Level Order Traversal.ts
4.03125
4
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ /* * Iteration - Breadth First Search */ function levelOrder(root: TreeNode | null): number[][] { const queue = [root]; const res = []; while (queue.length) { const levelSize = queue.length; const levelVals = []; for (let i = 0; i < levelSize; ++i) { const node = queue.shift(); if (node) { levelVals.push(node.val); queue.push(node.left, node.right); } } if (levelVals.length > 0) res.push(levelVals); } return res; }; /* * Time & Space Complexities */ // n = number of nodes in tree // Iteration - Breadth First Search: // Time: O(n) // Space: O(n)
3110c9912100d820071050f92f7b706cb5993ba9
TypeScript
djr-taureau/investment-portfolio-demo
/src/app/core/domain/enum/date-part-type.enum.ts
2.578125
3
export interface DatePartType { name: string; id: string; } export class DatePartTypeEnum { static readonly MON = { name: "MON", id: "M" } as DatePartType; static readonly QTR = { name: "QTR", id: "Q" } as DatePartType; static readonly YEAR = { name: "YEAR", id: "Y" } as DatePartType; }
52a9d13c0be4f04153d7715f32aaa0d815664fa7
TypeScript
bitsy-ui/bitsy-framework
/packages/bitsy-ui-state/src/useWindowCallback.ts
2.96875
3
import EventEmitter from 'eventemitter3'; import { useState, useEffect, useCallback } from 'react'; type UseWindowCallback = <S>(defaultCallback: (...args: any[]) => any, deps: any[], path: string) => any; const useWindowCallback: UseWindowCallback = (defaultCallback, deps, path) => { // Create the usecallback callback const callback = useCallback(defaultCallback, deps); // Set up the initial state const [cb, setCb] = useState(() => window[`__${path}_CALLBACK__`] ? window[`__${path}_CALLBACK__`].current : callback, ); // Callback to handle the update of the state const handleStateChange = (_cb) => { // Ensure that the new state isn't just the same we have previously stored if (_cb === cb) return undefined; // Update the local state setCb(() => _cb); }; // On initiate we want to either create a new emitter or listen to the current one useEffect(() => { // If no window state has yet been set up if (!window[`__${path}_CALLBACK__`]) { // Set up the window emitter window[`__${path}_CALLBACK__`] = { current: callback, emitter: new EventEmitter(), }; } // Add a listener to the created emitter // We want to listen for any changes // These could come from the outside or from within window[`__${path}_CALLBACK__`].emitter.addListener('change', handleStateChange); // Clean up and remove subscription return () => { window[`__${path}_CALLBACK__`].emitter.removeListener('change', handleStateChange); }; }, []); // What happens if I change? useEffect(() => { // Ensure we are not just trying to redispatch the same thing if (window[`__${path}_CALLBACK__`].current === callback) return undefined; // Update the current state window[`__${path}_CALLBACK__`].current = callback; // Emit the change window[`__${path}_CALLBACK__`].emitter.emit('change', callback); }, [callback]); // What happens if someone else changes? return cb; }; export default useWindowCallback;
f11b8d39b511bfd1a596bbadd22fb54a3ce54606
TypeScript
ventful/Customer-Support-Software-with-Ticketing-System
/Mobile App Code/src/app/shared/models/Setting.ts
2.609375
3
export class Setting { id: number; name: string; value: string; private: boolean; created_at?: string; updated_at?: string; constructor(params: Object = {}) { for (let name in params) { this[name] = params[name]; } } }
39f83fea06107d10bacf57fe07f58239734c46cb
TypeScript
marmelab/react-admin
/packages/ra-core/src/util/getValue.spec.ts
2.515625
3
import getValue from './getValue'; import expect from 'expect'; describe('getValue', () => { it('returns directly the value if it is not an object', () => { expect(getValue(10, 'foo.bar')).toEqual(10); }); it('returns the value at specified path if it is an object', () => { expect(getValue({ foo: { bar: 10 } }, 'foo.bar')).toEqual(10); }); });
894d02c7ceb654786c2527311a3c210faefe0891
TypeScript
CDSeattleMEAN201710/jack_brounstein
/angular/angular-demo/src/app/cars/filter.pipe.ts
2.703125
3
import { Pipe, PipeTransform } from '@angular/core'; import { Car } from "./car" @Pipe({ name: 'filter' }) export class FilterPipe implements PipeTransform { transform(cars: Array<Car>, search_text: string): Array<Car> { if(!search_text){ return cars } search_text = search_text.toLowerCase() return cars.filter(car => car.make.toLowerCase().includes(search_text) || car.model.toLowerCase().includes(search_text)) } }
2a3a1276104d543551a4708754a7f231934543b7
TypeScript
hraniere/nlw-01
/server/src/controllers/FacilitiesController.ts
2.734375
3
import { Request, Response, response } from 'express' import knex from '../database/connection' class FacilitiesController { async create(req: Request, res: Response) { const { name, email, whatsapp, latitude, longitude, city, uf, categories, } = req.body const facility = { image: req.file.filename, name, email, whatsapp, latitude, longitude, city, uf } const trx = await knex.transaction(); try { const insertedIds = await trx('facilities').insert(facility) const facility_id = insertedIds[0] const facilityCategories = categories .split(',') .map((category: string) => Number(category.trim())) .map((category_id: number) => ({ facility_id, category_id })) await trx('facility_categories').insert(facilityCategories) await trx.commit() return res.json({ id: facility_id, ...facility }) } catch { trx.rollback() return res.status(400).json({ message: 'Could not create Facility' }) } } async show(req: Request, res: Response) { const { id } = req.params const facility = await knex('Facilities').where('id', id).first() if (!facility) { return res.status(404).json({ message: 'Facility not found' }) } facility.categories = await knex('categories') .join('facility_categories', 'categories.id', '=', 'facility_categories.category_id') .where('facility_categories.facility_id', id).select('categories.title') const serializedFacility = { ...facility, image_url: `http://localhost:3333/uploads/${facility.image}` } res.json(serializedFacility) } async index(req: Request, res: Response) { const { city, uf, categories } = req.query const parsedCategories = String(categories).split(',').map(item => Number(item.trim())) const facilities = await knex('facilities') .join('facility_categories', 'facilities.id', '=', 'facility_categories.facility_id') .whereIn('facility_categories.category_id', parsedCategories) .where('city', String(city)) .where('uf', String(uf)) .distinct() .select('facilities.*') const serializedFacilities = facilities.map(facility => { return { ...facility, image_url: `http://localhost:3333/uploads/${facility.image}` } }) return res.json(serializedFacilities) } } export default FacilitiesController
c93b725904214417cc230c43269bfebac7772d14
TypeScript
no-chris/chord-symbol
/packages/chord-symbol/types/index.d.ts
3.109375
3
export { Chord, ChordInput, ChordParseFailure, CustomFilter, FormattedChord, MaybeChord, NormalizedChord, ParserConfiguration, RendererConfiguration, chordParserFactory, chordRendererFactory, }; /** * An object that may be a chord data object or a chord parsing failure object. */ type MaybeChord = Chord | ChordParseFailure; /** * A data object representing a chord. It is the result of a successful parsing operation and can be used for rendering. */ type Chord = { /** * - information derived from the symbol given as an input. * If you need to trace what has generated a given chord, you'll find it here. */ input: ChordInput; /** * - abstract representation of the chord based on its intervals. */ normalized: NormalizedChord; /** * - pre-rendering of the normalized chord. */ formatted: FormattedChord; /** /** * - chord in the roman numeral notation. */ numeral: NumeralChord; /** * - configuration passed to the parser on chord creation. */ parserConfiguration: ParserConfiguration; }; /** * An error object for a chord that could not be parsed. */ type ChordParseFailure = { /** * - the reason(s) why the parsing failed. */ error: ChordSymbolError[]; }; /** * The source from which the chord structure has been built */ type ChordInput = { /** * - the exact string used as a source for parsing. Ex: `Cm7b5/Gb` */ symbol: string; /** * - the root note from the input string. Ex: `C` */ rootNote: string; /** * - the bass note from the input string. Ex: `Gb` */ bassNote: string; /** * - the string between the root note and the bass note. Ex: `m7b5` */ descriptor: string; /** * - the modified descriptor such as parsing is possible. * Ex: `m add9` for `Cmadd9`, a space is added for disambiguation between `m + add` and `ma + dd`. */ parsableDescriptor: string; /** * - the detected modifiers during parsing */ modifiers: string; /** * - notation system in which the symbol was parsed */ notationSystem: 'english' | 'german' | 'latin'; }; /** * Abstract representation of the chord based on its intervals */ type NormalizedChord = { /** * - the normalized root note in english notation. Ex: `C` */ rootNote: string; /** * - the normalized bass note in english notation. Ex: `Gb` */ bassNote: string; /** * - list of intervals composing the chord. Ex: `['1', 'b3', 'b5', 'b7']` for `Cm7b5/Gb` */ intervals: string[]; /** * - list of notes composing the chord. Ex: `['C', 'Eb', 'Gb', 'Bb']` for `Cm7b5/Gb` */ notes: string[]; /** * - intervals converted to semitones. Ex: `[0, 3, 6, 10]` */ semitones: number[]; /** * - keep track of intents that are part of the symbol but cannot be conveyed by the interval list only */ intents: { major: boolean; eleventh: boolean; alt: boolean; }; /** * - "Vertical quality" of the chord, its core characteristics, * usually conveyed by the 3rd and the 7th, and sometimes the 5th. Ex: `major`, `minor7`, `minorMajor7`... */ quality: string; /** * - whether the chord has a suspended 3rd or not */ isSuspended: boolean; /** * - upper extensions of the base chord, can be one or more of `9`, `11` & `13`. * Ex: `['9', '11', '13']` for `Cm13` */ extensions: string[]; /** * - notes that are part of the chord or its extensions, but either flattened or sharpened. * Ex: `['b5']` for `Cm7b5/Gb` */ alterations: string[]; /** * - added notes that are neither extensions nor alterations. * Ex: `['9']` for `C(add9,omit3)` */ adds: string[]; /** * - removed notes from chord * Ex: `['3']` for `C(add9,omit3)` */ omits: string[]; }; /** * Pre-rendered version of the chord with the main "vertical quality" and the chord changes. * Intended to be used as building blocks of a rendered chord * The `symbol` property contains the default assembled rendering */ type FormattedChord = { /** * - full rendering of the chord */ symbol: string; /** * - formatted root note */ rootNote: string; /** * - formatted bass note */ bassNote: string; /** * - the descriptor, gives the vertical quality of the chords and its extensions */ descriptor: string; /** * - sorted and prefixed list of changes, whether altered, added or omitted notes. * Changes are given in the following order: alterations and added, sorted by interval, then omitted. * If multiple added/omits are present, the `add/omit` symbol is only printed once: `A+(add b9,#9)` */ chordChanges: string[]; }; /** * Roman numeral symbol of the chord, both rendered in a single string and also decomposed in its sub-parts. * The detection of the degree is based on the key given to the parser configuration. * The used approach is very naive and only based on whether the chord is diatonic to the given key or borrowed to its parallel major/minor scale * As such, it is only suitable for very basic harmonic analysis and a lot of chords will render as "?" because they won't fit * either scenario. * Having the symbol decomposed in its part will allow an external tool to easily override the detected degree * and reconstruct the symbol if needed. */ type NumeralChord = { /** * - concatenation of the `degree`, the `descriptor` and the `inversion` properties */ symbol: string; /** * - degree of the chord in the scale, or "?" if it cannot be determined. * If the `key` property is not given to the parser configuration, the degree will be either "I", "i" or "?" */ degree: string; /** * - quality of the chord (e.g. seventh, major seventh, diminished, etc.) */ descriptor: string; /** * - inversion notation in the roman numeral format (e.g. ⁶₄, ⁶₅, etc.) */ inversion: string; /** * - quality of the third of the chord, either "minor" or "major" */ thirdQuality: 'minor' | 'major'; /** * - Either "diatonic" if the degree is part of the key scale, * "borrowed" if it is part of the parallel minor or major scale, "unknown" otherwise. */ type: 'diatonic' | 'borrowed' | 'unknown'; }; /** * Configuration of the chord parser */ type ParserConfiguration = { /** * =['english','german','latin'] - * Notation systems that should be used to try parsing a symbol. All by default. */ notationSystems?: Array<'english' | 'german' | 'latin'>; /** * =['b5','#5','b9','#9','#11','b13'] - * user selection of intervals affected by the `alt` modifier (all by default). * Since using the `C7alt` symbol is a way to leave some room for interpretation by the player, Chord-symbol offer the possibility to declare what are * the intervals that the `alt` modifier should yield * If you would like `alt` to consistently yield a specific set of intervals, you can specify those here. */ altIntervals?: Array<'b5' | '#5' | 'b9' | '#9' | '#11' | 'b13'>; /** * - custom filters applied during parsing */ customFilters?: CustomFilter[]; /** * - key on which to base the rendering of the numeral symbol. * The key needs to be given in english notation with a maximum of 3 characters using non-unicode accidentals. * E.g. `C`, `C#m` or `Ab` are all valid keys, while `B♭` and `C7` are not. * If not given, the parser will not be able to detect the degree of the chord. */ key?: string; }; /** * Description of an error that occurred during the parsing. */ type ChordSymbolError = { /** * - error code, * or exception type in custom filters */ type: | 'InvalidIntervals' | 'InvalidInput' | 'InvalidModifier' | 'NoSymbolFound' | 'UnexpectedError'; /** * - error description, or the exception message in custom filters */ message: string; /** * - the chord object, in the state that it was when the error occurred */ chord?: Chord; /** * - the notation system context in which the error occurred */ notationSystem?: 'english' | 'german' | 'latin'; }; /** * Configuration of the chord renderer */ type RendererConfiguration = { /** * - if true, use short namings instead of the "academic" ones */ useShortNamings?: boolean; /** * - The level of simplification. * `max` will basically remove everything but minor 3rd, * `core` will try to keep only the chord core characteristics, leaving out suspensions, extensions, alterations, adds and omits. */ simplify?: 'none' | 'max' | 'core'; /** * - positive or negative semitones value */ transposeValue?: number; /** * - accidental to use when rendering a chord. * 'original' keeps the current one, if any. If transposeValue !== 0, sharp will be used * 'flat' render with flats * 'sharp' render with sharps */ accidental?: 'original' | 'flat' | 'sharp'; /** * - the printer to use for the rendering. `text` returns a string, `raw` the processed chord object. */ printer?: 'text' | 'raw'; /** * - the notation system to use when rendering the chord. * `auto` will use the same system in which the symbol was originally parsed. */ notationSystem?: 'auto' | 'english' | 'german' | 'latin'; /** * - custom filters applied during rendering */ customFilters?: CustomFilter[]; }; /** * Custom filter applied during processing or rendering. Custom filters will be applied at the end of the processing pipe, * after all built-in filters have been applied. * * **Parsing filters** * - We recommend that you do not delete any property of the Chord object, because some rendering filters might rely on them. * For maximum compatibility, your best bet is to always rely on the existing chord object structure. * - To fail the parsing, throw an exception and it will use the Error API. * If you want to be able to filter your exception in error handling, or to pass the chord object in its current state, use * [custom error types]{@link https://github.com/no-chris/chord-symbol/blob/master/packages/chord-symbol/src/helpers/ChordParsingError.js} * * **Rendering filter** * - If the purpose of your rendering filter is to change the text output of `ChordSymbol`, * then use the `text` printer and override the `.formatted.symbol` property. * - If the purpose is to enrich the chord symbol object with some new information or data structure, * then use the `raw` printer and modify the `Chord` object accordingly. * - To fail the rendering, simply return `null`. * Warning: if you throw an exception in a rendering filter, `ChordSymbol` will not catch it and the client code will need to handle it. * Don't do that! */ type CustomFilter = (chord: Chord) => Chord | null; /** * Create a chord parser function. */ declare function chordParserFactory( configuration?: ParserConfiguration ): (input: string) => MaybeChord; /** * Create a chord rendering function. */ declare function chordRendererFactory( configuration?: RendererConfiguration ): (chord: Chord) => string;
a4990bd33c8dc85d6e52bc08efb0522aaf5d177c
TypeScript
cyco/WebFun
/test/helpers/script.ts
2.515625
3
import { Result, ConditionChecker, EvaluationMode, InstructionExecutor } from "../../src/engine/script"; import { ConditionImplementations } from "src/engine/script/conditions"; import { InstructionImplementations } from "src/engine/script/instructions"; import { Condition, Instruction } from "src/engine/objects"; import { Engine, AssetManager } from "src/engine"; type JasmineDescribe = (description: string, block: () => void) => void; type ConditionTester = ( check: (condition: Condition, mode?: EvaluationMode) => Promise<boolean>, engine: Engine ) => void; type InstructionTester = ( check: (instruction: Instruction, mode: EvaluationMode) => void, engine: Engine ) => Promise<Result>; const makeConditionDescription = ( desc: JasmineDescribe ): ((name: string, block: ConditionTester) => void) => (Name, block) => { desc(`WebFun.Engine.Script.Condition.${Name}`, () => { const engine: any = mockEngine(); const checker: any = new ConditionChecker(ConditionImplementations, engine); beforeEach(() => Object.assign(engine, mockEngine())); block( async (condition: Condition, mode: EvaluationMode) => await checker.check(condition, mode, engine.currentZone), engine ); }); }; const makeInstructionDescription = (desc: JasmineDescribe) => ( Name: string, block: InstructionTester ) => { desc(`WebFun.Engine.Script.Instruction.${Name}`, () => { const engine = mockEngine(); const executor = new InstructionExecutor(InstructionImplementations, engine); beforeEach(() => Object.assign(engine, mockEngine())); block(async instruction => { executor.action = { zone: engine.currentZone, instructions: [instruction] } as any; return await executor.execute(instruction); }, engine); }); }; function mockEngine(): Engine { return { currentZone: { setTile: (): void => void 0, getTile: (): void => void 0 }, hero: {}, assets: new AssetManager(), currentWorld: { findLocationOfZone: (): void => void 0, at: (): void => void 0, findSectorContainingZone: (): void => void 0 }, speak: (): void => void 0, dropItem: (): void => void 0, persistentState: {}, sceneManager: { pushScene: (): void => void 0 }, mixer: { play: (): void => void 0 }, inventory: { items: [], contains(i: any) { return this.items.includes(i); }, addItem(i: any) { this.items.push(i); } }, inputManager: {}, findLocationOfZone: (): void => void 0, story: { goal: {} } } as any; } export const describeCondition = makeConditionDescription(describe); export const xdescribeCondition = makeConditionDescription(xdescribe); export const fdescribeCondition = makeConditionDescription(fdescribe); declare global { let describeCondition: (name: string, block: ConditionTester) => void; let xdescribeCondition: (name: string, block: ConditionTester) => void; let fdescribeCondition: (name: string, block: ConditionTester) => void; } export const describeInstruction = makeInstructionDescription(describe); export const xdescribeInstruction = makeInstructionDescription(xdescribe); export const fdescribeInstruction = makeInstructionDescription(fdescribe); declare global { let describeInstruction: (name: string, cb: (ex: Function, engine: any) => void) => void; let xdescribeInstruction: (name: string, cb: (ex: Function, engine: any) => void) => void; let fdescribeInstruction: (name: string, cb: (ex: Function, engine: any) => void) => void; }
15c07321a3da9b6fa25b5b4f3e3b05775b442211
TypeScript
yurimikushov/airline-tickets
/src/utils/__tests__/splitToThousands.test.ts
2.71875
3
import { splitToThousands } from '../splitToThousands' test('should don`t split numbers that less 999 modulo', () => { expect(splitToThousands(0)).toBe('0') expect(splitToThousands(999)).toBe('999') expect(splitToThousands(-999)).toBe('-999') }) test('should split numbers that more 999 modulo', () => { expect(splitToThousands(1234)).toBe('1 234') expect(splitToThousands(-1965)).toBe('-1 965') expect(splitToThousands(1234567)).toBe('1 234 567') expect(splitToThousands(-1234567)).toBe('-1 234 567') })
6b120140901d530873d9fe2b9b4d96e9dc3f0495
TypeScript
future4code/Mayara-Amaral
/semana16/aula46/src/endpoints/getCountByGender.ts
2.515625
3
import { Request, Response } from "express"; import { selectCountByGender } from "../data/selectCountByGender"; export const getCountByGender = async (req: Request, res: Response) => { try { const count = await selectCountByGender(req.query.gender as string) res.status(200).send(count) } catch (error) { res.send(error) } }
a6fe84181535fbf8d1cd0bf0b9b73fe9bfc8a3f9
TypeScript
nderise/spartacus
/feature-libs/cart/saved-cart/core/connectors/saved-cart.adapter.ts
2.515625
3
import { Cart } from '@spartacus/core'; import { Observable } from 'rxjs'; export abstract class SavedCartAdapter { /** * * Abstract method used to load a single saved cart */ abstract load(userId: String, cartId: String): Observable<Cart>; /** * * Abstract method used to load a list of saved carts */ abstract loadList(userId: string): Observable<Cart[]>; /** * * Abstract method used to restore a saved cart to an active cart */ abstract restoreSavedCart(userId: string, cartId: string): Observable<Cart>; /** * * Abstract method used to save a cart or update a saved cart */ abstract saveCart( userId: string, cartId: string, saveCartName?: string, saveCartDescription?: string ): Observable<Cart>; /** * * Abstract method used to clone a saved cart */ abstract cloneSavedCart(userId: string, cartId: string): Observable<Cart>; }
5b854cf0cdc05245ca882f821501df67c4a07f94
TypeScript
ossang/olib-admin
/olib-admin-dashboard/src/app/@olib/@olib-chart/olib-chart-text/olib-chart-text-config.model.ts
2.59375
3
export class OlibChartTextConfig{ private title : any; private status : string; private value : any; constructor(){ } /** * Getter $title * @return {any} */ public get $title(): any { return this.title; } /** * Getter $status * @return {string} */ public get $status(): string { return this.status; } /** * Getter $value * @return {any} */ public get $value(): any { return this.value; } /** * Setter $title * @param {any} value */ public set $title(value: any) { this.title = value; } /** * Setter $status * @param {string} value */ public set $status(value: string) { this.status = value; } /** * Setter $value * @param {any} value */ public set $value(value: any) { this.value = value; } }
56d39a0966aa0c5f9f043b7e7b44097708bd4c57
TypeScript
PeterKaffeeKrieger/teambuktu
/src/app/model/Info.ts
2.640625
3
import {DataObject} from "./DataObject"; export class Info extends DataObject{ constructor(private _name: string) { super(_name); } get name(): string { return this._name; } }
23c113cd318cfed717ab0d9dac49b8365a9b9268
TypeScript
wan54/datahub
/datahub-web/@nacho-ui/core/tests/unit/utils/lib/is-primitive-test.ts
3.203125
3
import isPrimitive from 'dummy/utils/lib/is-primitive'; import { module, test } from 'qunit'; module('Unit | Utility | lib/is-primitive', function() { test('it works for positive cases', function(assert) { const resultA = isPrimitive('Ash Ketchum'); const resultB = isPrimitive(5); const resultC = isPrimitive(null); const resultD = isPrimitive(undefined); const resultE = isPrimitive(true); assert.ok(resultA, 'Works for strings'); assert.ok(resultB, 'Works for numbers'); assert.ok(resultC, 'Works for null'); assert.ok(resultD, 'WOrks for undefined'); assert.ok(resultE, 'Works for boolean'); }); test('it works for negative cases', function(assert) { const resultA = isPrimitive(function() { return 'Pikachu'; }); const resultB = isPrimitive({ hellodarkness: 'my old friend' }); assert.notOk(resultA, 'Negative on functions'); assert.notOk(resultB, 'Negative on objects'); }); });
1f7df139aa3c0372f2f0ce8585dbd26dfa79a548
TypeScript
maapteh/graphql-modules-app
/packages/server/src/middleware/allowed-origin/allowed-origins.ts
2.65625
3
import express from 'express'; import { ORIGINS_LIST } from './origins-list'; /** * ONLY ALLOW ORIGINS WHICH WE DO ALLOW */ export const ALLOWED_ORIGIN = ( req: express.Request, res: express.Response, next: express.NextFunction, ) => { const origin = req.get('origin'); if (origin) { const index = ORIGINS_LIST.indexOf(origin); if (index === -1) { const msg = 'The CORS policy does not allow access from the specified Origin.'; return next(new Error(msg)); } res.header('Access-Control-Allow-Credentials', 'true'); res.header('Access-Control-Allow-Origin', ORIGINS_LIST[index]); } next(); };
2d86a813c25212b24ac641dc70a97338941aeb6f
TypeScript
RamAddict/flwarrior
/src/__test__/grammarTransforms/grammar.test.ts
2.75
3
import { IAlphabet } from "@/lib/Alphabet"; import Immutable from "immutable"; import { inspect } from "util"; import { addNonTerminalSymbol, addTerminalSymbol, fromDBEntry as createGrammarFromDBEntry, removeTerminalSymbol, removeNonTerminalSymbol, getBodiesOfHead, IIGrammar, getFollows, getAnalysisTable, runTableLL1, } from "../../lib/grammar/Grammar"; import { GrammarType } from "../../database/schema/grammar"; function buildGrammar1(): IIGrammar { // S -> Sa|b return createGrammarFromDBEntry({ id: "test", name: "test", alphabetT: ["b", "a", "ε"], alphabetNT: ["S"], startSymbol: "S", transitions: [ { from: ["S"], to: [["S", "a"], ["b"], ["B"]] }, { from: ["B"], to: [["a"], ["b"]] }, ], type: GrammarType.REGULAR, }); } function buildGrammar2(): IIGrammar { // S -> Sa|b return createGrammarFromDBEntry({ id: "test", name: "test", alphabetT: ["c", "com", "ε", ";", "v", "f", "b", "e"], alphabetNT: ["P", "V", "C", "K", "F"], startSymbol: "P", transitions: [ { from: ["P"], to: [["K", "V", "C"]] }, { from: ["K"], to: [["c", "K"], ["ε"]] }, { from: ["V"], to: [["v", "V"], ["F"]] }, { from: ["F"], to: [["f", "P", ";", "F"], ["ε"]] }, { from: ["C"], to: [["b", "V", "C", "e"], ["com", ";", "C"], ["ε"]], }, ], type: GrammarType.CONTEXT_FREE, }); } test("test add symbols to new IIGrammar", () => { // IIGrammar const immutableGrammar = createGrammarFromDBEntry({ id: "test", name: "test", alphabetT: [], alphabetNT: [], startSymbol: "S", transitions: [], type: GrammarType.REGULAR, }); let modifiedGrammar = addNonTerminalSymbol(immutableGrammar, "j"); expect( (immutableGrammar.get("nonTerminalSymbols") as IAlphabet).includes("j") ).toBeFalsy(); expect( (modifiedGrammar.get("nonTerminalSymbols") as IAlphabet).includes("j") ).toBeTruthy(); modifiedGrammar = addTerminalSymbol(immutableGrammar, "s"); expect( (immutableGrammar.get("nonTerminalSymbols") as IAlphabet).includes("j") ).toBeFalsy(); expect( (modifiedGrammar.get("terminalSymbols") as IAlphabet).includes("s") ).toBeTruthy(); }); test("test remove symbols to new IIGrammar", () => { // IIGrammar const immutableGrammar = createGrammarFromDBEntry({ id: "test", name: "test", alphabetT: ["c"], alphabetNT: ["C"], startSymbol: "S", transitions: [], type: GrammarType.REGULAR, }); let modifiedGrammar = removeTerminalSymbol(immutableGrammar, "c"); expect( (modifiedGrammar.get("terminalSymbols") as IAlphabet).includes("c") ).toBeFalsy(); expect( (modifiedGrammar.get("nonTerminalSymbols") as IAlphabet).includes("C") ).toBeTruthy(); modifiedGrammar = removeNonTerminalSymbol(modifiedGrammar, "C"); expect( (modifiedGrammar.get("nonTerminalSymbols") as IAlphabet).includes("C") ).toBeFalsy(); }); test("test get bodies of head", () => { const grammar = buildGrammar1(); expect( getBodiesOfHead(grammar, ["B"]).equals( Immutable.Set([Immutable.List(["a"]), Immutable.List(["b"])]) ) ).toBeTruthy(); expect( getBodiesOfHead(grammar, ["S"]).equals( Immutable.Set([ Immutable.List(["S", "a"]), Immutable.List(["b"]), Immutable.List(["B"]), ]) ) ).toBeTruthy(); }); test("test get follows of grammar", () => { const grammar = buildGrammar2(); const firsts = Immutable.Map({ com: Immutable.Set(["com"]), b: Immutable.Set(["b"]), C: Immutable.Set(["b", "com", "ε"]), c: Immutable.Set(["c"]), F: Immutable.Set(["f", "ε"]), f: Immutable.Set(["f"]), K: Immutable.Set(["c", "ε"]), P: Immutable.Set(["c", "v", "f", "b", "com", "ε"]), ε: Immutable.Set(["ε"]), V: Immutable.Set(["v", "f", "ε"]), v: Immutable.Set(["v"]), ";": Immutable.Set([";"]), e: Immutable.Set(["e"]), }); // console.log(inspect(getFollows(grammar, firsts).toJS(), false, null, true)); }); test("run table", () => { const grammar = buildGrammar2(); const table = getAnalysisTable(grammar); console.log(runTableLL1("ccvfbe;", grammar, table)); });
dc627488a2e9970a7949b571e1576d0221cbea7d
TypeScript
gios/diploma-nets
/src/app/shared/net/linkConnections.ts
2.515625
3
import * as joint from 'jointjs'; import { find } from 'lodash'; import { ILinkConnection } from './net.interface'; const defaultLinkOptions = { label: '' }; export function link( id: number, connectFirst: joint.dia.Cell, connectSecond: joint.dia.Cell, options = defaultLinkOptions ) { options = Object.assign({}, defaultLinkOptions, options); const { label } = options; const configLinkOptions = { id, source: { id: connectFirst.id, selector: '.root' }, target: { id: connectSecond.id, selector: '.root' }, attrs: { '.connection': { 'fill': 'none', 'stroke-linejoin': 'round', 'stroke-width': '1', 'stroke': '#5d5d5e' }, '.marker-target': { 'fill': '#5d5d5e', 'stroke': '#5d5d5e', } }, labels: [{ position: 0.5, attrs: { rect: { fill: '#fafafa', }, text: { fill: '#5d5d5e', text: `${label}` } } }] }; return new joint.shapes.pn.Link(configLinkOptions); } export function getLinkValue(link: joint.shapes.pn.Link) { const linkValue = link.get('labels')[0].attrs.text.text; return parseInt((linkValue) ? linkValue : 1, 10); } export function generateConnections( pinnacles: joint.dia.Cell[], transitions: joint.dia.Cell[], connections: ILinkConnection[] ) { const generatedConnections: joint.shapes.pn.Link[] = []; connections.forEach((connectionItem) => { let options = null; const connectedItems = connectionItem.connect.map((item) => { let foundItem: joint.dia.Cell; if (item.type === 'pinnacle') { foundItem = find(pinnacles, ['attributes.baseId', item.id]); } else { foundItem = find(transitions, ['attributes.baseId', item.id]); } if (foundItem) { foundItem.set('connectionType', item.type); return foundItem; } else { return null; } }); if (connectionItem.value > 1) { options = { label: connectionItem.value.toString() }; } if (connectionItem.id && connectedItems[0] && connectedItems[1]) { generatedConnections.push(link(connectionItem.id, connectedItems[0], connectedItems[1], options)); } }); return generatedConnections; }
946183f2e30c114f07f5dfae6ebbd60eaf84f022
TypeScript
jcabanillas/clinicbox
/src/models/telefono.ts
2.546875
3
// Evento model based on the structure of evento // https://api.github.com/users/{username} export interface Telefono { id: number; tipo: string; numero: string; extension: string; }
8dbfee53e64c42154fecea9ce18d98af86a40dc9
TypeScript
keyur2714/Angular_6_2
/InputDemo/src/app/app.component.ts
2.578125
3
import { Component,OnInit } from '@angular/core'; import { Lookup } from './my-dropdown/lookup-model'; import { Server } from './server/server.model'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit{ countryLookupList : Lookup[] = []; stateLookupList : Lookup[] = []; selectedCountry : Lookup = new Lookup(); selectedState : Lookup = new Lookup(); title = 'app'; message = "Good After noon"; name: string = "keyur"; revStr: string = ''; serverHeaderList: string[] = ["Server Name","Server OS"]; serverColumnList: string[] = ["serverName","serverOs"]; serverList: Server[] = [ { serverName : "Server 1", serverOs: "Windows" }, { serverName : "Server 2", serverOs: "Linux" } ]; ngOnInit(){ const countryLookup1 = new Lookup(); countryLookup1.id = 11; countryLookup1.code = "IND"; countryLookup1.name = "India"; const countryLookup2 = new Lookup(); countryLookup2.id = 12; countryLookup2.code = "US"; countryLookup2.name = "United States"; const countryLookup3 = new Lookup(); countryLookup3.id = 13; countryLookup3.code = "UK"; countryLookup3.name = "United Kindgdom"; this.countryLookupList.push(countryLookup1); this.countryLookupList.push(countryLookup2); this.countryLookupList.push(countryLookup3); const stateLookup1 = new Lookup(); stateLookup1.id = 101; stateLookup1.code = "MH"; stateLookup1.name = "Maharashtra"; const stateLookup2 = new Lookup(); stateLookup2.id = 102; stateLookup2.code = "GJ"; stateLookup2.name = "Gujarat"; const stateLookup3 = new Lookup(); stateLookup3.id = 103; stateLookup3.code = "MP"; stateLookup3.name = "Madhya Pradesh"; this.stateLookupList.push(stateLookup1); this.stateLookupList.push(stateLookup2); this.stateLookupList.push(stateLookup3); } msgList : string[] = [ "Good Morning...!", "Good Afternoon...!", "Good Evening...!", "How are you?" ]; reverseStr():void{ console.log(this.name); let str = this.name.split('').reverse().join(""); this.revStr = str; } setSelectedState(state){ this.selectedState = state; } setSelectedCountry(country){ this.selectedCountry = country; } addServerToList(server){ console.log("2: "+server); this.serverList.push(server); } }
ecb4b3789dfb259e16be4037355bb6888722f575
TypeScript
jingkeke/ramda_utils
/src/FuncUtils.ts
2.96875
3
// 这里面的感觉只是用于 class 的 比如debounce https://steelsojka.github.io/lodash-decorators/ // export function debounce(func, delay) { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => { func(...args); }, delay); }; } /** * @param {Function} func * @param {number} wait * @param {boolean} immediate * @return {*} */ export function debounceV(func, wait, immediate) { let timeout, args, context, timestamp, result const later = function() { // 据上一次触发时间间隔 const last = +new Date() - timestamp // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait if (last < wait && last > 0) { timeout = setTimeout(later, wait - last) } else { timeout = null // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用 if (!immediate) { result = func.apply(context, args) if (!timeout) context = args = null } } } return function(...args) { context = this timestamp = +new Date() const callNow = immediate && !timeout // 如果延时不存在,重新设定延时 if (!timeout) timeout = setTimeout(later, wait) if (callNow) { result = func.apply(context, args) context = args = null } return result } } // import { throttle,debounce } from 'throttle-debounce' // const showDivPoint_throttle = throttle(1000, showDivPoint) // const debounce_flyTo = debounce(1500, flyTo) // debounce way 4 // https://lodash.com/ // const _ = require('lodash') // const debounce_flyTo = _.debounce(flyTo, 1500)
71df017171dce25f414b9b410b34242d9afb1711
TypeScript
andywer/deep-assert
/src/index.ts
2.53125
3
import { deepEquals as internalDeepEquals, Options } from "./deep-equals" export * from "./deep-equals" export default function deepEquals(actual: any, expected: any, opts?: Options) { const result = internalDeepEquals(actual, expected, [], opts) if (result instanceof Error) { // Keep the stack trace short and sweet throw Error(result.message) } return true } export { deepEquals }
b56c4cf1bb1706bb0645f76b107a51644bc10f99
TypeScript
IronOnet/codebases
/codebases/pipedrive.com(dashboard)/webpack---lib/client/hooks/useInterval.ts
2.6875
3
import { useRef, useEffect, DependencyList } from 'react'; interface UseIntervalOptions { runImmediately: boolean; deps?: DependencyList; } // copied over from leadbooster // Inspired by Dan Abramov - https://overreacted.io/making-setinterval-declarative-with-react-hooks/ export function useInterval(callback: () => void, ms: number, options?: UseIntervalOptions) { const savedCallbackRef = useRef<() => void>(); const intervalRef = useRef<number>(); const clear = () => { clearInterval(intervalRef.current); }; // Remember the latest callback. useEffect(() => { savedCallbackRef.current = callback; }, [callback]); useEffect(() => { const tick = () => { savedCallbackRef.current && savedCallbackRef.current(); }; if (options?.runImmediately) { tick(); } const interval = window.setInterval(tick, ms); intervalRef.current = interval; return () => clear(); // eslint-disable-next-line }, options?.deps ?? []); return clear; }
bf7224c088899800a5f0f00aae2bce5ed8e36075
TypeScript
yuersen/fx
/src/object/isFunction.ts
3.640625
4
import type from './type'; /** * 检测当前参数是否为函数 * * @function * @memberof Fx * @param {Any} obj 任意类型的数据 * @returns {Boolean} * @example * * // -> true * Fx.isFunction(function test() {}); * * // -> false * Fx.isFunction({}); * * // -> false * Fx.isFunction(2019); */ const isFunction = (obj: any): boolean => { return type(obj) === 'function'; }; export default isFunction;
993e6451721bd6e48aa9777075a56e4daecd0b78
TypeScript
raulrozza/Gametask_API
/src/modules/players/domain/entities/fakes/FakeUnlockAchievementRequest.ts
2.53125
3
import { IUnlockAchievementRequest } from '@modules/players/domain/entities'; import { IAchievement, IUser } from '@shared/domain/entities'; import { FakeAchievement, FakeUser } from '@shared/domain/entities/fakes'; import faker from 'faker'; import { v4 as uuid } from 'uuid'; interface IConstructor { game?: string; requester?: string; achievement?: string; requestDate?: Date; information?: string; } export default class FakeUnlockAchievementRequest implements IUnlockAchievementRequest { public id: string = uuid(); public requestDate: Date; public information: string; public game: string; public requester: IUser; public achievement: IAchievement; constructor({ game = uuid(), requester, achievement, requestDate = new Date(), information = faker.random.words(), }: IConstructor = {}) { this.game = game; this.requester = new FakeUser({ id: requester }); this.achievement = new FakeAchievement({ id: achievement }); this.requestDate = requestDate; this.information = information; } }
4c798dd538d5f60d28b368b524f521c8f7502cd4
TypeScript
taomas/mrapi
/packages/create-mrapi-app/src/install.ts
2.671875
3
import { exec } from 'child_process' const execa = ( cmd: string, options?: { cwd: string; env?: { [name: string]: string | undefined } }, ): Promise<string | Buffer> => { if (process.env.verbose == 'true') { console.log(' $> ' + cmd) } return new Promise((resolve, reject) => { exec( cmd, options, ( error: Error | null, stdout: string | Buffer, stderr: string | Buffer, ) => { if (process.env.verbose == 'true') { console.log(stderr || stdout) } if (error) reject(error) resolve(stdout) }, ) }) } export const useYarn = () => { return execa('yarn --version') .then(() => true) .catch(() => false) } export const install = async (targetDir: string) => { const yarnOrNpm = (await useYarn()) ? 'yarn install' : 'npm install' console.log('Installing dependencies...') await execa(yarnOrNpm, { cwd: targetDir, }) }
4a345db4a774543c5fd7afc6eeb9be48a3bfdd51
TypeScript
Mujib517/angular4-training
/src/shared/math.spec.ts
3.28125
3
import { Math } from './math'; describe("Math Service", ()=> { let math; beforeEach(function () { //Arrange math = new Math(); }); describe("Add function", ()=> { it("should add two number and return result", function () { //AAA //Act var c = math.add(2, 3); //Assert expect(c).toBe(5); }); it('should add two strings', function () { var result = math.add("Mujib", "Rahman"); expect(result).toBe("MujibRahman"); }); it('should return zero when first parameter is zero', function () { var result = math.add(0, 100); expect(result).toBe(0); }); it('should return 2 when first parameter is one', function () { var result = math.add(1, 100); expect(result).toBe(2); }); }); describe("Sub function", function () { it('should subtract two numbers and return result', function () { var c = math.sub(4, 2); expect(c).toBe(2); }); }); afterEach(function () { math = null; }); });
743ad78fa0aa286815eb0b508da2575352bdcaf0
TypeScript
massmediagroup-5/node.js-presentation
/controllers/OrderController.ts
2.5625
3
import { Authorized, Body, CurrentUser, JsonController, Post, } from 'routing-controllers'; import { Order } from '../models/Order'; import { OrderService } from '../services/OrderService'; import { User } from '../models/User'; import { ValidationError } from '../errors/ValidationError'; import { ResourceNotFoundError } from '../errors/ResourceNotFoundError'; import { Validator } from 'class-validator'; import { OrderRequest } from '../validators/OrderRequest'; import { ProductService } from '../services/ProductService'; @Authorized() @JsonController('/orders') export class OrderController { constructor( private orderService: OrderService, private productService: ProductService, private validator: Validator ) {} /** * Create new order * * @param {OrderRequest} data * @param {User} user * @throws ResourceNotFoundError * @throws ValidationError * @return {Promise<Order>} */ @Post() public async create(@Body() data: OrderRequest, @CurrentUser() user?: User): Promise<Order> { const errors = this.validator.validateSync(data); if (errors.length > 0) { throw new ValidationError(errors); } const product = await this.productService.findOne(data.productId); if (!product) { throw new ResourceNotFoundError(); } const order = await this.orderService.prepareOrderData(data, user, product); return this.orderService.buy(order); } }
d7f2268d5563135e62a2bcb6e4e30a4488bf4678
TypeScript
karthikapp/base
/src/app/pipes/competitornames.pipe.ts
2.59375
3
import { Pipe, PipeTransform } from '@angular/core'; import { FirebaseService } from '../services/firebase.service'; import "rxjs/add/operator/map"; @Pipe({ name: 'competitornames' }) export class CompetitornamesPipe implements PipeTransform { competitorlists: Object[]; constructor(public firebaseservice: FirebaseService){} transform(value: any, args?: any): any { console.log("hello",value); //this.anothermethod(value).subscribe(); if(value == undefined){ return []; } let value_count = Object.keys(value).length; let values = Object.values(value); //console.log(value_count, values); let competitorlists = []; for(let i=0; i<= value_count; i++){ if(values[i]!= undefined){ this.firebaseservice.getCompetitorList(values[i]).forEach(competitorlist => { competitorlists.push(competitorlist) }) } } //console.log(competitorlists); return competitorlists } }
370d16b96fd94468628afeaf20507570fa5607b2
TypeScript
Esirei/Legit9ja.com-RN
/src/navigation/NavigationService.ts
2.515625
3
import { NavigationActions, StackActions, NavigationContainer, NavigationRoute, NavigationDispatch, NavigationPopActionPayload, } from 'react-navigation'; import { DrawerActions } from 'react-navigation-drawer'; import RouteNames from './RouteNames'; import { PostScreenParams } from '@screens/post/types'; import { WebScreenParams } from '@screens/web/types'; let _navigator: NavigationContainer & { dispatch: NavigationDispatch }; function setRef(nav) { _navigator = nav; } function getRef(): NavigationContainer { return _navigator; } function navigate(routeName: string, params?, action?) { _navigator.dispatch( NavigationActions.navigate({ routeName, params, action, }), ); } function setParams(params, key) { _navigator.dispatch( NavigationActions.setParams({ params, key, }), ); } function push(routeName, params?, action?) { _navigator.dispatch( StackActions.push({ routeName, params, action, }), ); } function pop(options: NavigationPopActionPayload = {}) { _navigator.dispatch(StackActions.pop(options)); } function popToTop() { _navigator.dispatch(StackActions.popToTop()); } function back() { _navigator.dispatch(NavigationActions.back()); } function openDrawer() { _navigator.dispatch(DrawerActions.openDrawer()); } function closeDrawer() { _navigator.dispatch(DrawerActions.closeDrawer()); } function toggleDrawer() { _navigator.dispatch(DrawerActions.toggleDrawer()); } type RouteState = { index: number; routes?: NavigationRoute[]; routeName?: string }; const getCurrentRouteName = (route: RouteState): string => { const { index, routes, routeName } = route; return routes ? getCurrentRouteName(routes[index]) : routeName || ''; }; const currentRouteName = (): string => { return getRef() ? getCurrentRouteName(getRef().state.nav!) : ''; }; const navToPost = (params: PostScreenParams) => push(RouteNames.POSTS, params); const navToWeb = (params: WebScreenParams, action?) => push(RouteNames.WEB, params, action); export default { setRef, getRef, navigate, setParams, push, pop, popToTop, back, openDrawer, closeDrawer, toggleDrawer, currentRouteName, navToPost, navToWeb, };
f0dcd9258365a6812fa76a6da038501d5914c8ed
TypeScript
tarvyn/nodejs-guide
/graphQL/app/graphql/post/post.input.ts
2.71875
3
import { IsNotEmpty, MinLength } from 'class-validator'; import { Field, InputType } from 'type-graphql'; import { Post } from '../../models/post.model'; @InputType() export class PostInput implements Partial<Post> { @Field({ nullable: true }) id?: string; @Field() @IsNotEmpty({ message: 'Title field is required' }) title: string; @Field({ nullable: true }) imageUrl: string; @Field() @MinLength(5, { message: 'Content should be at least 5 characters long' }) content: string; }
325aac4a13d8577011dd15aedb01006c05ef6ea4
TypeScript
AdinoWayne/VuMucDiThu
/code/dynamic-programming/2379-minimum-recolors-to-get-k-consecutive-black-blocks.ts
2.953125
3
function minimumRecolors(blocks: string, k: number): number { let min_count = Number.MAX_VALUE for(let i=0; i<blocks.length; i++){ let black_count = 0, count = 0 for(let j=i; j<blocks.length; j++){ if(blocks.charAt(j) == 'B') black_count++ else{ black_count++ count++ } if(black_count == k){ min_count = Math.min(min_count, count) break } } } return min_count };
0a58986bc3b4f55a27a2abd06dcc2a7e6d966136
TypeScript
osvodef/collision-buffer-research
/src/bitBuffer.ts
3.34375
3
import { CollisionDetector, Marker } from './types'; export class BitBufferImpl implements CollisionDetector { private width: number; private height: number; private buffer: Uint8Array; constructor(width: number, height: number) { // Width must be a multiple of 8 this.width = Math.ceil(width / 8) * 8; this.height = height; // TODO: check size calculation this.buffer = new Uint8Array(this.width * this.height / 8); } insert(marker: Marker): void { const { minX, minY, maxX, maxY } = marker; const { width, buffer } = this; for (let j = minY; j < maxY; j++) { const start = j * width + minX >> 3; const end = j * width + maxX >> 3; // Если начальный байт равен конечному, то нужно закрасить биты только в нем if (start === end) { buffer[start] = buffer[start] | (255 >> (minX & 7) & 255 << (8 - (maxX & 7))); } else { // Закрашиваем биты в начальном байте buffer[start] = buffer[start] | (255 >> (minX & 7)); // Закрашиваем все промежуточные байты между начальным и конечным for (let i = start + 1; i < end; i++) { buffer[i] = 255; } // Закрашиваем биты в коненом байте buffer[end] = buffer[end] | (255 << (8 - (maxX & 7))); } } } collides(marker: Marker): boolean { const { minX, minY, maxX, maxY } = marker; const { width, buffer } = this; for (let j = minY; j < maxY; j++) { const start = j * width + minX >> 3; const end = j * width + maxX >> 3; let sum = 0; // Если начальный байт равен конечному, то нужно проверить только его if (start === end) { sum = buffer[start] & (255 >> (minX & 7) & 255 << (8 - (maxX & 7))); } else { // Проверяем начальный байт sum = buffer[start] & (255 >> (minX & 7)); // Перебираем все промежуточные между начальным и конечным for (let i = start + 1; i < end; i++) { sum = buffer[i] | sum; } // Проверяем конечный байт sum = buffer[end] & (255 << (8 - (maxX & 7))) | sum; } if (sum !== 0) { return true; } } return false; } }
5c7bd5d119ef3e87d9d11fbd402e8f779b80e1b7
TypeScript
epicmaxco/vuestic-ui
/packages/docs/page-config/ui-elements/tree-view/index.ts
2.640625
3
import { VaTreeViewOptions } from "./api-options"; import apiDescription from './api-description'; const treeNodeType = ` interface TreeNode { id: number | string children: TreeNode[] level?: number checked?: boolean | null disabled?: boolean expanded?: boolean hasChildren?: boolean matchesFilter?: boolean indeterminate?: boolean [key: string]: any } `; export default definePageConfig({ blocks: [ block.title("Tree view"), block.paragraph("Component for the hierarchical and nested data"), block.example("Default", { title: "Basic usage" }), block.example("CustomizableContent", { title: "Customizable content", description: "You can customize the body of node" }), block.example("Filters", { title: "Filters" }), block.example("Selectable", { title: "Selectable" }), block.example("SelectableColored", { title: "Colored checkboxes" }), // API block.api("VaTreeView", apiDescription, VaTreeViewOptions), block.collapse("TreeNode type", [block.code(treeNodeType)]), ], });
5b65cffada54289b72bc684e311c7a76f0b99367
TypeScript
icivann/ivann
/src/app/ir/OutModel.ts
2.59375
3
class OutModel { constructor( public readonly name: string, ) {} static build(options: Map<string, any>): OutModel { return new OutModel( options.get('name'), ); } } export default OutModel;
d61996601df18822b2c6c4d93245a1d5666a804e
TypeScript
8Observer8/express-example-ts
/src/server/App.ts
2.65625
3
import * as express from "express"; import * as http from "http"; // Playground: https://repl.it/@8Observer8/My-First-Express-Server-in-TypeScript class App { private _port = process.env.PORT || 3000; public constructor() { const app = express(); app.get("/", (request, response) => { response.send("<h2>Hello from Express!</h2>"); }); const httpServer = http.createServer(app); httpServer.listen(this._port, () => { console.log("Server started. Port:", this._port); }); } } new App();
5c79258ba091771997c12c6e34122eca6e813786
TypeScript
jhipster/prettier-java
/packages/prettier-plugin-java/src/printers/lexical-structure.ts
2.65625
3
import { printTokenWithComments } from "./comments/format-comments"; import { join } from "./prettier-builder"; import { BaseCstPrettierPrinter } from "../base-cst-printer"; import { BooleanLiteralCtx, FloatingPointLiteralCtx, IntegerLiteralCtx, IToken, LiteralCtx } from "java-parser"; import { builders } from "prettier/doc"; const { hardline } = builders; export class LexicalStructurePrettierVisitor extends BaseCstPrettierPrinter { literal(ctx: LiteralCtx) { if (ctx.TextBlock) { const lines = ctx.TextBlock[0].image.split("\n"); const open = lines.shift()!; const baseIndent = Math.min( ...lines.map(line => line.search(/\S/)).filter(indent => indent >= 0) ); return join(hardline, [ open, ...lines.map(line => line.slice(baseIndent)) ]); } if (ctx.CharLiteral || ctx.StringLiteral || ctx.Null) { return printTokenWithComments(this.getSingle(ctx) as IToken); } return this.visitSingle(ctx); } integerLiteral(ctx: IntegerLiteralCtx) { return printTokenWithComments(this.getSingle(ctx) as IToken); } floatingPointLiteral(ctx: FloatingPointLiteralCtx) { return printTokenWithComments(this.getSingle(ctx) as IToken); } booleanLiteral(ctx: BooleanLiteralCtx) { return printTokenWithComments(this.getSingle(ctx) as IToken); } }
1d3db7319bfaf77b1c273e2777266daca2faa1e6
TypeScript
flowtsohg/mdx-m3-viewer
/src/parsers/m3/camera.ts
2.515625
3
import BinaryStream from '../../common/binarystream'; import IndexEntry from './indexentry'; import Reference from './reference'; import { Float32AnimationReference } from './animationreference'; /** * A camera. */ export default class Camera { version = -1; bone = -1; name = new Reference(); fieldOfView = new Float32AnimationReference(); unknown0 = 0; farClip = new Float32AnimationReference(); nearClip = new Float32AnimationReference(); clip2 = new Float32AnimationReference(); focalDepth = new Float32AnimationReference(); falloffStart = new Float32AnimationReference(); falloffEnd = new Float32AnimationReference(); depthOfField = new Float32AnimationReference(); load(stream: BinaryStream, version: number, index: IndexEntry[]): void { this.version = version; this.bone = stream.readUint32(); this.name.load(stream, index); this.fieldOfView.load(stream); this.unknown0 = stream.readUint32(); this.farClip.load(stream); this.nearClip.load(stream); this.clip2.load(stream); this.focalDepth.load(stream); this.falloffStart.load(stream); this.falloffEnd.load(stream); this.depthOfField.load(stream); } }
046e89ee3f0162439ce210594350b90916d992b2
TypeScript
isyed-intuit/website
/minarets-api/minarets/tours.ts
2.765625
3
import LRUCache from 'lru-cache'; import { ApiBase } from './apiBase'; import type { ListAllResponse, ListResponse, Tour, TourSummary, TourWithChildren } from './types'; const cache = new LRUCache<string, TourWithChildren>({ max: 100000, maxAge: 60 * 60 * 1000, // 60 minutes }); export class Tours extends ApiBase { public async getTour(idOrSlug: number | string): Promise<TourWithChildren> { if (!idOrSlug) { throw new Error('Unable to get tour by empty id.'); } const cacheKey = `tours/${idOrSlug}`; let result = cache.get(cacheKey); if (!result) { const response = await this.get(`${this.apiUrl}/api/tours/${idOrSlug}`); result = (await response.json()) as TourWithChildren; if (result) { cache.set(cacheKey, result); cache.set(`tours/${result.id}`, result); cache.set(`tours/${result.slug}`, result); } } return result; } public async listAllTours(): Promise<ListAllResponse<TourSummary>> { const response = await this.get(`${this.apiUrl}/api/tours/all`); return (await response.json()) as ListAllResponse<TourSummary>; } public async listTours(): Promise<ListResponse<Tour>> { const response = await this.get(`${this.apiUrl}/api/tours`); return (await response.json()) as ListResponse<Tour>; } }
07137275ce51e42cba78d8ea7cf8999bcba08eef
TypeScript
dsfb/sw-backend
/frontend/src/api/generic/generic-api.ts
3.015625
3
import {getAxiosInstance} from "./axios-instance"; import {AxiosResponse} from "axios"; export interface PageData { next: number | null; prior: number | null; pageTotal: number; recordTotal : number; } export interface PagebleResponse<T> { data: T[]; page: PageData; } export interface ResourceReturn<T> { getById: (id: number)=> Promise<T>; getByPartialName: (search: string, pageNumber: number) => Promise<PagebleResponse<T>> getAll: (page: number) => Promise<PagebleResponse<T>>; } export type SWAPIEndpoint = 'people' | 'films'; /** * This code deals to access for the API. * It's not its responsability to handle errors 5xx. Only client search-text not found 404 * 5xx are going to be tackled by the hooks that access data. * @param endpoint the endpoint name (ie people). This is type safe in order to avoid calling mistakes. * @T Generic type for the returns */ export const genericController = <T>(endpoint: SWAPIEndpoint): ResourceReturn<T> => { const axios = getAxiosInstance(); const getById = async (id: Number): Promise<T> => { const response = await axios.get(`/${endpoint}/${id}`) return response?response.data:null; } const getAll = async (pageNumber: number): Promise<PagebleResponse<T>> => { const response = await axios.get(`/${endpoint}?page=${pageNumber}`) const data: T[] = (response.data.results); const page: PageData = getPageData(response); return {page, data: data}; } const getByPartialName = async (search: string, pageNumber: number): Promise<PagebleResponse<T>> => { const response = await axios.get(`/${endpoint}/?search=${search}&page=${pageNumber}`) const dados: T[] = (response.data.results); const page: PageData = getPageData(response); return {page, data: dados}; } const getPageData = (response: AxiosResponse): PageData => { const next: number | null = getPageNumber(response.data.next); const prior: number | null = getPageNumber(response.data.previous); const resultSize = response.data.results.length; const count = response.data.count const total: number = (count % resultSize) === 0 ? (count / resultSize)||0 : (Math.floor(count / resultSize) + 1)||0; return {next: next, prior: prior, pageTotal: total,recordTotal:count} } const getPageNumber = (url:string|null):number|null=>{ if (!url) return null; const matchs = url.match('page=\\d+'); if (matchs) return parseInt(matchs[0].replace('page=','')); return null; } return {getById, getAll, getByPartialName} }
b76a464413c00dc9e2ddca3eda2a209663238388
TypeScript
project-accelerate/m.app
/backend/app/common/ConfigService.ts
2.765625
3
import { Service } from 'typedi' @Service() export class ConfigService { constructor(public configs = process.env) {} private forceOptional = false makeOptional() { this.forceOptional = true } get(variable: string) { if (this.forceOptional) { return this.configs[variable] || variable } const value = this.configs[variable] if (!value) { throw Error(`Missing required config: ${variable}`) } return value } getOptional(variable: string) { return this.configs[variable] } }
8be1cc59919058a4dd66f326def7474a2b9327ce
TypeScript
yuanhjty/algorithms-in-typescript
/src/singly-linked-list/values.ts
2.921875
3
import ListNode from './list-node'; export default function values<T>(head: ListNode<T>): T[] { let curr = head.next; const result: T[] = []; while (curr) { result.push(curr.value); curr = curr.next; } return result; }
06aa1f4eb9947d88c1ee7c23d4f41f00122658aa
TypeScript
abdulbeard/frogger
/src/app/models/Game.ts
2.6875
3
export class Game { lives: number; extra: number; level: number; score: number; posX: number; posY: number; facing: string; log: number; current: number; highest: number; dead: number; win: number; won: Array<any>; constructor() { this.lives = 5; this.extra = 0; this.level = 1; this.score = 0; this.posX = 187; this.posY = 503; this.facing = 'u'; this.log = -1; this.current = -1; this.highest = -1; this.dead = -1; this.win = -1; this.won = [false, false, false, false, false]; } reset() { this.posY = 503; this.posX = 187; this.facing = 'u'; this.log = -1; this.current = -1; this.highest = -1; this.dead = -1; this.win = -1; } }