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
|
|---|---|---|---|---|---|---|
d563ef7c861d81b073e2ee1de6d4b2d1f0b94e67
|
TypeScript
|
jjPlusPlus/not-trello
|
/src/actions/columns.ts
| 2.78125
| 3
|
import * as constants from "../constants";
import { Card, Column } from "../types";
export interface NewColumn {
type: constants.NEW_COLUMN;
}
export interface AddColumn {
type: constants.ADD_COLUMN;
payload: {
name: string;
};
}
export interface RemoveColumn {
type: constants.REMOVE_COLUMN;
payload: {
id: string;
};
}
export interface MoveColumn {
type: constants.MOVE_COLUMN;
payload: {
column: Column;
direction: string;
};
}
export interface UpdateColumn {
type: constants.UPDATE_COLUMN;
payload: {
id: string;
column: string;
};
}
export type ColumnAction =
| NewColumn
| AddColumn
| RemoveColumn
| MoveColumn
| UpdateColumn;
export const newColumn = () => ({
type: "NEW_COLUMN",
});
export const addColumn = (name: string) => ({
type: "ADD_COLUMN",
payload: name,
});
export const removeColumn = (id: string) => ({
type: "REMOVE_COLUMN",
payload: id,
});
export const moveColumn = (column: Column, direction: string) => ({
type: "MOVE_COLUMN",
payload: { column, direction },
});
export const updateColumn = (id: string, column: string) => ({
type: "UPDATE_COLUMN",
payload: { id, column},
});
|
ae6f8c7c048e14c7545902d886909fcb2567416b
|
TypeScript
|
arknotts/TypeScript-Angular-Utilities
|
/source/services/test/mockAsync.tests.ts
| 2.828125
| 3
|
import { Observable } from 'rxjs';
import { mock, IMockedRequest } from './mockAsync';
import { rlFakeAsync } from './fakeAsync';
interface ITestType {
value: number;
}
interface ITestDataService {
request1: IMockedRequest<ITestType>;
request2: IMockedRequest<ITestType>;
}
describe('mockAsync', () => {
it('should create a request that resolves when flushed', rlFakeAsync(() => {
let mockedObservable: IMockedRequest<ITestType> = mock.request({ value: 10 });
mockedObservable()
.subscribe((result: ITestType) => {
expect(result.value).to.equal(10);
});
mockedObservable.flush();
}));
it('should create a request that resolves with dynamic content when flushed', rlFakeAsync(() => {
let mockedObservable: IMockedRequest<ITestType> = mock.request((value1: number, value2: number) => {
return { value: value1 + value2 };
});
mockedObservable(5, 3)
.subscribe((result: ITestType) => {
expect(result.value).to.equal(8);
});
mockedObservable.flush();
}));
it('should create a request that is rejected', rlFakeAsync(() => {
let mockedObservable: IMockedRequest<ITestType> = mock.rejectedRequest<ITestType>(new Error('an error'));
mockedObservable()
.subscribe(() => {
assert.fail(null, null, 'Request should be rejected, not resolved');
}, (error: Error) => {
expect(error.message).to.equal('an error');
});
mockedObservable.flush();
}));
it('should create a request and set it to be rejected', rlFakeAsync(() => {
let mockedObservable: IMockedRequest<ITestType> = mock.request<ITestType>({ value: 3 });
mockedObservable.reject(new Error('error message'));
mockedObservable()
.subscribe(() => {
assert.fail(null, null, 'Observable should be rejected, not resolved');
}, (error: Error) => {
expect(error.message).to.equal('error message');
});
mockedObservable.flush();
}));
it('should be able to reuse mocked requests', rlFakeAsync(() => {
let mockedObservable: IMockedRequest<ITestType> = mock.request<ITestType>({ value: 3 }, true);
mockedObservable()
.subscribe((result1: ITestType) => {
expect(result1.value).to.equal(3);
mockedObservable()
.subscribe((result2: ITestType) => {
expect(result2.value).to.equal(3);
});
mockedObservable.flush();
});
mockedObservable.flush();
}));
it('should allow unique parameters with successive calls', rlFakeAsync(() => {
let mockedObservable: IMockedRequest<ITestType> = mock.request((value1: number, value2: number) => {
return { value: value1 + value2 };
}, true);
mockedObservable(5, 3)
.subscribe((result: ITestType) => {
expect(result.value).to.equal(8);
mockedObservable(8, 2)
.subscribe((result: ITestType) => {
expect(result.value).to.equal(10);
});
mockedObservable.flush();
});
mockedObservable.flush();
}));
it('should reuse a pending request when sharing', (): void => {
let mockedObservable: IMockedRequest<ITestType> = mock.request({ value: 3 }, true);
expect(mockedObservable()).to.equal(mockedObservable());
});
it('should not reuse a pending request by default or not sharing', (): void => {
let mockedObservable: IMockedRequest<ITestType> = mock.request({ value: 3 });
expect(mockedObservable()).to.not.equal(mockedObservable());
mockedObservable = mock.request({ value: 3 }, false);
expect(mockedObservable()).to.not.equal(mockedObservable());
});
it('should flush all requests on an unshared mock request', rlFakeAsync((): void => {
let mockedObservable: IMockedRequest<number> = mock.request(result => result);
Observable.forkJoin<number[]>([
mockedObservable(5),
mockedObservable(10),
]).subscribe(([result1, result2]: number[]): void => {
expect(result1).to.equal(5);
expect(result2).to.equal(10);
});
mockedObservable.flush();
}));
it('should spy on the request function', (): void => {
let mockedObservable: IMockedRequest<ITestType> = mock.request({ value: 3 });
mockedObservable(6);
sinon.assert.calledOnce(mockedObservable);
sinon.assert.calledWith(mockedObservable, 6);
});
it('should flush all request on an object', rlFakeAsync((): void => {
let service: ITestDataService = {
request1: mock.request({ value: 3 }),
request2: mock.request({ value: 4 }),
};
Observable.forkJoin<ITestType[]>([
service.request1(),
service.request2(),
]).subscribe(([result1, result2]: ITestType[]): void => {
expect(result1.value).to.equal(3);
expect(result2.value).to.equal(4);
});
mock.flushAll(service);
}));
it('should work with Observable.from and Observable.forkJoin', rlFakeAsync((): void => {
const mockedObservables: IMockedRequest<number>[] = [
mock.request(5),
mock.request(10),
];
const whens: Observable<number>[] = mockedObservables.map((mocked: IMockedRequest<number>) => Observable.from(mocked()));
Observable.forkJoin<number[]>(whens).subscribe(([result1, result2]: number[]): void => {
expect(result1).to.equal(5);
expect(result2).to.equal(10);
});
mock.flushAll(mockedObservables);
}));
it('should work with toPromise', rlFakeAsync((): void => {
let mockedObservable: IMockedRequest<ITestType> = mock.request({ value: 10 });
mockedObservable()
.toPromise()
.then((result: ITestType) => {
expect(result.value).to.equal(10);
});
mockedObservable.flush();
}));
});
|
a395559ce9491e7f4ec164cbf82ba310eca0868b
|
TypeScript
|
darky/Nothing
|
/index.d.ts
| 2.78125
| 3
|
interface INothing {
(): INothing;
(p1: any): INothing;
(p1: any, p2: any): INothing;
(p1: any, p2: any, p3: any): INothing;
(p1: any, p2: any, p3: any, p4: any): INothing;
(p1: any, p2: any, p3: any, p4: any, p5: any): INothing;
(p1: any, p2: any, p3: any, p4: any, p5: any, p6: any): INothing;
(p1: any, p2: any, p3: any, p4: any, p5: any, p6: any, p7: any): INothing;
(p1: any, p2: any, p3: any, p4: any, p5: any, p6: any, p7: any, p8: any): INothing;
(p1: any, p2: any, p3: any, p4: any, p5: any, p6: any, p7: any, p8: any, p9: any): INothing;
(p1: any, p2: any, p3: any, p4: any, p5: any, p6: any, p7: any, p8: any, p9: any, p10: any): INothing;
[key: string]: INothing;
}
interface IFunctionProps {
length: 0;
name: string;
prototype: object;
toLocaleString(): "";
toString(): "";
valueOf(): false;
}
declare function toBool <T>(p: T): T extends INothing ? false : boolean;
declare function isNothing <T>(p: T): T extends INothing ? true : false;
declare function isSomething <T>(p: T): T extends INothing | null | void ? false : true;
declare function serialize (p: object): string;
declare function deserialize (p: string): object;
declare const Nothing: IFunctionProps & INothing;
export { Nothing, toBool, isNothing, isSomething, serialize, deserialize };
|
a8dcfad231c7ee14e6979d8940cafd458a4c59d8
|
TypeScript
|
GoogleChrome/workbox
|
/packages/workbox-webpack-plugin/src/lib/get-asset-hash.ts
| 2.59375
| 3
|
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import crypto from 'crypto';
import type {Asset} from 'webpack';
/**
* @param {Asset} asset
* @return {string} The MD5 hash of the asset's source.
*
* @private
*/
export function getAssetHash(asset: Asset): string | null {
// If webpack has the asset marked as immutable, then we don't need to
// use an out-of-band revision for it.
// See https://github.com/webpack/webpack/issues/9038
if (asset.info && asset.info.immutable) {
return null;
}
return crypto.createHash('md5')
.update(Buffer.from(asset.source.source()))
.digest('hex');
}
|
fe3902dcc22410e72b65df4719fdc0b5204badb8
|
TypeScript
|
tylerhubert/rsql-criteria-typescript
|
/src/files/rsql-criteria.ts
| 3
| 3
|
import { RSQLFilterList } from './rsql-filter-list';
import { RSQLOrderByList } from './rsql-order-by-list';
import { RSQLBuildOptions } from './rsql-build-options';
/**
* Main class for bringing together API filtering, sorting and pagination.
*/
export class RSQLCriteria {
public orderBy: RSQLOrderByList;
public filters: RSQLFilterList;
public pageSize?: number;
public includeTotalCount = true;
public pageNumber?: number;
constructor(
private whereKeyword: string = '$where',
private orderByKeyword: string = '$orderBy',
private pageSizeKeyword: string = '$pageSize',
private includeTotalCountKeyword: string = '$includeTotalCount',
private pageNumberKeyword: string = '$pageNumber'
) {
this.filters = new RSQLFilterList();
this.orderBy = new RSQLOrderByList();
}
/**
* Brings together the two criteria filters, ignoring the order by and pagination
* from the passed in criteria. Only keeps it from the original RSQLCriteria.
*/
public and(criteria2: RSQLCriteria): void {
this.filters.and(criteria2.filters);
}
/**
* Brings together the two criteria filters, ignoring the order by and pagination
* from the passed in criteria. Only keeps it from the original RSQLCriteria.
*/
public or(criteria2: RSQLCriteria): void {
this.filters.or(criteria2.filters);
}
/**
* Builds the query string that will be needed to send down to the server side API.
* Combines the keywords with their appropriate clauses to create the string.
*/
public build(options: RSQLBuildOptions = { encodeString: true }): string {
const queryStringParts: string[] = [];
const whereClause = this.filters.build(options);
if (whereClause !== '') {
queryStringParts.push(`${this.whereKeyword}=${whereClause}`);
}
const orderByClause = this.orderBy.build();
if (orderByClause !== '') {
queryStringParts.push(`${this.orderByKeyword}=${orderByClause}`);
}
if (this.pageSize !== undefined) {
queryStringParts.push(`${this.pageSizeKeyword}=${this.pageSize}`);
if (this.includeTotalCount) {
queryStringParts.push(`${this.includeTotalCountKeyword}=true`);
}
}
if (this.pageNumber !== undefined) {
queryStringParts.push(`${this.pageNumberKeyword}=${this.pageNumber}`);
}
return queryStringParts.join('&');
}
}
|
68785522a5948ddc2856bbec33759f8c8650e76e
|
TypeScript
|
thomas-crane/sgml
|
/src/syntax/syntax-kind.ts
| 2.59375
| 3
|
export enum SyntaxKind {
// tokens
FirstToken,
EOF,
Unknown,
// literals
IntLiteral,
RealLiteral,
HexLiteral,
StringLiteral,
Identifier,
TrueLiteral,
FalseLiteral,
// misc
Dot,
Semicolon,
Colon,
Comma,
Bang,
QuestionMark,
Hash,
At,
// variables
Equals,
PlusEquals,
MinusEquals,
StarEquals,
// arithmetic
Plus,
PlusPlus,
Minus,
MinusMinus,
Star,
Slash,
Percent,
// comparison
LessThan,
LessThanEquals,
EqualsEquals,
BangEquals,
GreaterThan,
GreaterThanEquals,
// bitwise
Ampersand,
Pipe,
AmpersandAmpersand,
PipePipe,
Caret,
CaretCaret,
LessThanLessThan,
GreaterThanGreaterThan,
Tilde,
// parens
LeftParenthesis,
RightParenthesis,
LeftCurlyBracket,
RightCurlyBracket,
LeftBracket,
RightBracket,
// keywords
Var,
Mod,
Div,
If,
Else,
Repeat,
While,
Do,
Until,
For,
Continue,
Switch,
Case,
Break,
Default,
Exit,
With,
Enum,
Return,
LastToken,
// trivia
FirstTrivia,
LineComment,
BlockComment,
Whitespace,
LastTrivia,
// statements
FirstStatement,
TerminatedStatement,
ExpressionStatement,
BlockStatement,
LocalDeclarationListStatement,
IfStatement,
RepeatStatement,
WhileStatement,
BreakStatement,
ContinueStatement,
ExitStatement,
DoStatement,
ForStatement,
SwitchStatement,
CaseStatement,
DefaultStatement,
WithStatement,
ReturnStatement,
LastStatement,
// expressions
FirstExpression,
IntLiteralExpression,
HexLiteralExpression,
RealLiteralExpression,
BoolLiteralExpression,
StringLiteralExpression,
BinaryExpression,
UnaryExpression,
PostfixExpression,
PrefixExpression,
ParenthesisedExpression,
IdentifierExpression,
PropertyAccessExpression,
ArrayIndexExpression,
CallExpression,
ListAccessExpression,
MapAccessExpression,
GridAccessExpression,
ArrayAccessExpression,
LastExpression,
}
|
dec44f63c94987c2dc1dd952067d3a7fdef49a17
|
TypeScript
|
christinebelle/MaxTodoListe
|
/src/app/service/dataliste.service.ts
| 2.578125
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { Projet } from '../modeles/Projet';
import {map} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DatalisteService {
public projetliste: Projet[];
projetliste$: BehaviorSubject<Projet[]> = new BehaviorSubject(this.projetliste);
constructor(private httpClient: HttpClient) { }
public getListeProjet(): Observable<Projet[]> {// l'observable verfifie le type et le delais de retour
return this.httpClient.get<Projet[]>('http://localhost:8080/liste');// interprete le retour JSON et lance un observable
}
public publishListes() {
this.getListeProjet().subscribe(lesprojets => {
this.projetliste = lesprojets;
this.projetliste$.next(this.projetliste);
});
}
/**
* fonction qui permet de chercher un projet dans la liste suivant son id
* @param idListe
* @return Observable<Todoliste>
*/
public findListe(id: number): Observable<Projet> {
if(id) {
if (!this.projetliste) {
return this.getListeProjet().pipe(map(litesprojet => litesprojet.find(projet => projet.idListe === id)));
}
return of(this.projetliste.find(projet => projet.idListe === id));
} else {
return of(new Projet(0, '', '', "",new Date()))
}
}
/**
* fonction de création d'un projet dans la bdd, et qui rajoute un projet a la liste afin de creer
* un affichage dynamique
* @param projetCreate
*/
public createListe(projetCreate: Projet) {
this.httpClient.post<Projet>('http://localhost:8080/ajouter', projetCreate).subscribe(
newProjet => {
this.projetliste.push(newProjet);
this.projetliste$.next(this.projetliste);
});
}
/**
* fonction de modification d'un projet dans la bdd et dans la liste afin de creer une affichage dynamique
* @param projetUpdate
*/
public updateListe(projetUpdate: Projet) {
this.httpClient.put<Projet>('http://localhost:8080/modifier',projetUpdate).subscribe(
updatedProjet => {
const index = this.projetliste.findIndex(projet => {
if (projet.idListe === updatedProjet.idListe) {
return true;
}
});
this.projetliste[index] = updatedProjet;
this.projetliste$.next(this.projetliste);
});
}
/**
* fonction de suppression d'un projet dans la bdd et dans la liste afin de creer un affichage dynamique
* @param idListe
*/
public deleteListe(idListe: number) {
this.httpClient.delete('http://localhost:8080/supprime/' + idListe).subscribe(
()=> {
const index = this.projetliste.findIndex(projet => {
if (projet.idListe === idListe) {
return true;
}
},
(error)=>{
console.log("error", error);
});
this.projetliste.splice(index, 1);
this.projetliste$.next(this.projetliste);
});
}
}
|
6bbeb9ca3bb0cc33000264cf4fc0d97f525e05c7
|
TypeScript
|
jubran/demo-react-redux-saga-ts
|
/src/components/login/loginReducer.ts
| 2.84375
| 3
|
import {ActiveUserType} from "./LoginTypes";
import {LOGIN_FAIL, LoginReducerActionTypes} from "./loginActionTypes";
const defaultLoginState: ActiveUserType = {
isLoginFailed: false
};
export const loginReducer = (state = defaultLoginState, action: LoginReducerActionTypes): ActiveUserType => {
switch (action.type) {
case LOGIN_FAIL:
return {
...state,
isLoginFailed: true
};
default:
return {
...state
}
}
};
|
85e215113bdec19228ae5c105e9f90f86289dbd2
|
TypeScript
|
riiiiion/spotify-mix-automation
|
/lib/type/handler.ts
| 2.78125
| 3
|
import type { NextApiRequest, NextApiResponse } from 'next';
interface SessionContent {
userId: string,
accessToken: string
refreshToken?: string,
authedTs: string,
expiresIn: number,
}
interface Request<T> extends NextApiRequest {
body: T,
session: {
set: (
name: string,
body: SessionContent
) => void,
save: () => Promise<void>,
get: (name: string) => SessionContent,
destroy: () => Promise<void>
}
}
interface Response<U> extends NextApiResponse {
json: (param: U) => void
}
export type ApiHandler<T, U> = (req: Request<T>, res: Response<U>) => Promise<void> | void;
|
8df813341660793c1f9566df88dd50ad5bab5cac
|
TypeScript
|
Gaubee/Simple-OMS
|
/src/app/md-dev-com/core/portal/portal-errors.ts
| 3.0625
| 3
|
import {MdError} from '../errors/error';
/** Exception thrown when attempting to attach a null portal to a host. */
export class MdNullPortalError extends MdError {
constructor() {
super('Must provide a portal to attach');
}
}
/** Exception thrown when attempting to attach a portal to a host that is already attached. */
export class MdPortalAlreadyAttachedError extends MdError {
constructor() {
super('Host already has a portal attached');
}
}
/** Exception thrown when attempting to attach a portal to an already-disposed host. */
export class MdPortalHostAlreadyDisposedError extends MdError {
constructor() {
super('This PortalHost has already been disposed');
}
}
/** Exception thrown when attempting to attach an unknown portal type. */
export class MdUnknownPortalTypeError extends MdError {
constructor() {
super(
'Attempting to attach an unknown Portal type. ' +
'BasePortalHost accepts either a ComponentPortal or a TemplatePortal.');
}
}
/** Exception thrown when attempting to attach a portal to a null host. */
export class MdNullPortalHostError extends MdError {
constructor() {
super('Attempting to attach a portal to a null PortalHost');
}
}
/** Exception thrown when attempting to detach a portal that is not attached. */
export class MdNoPortalAttachedError extends MdError {
constructor() {
super('Attempting to detach a portal that is not attached to a host');
}
}
|
1d7ebd79eed159b6277af871252b1975e247c9f4
|
TypeScript
|
PaulKovalov/codehub-frontend
|
/src/app/accounts/userform-utils.ts
| 2.671875
| 3
|
import { FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
export interface FormControlError {
control: string;
error: string;
value: any;
}
export function getFormValidationErrors(form: FormGroup) {
const result: FormControlError | ValidationErrors[] = [];
if (form.errors) {
result.push(form.errors);
}
Object.keys(form.controls).forEach(key => {
const control = form.get(key);
if (control !== null) {
const errors = control.errors;
if (errors) {
Object.keys(errors).forEach(keyError => {
result.push({
control: key,
error: keyError,
value: errors[keyError]
});
});
}
}
});
return result;
}
export function sortErrors(controlErrorsOrder, errors: ValidationErrors[]) {
function compareErrors(a: FormControlError, b: FormControlError): number {
return controlErrorsOrder[b.control] - controlErrorsOrder[a.control];
}
errors.sort(compareErrors);
}
export const passwordMatchValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
const newPassword = control.get('password');
const confirmNewPassword = control.get('confirmPassword');
return newPassword && confirmNewPassword && newPassword.value !== confirmNewPassword.value ? {passwordMatchValidator: true} : null;
};
|
5dcb700bda2a02ae749f0ba61155536674351f18
|
TypeScript
|
adjust/web_sdk
|
/src/sdk/smart-banner/utilities.ts
| 3.21875
| 3
|
/**
* Wraps JSON.parse() with try-catch.
* Returns parsed object if successfully parsed and null otherwise.
*/
export function parseJson(str?: string | null): any {
if (!str) {
return null
}
try {
return JSON.parse(str)
} catch (error) {
return null
}
}
|
49bbd8e3a8b2bbd57ac7b2a0fb202394780e6367
|
TypeScript
|
elJuanjoRamos/-OLC2-Proyecto-1
|
/src/app/jison/tools/sentences/Call.ts
| 2.65625
| 3
|
import { Console } from './Console';
import { TablaSimbolosController } from 'src/app/components/controller/tablasimbolo.conroller';
import { Expression } from '../abstract/expression';
import { Instruction } from '../abstract/instruction';
import { Ambit } from '../id/ambit.identifier';
import { Literal } from '../expression/Literal';
export class Call extends Instruction {
public id: string;
public expresiones: Array<Expression> = new Array();
public row:number;
public column: number;
constructor( i:string, ex : Array<Expression>, r: number, c: number ){
super(r, c);
this.id = i;
this.expresiones = ex;
this.row = r;
this.column = c;
}
public exec(ambit : Ambit) {
if (this.id.includes("graficar_ts")) {
var tempo: any[] = TablaSimbolosController.getInstance().variablesByAmbit(ambit.getName())
if (tempo != []) {
this.printAmbit("========== " + ambit.getName() + " AMBIT ==========")
this.printAmbit("Nombre |Tipo |Ambito |Valor |Retorno |Vari |Func");
for (let i = 0; i < tempo.length; i++) {
const element = tempo[i];
var temp = element.getName() + " |" + element.getType() + " |" + element.getAmbit()+ " |" + element.getValue() + " |" + element.getReturned() + " |" + element.getVariable() + " |" + element.getFuncion()
this.printAmbit( temp );
}
this.printAmbit("========== END AMBIT ==========")
}
} else {
var ambitName = "Function_"+this.id;
var func = ambit.getFunc(this.id);
if(func != undefined){
const newEnv = new Ambit(ambit.getGlobal(), ambitName);
for(let i = 0; i < this.expresiones.length; i++){
const value = this.expresiones[i].exec(ambit);
newEnv.save(func.params[i], value.value, value.type, false);
}
if (func.sentecias != null) {
func.sentecias.exec(newEnv);
}
}
}
}
public printAmbit(texto: string){
var lit = new Literal(texto, 0,0,1);
var temp = new Console(lit, 0, 0);
temp.exec(null);
}
}
|
81ec061ad8f65fefa8486727579d89393b5eaf9f
|
TypeScript
|
wildex999/Derange.io
|
/src/common/sync/syncobject.ts
| 3.328125
| 3
|
/**
* Place as decorator on properties to sync which are an object.
* The object type to sync must have a @SyncedObject placed on it.
* They are essentially groups of synced properties.
*/
export function SyncObject(target: any, key: string) {
//TODO: Same as Sync, but should call the target's Encode/Decode method
let _val = target[key];
let getter = function() {
//console.log("Get: " + key + " = " + _val);
return _val;
};
let setter = function(value) {
//console.log("Set: " + key + " = " + value + " | " + this);
_val = value;
//Mark as changed in the class instance
this.syncHasChanged = true;
this.syncChanged[key] = true;
};
let encode = function(): string {
//console.log("Encode: " + _val + " => " + JSON.stringify(_val));
return JSON.stringify(_val);
};
let decode = function(value: string): any {
//console.log("Decode: " + value + " => " + JSON.parse(value));
return JSON.parse(value);
};
if(!target.sync)
target.sync = {}; //List of all synced properties
target.sync[key] = null;
target["syncEncode_" + key] = encode;
target["syncDecode_" + key] = decode;
//Delete the original property so we can replace with a getter/setter
delete target[key];
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
|
2104d6cdd6a0a218efad9ce342906b3b9def40d4
|
TypeScript
|
haohaaorg/frontend-dataform
|
/src/store.ts
| 2.640625
| 3
|
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
import rootReducer from "./reducers";
const initialState = {};
const middleware = [thunk];
const store = createStore(
rootReducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
// set up a store subscription listener
// to store the users token in localStorage
// initialize current state from redux store for subscription comparison
// preventing undefined error
let currentState = store.getState();
store.subscribe(() => {
// keep track of the previous and current state to compare changes
let previousState = currentState;
currentState = store.getState();
// if the token changes set the value in localStorage and axios headers
if (previousState.auth.token !== currentState.auth.token) {
const token = currentState.auth.token;
// setAuthToken(token);
}
});
export default store;
|
fe43f2f78429603a2976d4aaee342ef7cbe5ca17
|
TypeScript
|
shakya008/data-prefetch
|
/src/producer.ts
| 2.90625
| 3
|
/**
* This is an abstract class with one method as abstract.
* fetchdata() should be implemented by integration class whitch has implementation to fetch data
* from destination resource like server.
* @author Shyam Singh<singh.shakya008@gmail.com>
*/
import { Observable } from 'rxjs/Observable';
export abstract class ProducerService {
/**
* This flag indicates whether prefetch service should call the method fetchdata().
* When this flag get set to true then, prefetch service will not call for server because as it indicates,
* server has provided all the data.
* Prefetch will provide data if any present in the queue or blank array.
*/
private _noServe: boolean;
constructor() {
this._noServe = false;
}
/**
* This method set the noServe variable.
*/
public setNoServe(val: boolean) {
this._noServe = !!val;
}
/**
* Returns the current status of no serve
*/
public getNoServeStatus(): boolean {
return this._noServe;
}
public abstract fetchData(): Observable<any>;
}
|
bb61128716605e85be67d0c402a3d7a97055b13b
|
TypeScript
|
yorni/indicators
|
/lib/src/providers/percent-rank.d.ts
| 2.515625
| 3
|
/**
* Returns the percentile of a value. Returns the same values as the Excel PERCENTRANK and PERCENTRANK.INC functions.
*/
export declare class PercentRank {
private period;
private values;
private fill;
constructor(period: number);
nextValue(value: number): number;
momentValue(value: number): number;
private calc;
}
|
e2fd38c2692ea251125008dd3c5f77a588639013
|
TypeScript
|
Ciantic/model-validation
|
/test/example-with-typescript.ts
| 3.03125
| 3
|
import * as V from '../index';
interface Address {
city : string
street : string
}
var addressValidator = V.object<Address>({
city : V.required(V.string),
street : V.string,
});
interface User {
id: number
name: string
email: string
address: Address
}
var userValidator = V.object<User>({
id : V.integer,
name : V.required(V.string),
email : V.string,
address : addressValidator
});
userValidator.validate({
id : 5,
name : "Jack Doe",
email : "jack@example.com",
address: {
city : "Philly",
street : "Homestreet 123"
}
}).then((v) => {
// v is validated object
}).catch((errs) => {
// errs is object of errors {[name: string] : string[]}
});
|
efa57effb29080b3347f0082af27e5f1fab3e5a9
|
TypeScript
|
pmill/ml-ui
|
/src/app/core/models/abstract.model.ts
| 2.640625
| 3
|
import {Model} from './model.interface';
import {getMetadataMap} from './decorators/model-decorators.helpers';
export class AbstractModel implements Model {
fillFromApiResponseData(apiResponseData: Object): void {
getMetadataMap(this).forEach((propertyMetadata, propertyKey) => {
const apiKey = propertyMetadata.apiKey;
if (apiResponseData.hasOwnProperty(propertyMetadata.apiKey)) {
this[propertyKey.valueOf()] = apiResponseData[propertyMetadata.apiKey];
}
});
}
}
|
aadb7cb5743c73ce2219078c6748e44b0b5a858c
|
TypeScript
|
alepim-dev/NLW-Together
|
/src/services/CreateUserService.ts
| 2.859375
| 3
|
import { getCustomRepository } from "typeorm";
import { UserRepositories } from "../repositories/UsersRepositories";
import{hash} from"bcryptjs";
interface IUserRequest{
name:string;
email:string;
password:string;
admin?: boolean;
}
class CreatUserService{
async execute({name,email,admin=false,password}:IUserRequest){
const usersRepository = getCustomRepository(UserRepositories);
if(!email) {
throw new Error ("Email incorrect");
}
const userAlreadyExists = await usersRepository.findOne({
email,
});
if(userAlreadyExists){
throw new Error("User alrady exists");
}
const passwordhash = await hash(password,8);
const user= usersRepository.create(
{name,email,admin,password:passwordhash}
);
await usersRepository.save(user);
return user;
}
}
export {CreatUserService};
|
8b1015de0be501845f912d1cda09fd3c1a7916a7
|
TypeScript
|
nosteiner/four-in-a-row
|
/src/app/models/Player.ts
| 2.984375
| 3
|
import { Color } from './Color';
export class Player {
id: Number;
isTurn: Boolean;
color: Color;
constructor(id, color) {
this.id = id;
this.isTurn = false;
this.color = color;
}
changeTurn() {
this.isTurn = !this.isTurn;
}
}
|
57bac391e90e3670e64ba202747da93351e243a3
|
TypeScript
|
mariusmoe/polling-stations
|
/client/src/app/services/search.service.ts
| 2.875
| 3
|
import {
HttpClient,
HttpErrorResponse,
HttpHeaders,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { throwError } from 'rxjs';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
@Injectable({
providedIn: 'root',
})
export class SearchService {
constructor(private http: HttpClient) {}
private data = new BehaviorSubject<any>([{}]);
getData() {
return this.data;
}
search(searchParam: any): void {
this.http
.post<any>('http://localhost:4000/api/search', searchParam, httpOptions)
.subscribe(
(data) => {
console.log(data);
this.data.next(Object.assign([], data));
},
(error) => this.handleError(error)
);
}
/**
* From the angular documentation
*
* Try to make sense of the error
* @param error the error thrown
*/
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong.
console.error(
`Backend returned code ${error.status}, ` + `body was: ${error.error}`
);
}
// Return an observable with a user-facing error message.
return throwError('Something bad happened; please try again later.');
}
}
|
7a047795c4fbc28fe3933c3c12eaeefd6c27a992
|
TypeScript
|
kronick/race-playback
|
/src/utilities/vessel-data.test.ts
| 2.984375
| 3
|
import { interpolatePosition } from "./vessel-data";
import { PositionsArray } from "../shared-types/race-data";
// Fixtures
const twoPointsFixture = (): PositionsArray => [
{ timestamp: 0, coordinates: [0, 0], heading: 0, speed: 0 },
{ timestamp: 1, coordinates: [1, 1], heading: 1, speed: 0 }
];
const threePointsFixture = (): PositionsArray => [
{ timestamp: 0, coordinates: [0, 0], heading: 0, speed: 0 },
{ timestamp: 1, coordinates: [1, 4], heading: 1, speed: 0 },
{ timestamp: 2, coordinates: [2, 2], heading: 2, speed: 0 }
];
const fourPointsFixture = (): PositionsArray => [
{ timestamp: 0, coordinates: [0, 0], heading: 0, speed: 0 },
{ timestamp: 1, coordinates: [1, 4], heading: 1, speed: 0 },
{ timestamp: 2, coordinates: [2, 2], heading: 2, speed: 0 },
{ timestamp: 3, coordinates: [3, 3], heading: 3, speed: 0 }
];
const manyPointsFixture = (): PositionsArray => [
{ timestamp: 0, coordinates: [0, 0], heading: 0, speed: 0 },
{ timestamp: 1, coordinates: [1, 100], heading: 1, speed: 0 },
{ timestamp: 2, coordinates: [2, 2], heading: 2, speed: 0 },
{ timestamp: 3, coordinates: [3, 3], heading: 3, speed: 0 },
{ timestamp: 4, coordinates: [4, 4], heading: 4, speed: 0 },
{ timestamp: 5, coordinates: [5, 5], heading: 5, speed: 0 },
{ timestamp: 6, coordinates: [6, 6], heading: 6, speed: 0 }
];
describe("Position interpolator", () => {
it("works with two point paths", () => {
expect(interpolatePosition(0, twoPointsFixture())?.coordinates).toEqual([
0,
0
]);
expect(interpolatePosition(1, twoPointsFixture())?.coordinates).toEqual([
1,
1
]);
expect(
interpolatePosition(0.5, twoPointsFixture())?.coordinates[0]
).toBeCloseTo(0.5);
expect(
interpolatePosition(0.5, twoPointsFixture())?.coordinates[1]
).toBeCloseTo(0.5);
});
it("works with three point paths", () => {
expect(interpolatePosition(0, threePointsFixture())?.coordinates).toEqual([
0,
0
]);
expect(interpolatePosition(1, threePointsFixture())?.coordinates).toEqual([
1,
4
]);
expect(interpolatePosition(2, threePointsFixture())?.coordinates).toEqual([
2,
2
]);
expect(
interpolatePosition(0.5, threePointsFixture())?.coordinates[0]
).toBeCloseTo(0.5);
expect(
interpolatePosition(0.5, threePointsFixture())?.coordinates[1]
).toBeCloseTo(2);
expect(
interpolatePosition(1.5, threePointsFixture())?.coordinates[0]
).toBeCloseTo(1.5);
expect(
interpolatePosition(1.5, threePointsFixture())?.coordinates[1]
).toBeCloseTo(3);
});
it("works with four point paths", () => {
expect(interpolatePosition(0, fourPointsFixture())?.coordinates).toEqual([
0,
0
]);
expect(interpolatePosition(1, fourPointsFixture())?.coordinates).toEqual([
1,
4
]);
expect(interpolatePosition(2, fourPointsFixture())?.coordinates).toEqual([
2,
2
]);
expect(
interpolatePosition(0.5, fourPointsFixture())?.coordinates[0]
).toBeCloseTo(0.5);
expect(
interpolatePosition(0.5, fourPointsFixture())?.coordinates[1]
).toBeCloseTo(2);
expect(
interpolatePosition(2.5, fourPointsFixture())?.coordinates[0]
).toBeCloseTo(2.5);
expect(
interpolatePosition(2.5, fourPointsFixture())?.coordinates[1]
).toBeCloseTo(2.5);
});
it("works with many point paths", () => {
expect(interpolatePosition(0, manyPointsFixture())?.coordinates).toEqual([
0,
0
]);
expect(interpolatePosition(1, manyPointsFixture())?.coordinates).toEqual([
1,
100
]);
expect(interpolatePosition(2, manyPointsFixture())?.coordinates).toEqual([
2,
2
]);
expect(interpolatePosition(6, manyPointsFixture())?.coordinates).toEqual([
6,
6
]);
expect(interpolatePosition(3, manyPointsFixture())?.coordinates).toEqual([
3,
3
]);
expect(
interpolatePosition(0.5, manyPointsFixture())?.coordinates[0]
).toBeCloseTo(0.5);
expect(
interpolatePosition(0.5, manyPointsFixture())?.coordinates[1]
).toBeCloseTo(50);
expect(
interpolatePosition(1.5, manyPointsFixture())?.coordinates[0]
).toBeCloseTo(1.5);
expect(
interpolatePosition(1.5, manyPointsFixture())?.coordinates[1]
).toBeCloseTo(51);
});
it("returns null for out-of-bounds times", () => {
expect(interpolatePosition(-1, twoPointsFixture())).toBe(null);
expect(interpolatePosition(10, twoPointsFixture())).toBe(null);
expect(interpolatePosition(-1, threePointsFixture())).toBe(null);
expect(interpolatePosition(10, threePointsFixture())).toBe(null);
});
it("returns null for empty array", () => {
expect(interpolatePosition(0, [])).toBe(null);
expect(interpolatePosition(1, [])).toBe(null);
expect(interpolatePosition(100, [])).toBe(null);
expect(interpolatePosition(-10, [])).toBe(null);
});
});
|
e8edf9aae7a9ebbb168fdeb89985e9248b1e48b5
|
TypeScript
|
MarlonReis/MarvelDeveloper
|
/test/infrastructure/database/orm/repository/user/FindUserAccountByEmailORMRepository.test.ts
| 2.578125
| 3
|
import {
FindUserAccountByEmailORMRepository
} from '@/infrastructure/database/orm/repository/user/FindUserAccountByEmailORMRepository'
import {
MySQLTypeOrmConnection
} from '@/infrastructure/database/orm/connection/MySQLTypeOrmConnection'
import {
CreateUserAccountORMRepository
} from '@/infrastructure/database/orm/repository/user/CreateUserAccountORMRepository'
import { UserOrm } from '@/infrastructure/database/orm/model/UserOrm'
import { StatusUser } from '@/domain/model/user/StatusUser'
import { RepositoryInternalError } from '@/data/error'
import { NotFoundError } from '@/domain/errors'
import { EnvironmentConfiguration } from '@/infrastructure/util/EnvironmentConfiguration'
describe('FindUserAccountByEmailORMRepository', () => {
let connectionDatabase: MySQLTypeOrmConnection
let sut: FindUserAccountByEmailORMRepository
beforeAll(async () => {
const config = EnvironmentConfiguration.database()
connectionDatabase = new MySQLTypeOrmConnection(config)
await connectionDatabase.open()
})
beforeEach(async () => {
sut = new FindUserAccountByEmailORMRepository(connectionDatabase)
await connectionDatabase.connection()
.createQueryBuilder()
.delete()
.from(UserOrm)
.execute()
})
afterAll(async () => {
await connectionDatabase.close()
})
test('should return user account when found by email', async () => {
const createUserAccount = new CreateUserAccountORMRepository(connectionDatabase)
await createUserAccount.execute({
name: 'Any Name', email: 'example@email.com.br', password: 'V4lid@P4ssW0rd'
})
await createUserAccount.execute({
name: 'Other Any Name', email: 'other@example.com.br', password: 'V4lid@P4ssW0rd'
})
const response = await sut.execute('example@email.com.br')
expect(response.isSuccess()).toBe(true)
expect(response.value).toMatchObject({
name: 'Any Name',
email: 'example@email.com.br',
status: StatusUser.CREATED
})
})
test('should return not found when not found register', async () => {
const response = await sut.execute('not_exist@email.com')
expect(response.isFailure()).toBe(true)
expect(response.value).toBeInstanceOf(NotFoundError)
expect(response.value).toMatchObject({
message: "Cannot found account by email equals 'not_exist@email.com'!"
})
})
test('should return same error that orm throws', async () => {
jest.spyOn(connectionDatabase, 'connection')
.mockImplementationOnce(() => { throw new Error('Any operation error') })
sut = new FindUserAccountByEmailORMRepository(connectionDatabase)
const response = await sut.execute('not_exist@email.com')
expect(response.isFailure()).toBe(true)
expect(response.value).toEqual(new RepositoryInternalError(new Error('Any operation error')))
})
})
|
fabbcd3d8e44daf9fe9b8bb0a106a860b8a0abdf
|
TypeScript
|
RobLoach/twing
|
/test/tests/unit/node/expression/test.ts
| 2.640625
| 3
|
import {Test} from "tape";
import TwingMap from "../../../../../src/map";
import TwingNodeExpressionConstant from "../../../../../src/node/expression/constant";
import TwingTestCompilerStub from "../../../../compiler-stub";
import TwingNode from "../../../../../src/node";
import TwingNodeExpressionTest from "../../../../../src/node/expression/test";
import TwingTestEnvironmentStub from "../../../../environment-stub";
import TwingTest from "../../../../../src/test";
import TwingNodeExpressionTestNull from "../../../../../src/node/expression/test/null";
const tap = require('tap');
function twig_tests_test_barbar(string: string, arg1: any = null, arg2: any = null, args: Array<any> = []) {
}
function createTest(node: TwingNode, name: string, args: TwingMap<any, TwingNode> = new TwingMap()) {
return new TwingNodeExpressionTest(node, name, new TwingNode(args), 1);
}
tap.test('node/expression/test', function (test: Test) {
test.test('constructor', function (test: Test) {
let expr = new TwingNodeExpressionConstant('foo', 1);
let name = new TwingNodeExpressionConstant('null', 1);
let args = new TwingNode();
let node = new TwingNodeExpressionTest(expr, name, args, 1);
test.same(node.getNode('node'), expr);
test.same(node.getNode('arguments'), args);
test.same(node.getAttribute('name'), name);
test.end();
});
test.test('compile', function (test: Test) {
let environment = new TwingTestEnvironmentStub();
environment.addTest(new TwingTest('barbar', twig_tests_test_barbar, {is_variadic: true, need_context: true}));
environment.addTest(new TwingTest('anonymous', function () {}));
let compiler = new TwingTestCompilerStub(environment);
test.test('basic', function (test: Test) {
let expr = new TwingNodeExpressionConstant('foo', 1);
let node = new TwingNodeExpressionTestNull(expr, 'null', new TwingNode(new TwingMap()), 1);
test.same(compiler.compile(node).getSource(), '("foo" === null)');
test.end();
});
test.test('test as an anonymous function', function (test: Test) {
let node = createTest(new TwingNodeExpressionConstant('foo', 1), 'anonymous', new TwingMap([
[0, new TwingNodeExpressionConstant('foo', 1)]
]));
test.same(compiler.compile(node).getSource(), 'await this.env.getTest(\'anonymous\').getCallable()(...["foo", "foo"])');
test.end();
});
test.test('arbitrary named arguments', function (test: Test) {
let string = new TwingNodeExpressionConstant('abc', 1);
let node = createTest(string, 'barbar');
test.same(compiler.compile(node).getSource(), 'await this.env.getTest(\'barbar\').getCallable()(...["abc"])');
node = createTest(string, 'barbar', new TwingMap([
['foo', new TwingNodeExpressionConstant('bar', 1)]
]));
test.same(compiler.compile(node).getSource(), 'await this.env.getTest(\'barbar\').getCallable()(...["abc", null, null, ["bar"]])');
node = createTest(string, 'barbar', new TwingMap([
[0, new TwingNodeExpressionConstant('1', 1)],
[1, new TwingNodeExpressionConstant('2', 1)],
[2, new TwingNodeExpressionConstant('3', 1)],
['foo', new TwingNodeExpressionConstant('bar', 1)]
]));
test.same(compiler.compile(node).getSource(), 'await this.env.getTest(\'barbar\').getCallable()(...["abc", "1", "2", ["3", "bar"]])');
test.end();
});
test.end();
});
test.end();
});
|
b0b8c9e4dd89e0ee9b9d6dbe051750add426df44
|
TypeScript
|
Troyan37/recipe-app
|
/src/app/shopping-list/shopping-list.service.ts
| 2.78125
| 3
|
import { Subject } from "rxjs";
import { Ingredient } from "../shared/ingredient.model";
export class ShoppingListService {
shoppingItemAdded = new Subject<Ingredient[]>();
private ingredients : Ingredient[] = [
new Ingredient('Apples', 5),
new Ingredient('Tomates', 4)
];
addIngredient(newShoppingItem : Ingredient){
this.ingredients.push(newShoppingItem);
this.shoppingItemAdded.next(this.ingredients);
}
addIngredients(newShoppingItems : Ingredient[]) {
// newShoppingItems.forEach(
// (item)=>{
// this.addIngredient(item);
// }
// )
this.ingredients.push(...newShoppingItems);
this.shoppingItemAdded.next(this.ingredients);
}
getIngredients() {
return this.ingredients.slice();
}
}
|
1cde28cf7ac0a043ebb4d50f9f231440039d4622
|
TypeScript
|
lodka17/uchi-ru
|
/src/api/API.types.ts
| 2.625
| 3
|
type Method = (url: string, payload?: object, queryParams?: object) => Promise<any>
export interface MethodDescriptor extends PropertyDescriptor {
value?: Method | undefined
}
export namespace Endpoint {
export type Id = number
export type Body = string
}
export interface IInstanceAPI {
readonly endpoint: string
}
|
201a0a18426e2324442a44877bd155d54d460996
|
TypeScript
|
birdofpreyru/react-global-state
|
/__tests__/ts-types/GlobalState/get.ts
| 3.1875
| 3
|
import { expectError, expectType } from 'tsd-lite';
import GlobalState from 'src/GlobalState';
type ValueT = 'value-a' | 'value-b';
type StateT1 = {
some: {
path: ValueT;
};
};
const gs = new GlobalState<StateT1>({ some: { path: 'value-a' } });
expectType<StateT1>(gs.getEntireState());
expectError(() => gs.setEntireState('invalid'));
expectType<StateT1>(gs.get());
expectType<StateT1>(gs.get(null));
expectType<StateT1>(gs.get(undefined));
declare const p1: null | string;
expectType<void>(gs.get(p1));
declare const p2: string;
expectType<void>(gs.get(p2));
expectError(() => {
const x: string = gs.get(p2);
});
expectType<ValueT>(gs.get('some.path'));
expectType<void>(gs.get('invalid.path'));
expectError(() => gs.get('some.path', { initialValue: 'invalid' }));
expectError(() => gs.get('invalid.path', { initialValue: 'invalid' }));
expectType<void>(gs.get<1>());
expectType<'OK'>(gs.get<1, 'OK'>());
expectError(() => gs.get<1>('some.path', { initialValue: 'invalid' }));
|
3a7a1d55721f553813cffc0204da0e47d098e513
|
TypeScript
|
hduprat/advent-of-code-2020
|
/20/image.ts
| 2.703125
| 3
|
import { toNumber } from "../utils/number";
import { Tile } from "./tile";
export const getImage = (
arrangementMap: Map<string, Tile>,
gridSize: number
): string[] => {
let [xmin, ymin, xmax, ymax] = [0, 0, 0, 0];
arrangementMap.forEach((_, coords) => {
const [x, y] = coords.split(",").map(toNumber);
xmin = Math.min(xmin, x);
xmax = Math.max(xmax, x);
ymin = Math.min(ymin, y);
ymax = Math.max(ymax, y);
});
const result = [];
for (let y = ymin; y <= ymax; y++) {
for (let k = 1; k < gridSize - 1; k++) {
let line = "";
for (let x = xmin; x <= xmax; x++) {
if (arrangementMap.has(`${x},${y}`))
line += arrangementMap
.get(`${x},${y}`)
.grid[k].slice(1, gridSize - 1);
else line += ".".repeat(gridSize);
}
result.push(line);
line = "";
}
}
return result;
};
export const countHashes = (image: string[]): number =>
image.reduce((count, line) => count + (line.match(/#/g) || []).length, 0);
|
856b7894f179ef9c70dcc598f345e69128089b2e
|
TypeScript
|
sinnatrix/dex
|
/app/src/helpers/general.ts
| 2.734375
| 3
|
import { BigNumber } from '@0x/utils'
import { IDexOrder, IMarket } from 'types'
import format from 'date-fns/format'
export const DAI_SYMBOL = '⬙'
export const ETHER_SYMBOL = 'Ξ'
export const MIN_POINTS_TO_DRAW_CHART = 2
export const getQuoteAssetSymbol = (market: IMarket): string =>
market.quoteAsset.symbol === 'DAI' ? DAI_SYMBOL : ETHER_SYMBOL
export const delay = ts => new Promise(resolve => setTimeout(resolve, ts))
export const formatAssetAmount = (
assetAmount: string | number,
decimals: number = 18,
digits: number = 6
): string => (new BigNumber(assetAmount).dividedBy(Math.pow(10, decimals)).toFixed(digits))
export const toBN = (value: string | number | null | undefined): BigNumber => new BigNumber(value || 0)
export const trimChars = (
target: string,
charsToTrim: string = ' ',
{ fromLeft = true, fromRight = true } = {}
): string => {
const escapedChars = charsToTrim.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
const charsAsArray = escapedChars.split('')
let pattern = ''
if (fromLeft) {
pattern += `^[${charsAsArray.join('')}]+`
}
if (fromRight) {
pattern += (fromLeft ? '|' : '') + `[${charsAsArray.join('')}]+$`
}
const trimer = new RegExp(pattern, 'g')
return target.replace(trimer, '')
}
export const getFormattedMarketPrice = (market: IMarket, addQuoteAssetSymbol: boolean = true) => {
const { price } = market
let symbol = ''
if (addQuoteAssetSymbol) {
symbol = getQuoteAssetSymbol(market) + ' '
}
return symbol + formatMarketPrice(price)
}
export const getFormattedMarketEthPrice = (market: IMarket, addQuoteAssetSymbol: boolean = true): string => {
const { priceEth: price } = market
return (addQuoteAssetSymbol ? ETHER_SYMBOL + ' ' : '') + formatMarketPrice(price)
}
export const getFormattedMarketVolume = (market: IMarket, addQuoteAssetSymbol: boolean = true) => {
const {
quoteAsset: { decimals },
stats: { volume24Hours: volume }
} = market
let symbol = ''
if (addQuoteAssetSymbol) {
symbol = getQuoteAssetSymbol(market) + ' '
}
return symbol + formatMarketVolume(volume, decimals)
}
export const formatMarketPrice = (price: BigNumber, toFixedDecimals = 7): string => {
if (price.equals(0)) {
return '0'
}
return trimChars(
price.toFixed(toFixedDecimals),
'0.',
{ fromRight: true, fromLeft: false }
)
}
export const formatMarketVolume = (volume: BigNumber, assetDecimals: number = 18, toFixedDecimals = 2): string => {
if (volume.equals(0)) {
return '0'
}
return volume.dividedBy(Math.pow(10, assetDecimals)).toFixed(toFixedDecimals)
}
export const renderExpiresAt = (order: IDexOrder): string => {
const date = new Date(order.order.expirationTimeSeconds.toNumber() * 1000)
return format(date, 'MM/DD HH:mm')
}
|
1ceb85eca790d1c4129539bd01f88eeb6344c0ad
|
TypeScript
|
korny-yana/nodejs
|
/other/app2(promises).ts
| 2.640625
| 3
|
const http = require('http');
const fs = require('fs').promises;
const host = 'localhost';
const port = 1000;
let indexFile;
const requestListener = function (req, res) {
switch (req.url) {
case "/": fs.readFile(__dirname+'/index.html')
.then(contents => {
indexFile = contents;
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.end(indexFile);})
.catch(err => {
res.writeHead(500);
res.end(err);
console.log("error");
return;
});
case "/style.css":
fs.readFile(__dirname+'/style.css')
.then(contents => {
indexFile = contents;
res.setHeader("Content-Type", "text/css");
res.writeHead(200);
res.end(contents,"utf-8");})
.catch(err => {
res.writeHead(500);
res.end(err);
console.log("error");
return;
});
}
};
const server = http.createServer(requestListener);
fs.readFile(__dirname + "/index.html")
.then(contents => {
indexFile = contents;
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
})
.catch(err => {
console.error(`Could not read index.html file: ${err}`);
process.exit(1);
});
|
f1e8bbec4dc6732c29f693a5ef6081387352f896
|
TypeScript
|
nmanumr/nodegtk-types
|
/@types/node-gtk/Gtk/Viewport.d.ts
| 2.84375
| 3
|
import * as Gtk from '../Gtk';
export declare interface Viewport extends Gtk.Bin, Gtk.Scrollable { }
/**
* The Gtk.Viewport widget acts as an adaptor class, implementing
scrollability for child widgets that lack their own scrolling
capabilities. Use Gtk.Viewport to scroll child widgets such as
Gtk.Grid, Gtk.Box, and so on.
*/
export declare class Viewport {
/**
* Creates a new Gtk.Viewport with the given adjustments, or with default adjustments if none are given.
* @param hadjustment horizontal adjustment
* @param vadjustment vertical adjustment
* @returns a new Gtk.Viewport
*/
static new(hadjustment: import('../Gtk').Adjustment | null, vadjustment: import('../Gtk').Adjustment | null): import('../Gtk').Widget;
/**
* Gets the bin window of the Gtk.Viewport.
* @returns a Gdk.Window
*/
getBinWindow(): import('../Gdk').Window;
/**
* Returns the horizontal adjustment of the viewport.
* @returns the horizontal adjustment of self.
*/
getHadjustment(): import('../Gtk').Adjustment;
/**
* Gets the shadow type of the Gtk.Viewport. See Gtk.Viewport.set_shadow_type().
* @returns the shadow type
*/
getShadowType(): import('../Gtk').ShadowType;
/**
* Returns the vertical adjustment of the viewport.
* @returns the vertical adjustment of self.
*/
getVadjustment(): import('../Gtk').Adjustment;
/**
* Gets the view window of the Gtk.Viewport.
* @returns a Gdk.Window
*/
getViewWindow(): import('../Gdk').Window;
/**
* Sets the horizontal adjustment of the viewport.
* @param adjustment a Gtk.Adjustment.
*/
setHadjustment(adjustment: import('../Gtk').Adjustment | null): void;
/**
* Sets the shadow type of the viewport.
* @param type the new shadow type.
*/
setShadowType(type: import('../Gtk').ShadowType): void;
/**
* Sets the vertical adjustment of the viewport.
* @param adjustment a Gtk.Adjustment.
*/
setVadjustment(adjustment: import('../Gtk').Adjustment | null): void;
/**
* Determines how the shadowed box around the viewport is drawn
*/
shadowType: import('../Gtk').ShadowType;
}
|
81948a5811f73df16135abdf795bb7e14585d7cb
|
TypeScript
|
greenbech/signal
|
/src/main/helpers/areEqualShallow.ts
| 3.015625
| 3
|
// https://stackoverflow.com/a/22266891/1567777
export function areEqualShallow<T>(a: T, b: T): boolean {
for (var key in a) {
if (a[key] !== b[key]) {
return false
}
}
return true
}
|
509282f812ba1b6df758c4902b1ada6da79b33fd
|
TypeScript
|
primefaces/primevue
|
/components/lib/confirmdialog/ConfirmDialog.d.ts
| 2.6875
| 3
|
/**
*
* ConfirmDialog uses a Dialog UI with confirmDialog method or <ConfirmDialog> tag.
*
* [Live Demo](https://www.primevue.org/confirmdialog)
*
* @module confirmdialog
*
*/
import { VNode } from 'vue';
import { ComponentHooks } from '../basecomponent';
import { ButtonPassThroughOptions } from '../button';
import { ConfirmationOptions } from '../confirmationoptions';
import { ClassComponent, GlobalComponentConstructor, PTOptions } from '../ts-helpers';
export declare type ConfirmDialogPassThroughOptionType = ConfirmDialogPassThroughAttributes | ((options: ConfirmDialogPassThroughMethodOptions) => ConfirmDialogPassThroughAttributes | string) | string | null | undefined;
/**
* Custom passthrough(pt) option method.
*/
export interface ConfirmDialogPassThroughMethodOptions {
instance: any;
props: ConfirmDialogProps;
state: ConfirmDialogState;
}
/**
* Custom passthrough(pt) options.
* @see {@link ConfirmDialogProps.pt}
*/
export interface ConfirmDialogPassThroughOptions {
/**
* Used to pass attributes to the root's DOM element.
*/
root?: ConfirmDialogPassThroughOptionType;
/**
* Used to pass attributes to the header's DOM element.
*/
header?: ConfirmDialogPassThroughOptionType;
/**
* Used to pass attributes to the header title's DOM element.
*/
headerTitle?: ConfirmDialogPassThroughOptionType;
/**
* Used to pass attributes to the header icons' DOM element.
*/
headerIcons?: ConfirmDialogPassThroughOptionType;
/**
* Used to pass attributes to the close button's component.
*/
closeButton?: ConfirmDialogPassThroughOptionType;
/**
* Used to pass attributes to the close button icon's component.
*/
closeButtonIcon?: ConfirmDialogPassThroughOptionType;
/**
* Used to pass attributes to the content's DOM element.
*/
content?: ConfirmDialogPassThroughOptionType;
/**
* Used to pass attributes to the icon's DOM element.
*/
icon?: ConfirmDialogPassThroughOptionType;
/**
* Used to pass attributes to the message's DOM element.
*/
message?: ConfirmDialogPassThroughOptionType;
/**
* Used to pass attributes to the footer's DOM element.
*/
footer?: ConfirmDialogPassThroughOptionType;
/**
* Used to pass attributes to the Button component.
* @see {@link ButtonPassThroughOptions}
*/
rejectButton?: ButtonPassThroughOptions;
/**
* Used to pass attributes to the Button component.
* @see {@link ButtonPassThroughOptions}
*/
acceptButton?: ButtonPassThroughOptions;
/**
* Used to manage all lifecycle hooks
* @see {@link BaseComponent.ComponentHooks}
*/
hooks?: ComponentHooks;
}
/**
* Custom passthrough attributes for each DOM elements
*/
export interface ConfirmDialogPassThroughAttributes {
[key: string]: any;
}
/**
* Defines current inline state in ConfirmDialog component.
*/
export interface ConfirmDialogState {
/**
* Current visible state as a boolean.
* @defaultValue false
*/
visible: boolean;
/**
* Current confirmation message.
*/
confirmation: any;
}
/**
* Breakpoint metadata.
*/
export interface ConfirmDialogBreakpoints {
/**
* Breakpoint for responsive mode.
*
* Example:
*
* <ConfirmDialog :breakpoints="{'960px': '75vw', '640px': '100vw'}" ... />
*
* Result:
*
* @media screen and (max-width: ${breakpoint[key]}) {
* .p-dialog[attributeSelector] {
* width: ${breakpoint[value]} !important;
* }
* }
*/
[key: string]: string;
}
/**
* Defines valid properties in ConfirmDialog component.
*/
export interface ConfirmDialogProps {
/**
* Optional key to match the key of the confirmation, useful to target a specific confirm dialog instance.
*/
group?: string | undefined;
/**
* Object literal to define widths per screen size.
* @see ConfirmDialogBreakpoints
*/
breakpoints?: ConfirmDialogBreakpoints;
/**
* Enables dragging to change the position using header.
* @defaultValue true
*/
draggable?: boolean | undefined;
/**
* Used to pass attributes to DOM elements inside the component.
* @type {ConfirmDialogPassThroughOptions}
*/
pt?: PTOptions<ConfirmDialogPassThroughOptions>;
/**
* When enabled, it removes component related styles in the core.
* @defaultValue false
*/
unstyled?: boolean;
}
/**
* Defines valid slots in ConfirmDialog component.
*/
export interface ConfirmDialogSlots {
/**
* Custom message template.
* @param {Object} scope - message slot's params.
*/
message(scope: {
/**
* Message of the component
*/
message: ConfirmationOptions;
}): VNode[];
/**
* Custom icon template.
* @param {Object} scope - icon slot's params.
*/
icon(scope: {
/**
* Style class of the icon template
*/
class: any;
}): VNode[];
/**
* Custom icon template.
*/
accepticon(): VNode[];
/**
* Custom icon template.
*/
rejecticon(): VNode[];
}
/**
* Defines valid emits in ConfirmDialog component.
*/
export interface ConfirmDialogEmits {}
/**
* **PrimeVue - ConfirmDialog**
*
* _ConfirmDialog uses a Dialog UI with confirmDialog method or <ConfirmDialog> tag._
*
* [Live Demo](https://www.primevue.org/confirmdialog/)
* --- ---
* 
*
* @group Component
*/
declare class ConfirmDialog extends ClassComponent<ConfirmDialogProps, ConfirmDialogSlots, ConfirmDialogEmits> {}
declare module '@vue/runtime-core' {
interface GlobalComponents {
ConfirmDialog: GlobalComponentConstructor<ConfirmDialog>;
}
}
export default ConfirmDialog;
|
63d2f4c6548b5bf301793d4e817a0281912739c0
|
TypeScript
|
jurliyuuri/cerke_online_alpha
|
/src/protective_cover.ts
| 2.734375
| 3
|
export type MembraneState = {
protective_cover_over_field: boolean,
protective_tam_cover_over_field: boolean,
protective_cover_over_field_while_asyncawait: boolean,
protective_cover_over_field_while_waiting_for_opponent: boolean,
}
const MEMBRANE_STATE: MembraneState
= sessionStorage.getItem('membrane_state_backup')
? JSON.parse(sessionStorage.membrane_state_backup) /* Reflecting this into DOM is done when "ty_zau" button is pressed */
: {
protective_cover_over_field: false,
protective_tam_cover_over_field: false,
protective_cover_over_field_while_asyncawait: false,
protective_cover_over_field_while_waiting_for_opponent: true
}
;
export function apply_membrane_state_to_dom() {
function apply(id:
| "protective_cover_over_field"
| "protective_tam_cover_over_field"
| "protective_cover_over_field_while_asyncawait"
| "protective_cover_over_field_while_waiting_for_opponent") {
if (MEMBRANE_STATE[id]) {
document.getElementById(id)?.classList.remove("nocover");
} else {
document.getElementById(id)?.classList.add("nocover");
}
}
apply("protective_cover_over_field")
apply("protective_tam_cover_over_field")
apply("protective_cover_over_field_while_asyncawait")
apply("protective_cover_over_field_while_waiting_for_opponent")
}
export function add_cover(id:
| "protective_cover_over_field"
| "protective_tam_cover_over_field"
| "protective_cover_over_field_while_asyncawait"
| "protective_cover_over_field_while_waiting_for_opponent") {
document.getElementById(id)?.classList.remove("nocover");
MEMBRANE_STATE[id] = true;
sessionStorage.membrane_state_backup = JSON.stringify(MEMBRANE_STATE);
}
export function remove_cover(id:
| "protective_cover_over_field"
| "protective_tam_cover_over_field"
| "protective_cover_over_field_while_asyncawait"
| "protective_cover_over_field_while_waiting_for_opponent") {
document.getElementById(id)?.classList.add("nocover");
MEMBRANE_STATE[id] = false;
sessionStorage.membrane_state_backup = JSON.stringify(MEMBRANE_STATE);
}
|
638715c5a35d494896e650460a75db3caf5da1d3
|
TypeScript
|
jacob-shuman/music-search
|
/src/music.ts
| 2.8125
| 3
|
export interface MusicArtist {
id: number;
name: string;
artUrl?: string;
}
export interface MusicAlbum {
id: number;
name: string;
trackCount?: number;
artUrl?: string;
artistId?: number;
}
export interface MusicSong {
id: number;
name: string;
// Track index in album
track?: number;
// Time in milliseconds
duration?: number;
genre?: string;
artistId?: number;
albumId?: number;
}
|
2b08315a18238176620d322400ad2b1c463d122e
|
TypeScript
|
ajlao11/react-js-crud-todo-list
|
/src/domain/usecases/addTaskUsecase.ts
| 2.65625
| 3
|
import { TodoRepository } from "../repositories/todoRepository"
import { Todo } from "../entities/todo"
export class AddTodoUseCase {
todoRepo: TodoRepository
constructor(todoRepo: TodoRepository) {
this.todoRepo = todoRepo
}
execute(name: string): Promise<Todo> {
const newTodo = new Todo(-1, name)
return this.todoRepo.addData(newTodo)
}
}
|
492e95a40773dfd51c5b317a29f84bb5a7c20c4a
|
TypeScript
|
green-fox-academy/smnkrisz
|
/algorithm exercise/multiplyMatrix.ts
| 4.125
| 4
|
/*
Write a method called multiplyMatrix() that takes a matrix of non-negative integers (any matrix is allowed, including square matrices) as a parameter.
The function should:
multiply each odd (1, 3, 5, 7, 9, ...) number by 2 in each odd indexed row
multiply each even (2, 4, 6, 8, 10, ...) number by 2 in each even indexed row
use the same indexing which we use in most programming language (starting with 0) and remember that 0 is also an even number.
See the example for better understanding and ask questions if it is still unclear.
Example 1:
[
[1, 3, 6, 2],
[7, 5, 6, 1],
[3, 3, 1, 5],
[9, 0, 5, 3]
]
Output:
[
[1, 3, 12, 4],
[14, 10, 6, 2],
[3, 3, 1, 5],
[18, 0, 10, 6]
]
Example 2:
[
[2, 3],
[5, 0, 4, 0],
[6],
[5, 2]
]
Output:
[
[4, 3],
[10, 0, 4, 0],
[12],
[10, 2]
]
*/
const array1 = [
[1, 3, 6, 2],
[7, 5, 6, 1],
[3, 3, 1, 5],
[9, 0, 5, 3],
];
const array2 = [[2, 3], [5, 0, 4, 0], [6], [5, 2]];
function multiplyMatrix(matrix: number[][]): number[][] {
for (let rowI = 0; rowI < matrix.length; rowI++) {
for (let collumI = 0; collumI < matrix[rowI].length; collumI++) {
if (rowI % 2 !== 0) {
if (matrix[rowI][collumI] % 2 !== 0) {
matrix[rowI][collumI] = matrix[rowI][collumI] + matrix[rowI][collumI];
}
} else if (rowI % 2 === 0) {
if (matrix[rowI][collumI] % 2 === 0) {
matrix[rowI][collumI] = matrix[rowI][collumI] + matrix[rowI][collumI];
}
}
}
}
return matrix;
}
console.log("array1: ", multiplyMatrix(array1));
console.log("array2: ", multiplyMatrix(array2));
|
7c55dfcdf618ba7c1257353c5aef9a28d9c90df0
|
TypeScript
|
andywyatte17/virtual_tube_explorer
|
/src/app/route-tab/station-model.ts
| 2.546875
| 3
|
import { Naptan, MakeTubeNaptans } from "../naptans/naptans";
import { HttpClient } from "@angular/common/http";
export class StationModel {
filteredStations = new Array<Naptan>();
selectedStationId_: string = null;
selectedStation: Naptan = null;
filter: string = null;
lines: Array<string> = null;
selectedLine: string = null;
private stations = MakeTubeNaptans();
constructor(private http: HttpClient) {
this.filteredStations = this.stations.filter(() => true);
}
set selectedStationId(s: string) {
this.selectedStationId_ = s;
Naptan.TubeLinesForNaptan(s, this.http).then(
(lines: Array<string>) => {
lines.push("walk");
lines.push("bus/other");
this.lines = lines;
this.selectedLine = this.lines[0];
});
}
get selectedStationId() { return this.selectedStationId_; }
stationDidChange() {
}
lineDidChange() {
}
filterDidChange(filterValue: string) {
this.filter = filterValue;
this.updateFilteredStations();
}
updateFilteredStations() {
if (!this.filter || this.filter == '') {
this.filteredStations = this.stations;
return;
}
let filterLC = this.filter.toLowerCase();
let selectedStation = this.selectedStation;
this.filteredStations = this.stations.filter((naptan: Naptan) => {
return naptan == selectedStation || naptan.name.toLowerCase().indexOf(filterLC) >= 0;
});
}
};
|
73044fcca039db4e9c186a67fcdf84c1e46338a9
|
TypeScript
|
Karnaukhov-kh/deprecation-manager
|
/packages/deprecation-crawler/src/lib/log.ts
| 2.75
| 3
|
import * as kleur from 'kleur';
import { CrawlConfig, CrawledRelease } from './models';
export function logError(message: string) {
console.log(kleur.red(message));
}
const maxWidth = 40;
const headingIntend = 2;
const stepIntend = 3;
const headingSpacer = '-';
export function printHeadline(message: string) {
const heading = [
getString(headingIntend, headingSpacer),
` ${message} `,
getString(maxWidth - headingIntend + message.length + 2, headingSpacer),
].join('');
console.log(kleur.gray(heading));
}
export function printFooterLine(): void {
console.log('');
console.log(getString(maxWidth, headingSpacer));
}
export function printProgress(message = '⏰') {
const heading = [getString(stepIntend, headingSpacer), ` ${message}`].join(
''
);
console.log(kleur.gray(heading));
}
function getString(length, char): string {
return Array(length).fill(char).join('');
}
export interface ProcessFeedback {
printStart?(config?: CrawlConfig, rawRelease?: CrawledRelease): void;
printEnd?(config?: CrawlConfig, rawRelease?: CrawledRelease): void;
}
|
64171e9d7beb929515c8ca13f1c3a5fccc98dbd6
|
TypeScript
|
raynode/graphql-logging-app
|
/src/index.ts
| 2.515625
| 3
|
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloClient } from 'apollo-client'
import { WebSocketLink } from 'apollo-link-ws'
import { isAfter } from 'date-fns'
import gql from 'graphql-tag'
import * as Parser from 'rss-parser'
import { SubscriptionClient } from 'subscriptions-transport-ws'
import * as ws from 'ws'
import { log } from './services/logger'
const GRAPHQL_SERVER_URI = 'ws://localhost:3421/graphql'
const subscriptionClient = new SubscriptionClient(GRAPHQL_SERVER_URI, { reconnect: true }, ws)
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new WebSocketLink(subscriptionClient),
defaultOptions: {
watchQuery: {
fetchPolicy: 'no-cache',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
},
})
let running = false
const parser = new Parser()
const getNewestFeedItems = async (old: Date | string) => {
const feed = await parser.parseURL('https://www.heise.de/rss/heise.rdf')
const items = feed.items.filter(item => isAfter(item.isoDate, old))
console.log(items[0])
return items
}
const checkForNewItems = async () => {
if(running)
return triggerError('Already running')
running = true
log('Checking for new items')
const { data } = await client.query({
query: gql`query {
link: Link(
where: { tags_some: { tag: "Heise" }}
order: datetime_DESC
) { datetime }
}`,
})
const datetime: string = data.link ? data.link.datetime : '2000-01-01T00:00:00.000Z'
log('timestamp: ' + datetime)
return storeItems(datetime)
}
const triggerEvent = (event: string, data: any) => client.mutate({
mutation: gql`mutation CreateEvent($event: String!, $data: SequelizeJSON) {
triggerEvent(name: $event, data: $data)
}`,
variables: { event, data },
})
const triggerError = (error: string) => triggerEvent('heise-feed:error', { error })
interface Link {
url: string
content?: string
datetime: Date
title: string
}
const createLink = async (item: Link) => client.mutate({
mutation: gql`mutation createLink($title: String!, $url: String!, $date: Date!){
createLink(data: {
title: $title
url: $url
datetime: $date
tags: { tag: "Heise" }
}) { id createdAt }
}`,
variables: { title: item.title, url: item.url, date: item.datetime },
})
const storeItems = async (from: Date | string) => {
const items = await getNewestFeedItems(from)
await Promise.all(items.map(item => createLink({
content: item.content,
datetime: new Date(item.isoDate),
title: item.title,
url: item.link,
})))
triggerEvent('heise-feed:result', { items: items.length, from })
running = false
}
const observer = client.subscribe({
query: gql`subscription { event: eventListener(name: "*") { name }}`,
})
log('observer started')
observer
.filter(({ data: { event } }) => event.name.startsWith('heise-feed:'))
.map(({ data: { event, data } }) => ({ event: event.name.slice(11), data }))
.forEach(({ event, data }) => {
log(event, data)
if(event === 'start') return checkForNewItems()
// if(event.name === 'heise-feed')
return true
})
|
7c7b10133244fba35f290aa7ce054663f4f53fb6
|
TypeScript
|
jmchandonia/generix-ui
|
/src/app/shared/models/provenance-graph/homepage-node.ts
| 2.8125
| 3
|
import { Node, ClusterOptions } from 'vis-network/standalone';
export interface HomepageNode extends Node {
/*
Extension interface to provide metadata to nodes to
enable search and interaction with generix system. This
is a wrapper for the VisJS Node interface that will allow
us to use nodes with a 'data' property without throwing
a type error.
*/
data: INodeData;
cid?: number;
}
export interface INodeData {
/* JSON data structure for nodes from request to /types_graph */
index: number;
name: string;
category: string | false;
dataType: string;
dataModel: string;
thickness: number;
isParent: boolean;
x: number;
y: number;
root?: true;
count: number;
parent?: number;
}
export class HomepageNodeFactory {
public static createNode(data: INodeData, xScale: number, yScale: number): HomepageNode {
const node: HomepageNode = {
data,
id: data.index,
font: {
size: 16,
face: 'Red Hat Text, sans-serif',
},
color: {
background: data.category ? 'white' : 'rgba(0,0,0,0)', // make node invisible when its a connector
border: data.category === 'DDT_' ? 'rgb(246, 139, 98)' : 'rgb(78, 111, 182)',
hover: { background: '#ddd' }
},
shape: 'box',
shapeProperties: {
borderRadius: data.category === 'DDT_' ? 0 : 20
},
fixed: true,
x: data.x * xScale,
y: data.y * yScale
}
if (data.root) {
node.borderWidth = 4;
node.color = {
border: 'darkgreen',
hover: { background: '#ddd' },
background: 'white'
}
node.margin = {
top: 10,
left: 10,
bottom: 10,
right: 10
};
} else if (!data.category) {
node.borderWidth = 0;
}
if (data.category) {
node.label = `${data.count} ${data.name.replace(/<br>/g, '\n')}`;
}
if (data.parent) {
node.cid = data.parent;
}
if (data.isParent) {
node.label = '[-]'; // parent displays as expanded root node in cluster
}
return node;
}
public static createNodeCluster(data: INodeData, xScale: number, yScale: number): ClusterOptions {
return {
joinCondition: node => (node.cid && node.cid === data.index) || node.id === data.index,
clusterNodeProperties: {
label: `${data.count} ${data.name} [+]`,
physics: false,
color: {
border: data.category === 'DDT_' ? 'rgb(246, 139, 98)' : 'rgb(78, 111, 182)',
background: 'white'
},
borderWidth: 3,
shape: 'box',
shapeProperties: {
borderRadius: 0
},
x: data.x * xScale,
y: data.y * yScale,
font: {
size: 16,
face: 'Red Hat Text, sans-serif'
},
},
}
}
}
|
329a1f18f9b6f69c00dbf7ac2824c218d963d5eb
|
TypeScript
|
fstfwd/sheets
|
/src/lib/snapshot.ts
| 2.71875
| 3
|
import { SecurityHelpers } from './types';
import { RefService } from './ref';
export class DataSnapshot {
private isRef = false;
private input: any;
constructor(input: RefService | any, securityHelpers?: SecurityHelpers) {
this.input = input;
if (input instanceof RefService) {
this.isRef = true;
}
// add helpers
if (!!securityHelpers) {
for (const key of Object.keys(securityHelpers)) {
const helper = securityHelpers[key];
this[key] = () => helper(this);
}
}
}
// get data
val() {
if (this.isRef) {
return this.input['data']();
} else {
return this.input;
}
}
// only props
only(props = []) {
const data = this.val();
if (!props || !props.length) {
return true;
} else if (!!data && data instanceof Object) {
const _data = { ... data };
for (let i = 0; i < props.length; i++) {
const prop = props[i];
delete _data[prop];
}
return Object.keys(_data).length === 0;
} else {
return false;
}
}
}
|
4510baf125d372484af0b01864e0f19bfcfe58f8
|
TypeScript
|
Ahmedhamed77/MyContacts
|
/src/redux/user/action.ts
| 2.640625
| 3
|
import {User} from '../../api/contacts/types';
import {AppThunk} from '../store/types';
import {login, register} from '../../api/contacts';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {Alert} from 'react-native';
export const userIsLoading = (state: boolean) =>
<const>{
type: 'USER_IS_LOADING',
state,
};
export const getUser = (user: User) =>
<const>{
type: 'GET_USER',
user,
};
export const userRegister = (user: User) =>
<const>{type: 'REGISTER_USER', user};
export const userRegistrations =
(user: User): AppThunk =>
async dispatch => {
try {
const response = await register(user);
console.log(response, 'response register');
} catch (error) {
console.log(error, 'errror');
}
};
export const getUserLogin =
(username: string, password: string): AppThunk =>
async dispatch => {
console.log('iam here in getUSer');
console.log(username, password);
try {
console.log('insidexs');
const response = await login({username, password});
console.log(response.token, 'what is here');
const token = response.token;
await AsyncStorage.setItem('token', token);
console.log(response, 'repsonse');
} catch (error) {
Alert.alert('Error , try to enter correct username or password');
console.log(error, 'login Error');
}
};
|
23360763b9c85e14f0609f19475e8533ff27190b
|
TypeScript
|
boutainaLemrabet/composite-expected
|
/src/main/webapp/app/shared/model/with-id-string.model.ts
| 2.75
| 3
|
export interface IWithIdString {
id?: string;
}
export class WithIdString implements IWithIdString {
constructor(public id?: string) {}
}
|
d777c380e56117e86a46fd72c3e5e34b62b44d83
|
TypeScript
|
mdzzohrabi/azera-js
|
/packages/cms/src/bundle/portal/public/lib/Strings.ts
| 3.46875
| 3
|
const REGEX_WORD = /([A-Za-z]+?)(?=[A-Z_\-\\\/0-9]|\b|\s)/g;
/**
* camelCase an string
* @param value String to convert
*/
export function camelCase(value: string) {
let result = '';
value.replace(REGEX_WORD, (m, w) => {
result += w.charAt(0).toUpperCase() + m.slice(1).toLowerCase();
return '';
});
return result.replace(/^[A-Z]/, a => a.toLowerCase());
}
export function snakeCase(value: string) {
let result = [];
value.replace(REGEX_WORD, (m, w: string) => {
result.push(w.toLowerCase());
return '';
});
return result.join('_');
}
export function humanize(value: string) {
let result: string[] = [];
value.replace(REGEX_WORD, (m, w: string) => {
result.push(w.toLowerCase());
return '';
});
if (result.length > 0) result[0] = result[0].charAt(0).toUpperCase() + result[0].slice(1);
return result.join(' ');
}
|
fbfb2f49ba35899e88304633746e03a8a01224af
|
TypeScript
|
dmgolembiowski/edgedb-ui
|
/src/renderer/store/resizablePanel.ts
| 2.703125
| 3
|
import { Module, VuexModule, Action, Mutation } from 'vuex-class-modules'
@Module
export class ResizablePanelModule extends VuexModule {
layout: 'vertical' | 'horizontal' = 'vertical'
isCollapsed = true
size: number = 50
@Mutation
setCollapsed(collapsed?: boolean) {
this.isCollapsed = collapsed ?? !this.isCollapsed
}
@Mutation
updateSize(size: number) {
this.size = size > 90 ? 90 : (size < 10 ? 10 : size)
}
@Mutation
changeLayout(layout?: 'vertical' | 'horizontal') {
if (!layout) {
this.layout = this.layout === 'vertical' ? 'horizontal' : 'vertical'
} else {
this.layout = layout
}
}
}
|
400ad9250ae7a01fb0ca7ac52cac5289c324e0c7
|
TypeScript
|
captain-igloo/betfair-ts
|
/src/sport/PlaceInstructionReport.ts
| 2.65625
| 3
|
/**
* Copyright 2020 Colin Doig. Distributed under the MIT license.
*/
import JsonMember from '../JsonMember';
import InstructionReportErrorCode from '../sport/enum/InstructionReportErrorCode';
import InstructionReportStatus from '../sport/enum/InstructionReportStatus';
import OrderStatus from '../sport/enum/OrderStatus';
import PlaceInstruction, { IPlaceInstructionOptions } from '../sport/PlaceInstruction';
export interface IPlaceInstructionReportOptions {
status: InstructionReportStatus | string;
errorCode?: InstructionReportErrorCode | string;
orderStatus?: OrderStatus | string;
instruction: PlaceInstruction | IPlaceInstructionOptions;
betId?: string;
placedDate?: Date | string;
averagePriceMatched?: number;
sizeMatched?: number;
}
export default class PlaceInstructionReport extends JsonMember {
private status: InstructionReportStatus;
private errorCode?: InstructionReportErrorCode;
private orderStatus?: OrderStatus;
private instruction: PlaceInstruction;
private betId?: string;
private placedDate?: Date;
private averagePriceMatched?: number;
private sizeMatched?: number;
constructor(options: IPlaceInstructionReportOptions) {
super();
this.status = this.fromJson(options.status, InstructionReportStatus);
if (options.errorCode) {
this.errorCode = this.fromJson(options.errorCode, InstructionReportErrorCode);
}
if (options.orderStatus) {
this.orderStatus = this.fromJson(options.orderStatus, OrderStatus);
}
this.instruction = this.fromJson(options.instruction, PlaceInstruction);
this.betId = options.betId;
if (options.placedDate) {
this.placedDate = this.fromJson(options.placedDate, Date);
}
this.averagePriceMatched = options.averagePriceMatched;
this.sizeMatched = options.sizeMatched;
}
public toJson(): IPlaceInstructionReportOptions {
const json: IPlaceInstructionReportOptions = {
status: this.status.getValue(),
instruction: this.instruction.toJson(),
};
if (this.errorCode) {
json.errorCode = this.errorCode.getValue();
}
if (this.orderStatus) {
json.orderStatus = this.orderStatus.getValue();
}
if (typeof this.betId !== 'undefined') {
json.betId = this.betId;
}
if (typeof this.placedDate !== 'undefined') {
json.placedDate = this.placedDate.toISOString();
}
if (typeof this.averagePriceMatched !== 'undefined') {
json.averagePriceMatched = this.averagePriceMatched;
}
if (typeof this.sizeMatched !== 'undefined') {
json.sizeMatched = this.sizeMatched;
}
return json;
}
public getStatus(): InstructionReportStatus {
return this.status;
}
public setStatus(status: InstructionReportStatus): void {
this.status = status;
}
public getErrorCode(): InstructionReportErrorCode | undefined {
return this.errorCode;
}
public setErrorCode(errorCode: InstructionReportErrorCode): void {
this.errorCode = errorCode;
}
public getOrderStatus(): OrderStatus | undefined {
return this.orderStatus;
}
public setOrderStatus(orderStatus: OrderStatus): void {
this.orderStatus = orderStatus;
}
public getInstruction(): PlaceInstruction {
return this.instruction;
}
public setInstruction(instruction: PlaceInstruction): void {
this.instruction = instruction;
}
public getBetId(): string | undefined {
return this.betId;
}
public setBetId(betId: string): void {
this.betId = betId;
}
public getPlacedDate(): Date | undefined {
return this.placedDate;
}
public setPlacedDate(placedDate: Date): void {
this.placedDate = placedDate;
}
public getAveragePriceMatched(): number | undefined {
return this.averagePriceMatched;
}
public setAveragePriceMatched(averagePriceMatched: number): void {
this.averagePriceMatched = averagePriceMatched;
}
public getSizeMatched(): number | undefined {
return this.sizeMatched;
}
public setSizeMatched(sizeMatched: number): void {
this.sizeMatched = sizeMatched;
}
}
|
e88d06391cc1fec062eee678f832385f7889f066
|
TypeScript
|
Coursemology/coursemology2
|
/client/app/types/course/disbursement.ts
| 2.703125
| 3
|
/**
* Data types for disbursement data retrieved from backend through API call.
*/
export interface ForumDisbursementFilters {
startTime: Date;
endTime: Date;
weeklyCap: string;
}
export interface ForumDisbursementUserData {
id: number;
name: string;
level: number;
exp: number;
postCount: number;
voteTally: number;
points: number;
}
export interface ForumDisbursementPostData {
id: number;
title: string;
topicSlug: string;
forumSlug: string;
content: string;
voteTally: number;
createdAt: Date;
}
export interface DisbursementCourseGroupListData {
id: number;
name: string;
}
export interface DisbursementCourseUserListData {
id: number;
name: string;
groupIds: number[];
}
/**
* Data types for disbursement data used in frontend that are converted from
* received backend data.
*/
export interface DisbursementCourseGroupMiniEntity {
id: DisbursementCourseGroupListData['id'];
name: DisbursementCourseGroupListData['name'];
}
export interface DisbursementCourseUserMiniEntity {
id: DisbursementCourseUserListData['id'];
name: DisbursementCourseUserListData['name'];
groupIds: DisbursementCourseUserListData['groupIds'];
}
export interface ForumDisbursementUserEntity {
id: ForumDisbursementUserData['id'];
name: ForumDisbursementUserData['name'];
level: ForumDisbursementUserData['level'];
exp: ForumDisbursementUserData['exp'];
postCount: ForumDisbursementUserData['postCount'];
voteTally: ForumDisbursementUserData['voteTally'];
points: ForumDisbursementUserData['points'];
}
export interface ForumDisbursementPostEntity {
id: ForumDisbursementPostData['id'];
title: ForumDisbursementPostData['title'];
topicSlug: ForumDisbursementPostData['topicSlug'];
forumSlug: ForumDisbursementPostData['forumSlug'];
content: ForumDisbursementPostData['content'];
voteTally: ForumDisbursementPostData['voteTally'];
createdAt: ForumDisbursementPostData['createdAt'];
userId: number;
}
/**
* Data types for disbursement form data.
*/
export interface DisbursementFormData {
reason: string;
[key: `courseUser_${number}`]: string;
}
export interface ForumDisbursementFormData
extends ForumDisbursementFilters,
DisbursementFormData {}
/**
* Data types for forum disbursement data sent to backend
*/
export interface ForumDisbursementFilterParams {
params: {
['experience_points_forum_disbursement[start_time]']: Date;
['experience_points_forum_disbursement[end_time]']: Date;
['experience_points_forum_disbursement[weekly_cap]']: string;
};
}
|
520a3938cd2c9ba3366899838799c8f66cf36c6b
|
TypeScript
|
avivbiton/RandomContentGenerator
|
/src/__tests__/ContentGenerator.test.ts
| 2.890625
| 3
|
import { ContentGenerator } from "../ContentGenerator";
import { InvalidParserException } from "../Exceptions/InvalidParserException";
import { InvalidSchemaFormatException } from "../Exceptions/InvalidSchemaFormatException";
import mockSchema from "./mockData/mockSchema.json";
import { Schema } from '../Schema';
import { Field } from '../Field';
test("generated content is not empty", () => {
let json = mockSchema;
let content = new ContentGenerator(json);
let build = content.build();
console.log(JSON.stringify(build));
expect(Object.keys(build).length).toBeGreaterThan(0);
});
test("build throws InvalidParserException when parser is invalid", () => {
function buildContent() {
let schema = new Schema([
new Field("name", { invalid: "showthrow" })
], []);
let content = new ContentGenerator(schema);
content.build();
};
expect(buildContent).toThrowError(InvalidParserException);
});
test("build throws InvalidSchemaFormatException when schema is null", () => {
function buildWithInvalidSchema() {
let content = new ContentGenerator(null);
content.build();
}
expect(buildWithInvalidSchema).toThrowError(InvalidSchemaFormatException);
});
|
89fe53046ca0b241b89e42e897a795b67303ed58
|
TypeScript
|
Tankzorx/PhilipsHueFun
|
/server/hueSockets/hueSockets.ts
| 2.59375
| 3
|
import { HueApi, lightState } from "node-hue-api"
import config from '../config'
export const server = require('http').createServer();
// var io = require("socket.io")(server)
import * as io from 'socket.io'
import { request } from "http";
const ioServer = io(server)
/**
* Set up hue api and socket.io
*/
const hueApi = new HueApi(config.hueInfo.bridgeIp, config.hueInfo.username);
export const initHueSockets = () => {
hueApi.lights().then( (result) => {
for (const light of result.lights) {
createLightSocket(light)
}
})
}
function createLightSocket(light) {
console.log('Creating socket for light: ', light.id)
const lightSocket: SocketIO.Namespace = ioServer.of(`/${light.id}`)
lightSocket.on('connection', (socket) => {
console.log(`Connected light '${light.id}'`)
configureSocket(socket, light)
})
}
function configureSocket(socket: SocketIO.Socket, light) {
socket.on('disconnect', () => { console.log(`Disconnected light '${light.id}'`) })
socket.on('requestStateChange', (requestedState) => {
handleStateChangeRequest(requestedState, light, socket)
})
}
function handleStateChangeRequest(requestedState, light, socket) {
console.log(`New request for lamp: ${light.id}! \n ${JSON.stringify(requestedState)}`)
hueApi.setLightState(light.id, requestedState)
.then((result: boolean) => {
console.log(result)
if (result) {
socket.emit('stateChanged', { requestedState, success: true })
} else {
socket.emit('stateChanged', { requestedState, success: false})
}
})
}
|
77d1dc85e18ab96d0444e1646e1425ee4ce881ac
|
TypeScript
|
travetto/schema
|
/src/decorator/field.ts
| 2.734375
| 3
|
import { CommonRegExp, SchemaRegistry, ClassList, ValidatorFn } from '../service';
function prop(obj: { [key: string]: any }) {
return (f: any, p: string) => {
SchemaRegistry.registerPendingFieldFacet(f.constructor, p, obj);
};
}
function enumKeys(c: any): string[] {
if (Array.isArray(c) && typeof c[0] === 'string') {
return c;
} else {
return Object.values(c).filter((x: any) => typeof x === 'string') as string[];
}
}
export function Field(type: ClassList, config?: { [key: string]: any }) {
return (f: any, p: string) => {
SchemaRegistry.registerPendingFieldConfig(f.constructor, p, type);
if (config) {
SchemaRegistry.registerPendingFieldFacet(f.constructor, p, config);
}
};
}
export const Alias = (...aliases: string[]) => prop({ aliases });
export const Required = (message?: string) => prop({ required: { message } });
export const Enum = (vals: string[] | any, message?: string) => {
const values = enumKeys(vals);
message = message || `{path} is only allowed to be "${values.join('" or "')}"`;
return prop({ enum: { values, message } });
};
export const Trimmed = () => prop({ trim: true });
export const Match = (re: RegExp, message?: string) => prop({ match: { re, message } });
export const MinLength = (n: number, message?: string) => prop({ minlength: { n, message } });
export const MaxLength = (n: number, message?: string) => prop({ maxlength: { n, message } });
export const Min = (n: number | Date, message?: string) => prop({ min: { n, message } });
export const Max = (n: number | Date, message?: string) => prop({ max: { n, message } });
export const Email = (message?: string) => Match(CommonRegExp.email, message);
export const Telephone = (message?: string) => Match(CommonRegExp.telphone, message);
export const Url = (message?: string) => Match(CommonRegExp.url, message);
export const Precision = (precision: number) => prop({ precision });
export const Integer = () => Precision(0);
export const Float = () => Precision(10);
export const Currency = () => Precision(2);
export function View(...names: string[]) {
return (f: any, p: string) => {
for (const name of names) {
SchemaRegistry.registerPendingFieldFacet(f.constructor, p, {}, name);
}
};
}
// For Auto schemas
export function Ignore(): PropertyDecorator {
return (target: any, property: string | symbol) => { };
}
|
2074a0a7de28419887227729b2fd77fe3a827719
|
TypeScript
|
ALJCepeda/ts-generator
|
/src/services/schema/generateTypeMetadata.ts
| 2.8125
| 3
|
import {ReferenceSchema, ScalarSchema} from "../../extensions";
import {isReferenceSchema, isScalarSchema} from "../../guards";
export function generateTypeMetadata(schema:ScalarSchema | ReferenceSchema, options:GeneratePropertyMetadataOptions = {}): TypeMetadata {
if(isReferenceSchema(schema)) {
const parts = schema.$ref.split('/');
return {
discriminator: 'type',
type: parts[parts.length - 1]
};
}
if(isScalarSchema(schema)) {
let type = schema.type as string;
if(schema.format) {
if(options.formatMap && options.formatMap[schema.format]) {
type = options.formatMap[schema.format];
} else if(options.useFormatAsType === true) {
type = schema.format;
}
}
if(type === 'integer') {
type = 'number';
}
return {
discriminator:'type',
type
};
}
throw new Error(`Unable able to generate type metadata from schema`);
}
|
5ad8c2c375859f0cb63f3c4afa6563dc5be8352a
|
TypeScript
|
tanukichi5/react-accordion-typescript
|
/src/components/tab/helpers/uuid.ts
| 2.859375
| 3
|
// Get a universally unique identifier
let count = 0;
export default function uuid() {
//ランダムなIDを生成
const randomID = Math.random().toString(36).slice(2);
return `${randomID}--${count++}`;
}
export function reset() {
count = 0;
}
|
663213a72f90edff1f26311660b0b6397dcc7cf5
|
TypeScript
|
tamrat-bay/wix-challenge-1
|
/server/src/middlewares/verifyToken.ts
| 2.765625
| 3
|
import jwt from "jsonwebtoken";
import axios from "axios";
import { Request, Response, NextFunction } from "express";
const facebookAuthType = "facebook";
const verifyToken = (req: Request, res: Response, next: NextFunction): void => {
const authHeader: string | undefined = req.headers.authorization;
const token: string | undefined = authHeader && authHeader.split(" ")[1];
const { authType } = req.params;
authType === facebookAuthType
? verifyFbAccessToken(req, res, next, token!)
: verifyJsonWebToken(req, res, next, token!);
};
const verifyJsonWebToken = (
req: any,
res: Response,
next: NextFunction,
token: string
):void | Response<any> => {
if (!token) return res.status(401).send("Access Denied");
try {
const verified = jwt.verify(token, "anythingiwant");
if (verified) return next();
} catch (err) {
res.status(401).send("Invalid Token");
}
};
const verifyFbAccessToken = async (
req: Request,
res: Response,
next: NextFunction,
token: string
):Promise<void | Response<any>> => {
const fbUserID: string | string[] | undefined = req.headers.fbuserid;
const verifyTokenUrl:string = `https://z-p3-graph.facebook.com/v2.3/me?access_token=${token}&fields=name%2Cemail%2Cpicture&locale=en_US&method=get&pretty=0&sdk=joey&suppress_http_code=1`
if (!token) return res.status(401).send("Access Denied");
try {
const res = await axios.get(verifyTokenUrl);
if (res.data.id === fbUserID) return next();
} catch (err) {
res.status(401).send("Invalid Token");
}
};
export default verifyToken;
|
1b5f4475ba43506ac585756d3a2334f39573e351
|
TypeScript
|
mjunior/front-end-test
|
/src/app/core/models/item.ts
| 2.5625
| 3
|
export class Item {
id: number;
listId: number;
name: string;
done: boolean;
// tslint:disable-next-line:ban-types
constructor(values: Object = {}) {
Object.assign(this, values);
}
}
|
c97e6de4c3aef6f2c0d157b903b6d2b4afbbc694
|
TypeScript
|
newbeea/gl-widget
|
/src/Attribute.ts
| 2.96875
| 3
|
class Attribute {
array: Uint32Array | Float32Array
itemSize: number
normalized: boolean
constructor(itemSize: number, normalized: boolean = false) {
this.itemSize = itemSize
this.normalized = normalized
}
setXY ( index, x, y ): Attribute {
index *= this.itemSize;
this.array[ index + 0 ] = x;
this.array[ index + 1 ] = y;
return this;
}
setXYZ ( index, x, y, z ) {
index *= this.itemSize;
this.array[ index + 0 ] = x;
this.array[ index + 1 ] = y;
this.array[ index + 2 ] = z;
return this;
}
}
export {
Attribute
}
|
0a1699cdf8ca6a1aa08290e8883f1fa1d0145919
|
TypeScript
|
ismail-codar/qlike
|
/qlike-core/src/utils/query-utils.ts
| 2.8125
| 3
|
import { DbType, FieldType, IFieldLike, ParamType, ValueStringFn } from '..';
import {
AllQueryTypes,
isInsertQuery,
isSelectQuery,
isUpdateQuery,
} from '../lib/builders/builder-check';
import {
deleteQueryToString,
insertQueryToString,
selectQueryToString,
updateQueryToString,
} from '../lib/builders/generic-sql-builder';
export const isNumericDataType = (dataType: FieldType) =>
dataType.includes('num') ||
dataType.includes('int') ||
dataType === 'decimal';
export const isDateDataType = (dataType: FieldType) =>
dataType === 'timestamp' || dataType === 'datetime';
export const isStringDataType = (dataType: FieldType) =>
dataType.includes('char') || dataType.includes('text');
export const primitiveValueString = (
val,
field: IFieldLike<any>,
dbType: DbType
) => {
// in query vs..
if (isSelectQuery(val)) {
return (
'(' + selectQueryToString(val.meta, dbType, primitiveValueString) + ')'
);
} else if (Array.isArray(val)) {
return (
'(' +
val
.map((item) => {
return primitiveValueString(item, field, dbType);
})
.join(', ') +
')'
);
}
if (val instanceof Date) {
val = val.toISOString();
} else if (typeof val === 'string') {
val = val.replace(/'/g, "''");
}
if (
(dbType && field.data_type.includes('char')) ||
field.data_type.includes('text') ||
field.data_type.includes('date') ||
field.data_type.includes('time')
)
return "'" + val + "'";
else return val;
};
export const paramValueString = (params: ParamType[]) => {
const valueString: ValueStringFn = (
val,
field: IFieldLike<any>,
dbType: DbType
) => {
// in query vs..
if (isSelectQuery(val)) {
return '(' + selectQueryToString(val.meta, dbType, valueString) + ')';
} else if (Array.isArray(val)) {
return (
'(' +
val
.map((item) => {
return valueString(item, field, dbType);
})
.join(', ') +
')'
);
}
params.push({
field,
val,
dbType,
});
return '?';
};
return valueString;
};
export const queryToString = <T>(
query: AllQueryTypes<T>,
dbType: DbType,
valueString: ValueStringFn = primitiveValueString
) => {
const qlikeQueryStr = isSelectQuery<T>(query)
? selectQueryToString(query.meta, dbType, valueString)
: isInsertQuery<T>(query)
? insertQueryToString(query.meta, dbType, valueString)
: isUpdateQuery<T>(query)
? updateQueryToString(query.meta, dbType, valueString)
: deleteQueryToString(query.meta, dbType, valueString);
return qlikeQueryStr;
};
export const paramsBindValues = (params: ParamType[], dbType: DbType) => {
if (dbType === 'sqlite3' || dbType === 'absurd-sql') {
return params.map((p) => {
if (isNumericDataType(p.field.data_type)) {
return Number(p.val);
} else {
return p.val.toString();
}
});
} else {
return params.map((p) => p.val.toString());
}
};
|
c42a6e2abbcc9f3f9463552a03fea4f54370032a
|
TypeScript
|
jokester/scala-web-playground
|
/web/src/commonutil/async/index.ts
| 2.875
| 3
|
export function wait(delayMs: number) {
return new Promise<void>(f => setTimeout(f, delayMs));
}
export function timeout<FakeRetType = never>(delayMs: number) {
return new Promise<FakeRetType>((f, e) =>
setTimeout(e, delayMs, new Error(`timeout after ${delayMs}`)));
}
export async function withTimeout<T>(p: T | PromiseLike<T>, delayMs: number): Promise<T> {
return Promise.race([p, timeout<T>(delayMs)]);
}
|
2eed72104dc5238853a4c14f15e81d7f5332bff9
|
TypeScript
|
WildCodeSchool/projet2_carcassonne
|
/src/app/deck.service.ts
| 2.5625
| 3
|
import { Injectable } from '@angular/core';
import { tilesDeck } from './tuilesData';
@Injectable({
providedIn: 'root'
})
export class DeckService {
constructor() { }
pickTile() {
let numTile = Math.floor(Math.random() * tilesDeck.length)
let keepNumTile = tilesDeck[numTile]
const removedTiles = tilesDeck.splice(numTile, 1)
// console.log("tuile retiré du jeu :")
// console.log(removedTiles)
// console.log("tableau après pioche :")
// console.log(tilesDeck)
return keepNumTile
}
}
|
1299d77184f590f5c25075eb67aef89955e08462
|
TypeScript
|
AhzamSalik786/nest-project
|
/nest-js/src/books/books.controller.ts
| 2.59375
| 3
|
import { Controller, Post, Body, Get , Param} from '@nestjs/common';
import { BooksService } from './books.service';
@Controller('books')
export class BooksController {
constructor(private readonly booksServices: BooksService) {}
@Post()
async addBook(
@Body('bookName') bookBookName: string,
@Body('image') bookImage: string,
@Body('writter') bookWritter: string,
@Body('category') bookCategory: string,
@Body('description') bookDescription: string,
@Body('price') bookPrice: Number,
@Body('rating') bookRating: Number,
@Body('countInStock') bookCountInStock: Number,
@Body('numReviews') bookNumReviews: Number,
@Body('pages') bookPages: Number,
) {
const generatedId = await this.booksServices.insertBooks(
bookBookName,
bookImage,
bookWritter,
bookCategory,
bookDescription,
bookPrice,
bookRating,
bookCountInStock,
bookNumReviews,
bookPages,
);
return { id: generatedId };
}
@Get()
async getBooks() {
const books = await this.booksServices.getBooks();
return books;
}
@Get(':id')
getSingleBook(@Param('id') bookId: string) {
return this.booksServices.getSingleBook(bookId);
}
}
|
3f782bb47137c23f24daf85cdb5263c45fdfda89
|
TypeScript
|
NamXH/TypeScriptBrownbag
|
/my-app2/src/demo3_complete.ts
| 3.984375
| 4
|
//-- strictNullChecks --//
// TS compilers performs control-flow based type analysis
function countLines(text?: (string | null)[]): number {
let count = 0;
if (text) {
for (const line of text) {
if (line && line.length !== 0) {
count = count + 1;
}
}
}
return count;
}
// Steps:
// let count = 0;
// function countLines(text: string[]): number {
// if (text) { all the function }
// if (text) { only the for loop }
// function countLines(text?: (string | null)[]): number {
// if (line && line.length !== 0) {
let a2 = countLines(["one", "two", "", "three"]);
let b2 = countLines(["hello", null, "world"]);
let c2 = countLines();
//-- Quiz --//
// 1. 2nd line: string: because string empty is falsy
// 2. 1st line: null: because type of null is object
// 3. 1st line: it should be ===
|
81fdf8361d4520d06456fb544b4beae40d115217
|
TypeScript
|
eflauzo/afterglow
|
/ts/ui_widget.ts
| 2.703125
| 3
|
import { CxUIElement } from './ui_element'
import { CxScene } from './scene'
// widget is element with dimensions (it repots dimenstions)
// think about label, parent won't know how much space label need
// label knows, it can report to parent so it could be properly aligned
export class CxUIWidget extends CxUIElement{
constructor(scene:CxScene) {
super(scene)
}
// abstract width():number;
// abstract height():number;
}
|
953352db6d1b0a6c4e275629a3811e9e66b78cf6
|
TypeScript
|
Devsper/w3-projekt-frontend
|
/src/app/edit-settings/edit-settings.component.ts
| 2.578125
| 3
|
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { forkJoin } from 'rxjs';
import { AssignmentService } from '../_services/assignment.service';
import { Assignment } from '../_models/assignment';
import { TaskService } from '../_services/task.service';
@Component({
selector: 'app-edit-settings',
templateUrl: './edit-settings.component.html',
styleUrls: ['./edit-settings.component.scss']
})
export class EditSettingsComponent implements OnInit {
assignments: Assignment[];
initialCheckboxValues: any[] = [];
assignmentCheckboxes:any[];
taskCheckboxes:any[];
activeRoute;
showMessage = false;
constructor(private assignmentService: AssignmentService,
private taskService: TaskService,
private router: Router) {}
// Execute code when component initates
ngOnInit() {
if(this.router.url === '/user/edit/assignments'){
// Get assignment checkboxes and checked status that should be created
this.getAssignmentCheckboxValues();
this.activeRoute = 'assignments';
this.showMessage = false;
}
if(this.router.url === '/user/edit/tasks'){
// Get task checkboxes and checked status that should be created
this.getTaskCheckboxValues();
this.activeRoute = 'tasks';
this.showMessage = false;
}
}
/**
* Fetches assignments and determine if they should be active or not
*/
getAssignmentCheckboxValues(): void{
// Fetches all assignments
let allAssignments = this.assignmentService.fetchAllAssignments();
// Fetches only active assignments for employee
let activeAssignments = this.assignmentService.fetchEmployeeAssignments();
// Joins two Obserables together and executes logic when both has responded with values
forkJoin([allAssignments, activeAssignments]).subscribe(result =>{
let allCheckboxes = result[0];
let activeCheckboxes = result[1];
// Goes through every assignment
this.assignmentCheckboxes = allCheckboxes.map(element =>{
// Searches for matching elements
let foundTask = activeCheckboxes.find(el => el.id == element.id);
// Adds active value depending on search result
if(foundTask){
// as any needed to circumvent assignment object properties
(element as any).active = true;
}else{
(element as any).active = false;
}
return element;
});
});
}
/**
* Fetches tasks and determine if they should be active or not
*/
private getTaskCheckboxValues(): void{
// Fetches all tasks
let allTasks = this.assignmentService.fetchEmployeeAssignmentTasks();
// Fetches only active tasks for employee
let activeTasks = this.taskService.fetchEmployeeActiveTasks();
// Joins two Obserables together and executes logic when both has responded with values
forkJoin([allTasks, activeTasks]).subscribe(result =>{
let allTasks = result[0];
let activeTasks = result[1];
// Goes through every assignment
this.taskCheckboxes = allTasks.map(element =>{
let currentTasks = element.tasks;
// Loops through every task in assignment
currentTasks.forEach(task =>{
// Searches for matching elements
let taskFound = activeTasks.find(element => element.id == task.id);
// Adds active value depending on search result
if(taskFound){
// as any needed to circumvent task object properties
(task as any).active = true;
}else{
(task as any).active = false;
}
});
return element;
});
});
}
/**
* Change value of checkbox
* @param {HTMLInputElement} input - Input element of the checked checkbox
*/
onChange(input: HTMLInputElement){
// Gets numerical value from id
let checkboxId = input.id.split("-")[1];
if(this.assignmentCheckboxes){
// Find the right value in variable from id
let assignment = this.assignmentCheckboxes.find(obj => obj.id === checkboxId);
// Toggle value
assignment.active = !assignment.active;
}
if(this.taskCheckboxes){
this.taskCheckboxes.forEach(element => {
// Find the right value in variable from id
let task = element.tasks.find(obj => obj.id === checkboxId) || {};
// Toggle value
task.active = !task.active;
});
}
}
/**
* When form is submitted
*/
onSubmit(){
let checkedBoxes = [];
if(this.assignmentCheckboxes){
// Find all checked boxes
checkedBoxes = this.assignmentCheckboxes.filter(element => element.active == true);
}else if(this.taskCheckboxes){
this.taskCheckboxes.forEach(element => {
// Find all checked boxes
let tasks = element.tasks.filter(e => e.active == true);
checkedBoxes.push(tasks);
});
// Flattens array
checkedBoxes = checkedBoxes.concat.apply([], checkedBoxes);
}
// Convert id numbers to string
let idsOfCheckedBoxes = checkedBoxes.map(element => +element.id);
if(this.assignmentCheckboxes){
this.submitAssignments(idsOfCheckedBoxes);
}else if(this.taskCheckboxes){
this.submitTasks(idsOfCheckedBoxes);
}
}
/**
* Attempts to submit changes to service
* @param {string} idsOfCheckedBoxes
*/
private submitAssignments(idsOfCheckedBoxes){
this.assignmentService.updateAssignments(idsOfCheckedBoxes).subscribe((res: boolean) =>{
if(res){
this.showMessage = true;
}
});
}
/**
* Attempts to submit changes to service
* @param {string} idsOfCheckedBoxes
*/
private submitTasks(idsOfCheckedBoxes){
this.taskService.updateTasks(idsOfCheckedBoxes).subscribe((res: boolean) =>{
if(res){
this.showMessage = true;
}
});
}
}
|
4bbca45dbf868df2616af7d2dd599882160918fa
|
TypeScript
|
amirmohsen/repo-manager
|
/src/helpers/promptSoloOption/index.ts
| 2.53125
| 3
|
import { AutoComplete, AutoCompleteChoices } from 'enquirer';
export interface PromptOptionsParams {
message: string;
choices: AutoCompleteChoices;
}
const promptSoloOption = ({
message,
choices,
}: PromptOptionsParams): Promise<string> => {
const prompt = new AutoComplete({
message,
choices,
multiple: false,
});
return prompt.run() as Promise<string>;
};
export default promptSoloOption;
|
1532faa2ecd7b41186e3cffae485dc2d9c2e2bf5
|
TypeScript
|
JClap7/myFirstGit
|
/src/pages/tutor/tutor.ts
| 2.5625
| 3
|
import{ Component } from '@angular/core';
import{ Admin} from '../admin/admin';
import { Course } from '../course/course';
import { Schedule } from '../schedule/schedule';
import { Department } from '../department/department';
@Component({
selector: 'Tutor',
templateUrl:'tutor.html'
})
export class Tutor extends Admin{
officeLocation: string;
officeHours: string;
contact: string;
courses: Course[];
schedule: Schedule;
about: string;
constructor(
id: number ,
fullname: string,
email: string,
password: string,
department: Department,
accessType: string,
officeLocation: string,
officeHours: string,
contact: string,
courses: Course[],
schedule: Schedule,
about: string){
super(id,fullname,email,password,department,accessType);
this.id= id;
this.fullname= fullname;
this.email= email;
this.password= password;
this.department= department;
this.accessType= accessType;
this.officeLocation= officeLocation;
this.officeHours= officeHours;
this.contact= contact;
this.courses= courses;
this.schedule= schedule;
this.about= about;
}
}
export interface tutor extends Admin{
officeLocation: string;
officeHours: string;
contact: string;
courses: Course[];
schedule: Schedule;
about: string;
}
export function createTutor(
id: number ,
fullname: string,
email: string,
password: string,
department: Department,
accessType: string,
officeLocation: string,
officeHours: string,
contact: string,
courses: Course[],
schedule: Schedule,
about: string){
//super(number,fullname,email,password,accessType);
this.id= id;
this.fullname= fullname;
this.email= email;
this.password= password;
this.department= department;
this.accessType= accessType;
this.officeLocation= officeLocation;
this.officeHours= officeHours;
this.contact= contact;
this.courses= courses;
this.schedule= schedule;
this.about= about;
}
|
1551267f1e28a1c4aa23a385c2d19df750c1e7d5
|
TypeScript
|
believer/habitica
|
/src/habitica.ts
| 2.625
| 3
|
import { HttpMethod, User, ArmoireResult, Party, Spell } from './types'
import config from './config'
const hasItems = (items: { [key: string]: number }): Array<string> => {
const data = new Set<string>()
for (const [item, value] of Object.entries(items)) {
if (value <= 0) continue
data.add(item)
}
return Array.from(data)
}
export default class Habitica {
private baseUrl = 'https://habitica.com/api/v3'
private config = config
private fetch<T = any>(url: string, method: HttpMethod = HttpMethod.GET): T {
const response = UrlFetchApp.fetch(`${this.baseUrl}${url}`, {
method,
headers: {
'x-api-user': this.config.user.id,
'x-api-key': this.config.user.key,
},
}).getContentText()
const { data } = JSON.parse(response)
return data
}
private getUser() {
return this.fetch<User>('/user?userFields=stats,items')
}
private getParty() {
return this.fetch<Party>('/groups/party')
}
private castSpell(spell: Spell, threshold: number) {
const {
stats: { mp: mana },
} = this.getUser()
if (mana > threshold) {
this.fetch(`/user/class/cast/${spell}`, HttpMethod.POST)
Logger.log(`Casting *${spell}*`)
} else {
Logger.log(`Mana is at ${mana}. Threshold = ${threshold}`)
}
}
buyArmoire(): void {
const {
stats: { gp: gold },
} = this.getUser()
if (gold > this.config.goldThresholds.armoire) {
const { armoire } = this.fetch<ArmoireResult>(
'/user/buy-armoire',
HttpMethod.POST
)
if (armoire.type === 'food') {
Logger.log(`You gained ${armoire.dropText}`)
} else {
Logger.log(`You gained ${armoire.value} ${armoire.type}`)
}
} else {
Logger.log(
`Wallet contains ${gold} coins. Threshold = ${this.config.goldThresholds.armoire}`
)
}
}
earthquake(): void {
this.castSpell(Spell.Earthquake, this.config.manaThresholds.earthquake)
}
toolsOfTrade(): void {
this.castSpell(Spell.ToolsOfTrade, this.config.manaThresholds.toolsOfTrade)
}
hatchPets(): void {
const { items } = this.getUser()
const eggs = hasItems(items.eggs)
if (eggs.length === 0) {
Logger.log('All out of eggs')
return
}
const hatchingPotions = hasItems(items.hatchingPotions)
if (hatchingPotions.length === 0) {
Logger.log('All out of potions')
return
}
const pets = hasItems(items.pets)
const combinations = eggs
.map((egg) => hatchingPotions.map((potion) => `${egg}-${potion}`))
.map(
(combinedPets) =>
combinedPets.filter((p) => !pets.some((pet) => pet === p))[0]
)
.filter(Boolean)
combinations.forEach((combo) => {
const [pet, egg] = combo.split('-')
this.fetch(`/user/hatch/${pet}/${egg}`, HttpMethod.POST)
Logger.log(`Hatching ${egg} ${pet}`)
})
}
feedPets(): void {
const { items } = this.getUser()
const foods = []
for (const food of Object.entries(items.food)) {
if (food[1] <= 0) continue
foods.push(food)
}
if (foods.length === 0) {
Logger.log('All out of food')
}
const foodMap = {
Base: 'Meat',
CottonCandyBlue: 'CottonCandyBlue',
CottonCandyPink: 'CottonCandyPink',
Desert: 'Potatoe',
Golden: 'Honey',
Red: 'Strawberry',
Shade: 'Chocolate',
Skeleton: 'Fish',
White: 'Milk',
Zombie: 'RottenMeat',
}
const validPets = [
'BearCub',
'Cactus',
'Dragon',
'FlyingPig',
'Fox',
'LionCub',
'PandaCub',
'TigerCub',
'Wolf',
]
const pets = []
for (const pet of hasItems(items.pets)) {
const [petName, color] = pet.split('-')
const preferredFood = foodMap[color]
if (!validPets.includes(petName) || items.mounts[pet] || !preferredFood) {
continue
}
pets.push([pet, preferredFood])
}
const feed = foods
.map(([food, value]) => {
const matchFood = food.match(
/(Base|CottonCandyBlue|CottonCandyPink|Desert|Golden|Red|Shade|Skeleton|White|Zombie)/gi
)
const petFood = matchFood?.length > 0 ? foodMap[matchFood[0]] : food
const petThatLikesFood = pets.find(
([_, petLikes]) => petFood === petLikes
)
if (!petThatLikesFood) {
return null
}
return [petThatLikesFood[0], food, value]
})
.filter(Boolean)
feed.forEach(([pet, food, amount]) => {
const maxFeed = Math.floor((50 - items.pets[pet]) / 5)
const feedAmount = amount > 1 && amount > maxFeed ? maxFeed : amount
this.fetch(
`/user/feed/${pet}/${food}${
feedAmount > 1 ? `?amount=${feedAmount}` : ''
}`,
HttpMethod.POST
)
Logger.log(`Feeding ${feedAmount} ${food} to ${pet}`)
})
}
joinQuest(): void {
const { quest } = this.getParty()
if (!quest.key) {
Logger.log('No current quest')
return
}
if (quest.active) {
Logger.log('Quest has already started')
return
}
if (quest.members[this.config.user.id]) {
Logger.log('You have already joined the quest')
return
}
this.fetch('/groups/party/quests/accept', HttpMethod.POST)
Logger.log('You have joined the quest! Happy hunting')
}
healthPotion(): void {
const {
stats: { hp, gp },
} = this.getUser()
if (hp > this.config.healthThresholds.health) {
Logger.log('You are healthy enough')
return
}
if (gp < 25) {
Logger.log('Not enough gold to buy a health potion')
return
}
this.fetch('/user/buy-health-potion', HttpMethod.POST)
Logger.log(`You are healed up. Current hp = ${hp + 15}`)
}
}
|
f45345331118801c10aab4e08a6e9458088fd742
|
TypeScript
|
rostacik/CodeCon2014TSSamples
|
/CodeConTSSamples/01-BasicTypes/file1.ts
| 3.84375
| 4
|
//bool
var isDone: boolean = false;
//number
var height: number = 6;
//string
var name: string = "bob";
name = 'smith';
//array
var list: number[] = [1, 2, 3];
var list2: Array<number> = [1, 2, 3];
//enum
enum Color { Red, Green, Blue, White };
var c: Color = Color.Green;
c = Color.Red;
c = Color.White;
//any
var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
function warnUser(): void {
alert("This is my warning message");
}
function writeToConsole() {
console.log('ha!');
return true;
}
//var r: number = writeToConsole();
|
6e99d030dff931aa32fb333c6923c2ff69d66118
|
TypeScript
|
JOple/LRT-1-Bot-Assistant
|
/scripts/modules/default_dialog.ts
| 2.5625
| 3
|
import { BotModule, IBotModuleContext, DialogTypes } from "./bot_module";
import { sendCards } from "../utils/send_cards";
export const CONFIG = {
rejectThreshold: 0.5,
noneIntent: "none"
}
export class DefaultDialogModule extends BotModule {
constructor() {
super(CONFIG.noneIntent, "none")
}
protected generateDialog(context: IBotModuleContext): DialogTypes {
return session => {
let actions = context.recognizer.modules
.filter(m => m != this)
.map(m => m.fullName)
session.send("These are the things that I can do: <br/>" + actions.join(",<br/>"))
sendCards(session, "Choose Action", actions)
session.endDialog()
}
}
}
export const INSTANCE = new DefaultDialogModule();
|
09b2454340188faafb0dd725066b356fc5ebdde0
|
TypeScript
|
sergiomarmu/winter_latitude
|
/WinterLatitude_Backend/src/pages/home/home.ts
| 2.625
| 3
|
/**
* Imports de Angular y Ionic necesarios
*/
import { Component } from '@angular/core';
import { NavController,MenuController } from 'ionic-angular';
/**
* Imports necesarios para la utilización y ejecución de Firebase
*/
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
/**
* Imports del componente [.ts] de la página login
*/
import { LoginPage } from '../login/login';
import { Inicio } from '../admin-inicio/Inicio';
import { Estacion } from '../admin-estacion/Estacion';
/**
* Componente decorador, en el que incluye un selector para este componente y una página html la cuál utilizaremos
*/
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
/**
* Clase HomePage, componente de HomePage el cual nos permitira mostrar la cantidad de estaciones y deportes de nuestra BD,
* Firebase de nuestra aplicación, además de ser la página principal
*/
export class HomePage {
/**
* Definición de la variable loggedHome
* @param loggedHome
*/
loggedHome: boolean = false;
/**
* Definición de la variable estaciones, en la cuál declararemos una ListObservable
* para guardar la información que recuperamos de la BD de FireBase
* @param estaciones
*/
estaciones: FirebaseListObservable<any>;
/**
* Definición de la variable deportes, en la cuál declararemos una ListObservable
* para guardar la información que recuperamos de la BD de FireBase
* @param deportes
*/
deportes: FirebaseListObservable<any>;
/**
* Definición de la variable cmptEstaciones inicializada a 0
* @param cmptEstaciones
*/
cmptEstaciones: number = 0;
/**
* Definición de la variable cmptEstaciones inicializada a 0
* @param cmptDeportes
*/
cmptDeportes: number= 0;
/**
* Constructor de la clase HomePage
*/
constructor(public navCtrl: NavController,
db: AngularFireDatabase,
public menu: MenuController){
/**
* Habilita el menú de navegación de la aplicación
*/
this.menu.enable(true);
/**
* Comprueba si estas logueado o no, y si lo estas te lleva a la página principal
*/
if(!this.isLoggedIn()){
console.log('Estas logeado');
if(!this.loggedHome) {
this.navCtrl.push(LoginPage);
this.loggedHome = true;
}
}
/**
* Extraemos la información de las estaciones de la BD de FireBase y la guardamos en la variable estacion
*/
this.estaciones = db.list("/Estaciones", { preserveSnapshot: true });
/**
* Al recorrer las estaciones incrementamos cmptEstaciones para saber las estaciones totales
*/
this.estaciones.subscribe(snapshots => {
snapshots.forEach(snapshot => {
this.cmptEstaciones +=1;
});
})
/**
* Extraemos la información de los deportes de la BD de FireBase y la guardamos en la variable estacion
*/
this.deportes = db.list("/Home", { preserveSnapshot: true });
/**
* Al recorrer las estaciones incrementamos cmptDeportes para saber las estaciones totales
*/
this.deportes.subscribe(snapshots => {
snapshots.forEach(snapshot => {
this.cmptDeportes +=1;
});
})
}
/**
* Función comprueba si estás logueado, recuperando una variable de localStorage
* @return true
*/
isLoggedIn(){
if(window.localStorage.getItem('currentuser')){
return true;
}
}
/**
* Función que la cierra sessión y te vuelve a la página del login
*/
logOut(){
window.localStorage.removeItem('currentuser');
this.loggedHome = false;
}
/**
* Función que resetea el contenido del nav, a su correspondiente página y la muestra
* @param page
*/
openPage(page) {
switch (page){
case 'Inicio':
this.navCtrl.setRoot(Inicio);
break;
case 'Estacion':
this.navCtrl.setRoot(Estacion);
break;
}
}
}
|
de87eaaf90ae79a75e772378307ef53e0b6da4f5
|
TypeScript
|
hectorMurillo/Angular2Cli
|
/src/app/validators/custom-validators.ts
| 2.796875
| 3
|
import { FormControl, AbstractControl } from '@angular/forms';
export class CustomValidators {
static formatoNumero(control: FormControl): any{
let exp: any = /^[0-9]+$/
if(control.value !== undefined && !exp.test(control.value)) {
return {'formatoNumero': true, 'currentValue': control.value};
}
return null;
}
static filtraNombre(nombre: string): any{
return function(control){
if(control.value === nombre) {
return {'filtraNombre': true};
}
return null;
}
}
}
|
f48dc36170ff691ea68d47d97dd86ec1e5bcdb06
|
TypeScript
|
briangtn/b12normalize
|
/src/B12Normalizer.ts
| 3.390625
| 3
|
export type ParserFunction = (value: any, args?: any) => any;
export type ParserList = Map<string, ParserFunction>;
export interface Rule {
action?: ParserFunction;
parser?: string;
arguments?: any;
}
export class B12Normalizer {
constructor(private _parsers: ParserList = new Map()) {}
/**
* Return the list of registered parsers.
*
* @returns The list of registered parsers
*/
get parsers(): ParserList {
return this._parsers;
}
/**
* Add a parser to the list of parsers
* @param name The key to use for parse with this parser
* @param parser The function called for parse the data
*/
public addParser(name: string, parser: ParserFunction) {
if (this._parsers.get(name))
throw new Error('Parser already exist');
this.setParser(name, parser);
}
/**
* Set the parser for the key
* @param name
* @param parser
*/
public setParser(name: string, parser: ParserFunction) {
this._parsers.set(name, parser);
}
/**
* Return a parser by name.
* Throw an exception if the parser does not exist.
* @param name The name of the parser to find
*/
public getParserByName(name: string) {
const parser = this._parsers.get(name);
if (!parser) {
throw new Error(`Parser '${name}' not found`);
}
return parser
}
/**
* Remove a parser from the list
* @param name The name of the parser to remove
*/
public removeParser(name: string) {
this._parsers.delete(name);
}
/**
* Normalize the given object
* @param toNormalize The object to normalize
* @param rules The normalization options
*/
public normalize(toNormalize: object | [], rules: object) {
if (!toNormalize)
return toNormalize;
const toNormalizeCopy = JSON.parse(JSON.stringify(toNormalize)) as object | [];
if (Array.isArray(toNormalizeCopy))
return this.normalizeArray(toNormalizeCopy, rules);
for (let [key, rule] of Object.entries(rules)) {
let currentKey = toNormalizeCopy[key as keyof typeof toNormalize];
if (!currentKey) {
continue;
}
if (typeof rule === 'object' && !Array.isArray(rule) && typeof currentKey === 'object') {
if (Array.isArray(currentKey)) {
this.normalizeArray(currentKey, rule);
} else {
this.normalize(currentKey, rule);
}
continue;
}
if (!Array.isArray(rule)) {
rule = [rule];
}
currentKey = this.applyRules(currentKey, rule) as never;
toNormalizeCopy[key as keyof typeof toNormalizeCopy] = currentKey;
}
return toNormalizeCopy;
}
/**
* Normalize an array of element
* @param toNormalize The data to normalize
* @param rules The parsing rules to apply
* @private
*/
private normalizeArray(toNormalize: [], rules: object) {
for (let i = 0 ; i < toNormalize.length; i++) {
toNormalize[i] = this.normalize(toNormalize[i], rules) as never;
}
return toNormalize;
}
/**
* Apply some rules to data
* @param value The value to parse
* @param rules The rules used to parse
* @private
*/
private applyRules(value: any, rules: (ParserFunction | string)[]) {
for (const rule of rules) {
value = this.applyRule(value, rule);
}
return value;
}
private getRuleObject(rule: ParserFunction | string | Rule): Rule {
let result = {} as Rule;
if (typeof rule === 'function') {
result.action = rule;
} else if (typeof rule === 'string') {
result.action = this.getParserByName(rule);
} else {
if (!rule.action)
rule.action = this.getParserByName(rule.parser!);
result = rule;
}
result.arguments = result.arguments || {};
return result;
}
/**
* Apply a rule to data
* @param value The value to parse
* @param rule The rule used to parse
* @private
*/
private applyRule(value: any, rule: ParserFunction | string | Rule) {
rule = this.getRuleObject(rule);
return rule.action!(value, rule.arguments);
}
}
|
24d04b96f1e884e7e1b57023339df767be0c3621
|
TypeScript
|
OdatNurd/ts-game-engine
|
/ts/engine/Preloader.ts
| 3.140625
| 3
|
module nurdz.game.Preloader
{
/**
* The type of a callback function to invoke when all images and sound loading is complete. The
* function takes no arguments and returns no value.
*/
export type DataPreloadCallback = () => void;
/**
* The type of a callback function to invoke when an image preload is completed. The function is passed as
* an argument the handle to the loaded image element and returns no value.
*/
export type ImagePreloadCallback = (HTMLImageElement) => void;
/**
* The type of a callback function to invoke when a sound preload is completed. The function is passed as
* an argument the handle to the loaded audio element and returns no value.
*/
export type SoundPreloadCallback = (Sound) => void;
/**
* This interface is used to shape entries in our preload list for images. It tells the TypeScript
* compiler that objects of this type need to be indexed by a string and the result should be an HTML
* image.
*/
interface ImagePreload
{
[index : string] : HTMLImageElement;
}
/**
* This interface is used to shape entries in our preload list for sounds.
*
* Unlike images where we coalesce all duplicate images into a single image tag, for sounds we don't
* do this. If sounds share the same tag, then changes to the volume or loop of one instance would
* affect all instances.
*
* As such, this type associates the source of a sound with the tag that wraps it so that we can store
* the values in an array for preloading.
*/
interface SoundPreload
{
/**
* The source URL for this sound object.
*/
src : string;
/**
* The tag element that will be preloaded.
*/
tag : HTMLAudioElement;
}
/**
* This stores the extension that should be applied to sounds loaded by the preloader so that it loads
* a file type that is appropriate for the current browser.
*
* @type {string}
* @private
*/
var _audioExtension : string = function () : string
{
let tag = document.createElement ("audio");
if (tag.canPlayType ("audio/mp3"))
return ".mp3";
else
return ".ogg";
} ();
/**
* This tracks whether or not preloading has already started or not. Once preloading has started, we
* don't allow any more submissions to the preload queues.
*
* @type {boolean}
* @private
*/
var _preloadStarted = false;
/**
* The list of images to be preloaded.
*
* @type {Object<string,HTMLImageElement>}
* @private
*/
var _imagePreloadList : ImagePreload = {};
/**
* The list of sounds (and music, which is a special case of sound) to be preloaded.
* @type {Array<SoundPreload>}
* @private
*/
var _soundPreloadList : Array<SoundPreload> = [];
/**
* The number of images that still need to be loaded before all images are considered loaded. This
* gets incremented as preloads are added and decremented as loads are completed.
*
* @type {number}
* @private
*/
var _imagesToLoad = 0;
/**
* The number of sounds that still need to be loaded before all images are considered loaded. This
* gets incremented as preloads are added and decremented as loads are completed.
*
* @type {number}
* @private
*/
var _soundsToLoad = 0;
/**
* The stage passed to the commence method (if any). If this is set, every time the number of items to
* preload changes, the stage is updated to reflect it.
*
* @type {Stage}
* @private
*/
var _stage : Stage = null;
/**
* The callback to invoke when preloading has started and all images and sounds are loaded.
*/
var _completionCallback : DataPreloadCallback;
/**
* If we have a stage, this centers some text on it that tells us how many items we have left to
* preload. It gets update every time the number of items left to preload changes.
*/
function updatePreloadProgress () : void
{
// If there is no stage, just leave.
if (_stage == null)
return;
// Get the canvas context out, save its state and then set up our rendering.
let _context = (<CanvasRenderer>_stage.renderer).context;
_context.save ();
_context.textAlign = "center";
_context.textBaseline = "middle";
_context.font = "32px monospace";
// Clear the stage and draw the text now.
let text = "Preloading files, " + (_imagesToLoad + _soundsToLoad) + " left to go";
_stage.renderer.clear ('black');
_stage.renderer.drawTxt (text, _stage.width / 2, _stage.height / 2, 'white');
// Done now
_context.restore ();
}
/**
* This gets invoked as the event handler function for all of our preloads of all file types. For
* images this is one of "load" or "error", while for sounds it is one of "canplaythrough" or "error".
*
* Regardless of the event type, this removes itself as the event handler for events of the given
* type, counts down the preloaded file, and calls the main preload callback once everything is
* handled (error or not).
*
* Additionally, when an error happens, the file that is missing is logged to the console and a data
* URL is applied to the element so that everything still works. For images this is a red X in a box
* while for audio elements it is a small segment of silence.
*
* @param eventObj the event object being handled (one of "load", "error" or "canplaythrough"
*/
function preloadCallbackEvent (eventObj : Event) : void
{
// Get the element that is the target of the event. This requires a type cast since not all events
// are targeted to DOM elements, but we know that load/error/canplaythrough are.
let tag : HTMLImageElement|HTMLAudioElement = (<HTMLImageElement|HTMLAudioElement>eventObj.target);
// Determine if this is an image or not so we can act accordingly.
let isImage = tag.tagName.toLowerCase () == "img";
// Set up an error event object if this is an error event.
let errorEvent : ErrorEvent = (eventObj.type == "error") ? <ErrorEvent> eventObj : null;
// To start with, remove ourselves as the handlers for load and error events. We use a load event
// for an image but a canplaythrough event for audio.
if (isImage)
tag.removeEventListener ("load", preloadCallbackEvent, false);
else
tag.removeEventListener ("canplaythrough", preloadCallbackEvent, false);
tag.removeEventListener ("error", preloadCallbackEvent, false);
// Special handling if this is an error.
if (errorEvent != null)
{
// Note the error in the console.
console.log ("Preload error:", (isImage ? "image" : "sound"), tag.src);
// Depending on the tag type, use a data URL to approximate the missing data.
if (isImage)
tag.src = MISSING_IMAGE;
else
{
if (_audioExtension == ".mp3")
tag.src = MISSING_MP3;
else
tag.src = MISSING_OGG;
// For audio we want to make sure it doesn't loop.
(<HTMLAudioElement> tag).loop = false;
}
}
// Check now for preload callbacks the caller may have specified for this item.
//
// Multiple requests to preload the same image load it only once and share the same tag, so for
// images the callbacks are an array that contains the callback functions, although this array can
// be empty if nobody cared (the array is created when the tag is).
//
// For sound/music, requests do not share tags. As a result, for items of this type the callback
// property either does not exist or is the function to invoke.
//
// Image callbacks take the image element but sound/music callbacks take the Sound() instance that
// wraps the element. For this reason the audio elements are augmented not only with a callback
// but a reference to the owning Sound() instance.
if (isImage)
{
// If there are any callbacks on this element, invoke them now.
if (tag["_ng_callback"].length != 0)
{
let list = tag["_ng_callback"];
for (let i = 0 ; i < list.length ; i++)
list[i] (tag);
}
}
else
{
// If there is a callback, invoke it.
if (tag["_ng_callback"] != null)
tag["_ng_callback"] (tag["_ng_sndObj"]);
}
// Now decrement the appropriate count.
if (isImage)
_imagesToLoad--;
else
_soundsToLoad--;
// If everything is loaded, trigger the completion callback now. Otherwise, update our progress text.
if (_imagesToLoad == 0 && _soundsToLoad == 0)
_completionCallback ();
else
updatePreloadProgress ();
}
/**
* Add the image filename specified to the list of images that will be preloaded. The "filename" is
* assumed to be a path that is relative to the page that the game is being served from and inside of
* an "images/" sub-folder.
*
* The (optional) callback function can be provided to let you know when the image is finally finished
* loading, in case you need that information (e.g. for getting the dimensions). The callback is
* guaranteed to be invoked before the callback that indicates that all preloads have completed.
*
* The return value is an image tag that can be used to render the image once it is loaded.
*
* @param filename the filename of the image to load; assumed to be relative to a images/ folder in
* the same path as the page is in.
* @param callback if non-null, this will be invoked when the image is fully loaded.
* @returns {HTMLImageElement} the tag that the image will be loaded into.
* @throws {Error} if an attempt is made to add an image to preload after preloading has already started
*/
export function addImage (filename : string, callback : ImagePreloadCallback = null) : HTMLImageElement
{
// Make sure that preloading has not started.
if (_preloadStarted)
throw new Error ("Cannot add images after preloading has already begun or started");
// Create a key that is the URL that we will be loading, and then see if there is a tag already in
// the preload dictionary that uses that URL.
let key = "images/" + filename;
let tag = _imagePreloadList[key];
// If there is not already a tag, then we need to create a new one.
if (tag == null)
{
// Create a new tag, indicate the function to invoke when it is fully loaded or fails to load, and
// then add it to the preload list.
tag = document.createElement ("img");
tag.addEventListener ("load", preloadCallbackEvent, false);
tag.addEventListener ("error", preloadCallbackEvent, false);
_imagePreloadList[key] = tag;
// Set in a new property in the tag that lists callbacks that might be registered for this
// element.
tag["_ng_callback"] = [];
// This counts as an image that we are going to preload.
_imagesToLoad++;
}
// If a callback has been provided, add it to the callback list.
if (callback != null)
tag["_ng_callback"].push (callback);
// Return the tag back to the caller so that they know how to render later.
return tag;
}
/**
* This does all of the work of actually adding a sound to the preload queue for sound files as
* needed, returning back the audio tag that wraps the passed filename.
*
* This assumes that the filename is relative to a folder named subFolder inside the path that the game
* page is in, and that it does not have an extension so that one can be properly selected.
*
* The callback function can be provided to let you know when the sound is finally finished loading, in
* case you need that information.
*
* @param subFolder the subFolder that the filename is assumed to be in
* @param filename the filename of the sound to load; assumed to be relative to a sounds/ folder in
* the same path as the page is in and to have no extension
* @param callback if non-null, this will be invoked when the sound is fully loaded.
* @returns {HTMLAudioElement} the sound object that will (eventually) play the requested audio
* @throws {Error} if an attempt is made to add a sound to preload after preloading has already started
*/
var doAddSound = function (subFolder : string, filename : string,
callback : SoundPreloadCallback) : HTMLAudioElement
{
// Make sure that preloading has not started.
if (_preloadStarted)
throw new Error ("Cannot add sounds after preloading has already begun or started");
// Create a sound preload object.
let preload : SoundPreload =
{
src: subFolder + filename + _audioExtension,
tag: document.createElement ("audio")
};
// Create a new tag, indicate the function to invoke when it is fully loaded or fails to load, and
// then add it to the preload list.
preload.tag.addEventListener ("canplaythrough", preloadCallbackEvent);
preload.tag.addEventListener ("error", preloadCallbackEvent);
// Audio tags don't reuse a previous tag when a preload happens (so that playback can be controlled
// individually).
//
// For callbacks on loaded audio we just set the callback directly to the function if one is present.
// The absence of this property on the object means no callback.
if (callback != null)
preload.tag["_ng_callback"] = callback;
// Insert it into the sound preload list and count it as a sound to be preloaded.
_soundPreloadList.push (preload);
_soundsToLoad++;
// Return the tag back to the caller so that they can play it later.
return preload.tag;
};
/**
* Add the sound filename specified to the list of sounds that will be preloaded. The "filename" is
* assumed to be in a path that is relative to the page that the game is being served from an inside
* of a "sounds/" sub-folder.
*
* NOTE: Since different browsers support different file formats, you should provide both an MP3 and
* an OGG version of the same file, and provide a filename that has no extension on it. The code in
* this method will apply the correct extension based on the browser in use and load the appropriate
* file.
*
* The (optional) callback function can be provided to let you know when the browser thinks that
* enough of the file has loaded that playing would play right through. The callback is guaranteed to be
* invoked before the callback that indicates that all preloads have completed.
*
* The return value is a sound object that can be used to play the sound once it's loaded.
*
* @param filename the filename of the sound to load; assumed to be relative to a sounds/ folder in
* the same path as the page is in and to have no extension
* @param callback if non-null, this will be invoked with the sound object when the load is finished.
* @returns {Sound} the sound object that will (eventually) play the requested audio
* @throws {Error} if an attempt is made to add a sound to preload after preloading has already started
* @see addMusic
*/
export function addSound (filename : string, callback : SoundPreloadCallback = null) : Sound
{
// Get the audio tag and wrap it in a sound object.
let audioTag = doAddSound ("sounds/", filename, callback);
let snd = new Sound (audioTag);
// If there was a callback provided, we need to tell the audio tag what the sound object is so
// that it can be provided to the callback.
if (callback != null)
audioTag["_ng_sndObj"] = snd;
// If there is a callback,
return snd;
}
/**
* Add the music filename specified to the list of music that will be preloaded. The "filename" is
* assumed to be in a path that is relative to the page that the game is being served from an inside
* of a "music/" sub-folder.
*
* NOTE: Since different browsers support different file formats, you should provide both an MP3 and
* an OGG version of the same file, and provide a filename that has no extension on it. The code in
* this method will apply the correct extension based on the browser in use and load the appropriate file.
*
* The (optional) callback function can be provided to let you know when the browser thinks that
* enough of the file has loaded that playing would play right through. The callback is guaranteed to be
* invoked before the callback that indicates that all preloads have completed.
*
* This works identically to addSound() except that the sound returned is set to play looped by
* default.
*
* @param filename the filename of the sound to load; assumed to be relative to a sounds/ folder in
* the same path as the page is in and to have no extension
* @param callback if non-null, this will be invoked with the sound object when the load is finished.
* @returns {Sound} the sound object that will (eventually) play the requested audio
* @throws {Error} if an attempt is made to add a sound to preload after preloading has already started
* @see addSound
*/
export function addMusic (filename : string, callback : SoundPreloadCallback = null) : Sound
{
// Get the audio tag and wrap it in a sound object.
let audioTag = doAddSound ("music/", filename, callback);
let snd = new Sound (audioTag, true);
// If there was a callback provided, we need to tell the audio tag what the sound object is so
// that it can be provided to the callback.
if (callback != null)
audioTag["_ng_sndObj"] = snd;
// If there is a callback,
return snd;
}
/**
* Start the file preloads happening. Once all images and sound/music files requested are fully
* loaded, the callback function provided will be invoked, which means that everything is ready to go.
*
* The preloader handles errors by logging them to the console and replacing the failed file with a
* placeholder, either an image or a sound, which is embedded in the source and is guaranteed to work.
*
* If a stage is provided, the preloader will output the number of things still to preload to the
* center of the stage, just so that you know that it's doing something.
*
* @param callback the callback to invoke when all of the preloading is completed
* @param stage the stage that is hosting the game (optional).
*
* @throws {Error} if image preloading is already started
*/
export function commence (callback : DataPreloadCallback, stage : Stage = null)
{
// Make sure that image preloading is not already started
if (_preloadStarted)
throw new Error ("Cannot start preloading; preloading is already started");
// Save the callback and stage and then indicate that the preload has started.
_stage = stage;
_completionCallback = callback;
_preloadStarted = true;
// If there is nothing to preload, fire the callback now and leave.
if (_imagesToLoad == 0 && _soundsToLoad == 0)
{
_completionCallback ();
return;
}
// Update the stage to say how many things are left.
updatePreloadProgress ();
// Iterate over the entire preload list and set in the source to get the image from. This will start
// the browser loading things.
for (let key in _imagePreloadList)
{
if (_imagePreloadList.hasOwnProperty (key))
_imagePreloadList[key].src = key;
}
// For sounds they're in an array instead of an object so that we can load duplicates.
for (let i = 0 ; i < _soundPreloadList.length ; i++)
_soundPreloadList[i].tag.src = _soundPreloadList[i].src;
}
//noinspection SpellCheckingInspection
/**
* In case there is an image missing, this data URL is used to represent the image so that things can
* proceed, albeit in a broken manner. This aids in prototyping.
*
* This was drawn by me (which explains its quality) and is a 64x64 pixel image of a red X in a square
* with a white background.
*
* @type {string}
*/
const MISSING_IMAGE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABABAMAAABYR2ztAAAAAXNSR0IArs" +
"4c6QAAABVQTFRF////zDMz/8zMzGZmzJmZ/5mZ/2ZmAD7C7QAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAH" +
"dElNRQffDB8VMBekTnw9AAAAHWlUWHRDb21tZW50AAAAAABDcmVhdGVkIHdpdGggR0lNUGQuZQcAAAE4SURBVEjH5ZVNEoIwDI" +
"WxoGsRdS03gBvoDeQGev9LOEn/XtIGFu60C2bafg0v6Qs0/cZotoFmdfwa4JNOY6HpDYG44kdHs5OIsKOlVwRGmt0FsI9naDia" +
"XJRIWhsw3KQAFJFhAPKpps16AAARc04ZC5Xiol4EkogHqgEgiuAcz5W7iJFTkYrLCiKwIBJgEZiuBnjrSTle635gEQM9joZhUj" +
"PcDGAJ+yfLcrsigAL2fv9sm9YDkw0sokgVYJQ5lsCsctAAO2ntFXORpQS6fiOLsSykAFy8icEAOMB7pdR8WLaoAA685ezbDN3S" +
"C0MB0KKna4aJ3XIwLNdFIzjpiARw5KfqXABcLpBorAToj8NRA+8cV4oIQIvlESICMGPyle7uRFQhwgOPlGMhggGnTIAi/u6fZQ" +
"Pf/v0/eDU21RARJ0gAAAAASUVORK5CYII=";
//noinspection SpellCheckingInspection
/**
* In case there is a sound missing in MP3 format, this data URL is used to represent it. It
* represents 0.03 seconds of silence in MP3 format as generated by:
*
* ffmpeg -ar 22000 -t 0.01 -f s16le -acodec pcm_s16le -ac 2 -i /dev/zero -acodec libmp3lame missing.mp3
*
* @type {string}
*/
const MISSING_MP3 = "data:audio/mp3;base64,SUQzBAAAAAAAGVRTU0UAAAAPAAADTGF2ZjU0LjI1LjEwNQD/83AAAAAAAAAA" +
"AAAAAAAAAAAAAABJbmZvAAAABwAAAAMAAAMoAHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e729vb29vb29vb29vb" +
"29vb29vb29vb29vb29vb29vb29vf///////////////////////////////////////////0xhdmY1NC4yNS4xMDUAAAAAAAAA" +
"ACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/zgGQAAAABpAAAAAAAAANIAAAAAExBTUUzLjk5LjVVVVVVVVVVVVVVVVVVVVVVVV" +
"VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" +
"VVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjk5LjVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" +
"VVVVVVVVVVVVVVVVX/84JkQwAAAaQAAAAAAAADSAAAAABVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" +
"VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" +
"VVVVVVVVVVTEFNRTMuOTkuNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" +
"Vf/zgmRDAAABpAAAAAAAAANIAAAAAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" +
"VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" +
"VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV";
//noinspection SpellCheckingInspection
/**
* In case there is a sound missing in Ogg format, this data URL is used to represent it. It
* represents 0.03 seconds of silence in Ogg format.
*
* This was generated similarly to the MP3 version above by generating a wav file instead (-acodec
* copy) and using oggenc at the lowest possible quality, downsampling to mono.
*
* @type {string}
*/
const MISSING_OGG = "data:audio/ogg;base64,T2dnUwACAAAAAAAAAABUhPp7AAAAAAFv/AUBHgF2b3JiaXMAAAAAAfBVAAAA" +
"AAAAgD4AAAAAAACqAU9nZ1MAAAAAAAAAAAAAVIT6ewEAAADNTe8JDj3///////////////+aA3ZvcmJpcy0AAABYaXBoLk9yZy" +
"BsaWJWb3JiaXMgSSAyMDEwMTEwMSAoU2NoYXVmZW51Z2dldCkAAAAAAQV2b3JiaXMiQkNWAQAIAACAIAoZxoDQkFUAABAAAEKI" +
"RsZQp5QEl4KFEEfEUIeQ81Bq6SB4SmHJmPQUaxBCCN97z7333nsgNGQVAAAEAEAYBQ5i4DEJQgihGMUJUZwpCEIIYTkJlnIeOg" +
"lC9yCEEC7n3nLuvfceCA1ZBQAAAgAwCCGEEEIIIYQQQgoppRRSiimmmGLKMcccc8wxyCCDDDropJNOMqmkk44yyaij1FpKLcUU" +
"U2y5xVhrrTXn3GtQyhhjjDHGGGOMMcYYY4wxxghCQ1YBACAAAIRBBhlkEEIIIYUUUoopphxzzDHHgNCQVQAAIACAAAAAAEeRFM" +
"mRHMmRJEmyJEvSJM/yLM/yLE8TNVFTRVV1Vdu1fduXfdt3ddm3fdl2dVmXZVl3bVuXdVfXdV3XdV3XdV3XdV3XdV3XdSA0ZBUA" +
"IAEAoCM5jiM5jiM5kiMpkgKEhqwCAGQAAAQA4CiO4jiSIzmWY0mWpEma5Vme5WmeJmqiB4SGrAIAAAEABAAAAAAAoCiK4iiOI0" +
"mWpWma56meKIqmqqqiaaqqqpqmaZqmaZqmaZqmaZqmaZqmaZqmaZqmaZqmaZqmaZqmaZpAaMgqAEACAEDHcRzHURzHcRzJkSQJ" +
"CA1ZBQDIAAAIAMBQFEeRHMuxJM3SLM/yNNEzPVeUTd3UVRsIDVkFAAACAAgAAAAAAMDxHM/xHE/yJM/yHM/xJE/SNE3TNE3TNE" +
"3TNE3TNE3TNE3TNE3TNE3TNE3TNE3TNE3TNE3TNE3TNE3TgNCQVQAAAgAAIIhChjEgNGQVAAAEAIAQopEx1CklwaVgIcQRMdQh" +
"5DyUWjoInlJYMiY9xRqEEML33nPvvfceCA1ZBQAAAQAQRoGDGHhMghBCKEZxQhRnCoIQQlhOgqWch06C0D0IIYTLubece++9B0" +
"JDVgEAgAAADEIIIYQQQgghhJBCSimFlGKKKaaYcswxxxxzDDLIIIMOOumkk0wq6aSjTDLqKLWWUksxxRRbbjHWWmvNOfcalDLG" +
"GGOMMcYYY4wxxhhjjDGC0JBVAAAIAABhkEEGGYQQQkghhZRiiinHHHPMMSA0ZBUAAAgAIAAAAMBRJEVyJEdyJEmSLMmSNMmzPM" +
"uzPMvTRE3UVFFVXdV2bd/2Zd/2XV32bV+2XV3WZVnWXdvWZd3VdV3XdV3XdV3XdV3XdV3XdR0IDVkFAEgAAOhIjuNIjuNIjuRI" +
"iqQAoSGrAAAZAAABADiKoziO5EiO5ViSJWmSZnmWZ3map4ma6AGhIasAAEAAAAEAAAAAACiKojiK40iSZWma5nmqJ4qiqaqqaJ" +
"qqqqqmaZqmaZqmaZqmaZqmaZqmaZqmaZqmaZqmaZqmaZqmaZomEBqyCgCQAADQcRzHcRTHcRxHciRJAkJDVgEAMgAAAgAwFMVR" +
"JMdyLEmzNMuzPE30TM8VZVM3ddUGQkNWAQCAAAACAAAAAABwPMdzPMeTPMmzPMdzPMmTNE3TNE3TNE3TNE3TNE3TNE3TNE3TNE" +
"3TNE3TNE3TNE3TNE3TNE3TNE3TNCA0ZCUAAAQAgCDHtIMkCYSgguQZxBzEpBmFoILkOgYlxeQhp6Bi5DnJmEHkgtJFpiIIDVkR" +
"AEQBAADGIMYQc8g5J6WTFDnnpHRSGgihpY5SZ6m0WmLMKJXaUq0NhI5SSC2jVGItrXbUSq0ltgIAAAIcAAACLIRCQ1YEAFEAAI" +
"QxSCmkFGKMOcgcRIwx6BhkhjEGIXNOQccchVQqBx11UFLDGHOOQaigg1Q6R5WDUFJHnQAAgAAHAIAAC6HQkBUBQJwAgEGSNM3S" +
"NM+zNM/zPFFUVU8UVdUSPdP0TFNVPdNUVVM1ZVdUTVm2PNE0PdNUVc80VVU0Vdk1TdV1PVW1ZdNVdVl0Vd12bdm3XVkWbk9VZV" +
"tUXVs3VVfWVVm2fVe2bV8SRVUVVdV1PVV1XdV1ddt0XV33VFV2TdeVZdN1bdl1ZVtXZVn4NVWVZdN1bdl0Xdl2ZVe3VVnWbdF1" +
"fV2VZeE3Zdn3ZVvXfVm3lWF0XdtXZVn3TVkWftmWhd3VdV+YRFFVPVWVXVFVXdd0XVtXXde2NdWUXdN1bdlUXVlWZVn3XVfWdU" +
"1VZdmUZds2XVeWVVn2dVeWdVt0XV03ZVn4VVfWdVe3jWO2bV8YXVf3TVnWfVWWdV/WdWGYddvXNVXVfVN2feF0ZV3Yfd8YZl0X" +
"js91fV+VbeFYZdn4deEXllvXhd9zXV9XbdkYVtk2ht33jWH2feNYddsYZls3urpOGH5hOG7fOKq2LXR1W1he3Tbqxk+4jd+oqa" +
"qvm65r/KYs+7qs28Jw+75yfK7r+6osG78q28Jv67py7L5P+VzXF1ZZFobVloVh1nVh2YVhqdq6Mry6bxyvrSvD7QuN31eGqm0b" +
"y6vbwjD7tvDbwm8cu7EzBgAADDgAAASYUAYKDVkRAMQJAFgkyfMsyxJFy7JEUTRFVRVFUVUtTTNNTfNMU9M80zRNU3VF01RdS9" +
"NMU/M009Q8zTRN1XRV0zRlUzRN1zVV03ZFVZVl1ZVlWXVdXRZN05VF1XRl01RdWXVdV1ZdV5YlTTNNzfNMU/M80zRV05VNU3Vd" +
"y/NUU/NE0/VEUVVVU1VdU1VlV/M8U/VETzU9UVRV0zVl1VRVWTZV05ZNU5Vl01Vt2VVlV5Zd2bZNVZVlUzVd2XRd13Zd13Zd2R" +
"V2SdNMU/M809Q8TzVNU3VdU1Vd2fI81fREUVU1TzRVVVVd1zRVV7Y8z1Q9UVRVTdRU03RdWVZVU1ZF1bRlVVV12TRVWXZl2bZd" +
"1XVlU1Vd2VRdWTZVU3ZdV7a5siqrnmnKsqmqtmyqquzKtm3rruvqtqiasmuaqmyrqqq7smvrvizLtiyqquuarirLpqrKtizLui" +
"7LtrCrrmvbpurKuivLdFm1Xd/2bbrquravyq6vu7Js667t6rJu277vmaYsm6op26aqyrIsu7Zty7IvjKbp2qar2rKpurLtuq6u" +
"y7Js26JpyrKpuq5tqqYsy7Js+7Is27bqyrrs2rLtu64s27JtC7vsCrOvurKtu7JtC6ur2rbs2z5bV3VVAADAgAMAQIAJZaDQkJ" +
"UAQBQAAGAMY4xBaJRyzjkIjVLOOQchcw5CCKlkzkEIoaTMOQilpJQ5B6GUlEIIpaTUWgihlJRaKwAAoMABACDABk2JxQEKDVkJ" +
"AKQCABgcR9NM03Vl2RgWyxJFVZVl2zaGxbJEUVVl2baFYxNFVZVl29Z1NFFUVVm2bd1XjlNVZdm2fV04MlVVlm1b130jVZZtW9" +
"eFoZIqy7Zt675RSbZtXTeG46gk27bu+75xLPGFobAslfCVXzgqgQAA8AQHAKACG1ZHOCkaCyw0ZCUAkAEAABiklFFKKaOUUkop" +
"xpRSjAkAABhwAAAIMKEMFBqyIgCIAgAAnHPOOeecc84555xzzjnnnHPOOecYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMc" +
"YEAOxEOADsRFgIhYasBADCAQAAhBSCklIppZQSOeeklFJKKaWUyEEIpZRSSimlRNJJKaWUUkoppXFQSimllFJKKaGUUkoppZRS" +
"SgmllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZ" +
"RSSimllFJKKaWUUkoBACYPDgBQCTbOsJJ0VjgaXGjISgAgNwAAUIo5xiSUkEpIJYQQSuUYhM5JCSm1VkIKrYQKOmido5BSS62V" +
"lEpJmYQQQiihhFJaKSW1UjIIoYRQSgghpVJKCaFlUEIKJZSUUkkttFRKySCEUFoJqZXUWgollZRBKamEklIqrbWUSkqtg9JSKa" +
"211kpKIZWWUgelpJZSKaW1FkprrbVOUiktpNZSa62VVkopnaWUSkmttZZaaymlVkIprbTSWikltdZSay2V1FpLraXWUmutpdZK" +
"KSWlllprrbWWWioptZRCKaWVkkJqqaXWSiothNBSSaWVVlprKaWUSigllZRaKqm1llJopYXSSkklpZZKKiml1FIqoZQSUiqhld" +
"RSa6mllkoqLbXUUiuplJZKSqkUAAB04AAAEGBEpYXYacaVR+CIQoYJKAAAEAQAGIiQmUCgAAoMZADAAUKCFABQWGAoXeiCECJI" +
"F0EWD1w4ceOJG07o0AYAGIiQmQChGCIkZAPABEWFdACwuMAoXeiCECJIF0EWD1w4ceOJG07o0AIBAAAAAMABAB8AAAcGEBHRXI" +
"bGBkeHxwdIiAgAAAAAAAAAAAAAAIBPZ2dTAAQABAAAAAAAAFSE+nsCAAAAN7BaJQMBAQEAAAA=";
}
|
c611bedb64a8dbcf36657034c8c6b6427e2462f8
|
TypeScript
|
valen-developer/newspaper-backend-node
|
/src/context/User/domain/valueObject/UserPassword.valueObject.ts
| 3.171875
| 3
|
import { HTTPException } from '../../../shared/domain/HTTPException';
import { ValueObject } from '../../../shared/domain/valueObjects/valueObject.interface';
export class UserPassword implements ValueObject {
public readonly value: string | null | undefined;
constructor(value: string | null | undefined) {
this.value = value;
if (value) this.isValid();
}
private isValid(): void {
if (!UserPassword.isValidPassword(this.value ?? '')) {
throw new HTTPException(
'user password',
'user password is not a valid password',
400
);
}
}
public static isValidPassword(value: string): boolean {
if (!value) return false;
const regExp = /((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]))/;
return regExp.test(value) && value.length >= 8;
}
}
|
af74178d61355fd699ca30f86b1d888f1694666f
|
TypeScript
|
bahtirek/StartNG
|
/src/app/directives/format.directive.ts
| 2.640625
| 3
|
import { Directive, HostListener} from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appFormat]'
})
export class FormatDirective {
constructor (private ngControl: NgControl) {
}
@HostListener('keypress', ['$event'])
keyEvent(event: KeyboardEvent) {
console.log(event.charCode);
if (!(event.charCode > 47 && event.charCode < 58 || event.charCode == 42)) {
return false;
}
}
@HostListener('change')
ngOnChanges(){
this.formatPhoneNumber();
}
@HostListener('keyup')
keyUp() {
this.formatPhoneNumber();
}
formatPhoneNumber(): any {
let inputString = this.ngControl.control.value.replace(/\D/g, '');
const phoneNumber = inputString.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
this.ngControl.control.setValue(phoneNumber)
}
}
|
11dea584c1d7b641d918a283845122b39e202687
|
TypeScript
|
RiteshSolanki1987/demo-app-products
|
/src/app/pipes/split-text.pipe.ts
| 2.9375
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'splitText' })
export class SplitText implements PipeTransform {
/**
* Split text if length greater than 50 and add elipsis after 50 characters
* @param textContent Text string
*/
transform(textContent: any): any {
if (textContent) {
if (textContent.length > 50) {
textContent = textContent.substring(0, 50) + '...';
}
return textContent;
} else {
return '';
}
}
}
|
bf7acbe09395e333909688f8d22fbb5ed968edf8
|
TypeScript
|
ng-model/vscode-stencil-tools
|
/src/snippets/snippets-component.ts
| 3.125
| 3
|
import { Snippet } from "./interface";
export const LIFECYCLE_SNIPPETS: Snippet[] = [
{
name: 'component-will-load',
title: 'Component Lifecycle: componentWillLoad',
description: [
"The component is about to load and it has not rendered yet.\n",
"This is the best place to make any data updates before the first render.\n",
"`componentWillLoad` will only be called once."
],
body: [
"componentWillLoad() {",
"\t${0:console.log('Component is about to be rendered');}",
"}"
]
},
{
name: 'component-did-load',
title: 'Component Lifecycle: componentDidLoad',
description: [
"The component has loaded and has already rendered.\n",
"Updating data in this method will cause the component to re-render.\n",
"`componentDidLoad` will only be called once."
],
body: [
"componentDidLoad() {",
"\t${0:console.log('Component has been rendered');}",
"}"
]
},
{
name: 'component-will-update',
title: 'Component Lifecycle: componentWillUpdate',
description: [
"The component is about to update and re-render.\n",
"Called multiple times throughout the life of the component as it updates.\n",
"`componentWillUpdate` is not called on the first render."
],
body: [
"componentWillUpdate() {",
"\t${0:console.log('Component will update and re-render');}",
"}"
]
},
{
name: 'component-did-update',
title: 'Component Lifecycle: componentWillUpdate',
description: [
"The component has updated and re-rendered.\n",
"Called multiple times throughout the life of the component as it updates.\n",
"`componentDidUpdate` is not called on the first render."
],
body: [
"componentDidUpdate() {",
"\t${0:console.log('Component did update');}",
"}"
]
},
{
name: 'component-did-unload',
title: 'Component Lifecycle: componentDidUnload',
description: "The component did unload and the element will be destroyed.",
body: [
"componentDidUnload() {",
"\t${0:console.log('Component removed from the DOM');}",
"}"
]
}
]
export const COMPONENT_SNIPPETS: Snippet[] = [
...LIFECYCLE_SNIPPETS,
{
name: 'prop',
description: 'Props are custom attribute/properties exposed publicly on the element that developers can provide values for.',
body: "@Prop() ${1:propName}: ${2|any,string,boolean,number|};",
preview: "@Prop() newProp: any;",
autoImport: 'Prop'
},
{
name: 'watch',
description: "When a user updates a property, Watch will fire what ever method it's attached to and pass that methd the new value of the prop along with the old value.",
body: [
"@Watch('${1:propName}')",
"${1}Changed() {",
"\tconst { $1 } = this;",
"\t${0:console.log('$1 changed to ', $1);}",
"}"
],
preview: [
"@Watch('propName')",
"propNameChanged() {",
"\tconst { propName } = this;",
"\tconsole.log('propName changed to ', propName);",
"}"
],
autoImport: 'Watch'
},
{
name: 'state',
description: "The @State() decorator can be used to manage internal data for a component. Any changes to a @State() property will cause the components render function to be called again.",
body: "@State() ${1:stateName}: ${2|any,string,boolean,number|};",
preview: "@State() stateName: any",
autoImport: 'State'
},
{
name: 'method',
body: [
"@Method()",
"${1:methodName}($2) {",
"\t$0",
"}"
],
preview: [
"@Method()",
"methodName() {",
"\t",
"}"
],
description: "The @Method() decorator is used to expose methods on the public API. Functions decorated with the @Method() decorator can be called directly from the element.",
autoImport: 'Method'
},
{
name: 'element',
description: "The @Element() decorator is how to get access to the host element within the class instance. This returns an instance of an HTMLElement, so standard DOM methods/events can be used here.",
body: "@Element() ${1:element}: HTMLElement;",
preview: "@Element() element: HTMLElement;",
autoImport: 'Element'
},
{
name: 'event',
body: "@Event() ${1:eventName}: EventEmitter<${2:any}>;",
preview: "@Event() eventName: EventEmitter<any>;",
description: "The @Event() decorator allows a Component to dispatch Custom DOM events for other components to handle.",
autoImport: 'Event, EventEmitter'
},
{
name: 'listen',
body: [
"@Listen('${1:eventName}')",
"protected ${2:${1}Handler}(event) {",
"\t${0:console.log('Received the \"$1\" event: ', event);}",
"}"
],
preview: [
"@Listen('eventName')",
"protected eventNameHandler(event) {",
"\tconsole.log('Received the \"$1\" event: ', event);",
"}"
],
description: "The Listen() decorator is for handling events dispatched from @Events.",
autoImport: 'Listen'
}
];
|
6c046177c5ab259c25b5663cc25916928597ec7d
|
TypeScript
|
rmirville/stocks-ng-ionic
|
/src/app/shared/market/services/stock-const-loader.service.ts
| 2.515625
| 3
|
import { Observable } from 'rxjs';
import { STOCKS } from '@shared/market/types/data/stocks';
import { Stock } from '@shared/market/types';
import { Dictionary } from '@shared/types';
import { StockLoaderService } from './stock-loader.service';
export class StockConstLoaderService implements StockLoaderService {
stocks: Dictionary<Stock> = STOCKS;
constructor() {
}
loadAllStocks(): Observable<Dictionary<Stock>> {
// console.log(`StockConstLoaderService::loadNotes() - stocks: ${JSON.stringify(this.stocks)}`);
const stocks$: Observable<Dictionary<Stock>> = new Observable<Dictionary<Stock>>(observer => {
setTimeout(() => {
observer.next(this.stocks);
observer.complete();
}, 1500);
});
return stocks$;
}
loadStocks(symbols: string[]): Observable<Dictionary<Stock>> {
const stocks$: Observable<Dictionary<Stock>> = new Observable<Dictionary<Stock>>(observer => {
setTimeout(() => {
let stocks: Dictionary<Stock> = {};
for (const symbol of symbols) {
if (this.stocks.hasOwnProperty(symbol)) {
stocks[symbol] = this.stocks[symbol];
}
}
observer.next(stocks);
observer.complete();
}, 1500);
});
return stocks$;
}
loadStock(symbol: string): Observable<Stock> {
const stock$: Observable<Stock> = new Observable<Stock>(observer => {
setTimeout(() => {
// console.log(`symbol: ${JSON.stringify(symbol)}`);
symbol = symbol.toUpperCase();
const stock: Stock = this.stocks[symbol];
// console.log(`note: ${JSON.stringify(stock)}`);
observer.next(stock);
observer.complete();
}, 1500);
});
return stock$;
}
}
|
feb668f3d91e795bb29a14087ff31ab86a93e4d3
|
TypeScript
|
hotNipi/automation-uibuilder
|
/uibuilder/uibuilder/src/utils/Calc.ts
| 3.359375
| 3
|
class Calc {
static range(n: number, p: {minin: number; maxin: number; minout: number; maxout: number}, type: 'roll' | 'clamp', round: boolean, fixto: number): number {
if (type == 'clamp') {
if (n < p.minin) {
n = p.minin;
}
if (n > p.maxin) {
n = p.maxin;
}
}
if (type == 'roll') {
var d: number = p.maxin - p.minin;
n = ((((n - p.minin) % d) + d) % d) + p.minin;
}
var v: number = ((n - p.minin) / (p.maxin - p.minin)) * (p.maxout - p.minout) + p.minout;
if (round) {
v = Math.round(v);
} else {
if (fixto) {
v = parseFloat(v.toFixed(fixto));
}
}
return v;
}
}
|
03c626fdc69dbb11b6211ddadb94ae2f84a3b68c
|
TypeScript
|
nomis51/graphql-typed-client
|
/src/render/typeMap/objectType.ts
| 2.609375
| 3
|
import {
getNamedType,
GraphQLInterfaceType,
GraphQLObjectType,
isEnumType,
isInterfaceType,
isScalarType,
GraphQLInputObjectType,
GraphQLArgument,
GraphQLField,
} from 'graphql'
import { RenderContext } from '../common/RenderContext'
import { ArgMap, Field, FieldMap, Type } from './renderTypeMap'
export const objectType = (type: GraphQLObjectType | GraphQLInterfaceType | GraphQLInputObjectType, ctx: RenderContext) => {
const typeObj: Type & { fields: FieldMap } = {
name: type.name,
fields: Object.keys(type.getFields()).reduce<FieldMap>((r, f) => {
const field = type.getFields()[f]
const namedType = getNamedType(field.type)
const fieldObj: Field = { type: namedType.name }
r[f] = fieldObj
const args: GraphQLArgument[] = (<GraphQLField<any, any>>field).args || []
if (args.length > 0) {
fieldObj.args = args.reduce<ArgMap>((r, a) => {
r[a.name] = [a.type.toString(), getNamedType(a.type).name]
return r
}, {})
}
return r
}, {}),
}
if (isInterfaceType(type) && ctx.schema) {
ctx.schema.getPossibleTypes(type).map(t => {
typeObj.fields[`on_${t.name}`] = { type: t.name }
})
}
typeObj.fields.__typename = { type: 'String' }
const scalar = Object.keys(type.getFields())
.map(f => type.getFields()[f])
.filter(f => isScalarType(getNamedType(f.type)) || isEnumType(getNamedType(f.type)))
.map(f => f.name)
if (scalar.length > 0) typeObj.scalar = scalar
return typeObj
}
|
f19009cd06b352f302f117c579d56a35511a54f6
|
TypeScript
|
avjaz/mmd
|
/src/model/Position.ts
| 3.234375
| 3
|
import Orientation = require("./Orientation");
/**
* A position class
*/
class Position {
private _xPos: number;
private _yPos: number;
private _orientation: string;
constructor(xPos: number, yPos: number, orientation: string) {
this._xPos = xPos;
this._yPos = yPos;
this._orientation = orientation;
}
get xPos(): number {
return this._xPos;
}
set xPos(val: number) {
this._xPos = val;
}
get yPos(): number {
return this._yPos;
}
set yPos(val: number) {
this._yPos = val;
}
get orientation(): string {
return this._orientation;
}
set orientation(val: string) {
this._orientation = val;
}
}
export = Position;
|
974f9b7675b72fb92b93b01a9282d1665a86c0fd
|
TypeScript
|
topmonroe9/mk3_core
|
/src/middleware/logger.middleware.ts
| 2.515625
| 3
|
import { Injectable, NestMiddleware, Inject } from "@nestjs/common";
import { WINSTON_MODULE_PROVIDER } from "nest-winston";
import { Logger } from "winston";
// import { Request, Response, NextFunction } from 'express';
@Injectable()
export class AppLoggerMiddleware implements NestMiddleware {
constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) {
}
use(request, response, next): void {
const { baseUrl, method } = request;
const reqIP = request.headers["x-forwarded-for"] || request.connection.remoteAddress;
const userAgent = request.get("user-agent") || "undefined useragent";
response.on("finish", () => {
const { statusCode } = response;
const date = this.toIsoString(new Date);
this.logger.info(`${date} - ${method} ${baseUrl} FROM: ${reqIP} ${userAgent} - ${statusCode}`);
});
next();
}
private toIsoString(date: Date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? "+" : "-",
pad = function(num) {
var norm = Math.floor(Math.abs(num));
return (norm < 10 ? "0" : "") + norm;
};
return date.getFullYear() +
"-" + pad(date.getMonth() + 1) +
"-" + pad(date.getDate()) +
"T" + pad(date.getHours()) +
":" + pad(date.getMinutes()) +
":" + pad(date.getSeconds()) +
dif + pad(tzo / 60) +
":" + pad(tzo % 60);
}
}
|
56ebd1c79ee9f78d2feb7556186f6e0b92f0be3f
|
TypeScript
|
mihailik/pe.js
|
/tests/testLong.ts
| 2.59375
| 3
|
namespace tests.Long {
export function constructor_succeeds() {
var lg = new pe.Long(0, 0);
}
export function constructor_assigns_lo_602048() {
var lg = new pe.Long(602048, 0);
if (lg.lo !== 602048)
throw lg.lo;
}
export function constructor_assigns_hi_2130006() {
var lg = new pe.Long(0, 2130006);
if (lg.hi !== 2130006)
throw lg.hi;
}
export function toString_zeros() {
var lg = new pe.Long(0, 0);
if (lg.toString() !== "0h")
throw lg.toString();
}
export function toString_1() {
var lg = new pe.Long(1, 0);
if (lg.toString() !== "1h")
throw lg.toString();
}
export function toString_0xB() {
var lg = new pe.Long(0xB, 0);
if (lg.toString() !== "Bh")
throw lg.toString();
}
export function toString_0xFFFF() {
var lg = new pe.Long(0xFFFF, 0);
if (lg.toString() !== "FFFFh")
throw lg.toString();
}
export function toString_0xFFFF0() {
var lg = new pe.Long(0xFFF0, 0xF);
if (lg.toString() !== "FFFF0h")
throw lg.toString();
}
export function toString_0xFFFFFFFF() {
var lg = new pe.Long(0xFFFF, 0xFFFF);
if (lg.toString() !== "FFFFFFFFh")
throw lg.toString();
}
}
|
97fc075e05c8552eb70078185145b4c095b8ef86
|
TypeScript
|
DeepInThought/swim
|
/swim-system-js/swim-core-js/@swim/interpolate/main/InterpolatorInterpolator.ts
| 2.59375
| 3
|
// Copyright 2015-2020 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Interpolator} from "./Interpolator";
export class InterpolatorInterpolator<T extends U, U = T> extends Interpolator<Interpolator<T, U>> {
/** @hidden */
readonly i0: Interpolator<T, U>;
/** @hidden */
readonly i1: Interpolator<T, U>;
/** @hidden */
readonly i00: Interpolator<T, U>;
/** @hidden */
readonly i11: Interpolator<T, U>;
constructor(i0: Interpolator<T, U>, i1: Interpolator<T, U>) {
super();
this.i0 = i0;
this.i1 = i1;
this.i00 = this.i1.range(this.i0.interpolate(0), this.i1.interpolate(0));
this.i11 = this.i1.range(this.i0.interpolate(1), this.i1.interpolate(1));
}
interpolate(u: number): Interpolator<T, U> {
if (u === 0) {
return this.i0;
} else if (u === 1) {
return this.i1;
} else {
return this.i1.range(this.i00.interpolate(u), this.i11.interpolate(u));
}
}
deinterpolate(i: Interpolator<T, U>): number {
return 0; // not implemented
}
range(): ReadonlyArray<Interpolator<T, U>>;
range(is: ReadonlyArray<Interpolator<T, U>>): InterpolatorInterpolator<T, U>;
range(i0: Interpolator<T, U>, i1: Interpolator<T, U>): InterpolatorInterpolator<T, U>;
range(i0?: ReadonlyArray<Interpolator<T, U>> | Interpolator<T, U>,
i1?: Interpolator<T, U>): ReadonlyArray<Interpolator<T, U>> | InterpolatorInterpolator<T, U> {
if (i0 === void 0) {
return [this.i0, this.i1];
} else if (i1 === void 0) {
i0 = i0 as ReadonlyArray<Interpolator<T, U>>;
return InterpolatorInterpolator.between(i0[0], i0[1]);
} else {
return InterpolatorInterpolator.between(i0 as Interpolator<T, U>, i1);
}
}
equals(that: any): boolean {
if (this === that) {
return true;
} else if (that instanceof InterpolatorInterpolator) {
return this.i0.equals(that.i0) && this.i1.equals(that.i1);
}
return false;
}
static between<T extends U, U = T>(i0: Interpolator<T, U>, i1: Interpolator<T, U>): InterpolatorInterpolator<T, U>;
static between(a: unknown, b: unknown): Interpolator<unknown>;
static between(a: unknown, b: unknown): Interpolator<unknown> {
if (a instanceof Interpolator && b instanceof Interpolator) {
return new InterpolatorInterpolator(a, b);
}
return Interpolator.between(a, b);
}
static tryBetween(a: unknown, b: unknown): InterpolatorInterpolator<unknown> | null {
if (a instanceof Interpolator && b instanceof Interpolator) {
return new InterpolatorInterpolator(a, b);
}
return null;
}
}
Interpolator.Interpolator = InterpolatorInterpolator;
|
b4c281a51ba2e02a2af6bd25a34efc82e659bbbc
|
TypeScript
|
tayduivn/hawkeye-mobile
|
/src/environments/environment.ts
| 2.65625
| 3
|
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.p w z wrod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
// apiUrl: 'http://192.168.3.18/api/v1',
// fileUrlPath: 'http://keyi.xdrlgroup.com',
// usFileUrl: 'http://192.168.3.18/storage/',
// origin: 'http://192.168.3.18',
// apiUrl: 'http://192.168.1.103/api/v1',
// fileUrlPath: 'http://keyi.xdrlgroup.com',
// usFileUrl: 'http://192.168.3.8/',
// origin:'http://192.168.3.8'
// apiUrl: 'http://121.196.179.68/api/v1',
// fileUrlPath: 'http://keyi.xdrlgroup.com',
// usFileUrl: 'http://121.196.179.68/',
// origin:'http://121.196.179.68'
apiUrl: 'http://121.196.179.68:8081/api/v1',
fileUrlPath: 'http://keyi.xdrlgroup.com',
usFileUrl: 'http://121.196.179.68:8081/',
origin: 'http://121.196.179.68:8081',
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
|
3dd2ce09bde250aaf712cc40c429d6208a96031c
|
TypeScript
|
bluelovers/ws-mega
|
/packages/mega-nz-url-parse/index.ts
| 2.59375
| 3
|
/**
* Created by user on 2020/5/24.
*/
import LazyURL from 'lazy-url'
import { parseSubPath, parseLinkHash, parseLinkHash2 } from './lib/util';
const defaultHostname = [
'mega.nz',
'mega.co.nz',
]
export interface IParseMegaLink
{
url: LazyURL;
root: {
key: string;
directory: boolean;
downloadID: string;
loadedFile?: string;
};
sub?: IParseMegaLinkSub;
}
export interface IParseMegaLinkSub
{
directory: boolean;
downloadID: string;
}
export function parseMegaLink(link: string | URL | LazyURL, options?: {
hostname?: string[],
}): IParseMegaLink
{
options = options ?? {};
let url: LazyURL = link as any;
if (!(url instanceof LazyURL))
{
url = new LazyURL(url)
}
if (!(options.hostname ?? defaultHostname).includes(url.hostname))
{
throw TypeError(`Invalid URL: wrong hostname '${url.hostname}'`)
}
if (!url.hash) throw TypeError('Invalid URL: no hash');
if (['file', 'folder'].includes(url.paths[0]))
{
const root = parseSubPath(url.paths)
const { key, directory, downloadID } = parseLinkHash(url.hash);
if (downloadID)
{
return {
url,
root: {
...root,
key,
},
sub: {
directory,
downloadID,
},
}
}
return {
url,
root: {
...root,
key,
},
}
}
else
{
const root = parseLinkHash2(url.hash);
return {
url,
root,
}
}
}
export default parseMegaLink
|
42bcb469e58f8f00d4d58721a63df8ab8ca601b7
|
TypeScript
|
Ee-Chee/Inventur-CRUD-NgRx-app
|
/src/app/root-store/quantity-store/selectors.ts
| 2.53125
| 3
|
import { createFeatureSelector, createSelector, MemoizedSelector } from '@ngrx/store';
import { State } from './state';
const getError = (state: State): any => state.error;
const getIsLoading = (state: State): boolean => state.isLoading;
const getQuantity = (state: State): number[] => {
return state.quantityArray;
}
export const selectQuantityState: MemoizedSelector<object, State> = createFeatureSelector<State>('quantity');
export const selectRequestError: MemoizedSelector<object, any> = createSelector(
selectQuantityState,
getError
);
export const selectRequetIsLoading: MemoizedSelector<object,boolean> = createSelector(
selectQuantityState,
getIsLoading
);
export const selectQuantity: MemoizedSelector<object, number[]> = createSelector(
selectQuantityState,
getQuantity
);
|
090d912c114667a19c8feaf4493d86f08d18d122
|
TypeScript
|
orbitjs/orbit
|
/packages/@orbit/immutable/test/immutable-map-test.ts
| 3.125
| 3
|
import { ImmutableMap } from '../src/immutable-map';
const { module, test } = QUnit;
module('ImmutableMap', function () {
test('it can be instantiated with no data', function (assert) {
let map = new ImmutableMap<string, any>();
assert.ok(map, 'map exists');
});
test('records can be added and removed', function (assert) {
let map = new ImmutableMap<string, any>();
assert.equal(map.size, 0, 'size matches expectations');
assert.equal(map.has('jupiter'), false, 'map does not have record');
assert.strictEqual(map.get('jupiter'), undefined, 'get returns undefined');
let jupiter = {
type: 'planet',
id: 'jupiter',
attributes: { name: 'Jupiter' }
};
map.set('jupiter', jupiter);
assert.equal(map.has('jupiter'), true, 'record exists');
assert.strictEqual(
map.get('jupiter'),
jupiter,
'record matches expectations'
);
let jupiter2 = {
type: 'planet',
id: 'jupiter',
attributes: { name: 'Jupiter2' }
};
map.set('jupiter', jupiter2);
assert.strictEqual(
map.get('jupiter'),
jupiter2,
'replacement record matches expectations'
);
let pluto = { type: 'planet', id: 'pluto', attributes: { name: 'Pluto' } };
map.set('pluto', pluto);
assert.equal(map.size, 2, 'size matches expectations');
assert.deepEqual(
Array.from(map.keys()),
['pluto', 'jupiter'],
'keys match expectations'
);
assert.deepEqual(
Array.from(map.values()),
[pluto, jupiter2],
'values match expectations'
);
assert.deepEqual(
Array.from(map.entries()),
[
['pluto', pluto],
['jupiter', jupiter2]
],
'entries match expectations'
);
map.remove('jupiter');
map.remove('pluto');
assert.equal(map.size, 0, 'size matches expectations');
});
test('maps can be instantiated based on other maps and their contents will be equal (but then will diverge)', function (assert) {
let map = new ImmutableMap<string, any>();
let jupiter = {
type: 'planet',
id: 'jupiter',
attributes: { name: 'Jupiter' }
};
map.set('jupiter', jupiter);
assert.strictEqual(
map.get('jupiter'),
jupiter,
'record matches expectations'
);
// create a new map based on the original
let map2 = new ImmutableMap<string, any>(map);
assert.strictEqual(
map2.get('jupiter'),
jupiter,
'record matches expectations'
);
let jupiter2 = {
type: 'planet',
id: 'jupiter',
attributes: { name: 'Jupiter2' }
};
map2.set('jupiter', jupiter2);
let pluto = { type: 'planet', id: 'pluto', attributes: { name: 'Pluto' } };
map2.set('pluto', pluto);
assert.equal(map.size, 1, 'original map still has one member');
assert.strictEqual(
map.get('jupiter'),
jupiter,
'original map is unchanged'
);
assert.equal(map2.size, 2, 'new map now has two members');
assert.strictEqual(
map2.get('jupiter'),
jupiter2,
'replacement record matches expectations'
);
assert.strictEqual(
map2.get('pluto'),
pluto,
'new record matches expectations'
);
map2.remove('jupiter');
map2.remove('pluto');
assert.equal(map2.size, 0, 'size matches expectations');
assert.equal(map.size, 1, 'original map still has one member');
assert.strictEqual(
map.get('jupiter'),
jupiter,
'original map is unchanged'
);
});
test('maps can set and remove multiple items at once', function (assert) {
let jupiter = {
type: 'planet',
id: 'jupiter',
attributes: { name: 'Jupiter' }
};
let jupiter2 = {
type: 'planet',
id: 'jupiter',
attributes: { name: 'Jupiter2' }
};
let pluto = { type: 'planet', id: 'pluto', attributes: { name: 'Pluto' } };
let earth = { type: 'planet', id: 'earth', attributes: { name: 'Earth' } };
let map = new ImmutableMap<string, any>();
map.setMany([
['jupiter', jupiter],
['jupiter', jupiter2],
['pluto', pluto],
['earth', earth]
]);
assert.equal(map.size, 3, 'map has three members');
assert.strictEqual(
map.get('jupiter'),
jupiter2,
'jupiter has been updated'
);
assert.strictEqual(map.get('pluto'), pluto, 'pluto is set');
assert.strictEqual(map.get('earth'), earth, 'earth is set');
map.removeMany(['jupiter', 'earth']);
assert.equal(map.size, 1, 'map has one members');
assert.strictEqual(map.get('pluto'), pluto, 'pluto is set');
map.clear();
assert.equal(map.size, 0, 'map has been cleared');
});
});
|
44e2aebf541b5f8f0d0ba3fd1e66030f7932b5c4
|
TypeScript
|
rahulkmr/ts_musings
|
/merging.ts
| 2.78125
| 3
|
class Album {
label: Album.Label
}
namespace Album {
export class Label { }
}
function buildLabel(name: string): string {
return buildLabel.prefix + name + buildLabel.suffix
}
namespace buildLabel {
export const suffix = ''
export const prefix = 'Hello, '
}
|
1a15f9516b491432a7f6bff0451650fb6c3a764a
|
TypeScript
|
GhostRealm/rotmg-sandbox
|
/src/common/asset/rotmg/data/Stats.ts
| 2.71875
| 3
|
export class Stats {
hp: number = 0;
mp: number = 0;
atk: number = 0;
dex: number = 0;
spd: number = 0;
def: number = 0;
vit: number = 0;
wis: number = 0;
getAttacksPerSecond() {
return 1.5 + 6.5 * (this.dex / 75);
}
getAttackDamage(damage: number) {
return Math.floor(damage * (0.5 + this.atk / 50));
}
getTilesPerSecond() {
return 4 + 5.6 * (this.spd / 75);
}
getHealthPerSecond() {
return 1 + 0.24 * this.vit;
}
getManaPerSecond() {
return 0.5 + 0.12 * this.wis;
}
getInCombatTime() {
return 7 - 0.05 * this.vit;
}
getDamageReqForCombat() {
let currDef = 0;
for (let i = 0; i < this.def; i++) {
if (i <= 15) {
currDef += 1;
} else if (i <= 30) {
currDef += 0.75
} else if (i <= 45) {
currDef += 0.5
} else {
currDef += 0.25
}
}
return Math.floor(currDef);
}
add(stats: Stats): Stats {
const newStats = new Stats();
newStats.hp = this.hp + stats.hp;
newStats.mp = this.mp + stats.mp;
newStats.atk = this.atk + stats.atk;
newStats.dex = this.dex + stats.dex;
newStats.spd = this.spd + stats.spd;
newStats.def = this.def + stats.def;
newStats.vit = this.vit + stats.vit;
newStats.wis = this.wis + stats.wis;
return newStats;
}
isZero(): boolean {
return (
this.hp === 0 &&
this.mp === 0 &&
this.atk === 0 &&
this.def === 0 &&
this.spd === 0 &&
this.dex === 0 &&
this.vit === 0 &&
this.wis === 0
)
}
serialize() {
function mapToObject(statName: string, stat: number) {
return stat !== 0 ? {
"@_stat": statName,
"@_amount": stat,
"#text": "IncrementStat"
} : undefined
}
return {
ActivateOnEquip: [
mapToObject("MAXHP", this.hp),
mapToObject("MAXMP", this.mp),
mapToObject("ATT", this.atk),
mapToObject("DEF", this.def),
mapToObject("SPD", this.spd),
mapToObject("DEX", this.dex),
mapToObject("VIT", this.vit),
mapToObject("WIS", this.wis)
]
}
}
static min(statsA: Stats, statsB: Stats): Stats {
const newStats = new Stats();
newStats.hp = Math.min(statsA.hp, statsB.hp);
newStats.mp = Math.min(statsA.mp, statsB.mp);
newStats.atk = Math.min(statsA.atk, statsB.atk);
newStats.def = Math.min(statsA.def, statsB.def);
newStats.spd = Math.min(statsA.spd, statsB.spd);
newStats.dex = Math.min(statsA.dex, statsB.dex);
newStats.vit = Math.min(statsA.vit, statsB.vit);
newStats.wis = Math.min(statsA.wis, statsB.wis);
return newStats;
}
static fromXML(xml: any) {
const stats = new Stats();
const stat = xml["@_stat"];
const increment = xml["#text"] === "IncrementStat";
const amount = xml["@_amount"] * (increment ? 1 : -1);
switch(stat) {
case "MAXHP":
stats.hp += amount;
break;
case "MAXMP":
stats.mp += amount;
break;
case "ATT":
stats.atk += amount;
break;
case "DEF":
stats.def += amount;
break;
case "SPD":
stats.spd += amount;
break;
case "DEX":
stats.dex += amount;
break;
case "VIT":
stats.vit += amount;
break;
case "WIS":
stats.wis += amount;
break;
}
return stats;
}
static convertStatName(stat: string) {
switch(stat) {
case "MAXHP":
return "hp";
case "MAXMP":
return "mp"
case "ATT":
return "atk"
case "DEF":
return "def"
case "SPD":
return "spd"
case "DEX":
return "dex"
case "VIT":
return "vit"
case "WIS":
return "wis";
}
return "???"
}
}
export default function StatsSerializer(value: Stats) {
return value.serialize();
}
|
16941287853da8c6129cf93ba67e5a2fe5caeb3e
|
TypeScript
|
ginkgoch/node-map
|
/src/shared/Opener.ts
| 3.015625
| 3
|
export abstract class Opener {
opened: boolean = false;
async open() {
if (!this.opened) {
await this._open();
this.opened = true;
}
}
protected abstract async _open(): Promise<void>;
async close() {
if (this.opened) {
await this._close();
this.opened = false;
}
}
protected abstract async _close(): Promise<void>;
protected get _openRequired() {
return true;
}
}
export default class OpenerSync {
isOpened : boolean;
constructor() {
this.isOpened = false;
}
open() {
if (this.isOpened) return this;
this.isOpened = true;
this._open();
return this;
}
protected _open() { }
close() {
if(this.isOpened) {
this._close();
this.isOpened = false;
}
}
protected _close() { }
openWith(action: () => void) {
try {
this.open();
action();
} finally {
this.close();
}
}
}
|
4dbe4a15b11d8f28a625c3ed762fb396c572686a
|
TypeScript
|
ezolenko/rollup-plugin-typescript2
|
/src/icache.ts
| 2.84375
| 3
|
export interface ICache <DataType>
{
exists(name: string): boolean;
path(name: string): string;
match(names: string[]): boolean;
read(name: string): DataType | null | undefined;
write(name: string, data: DataType): void;
touch(name: string): void;
roll(): void;
}
|
6c14c319c3bcceebb46a5a16504066af3c5758b8
|
TypeScript
|
KiichiHamanaka/todo-nest
|
/src/todo/todo.repository.ts
| 2.625
| 3
|
import { Injectable } from '@nestjs/common';
import { TodoOutputType } from '../interface';
import { PrismaClient } from '@prisma/client';
// リポジトリ層はデータストアを扱う
@Injectable()
export class TodoRepository {
async getTodo(id: string): Promise<TodoOutputType> {
const prisma = new PrismaClient();
return await prisma.todo.findFirst({
where: {
id: Number(id),
},
});
}
async updateStatus(id: string, status: string): Promise<TodoOutputType> {
const prisma = new PrismaClient();
return await prisma.todo.update({
where: {
id: Number(id),
},
data: { status: status },
});
}
async postTodo(
id: string,
content: string,
title: string,
): Promise<TodoOutputType> {
const prisma = new PrismaClient();
return await prisma.todo.create({
data: {
content: content,
title: title,
status: 'open',
},
});
}
}
|
86bbdcedea87719f148fd9d336347074289c3538
|
TypeScript
|
pesoklp13/gloomhaven-tracker
|
/libs/common-library/src/lib/data-structures/linked-list.ts
| 3.6875
| 4
|
import {Iterable, Iterator} from "./iterator";
interface ListNode<T> {
value: T;
previous?: ListNode<T>;
next?: ListNode<T>;
}
class LinkedListIterator<T> implements Iterator<T> {
private previous: ListNode<T> | undefined;
constructor(private current: ListNode<T>, private onRemove: (isHead: boolean) => void) {}
hasNext(): boolean {
return !!this.current;
}
next(): T {
this.previous = this.current;
this.current = this.current?.next;
return this.previous?.value;
}
remove(): void {
if (!this.previous) {
throw new Error('Unable to remove non existing node or already removed one!');
}
const nodeToDelete = this.previous;
const isHead = nodeToDelete.previous === undefined;
if(nodeToDelete.previous) {
nodeToDelete.previous.next = nodeToDelete.next;
}
if(nodeToDelete.next) {
nodeToDelete.next.previous = nodeToDelete.previous;
}
this.previous = undefined;
this.onRemove(isHead);
}
}
export class LinkedList<T> implements Iterable<T>{
public get size(): number {
return this._size;
}
private head?: ListNode<T>;
private tail?: ListNode<T>;
private _size = 0;
public append(value: T): void {
if(!this.head) {
this.addFirstElement(value);
return;
}
const appendedNode = {
value,
previous: this.tail
}
this.tail.next = appendedNode;
this.tail = appendedNode;
this._size++;
}
public prepend(value: T): void {
if(!this.head) {
this.addFirstElement(value);
return;
}
const prependedNode = {
value,
next: this.head
}
this.head.previous = prependedNode;
this.head = prependedNode;
this._size++;
}
public peek(): T | undefined {
return this.tail?.value;
}
public peekFromStart(): T | undefined {
return this.head?.value;
}
public remove(): T | undefined {
const removedNode = this.tail;
if(this._size <= 1) {
this.removeLastElement();
return removedNode?.value;
}
this.tail = this.tail.previous;
this.tail.next = undefined;
this._size--;
if(this._size === 1) {
this.tail = this.head;
}
return removedNode.value;
}
public removeFromStart(): T | undefined {
const removedNode = this.head;
if(this._size <= 1) {
this.removeLastElement();
return removedNode?.value;
}
this.head = this.head.next;
this.head.previous = undefined;
this._size--;
if(this._size === 1) {
this.tail = this.head;
}
return removedNode.value;
}
iterator(): Iterator<T> {
return new LinkedListIterator(this.head, this.onRemove.bind(this));
}
public toString(): string {
const iterator = this.iterator();
let result = 'LinkedList -> ';
result += iterator.next();
while(iterator.hasNext()) {
result += ` -> ${iterator.next()}`;
}
return result;
}
private addFirstElement(value: T): void {
this.head = {
value
}
this.tail = this.head;
this._size++;
return;
}
private removeLastElement(): void {
this.head = this.tail = undefined;
this._size = 0;
}
private onRemove(isHead: true): void {
this._size--;
if(isHead) {
this.head = this.head.next;
}
}
}
|
b7aefeb60020ccf7ea127ee303fb9331d41d854d
|
TypeScript
|
villager/Edna-Moda
|
/plugins/plugins/battle/teams.ts
| 2.859375
| 3
|
import * as Storage from './storage';
export let teams = Object.create(null);
const mergeTeams = () => {
for (let i in Storage.teams) {
let team = Storage.teams[i];
if (teams[team.format]) teams[team.format] = [];
teams[team.format].push(team.packed);
}
};
const addTeam = (name: string, format: string, packed: AnyObject) => {
if (Storage.isSaved(name)) return false;
Storage.teams[name] = {
format: format,
packed: packed,
};
Storage.saveTeams();
mergeTeams();
return true;
};
const removeTeam = (name: string) => {
if (!Storage.isSaved(name)) return false;
delete Storage.teams[name];
Storage.saveTeams();
mergeTeams();
return true;
};
const getTeam = (format: string) => {
let formatId = toId(format);
let teamStuff = teams[formatId];
if (!teamStuff || !teamStuff.length) return false;
let teamChosen = teamStuff[Math.floor(Math.random() * teamStuff.length)]; //choose team
let teamStr: any = '';
try {
if (typeof teamChosen === 'string') {
//already parsed
teamStr = teamChosen;
} else if (typeof teamChosen === 'object') {
if (teamChosen.maxPokemon && teamChosen.pokemon) {
//generate random team
let team = [];
let pokes = teamChosen.pokemon.randomize();
let k = 0;
for (let i = 0; i < pokes.length; i++) {
if (k++ >= teamChosen.maxPokemon) break;
team.push(pokes[i]);
}
if (Config.debug.debug) console.log('Packed Team: ' + JSON.stringify(team));
teamStr = packTeam(team);
} else if (teamChosen.length) {
//parse team
teamStr = packTeam(teamChosen);
} else {
console.log('invalid team data type: ' + JSON.stringify(teamChosen));
return false;
}
} else {
console.log('invalid team data type: ' + JSON.stringify(teamChosen));
return false;
}
return teamStr;
} catch (e) {
console.log(e.stack);
}
};
const packTeam = (team: AnyObject[]) => {
Plugins.Dex.packTeam(team);
};
const hasTeam = (format: string) => {
let formatId = toId(format);
if (teams[formatId]) return true;
return false;
};
export const add = addTeam;
export const packed = packTeam;
export const remove = removeTeam;
export const merge = mergeTeams;
export const get = getTeam;
export const has = hasTeam;
|
787a814a3d9114eceae4bd92ec85c50e10f47292
|
TypeScript
|
absathiam15/Live-Angular
|
/src/app/pipes/time-left.pipe.ts
| 2.703125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'timeLeft'
})
export class TimeLeftPipe implements PipeTransform {
transform(value: Date ): string {
const currentTime = new Date();
const diff = currentTime.getTime() - value.getTime();
const y = Math.floor(diff/1000/60/60/24/365);
if(y>0){ return y + 'a';}
const d = Math.floor(diff/1000/60/60/24);
if(d>0){ return d + 'j';}
const h = Math.floor((diff/1000/60/60) % 24);
if(h>0){ return h + 'h';}
const m = Math.floor((diff/1000/60) % 60);
if(m>0){ return m + 'm';}
const s = Math.floor((diff/1000) %60);
if(s>0){ return s + 's';}
return '1s';
}
}
|
ef876369b26d605f0a09378d61c6aa7d14ad323a
|
TypeScript
|
RYRAJESH/QAAssessment
|
/qa-test-assessment-master/e2e/steps/searchPage.steps.ts
| 2.6875
| 3
|
import { Given, When, Then } from 'cucumber';
import { searchPage } from "../pages/searchPage.po";
import { characterResultsPage } from "../pages/characterResultsPage.po";
import { planetResultsPage } from "../pages/planetResultsPage.po";
import { setDefaultTimeout } from "cucumber";
const chai = require('chai').use(require('chai-as-promised'));
const expect = chai.expect;
setDefaultTimeout(25 * 1000);
let searchPo = new searchPage();
let characterResultsPo = new characterResultsPage();
let planetResultsPo = new planetResultsPage();
Given('The app is open on {string}', async (string) => {
// navigate to the application using url string provided in feature file
await searchPo.navigateTo(string);
await expect(searchPo.searchForm.isDisplayed(), 'Search Form is NOT displayed').to.eventually.be.true;
});
When('Search form is cleared and clicked Search', async () => {
// clear the search form and search with blank
await searchPo.searchField.clear();
await searchPo.searchButton.click();
});
Then('Previous search results are cleared', async () => {
// character results should NOT be displayed
let noOfCharResults = await characterResultsPo.getNumberOfResults();
if (noOfCharResults > 0) {
await expect(characterResultsPo.characterResultSets.get(0).isDisplayed(), 'Character Results are still displayed').to.eventually.be.false;
}
//planet results should NOT be displayed
let noOfPlanetResults = await planetResultsPo.getNumberOfResults();
if (noOfPlanetResults > 0) {
await expect(planetResultsPo.planetResultSets.get(0).isDisplayed(), 'Planet Results are still displayed').to.eventually.be.false;
}
});
When('You switch from character to planet radio button and search', async () => {
// select planet radio button and search
await searchPo.planetOption.click();
await searchPo.searchButton.click();
});
When('You switch from planet to character radio button and search', async () => {
// select people radio button and search
await searchPo.peopleOption.click();
await searchPo.searchButton.click();
});
Then('Search result is displayed as Not Found', async () => {
// character results should NOT be displayed
let noOfCharResults = await characterResultsPo.getNumberOfResults();
if (noOfCharResults > 0) {
await expect(characterResultsPo.characterResultSets.get(0).isDisplayed(), 'Character Results are still displayed').to.eventually.be.false;
}
//planet results should NOT be displayed
let noOfPlanetResults = await planetResultsPo.getNumberOfResults();
if (noOfPlanetResults > 0) {
await expect(planetResultsPo.planetResultSets.get(0).isDisplayed(), 'Planet Results are still displayed').to.eventually.be.false;
}
// Not found text should be displayed
await expect(searchPo.notFoundMessage.getText(), 'Not found message is not displayed').to.eventually.equals('Not found.');
});
|
3b3e7936cb7dc1715f5fd823bc15fb7d6fb7f2a8
|
TypeScript
|
vinely/go-webntp
|
/_example/webntp.ts
| 2.9375
| 3
|
module WebNTP {
export interface Response {
id: string;
it: number; // Initiate Time
st: number; // Send Time
leap: number;
next: number;
step: number;
}
export interface Result {
delay: number;
offset: number;
}
interface Request {
resolve: (r: Result) => void;
reject: (reason) => void;
}
class Connection {
url: string;
connection: WebSocket;
requests: Request[] = [];
constructor(url: string) {
this.url = url;
}
open(): Promise<WebSocket> {
return new Promise<WebSocket>((resolve, reject) => {
const conn = new WebSocket(this.url, ["webntp.shogo82148.com"]);
this.connection = conn;
conn.addEventListener("open", ev => {
resolve(conn);
});
conn.addEventListener("message", ev => {
this.onmessage(conn, ev);
});
conn.addEventListener("error", ev => {
this.onerror(conn, ev);
});
conn.addEventListener("close", ev => {
this.onclose(conn, ev);
});
});
}
do_get(): void {
if (this.requests.length === 0) {
// nothing to do.
return;
}
let promise: Promise<WebSocket>;
if (this.connection) {
promise = Promise.resolve(this.connection);
} else {
promise = this.open();
}
promise.then(conn => {
const now = Date.now()/1000;
conn.send(now);
}).catch(reason => {
if (this.requests.length > 0) {
this.requests.shift().reject(reason);
}
this.connection = null;
this.do_get();
});
}
onmessage(conn: WebSocket, ev: MessageEvent) {
const now = Date.now()/1000;
const res: Response = JSON.parse(ev.data);
const delay = now - res.it;
const offset = res.st - res.it - delay/2;
const result: Result = {
delay: delay,
offset: offset
};
if (this.requests.length > 0) {
this.requests.shift().resolve(result);
}
this.do_get();
}
onerror(conn: WebSocket, ev: Event) {
if (this.requests.length > 0) {
this.requests.shift().reject(ev);
}
}
onclose(conn: WebSocket, ev: Event) {
this.connection = null;
this.do_get();
}
public get(): Promise<Result> {
return new Promise<Result>((resolve, reject) => {
this.requests.push({
resolve: resolve,
reject: reject
});
if (this.requests.length === 1) {
this.do_get();
}
});
}
}
export class Client {
// connection pool
private pool = new Map<string,Connection>();
// get_connection from the pool
private get_connection(url : string): Connection {
if (this.pool.has(url)) {
// reuse connection
return this.pool.get(url);
}
// create new connection
const c = new Connection(url);
this.pool.set(url, c);
return c;
}
get(url : string): Promise<Result> {
return this.get_connection(url).get();
}
get_multi(url: string, samples: number): Promise<Result> {
if (samples === 0) {
return Promise.resolve({
delay: 0,
offset: 0
});
}
let promise: Promise<Result[]> = Promise.resolve([]);
for(let i = 0; i < samples; i++) {
promise = promise.then(results => {
return this.get(url).then(result => {
results.push(result);
return results;
});
});
}
return promise.then(results => {
// get min delay.
let min = results[0].delay;
for (let result of results) {
if (result.delay < min) {
min = result.delay;
}
}
// calulate the avarage.
let delay = 0;
let offset = 0;
let count = 0;
for (let result of results) {
if (result.delay > min*2) {
// this sample may be re-sent. ignore it.
continue;
}
delay += result.delay;
offset += result.offset;
count++;
}
return {
delay: delay/count,
offset: offset/count
};
});
}
}
}
|
87322574f3dc769e95ff04291329087b61ada507
|
TypeScript
|
Hash-Nomads/edge-index-frontend
|
/utils/shortenAddress.ts
| 2.640625
| 3
|
export function shortenAddress(address: string): string {
return `${address.substring(0, 8)}...${address.substring(42 - 4)}`;
}
|
e7374f44edf6218fa5bc5a4bd0622187976ac5a9
|
TypeScript
|
ConaGo/Quizflip
|
/apps/api/src/app/question/entities/userToQuestionStats.entity.ts
| 2.59375
| 3
|
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { BaseEntity } from '../../typeorm/base.entity';
import { User } from '../../user/entities/user.entity';
import { Question } from './question.entity';
@Entity()
export class UserToQuestionStats extends BaseEntity {
@Column()
public questionId!: number;
@Column()
public userId!: number;
@Column({ default: 0 })
public answeredCorrect!: number;
@Column({ default: 0 })
public answeredIncorrect!: number;
@ManyToOne(() => Question, (question) => question.userToQuestionStats)
public question!: Question;
@ManyToOne(() => User, (user) => user.userToQuestionStats)
public user!: User;
//This constructor is necessary for the Exclude decorator
constructor(partial: Partial<UserToQuestionStats>) {
super({});
Object.assign(this, partial);
}
}
|