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
|
|---|---|---|---|---|---|---|
2f8c1b67d2e8535bf6ec66c361fbd59c9000c77a
|
TypeScript
|
heritiermwalila/demo-rc-app
|
/src/hooks/useAuth.ts
| 2.859375
| 3
|
import React from 'react';
import { loginSchema, registerSchema } from '../utils/validation';
export interface IRegisterUser {
firstname: string;
lastname: string;
email: string;
password: string;
website?: string;
company?: string;
}
export interface IUser {
_id: number;
firstname: string;
lastname: string;
email: string;
website?: string;
company?: string;
}
export default () => {
const [isLoggedIn, setIsLoggedIn] = React.useState(false);
const [error, setError] = React.useState()
const [user, setUser] = React.useState<IUser>()
/**
* Login a user
* @param email
* @param password
*/
const onLogin = React.useCallback(async (email: string, password: string) => {
try {
await loginSchema.isValid({email, password});
} catch (error) {
console.log(error);
}
}, [])
/**
* Register new user
* @param payload
*/
const registerUser = React.useCallback(async (payload: IRegisterUser) => {
try {
await registerSchema.isValid(payload)
} catch (error) {
console.log(error);
}
}, [])
const onLogOut = () => setIsLoggedIn(false)
return [isLoggedIn, onLogin, onLogOut, registerUser, error]
}
|
b8b7244a0bd34febaad5cacab466dcfec09aacb1
|
TypeScript
|
Indaym/Web-Indaym
|
/src/app/threed-viewer/player.viewer.ts
| 2.546875
| 3
|
/**
* Created by nicolas on 13/04/17.
*/
import {
Mesh,
MeshBasicMaterial,
Geometry,
PlaneBufferGeometry,
BackSide,
Vector3,
} from 'three';
import { SceneViewer } from './scene.viewer';
import { RulesInterface } from '../components/editor/preview/rulesInterface';
export class PlayerViewer extends SceneViewer {
private _selected;
private _intersectPlane;
private _hovered;
private rulesInterface: RulesInterface;
constructor(conf: any = {}, rulesInterface?: RulesInterface) {
super(conf);
this._controls.enableKeys = false;
this._intersectPlane = new Mesh(
new PlaneBufferGeometry(500, 500, 8, 8),
new MeshBasicMaterial({color: 0xffffff, transparent: true, opacity: 0, depthWrite: false}),
);
this._scene.add(this._intersectPlane);
if (rulesInterface)
this.rulesInterface = rulesInterface;
}
/**
* Default param for load a scene
* @param container : id of container
*/
public defaultLoad(container) {
super.defaultLoad(container);
this._camera.position.copy(new Vector3(0.0, 50.0, 70.0));
}
/**
* Get the intersected objects by the mouse position
* @param event : mouseEvent
* @param objects : Objects to search in
* @returns {Intersection[]}
*/
public intersectObjects(event, objects = this._scene.children) {
this.setIntersection(event);
return this._raycaster.intersectObjects(objects.filter((elem) => elem instanceof Mesh), true);
}
/**
* Select an object on 3D view
* @param obj : Mesh to select
*/
public selectObject(obj: Mesh) {
if (this._selected !== undefined && this._selected.object !== undefined)
this.unselectObject();
this._selected = {
object: obj,
};
const outlineMaterial1 = new MeshBasicMaterial( { color: 0xff0000, side: BackSide } );
this._selected.glow = new Mesh(obj.geometry as Geometry, outlineMaterial1);
this._selected.glow.applyMatrix(this._selected.object.matrixWorld);
this._selected.glow.scale.addScalar(0.5);
this._selected.oldPosition = obj.position.clone();
this._scene.add(this._selected.glow);
}
/**
* Unselect the selected object
*/
public unselectObject() {
if (this._selected === undefined)
return;
if (this._selected.glow !== undefined) {
this._scene.remove(this._selected.glow);
delete this._selected.glow;
}
if (this._selected.object !== undefined)
delete this._selected.object;
}
/**
* Get information if there is an object already selected
* @returns {boolean}
*/
public hasSelection() {
return (this._selected !== undefined && (this._selected.object !== undefined || this._selected.glow !== undefined));
}
/**
* Get information if Object sent is Draggable or not
* @param obj : Intersected object
* @returns {boolean}
*/
public isDraggable(obj) {
const linkModel = (obj.object as any).LinkModel;
if (linkModel === undefined)
return false;
return (linkModel.object.draggable === true);
}
/**
* Get information if Object sent is Droppable or not
* @param obj : Intersected object
* @returns {boolean}
*/
public isDroppable(obj) {
const linkModel = (obj.object as any).LinkModel;
if (linkModel === undefined)
return false;
return (linkModel.object.droppable === true);
}
/**
* Get First object that are Draggable or Droppable
* @param objs : Object ti search in
* @param ignoreSelect : Ignore the object already selected
* @returns {any}
*/
public getFirstDragOrDrop(objs, ignoreSelect = true) {
return objs.find((val) => {
if (ignoreSelect === true)
if (this._selected !== undefined && (this._selected.object === val.object || this._selected.glow === val.object))
return false;
const linkModel = (val.object as any).LinkModel;
return (linkModel !== undefined && (linkModel.object.draggable === true || linkModel.object.droppable === true));
});
}
/**
* Get First object that are Draggable
* @param objs : Object ti search in
* @param ignoreSelect : Ignore the object already selected
* @returns {any}
*/
public getFirstDraggable(objs, ignoreSelect = true) {
return objs.find((val) => {
if (ignoreSelect === true)
if (this._selected !== undefined && (this._selected.object === val.object || this._selected.glow === val.object))
return false;
const linkModel = (val.object as any).LinkModel;
return (linkModel !== undefined && linkModel.object.draggable === true);
});
}
/**
* Get First object that are Droppable
* @param objs : Object ti search in
* @param ignoreSelect : Ignore the object already selected
* @returns {any}
*/
public getFirstDroppable(objs, ignoreSelect = true) {
return objs.find((val) => {
if (ignoreSelect === true)
if (this._selected !== undefined && (this._selected.object === val.object || this._selected.glow === val.object))
return false;
const linkModel = (val.object as any).LinkModel;
return (linkModel !== undefined && linkModel.object.droppable === true);
});
}
/**
* Move selected object to Droppable object
* @param drop : Droppable object
*/
public moveToDroppable(drop) {
if (drop === undefined
|| drop.object === undefined
|| drop.object.LinkModel === undefined
|| drop.object.LinkModel.object.droppable === false)
return;
this._selected.object.position.copy(drop.object.LinkModel.threeDModel.dropPosition(this._selected.object));
this._selected.glow.position.copy(this._selected.object.position);
this._selected.oldPosition.copy(this._selected.object.position);
}
/**
* Called when a mouse button is Down in 3D view
* @param event : MouseEvent
*/
public onMouseDown(event) {
// TODO: add call rule here ?
if (event.button === 0) {
const intersected = this.intersectObjects(event);
if (intersected.length > 0) {
if (this.getFirstDraggable(intersected, false) !== undefined)
this._controls.enableRotate = false;
if (!this.hasSelection()) {
const obj = this.getFirstDraggable(intersected);
if (obj !== undefined)
this.selectObject(obj.object);
} else {
const obj = this.getFirstDragOrDrop(intersected);
if (obj === undefined) {
this.unselectObject();
} else {
if (this.isDroppable(obj)) {
if (this.execAllRules(obj.object) === true) {
this.moveToDroppable(obj);
}
} else {
this.selectObject(obj.object);
}
// if (this.isDroppable(obj) && this.rulesInterface !== undefined) {
// this.rulesInterface.emit('canMoveObject', {
// source: this._selected,
// target: obj,
// },
// () => {
// this.moveToDroppable(obj);
// }
// );
// } else {
// this.selectObject(obj.object);
// }
}
}
if (this.hasSelection())
this._intersectPlane.position.copy(this._selected.object.position);
this._intersectPlane.lookAt(this._camera.position);
} else
this.unselectObject();
}
}
/**
* Called when mouse move in 3D view
* @param event : MouseEvent
*/
public onMouseMove(event) {
const drop = this.getFirstDroppable(this.intersectObjects(event));
if (drop !== undefined) {
if (drop.object.LinkModel !== undefined && drop.object.LinkModel !== this._hovered) {
if (this._hovered !== undefined)
this._hovered.hover(false);
this._hovered = drop.object.LinkModel.threeDModel;
this._hovered.hover(true);
}
} else {
if (this._hovered !== undefined)
this._hovered.hover(false);
}
if (event.buttons === 1 && this.hasSelection()) {
const intersected = this.intersectObjects(event, [this._intersectPlane]);
if (intersected.length > 0) {
this._intersectPlane.position.copy(intersected[0].point);
this._intersectPlane.lookAt(this._camera.position);
this._selected.object.position.copy(intersected[0].point);
this._selected.glow.position.copy(intersected[0].point);
}
}
}
/**
* Called when a mouse button is up on 3D view
* @param event
*/
public onMouseUp(event) {
// TODO: add call rule here ?
if (event.button === 0 && this._selected !== undefined && this._selected.object !== undefined) {
const intersected = this.intersectObjects(event);
const drop = this.getFirstDroppable(intersected);
if (drop === undefined) {
this._selected.object.position.copy(this._selected.oldPosition);
this._selected.glow.position.copy(this._selected.oldPosition);
} else {
if (this.execAllRules(drop.object) === true) {
this.moveToDroppable(drop);
} else {
this._selected.object.position.copy(this._selected.oldPosition);
this._selected.glow.position.copy(this._selected.oldPosition);
}
// if (this.rulesInterface !== undefined) {
// this.rulesInterface.emit('canMoveObject', {
// source: this._selected,
// target: drop,
// },
// () => {
// this.moveToDroppable(drop);
// },
// () => {
// this._selected.object.position.copy(this._selected.oldPosition);
// this._selected.glow.position.copy(this._selected.oldPosition);
// }
// );
// }
}
}
this._controls.enableRotate = true;
}
private execAllRules(args?: any): boolean {
const linkModel = (this._selected.object as any).LinkModel;
if (linkModel === undefined || linkModel.rules === undefined)
return true;
for (const rule in linkModel.rules) {
if (linkModel.rules[rule]._priority && linkModel.rules[rule]._priority === "HIGH")
if (linkModel.rules[rule].run(args) === false)
return false;
}
for (const rule in linkModel.rules) {
if (!linkModel.rules[rule]._priority && linkModel.rules[rule]._priority !== "HIGH")
if (linkModel.rules[rule].run(args) === false)
return false;
}
return true;
}
}
|
61ee17be70a5eb37e6560aa145713889e9fd429b
|
TypeScript
|
roybailey/neo4j-graph-loader
|
/src/graph/neo4j-util.ts
| 2.59375
| 3
|
"use strict";
import {QueryResult} from "neo4j-driver";
import neo4j from "neo4j-driver";
import logger from "../util/logger";
const neo4jUrl = (process.env.NEO4J_URL || "bolt://localhost:7687");
const neo4jUsername = (process.env.NEO4J_USERNAME || "neo4j");
const neo4jPassword = (process.env.NEO4J_PASSWORD || "neo4j");
const driver = neo4j.driver(neo4jUrl, neo4j.auth.basic(neo4jUsername, neo4jPassword));
logger.debug(`Neo4j ${neo4jUrl} Starting`);
export async function neo4jShutdown() {
return driver.close().then(() => logger.debug(`Neo4j ${neo4jUrl} Shutdown`));
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const NOHANDLER = (result: QueryResult) => Promise.resolve();
export const COUNTHANDLER = (result: QueryResult) => {
// On result, get count from first record
const count = result.records[0].get("count");
// Log response
logger.debug(`Graph now contains...${count} nodes`);
return Promise.resolve(count.toNumber());
};
export function runCypher(query: string, params: any, handler: (result: QueryResult) => any) {
// let result: any;
const session = driver.session();
logger.debug(query);
return session.run(query, params)
.then((result: QueryResult) => {
const passback = handler(result);
return passback;
})
.catch((err: any) => {
logger.error(err);
})
.then((result) =>{ session.close(); return result; })
.then((result) => Promise.resolve(result));
}
export function clearGraph() {
logger.debug("clearGraph()");
return runCypher("match (n) optional match (n)-[r]-() delete r,n", {}, NOHANDLER);
}
export function countGraph() {
logger.debug("countGraph()");
return runCypher("MATCH (n) RETURN count(n) as count", {}, COUNTHANDLER);
}
|
4908685150c545955971dd05c8b90266dac48f1b
|
TypeScript
|
ccllab/just-kanban
|
/src/server/controllers/providers/AppAuthProvider.ts
| 2.609375
| 3
|
import * as express from 'express';
import AuthError from "../../services/exceptions/AuthError";
import {IAuthService} from "../../services";
import {ILogger} from "../../utils";
import {inject, injectable} from "inversify";
import {interfaces} from 'inversify-express-utils';
import {Principal} from "./Principal";
import {TYPES} from "../../ioc";
/**
* HttpContext Auth Provider
* Verify user status by token in every http request.
*/
@injectable()
export class AppAuthProvider implements interfaces.AuthProvider {
/**
* AuthService
*/
@inject(TYPES.IAuthService) private readonly authService: IAuthService;
/**
* Logger
*/
@inject(TYPES.ILogger) private readonly logger: ILogger;
/**
* Get user principal by authToken, and refreshToken.
* @param req request
* @param res response
* @param next next function
* @return Promise<Principal>
*/
public getUser(
req: express.Request,
res: express.Response,
next: express.NextFunction): Promise<interfaces.Principal> {
const authToken: string = req.header('x-auth');
const refreshToken: string = req.header('x-refresh');
return this.authService.getUserAuthByToken(authToken, refreshToken).then((userAuthDto) => {
// set header after get User entity.
res.set({
'x-auth': userAuthDto.accessToken,
'x-refresh': userAuthDto.userDetail.refreshToken
});
return new Principal(userAuthDto.userDetail);
}).catch((err) => {
// only log unexpected error
if (!(err instanceof AuthError)) {
this.logger.error(err);
}
return new Principal(undefined);
});
}
}
|
36ba8775ff42f9595557a5db60e4009a5653219d
|
TypeScript
|
katafrakt/loremaster
|
/src/template/index.ts
| 3.0625
| 3
|
import Markdown from './markdown';
class Template {
render(source: string): string {
source = this.renderLinks(source);
source = this.renderMarkdown(source);
source = this.renderDetails(source);
return source;
}
private renderMarkdown(source: string): string {
const renderer = new Markdown();
return renderer.render(source);
}
private renderDetails(source: string): string {
return source.replace(/\[(.*)\]\{([^\}]*)\}/g, (_, label, text) => {
return this.htmlify(
'a',
{
href: 'javascript:void(0)',
'data-detail-show': this.renderMarkdown(text),
class: 'detail-link'
},
[label]
);
});
}
// copied from Chapbook
private renderLinks(source: string): string {
return source.replace(/\[\[(.*?)\]\]/g, (_, target) => {
let label = target;
// display|target format
const barIndex = target.indexOf('|');
if (barIndex !== -1) {
label = target.substr(0, barIndex);
target = target.substr(barIndex + 1);
} else {
// display->target format
const rightArrIndex = target.indexOf('->');
if (rightArrIndex !== -1) {
label = target.substr(0, rightArrIndex);
target = target.substr(rightArrIndex + 2);
} else {
// target<-display format
const leftArrIndex = target.indexOf('<-');
if (leftArrIndex !== -1) {
label = target.substr(leftArrIndex + 2);
target = target.substr(0, leftArrIndex);
}
}
}
return this.renderLink(target, label || target);
});
}
// copied from Chapbook
// adjusted not to use cb in attr
private renderLink(target, label) {
// Does the target look like an external link?
if (/^\w+:\/\/\/?\w/i.test(target)) {
return this.htmlify(
'a',
{
href: target,
target: '_blank'
},
[label || target]
);
}
// We'll treat it as an internal one if not.
return this.htmlify(
'a',
{
href: 'javascript:void(0)',
'data-passage-change': target
},
[label || target]
);
}
// copied from Chapbook
private domify(tagName: string, attrs, children = []) {
const result = document.createElement(tagName);
Object.keys(attrs).forEach(a => {
if (attrs[a] !== undefined) {
result.setAttribute(a, attrs[a]);
}
});
children.forEach(c => {
if (typeof c === 'string') {
result.appendChild(document.createTextNode(c));
} else {
result.appendChild(c);
}
});
return result;
}
// copied from Chapbook
private htmlify(tagName: string, attrs, children) {
return this.domify(tagName, attrs, children).outerHTML;
}
}
export default Template
|
82984025a92e449177572bd8c16fbd4722feb243
|
TypeScript
|
ToxicToast/Twitch
|
/apps/audit/src/app/domain/aggregates/app.domain.ts
| 2.53125
| 3
|
import { AggregateRoot } from '@nestjs/cqrs';
import { Nullable } from '@twitch/shared';
import { AnemicApp } from '../models/app.model';
export class AppDomain extends AggregateRoot {
constructor(
private readonly id: string,
private readonly channel: string,
private readonly username: string,
private readonly type: string,
private readonly payload: string,
private readonly created_at: Date,
private updated_at: Nullable<Date>,
private deleted_at: Nullable<Date>,
) {
super();
}
public isDeleted(): boolean {
return !!this.deleted_at;
}
public isUpdated(): boolean {
return !!this.updated_at;
}
public toAnemic(): AnemicApp {
return {
id: this.id,
channel: this.channel,
username: this.username,
type: this.type,
payload: this.payload,
created_at: this.created_at,
updated_at: this.updated_at,
deleted_at: this.deleted_at,
isUpdated: this.isUpdated(),
isDeleted: this.isDeleted(),
}
}
public deleteAudit(): void {
if (!this.isDeleted()) {
this.deleted_at = new Date();
}
}
public restoreAudit(): void {
if (this.isDeleted()) {
this.deleted_at = null;
}
}
}
|
27ba22b1fd1d89cf0f1b80d721c4ba014355ba1a
|
TypeScript
|
burdiuz/js-deferred-data-access
|
/packages/deferred-data-access/resource/src/resource.ts
| 2.8125
| 3
|
import { IdOwner } from '@actualwave/deferred-data-access/utils';
import { ResourcePool } from './resource-pool';
export class Resource extends IdOwner {
constructor(
public readonly pool: ResourcePool,
public readonly type: string
) {
super();
}
toObject(): ResourceObject {
return { id: this.id, poolId: this.pool.id, type: this.type };
}
toJSON() {
return JSON.stringify(this.toObject());
}
}
export type ResourceObject = {
id: string;
poolId: string;
type: string;
};
export const createResource = (
pool: ResourcePool,
target: unknown,
type?: string
) => new Resource(pool, type || typeof target);
export const isResourceObject = (obj: any) =>
obj &&
// type signature is not enough for non-ts env
typeof obj === 'object' &&
typeof obj.id === 'string' &&
typeof obj.poolId === 'string';
|
97351c06546ba5c8fec55e16600a6ad6a63f8903
|
TypeScript
|
iamlazy-dev/app
|
/packages/core/src/product-database/presentation/ProductState.ts
| 2.796875
| 3
|
import { Product } from '../domain/Model';
export interface CommonProductState {
id: string;
product: Product | null;
}
export interface LoadingProductState {
kind: 'Loading';
}
export interface LoadedProductState {
kind: 'Loaded';
product: Product;
}
export interface ErrorProductState {
kind: 'Error';
errMsg: string;
}
export type ProductState = (LoadingProductState | LoadedProductState | ErrorProductState) &
CommonProductState;
export const productInitialState: ProductState = {
kind: 'Loading',
id: '',
product: null,
};
|
b7d89f3c302a80fdc520e324d6260414e765223e
|
TypeScript
|
gsbelarus/gdmn
|
/packages/gdmn-nlp/src/morphology/rusAdjectivesData.ts
| 2.765625
| 3
|
import { RusAdjectiveInterface, RusAdjectiveCategory } from './types';
export const rusAdjectives: RusAdjectiveInterface[] = [
// абрикосовый
{
stem: 'абрикосов',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Rel,
declensionZ: '1a'
},
// самый
{
stem: 'сам',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Pron,
declensionZ: '1a'
},
// первый
{
stem: 'перв',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Rel,
declensionZ: '1a'
},
// новый
{
stem: 'нов',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '1a/c\''
},
// алый
{
stem: 'ал',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '1a\''
},
// братний
{
stem: 'братн',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Rel,
declensionZ: '2a'
},
// убогий
{
stem: 'убог',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '3a'
},
// минский
{
stem: 'минск',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Rel,
declensionZ: '3a'
},
// похожий
{
stem: 'похож',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '4a'
},
// крупнейший
{
stem: 'крупнейш',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '4a'
},
// лучший
{
stem: 'лучш',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '4a'
},
// вьющийся
{
stem: 'вьющ',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Rel,
declensionZ: '4a-ся'
},
// куцый
{
stem: 'куц',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Rel,
declensionZ: '5a'
},
// длинношеий
{
stem: 'длинноше',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '6a'
},
// пищевой
{
stem: 'пищев',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Rel,
declensionZ: '1b'
},
// живой
{
stem: 'жив',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '1b/c'
},
// людской
{
stem: 'людск',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Rel,
declensionZ: '3b'
},
// большой
{
stem: 'больш',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '4b'
},
// удобный
{
stem: 'удобн',
stem1: 'удобен',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '1*a'
},
// мирный
{
stem: 'мирн',
stem1: 'мирен',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '1*a\''
},
// тяжелый
{
stem: 'тяжел',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '1a/b'
},
// наглый
{
stem: 'нагл',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '1a/с'
},
// славный
{
stem: 'славн',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '1*a/c'
},
// добрый
{
stem: 'добр',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '1a/c\''
},
// смешной
{
stem: 'смешн',
stem1: 'смешон',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '1*b'
},
// излишний
{
stem: 'излишн',
stem1: 'излишен',
stem2: '',
category: RusAdjectiveCategory.Rel,
declensionZ: '2*a'
},
// последний
{
stem: 'последн',
stem1: 'последен',
stem2: '',
category: RusAdjectiveCategory.Rel,
declensionZ: '2*a'
},
// весь
{
stem: 'вес',
stem1: 'вс',
stem2: '',
category: RusAdjectiveCategory.Pron,
declensionZ: '2*b'
},
// синий
{
stem: 'син',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '2a/c'
},
// ветхий
{
stem: 'ветх',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '3a/c'
},
// громоздкий
{
stem: 'громоздк',
stem1: 'громоздок',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '3*a'
},
// широкий
{
stem: 'широк',
stem1: '',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '3a/c"^'
},
// зоркий
{
stem: 'зорк',
stem1: 'зорок',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '3*a\''
},
// громкий
{
stem: 'громк',
stem1: 'громок',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '3*a/c'
},
// короткий
{
stem: 'коротк',
stem1: 'короток',
stem2: '',
category: RusAdjectiveCategory.Qual,
declensionZ: '3*a/c\''
},
];
|
ef76021318391cd7bfc54c95c914c23542f89cff
|
TypeScript
|
Mr-shadow/lab
|
/ts-004/libs/src/index.ts
| 2.515625
| 3
|
export function post(url:string, data:{[key:string]:string}):void
{
}
export class ImageHelper
{
public static toBase64(img:HTMLImageElement):string
{
return null;
}
public static fromBase64(str:string):HTMLImageElement
{
return null;
}
}
export class Image
{
public constructor()
{
}
private _url:string;
public get url():string { return this._url;; }
public set url(v:string) { this._url = v; }
}
|
582377189c5755206c4da0ebfaa2045bee5e9c28
|
TypeScript
|
MindXL/koishi
|
/packages/koishi-utils/tests/time.spec.ts
| 2.828125
| 3
|
import { Time } from 'koishi-utils'
import { expect } from 'chai'
import { install, InstalledClock } from '@sinonjs/fake-timers'
describe('Time Manipulations', () => {
let clock: InstalledClock
const date = new Date(2020, 3, 1, 1, 30)
const now = date.valueOf()
before(() => {
clock = install({ now })
})
after(() => {
clock.uninstall()
})
it('timezone offset', () => {
Time.setTimezoneOffset(-480)
expect(Time.getTimezoneOffset()).to.equal(-480)
})
it('date number', () => {
Time.getDateNumber() /* make coverage happy */
expect(Time.getDateNumber(new Date(Date.UTC(2020, 0)))).to.equal(18262)
expect(Time.getDateNumber(1577808000000)).to.equal(18262)
expect(+Time.fromDateNumber(18262)).to.equal(+new Date(Date.UTC(2019, 11, 31, 16)))
})
it('parse time', () => {
expect(Time.parseTime('')).to.equal(0)
expect(Time.parseTime('0.5s')).to.equal(Time.second / 2)
expect(Time.parseTime('0.5m')).to.equal(Time.minute / 2)
expect(Time.parseTime('0.5h')).to.equal(Time.hour / 2)
expect(Time.parseTime('0.5d')).to.equal(Time.day / 2)
expect(Time.parseTime('0.5w')).to.equal(Time.week / 2)
})
it('parse date', () => {
expect(+Time.parseDate('')).to.equal(now)
expect(+Time.parseDate('1min')).to.equal(now + Time.minute)
expect(+Time.parseDate('2:30')).to.approximately(now, Time.day)
expect(+Time.parseDate('5-1-1:30')).to.approximately(now + 30 * Time.day, Time.day)
})
it('format time short', () => {
expect(Time.formatTimeShort(Time.millisecond)).to.equal('1ms')
expect(Time.formatTimeShort(Time.second)).to.equal('1s')
expect(Time.formatTimeShort(Time.minute)).to.equal('1m')
expect(Time.formatTimeShort(Time.hour)).to.equal('1h')
expect(Time.formatTimeShort(Time.day)).to.equal('1d')
})
it('format time long', () => {
expect(Time.formatTime(Time.millisecond)).to.equal('0 秒')
expect(Time.formatTime(Time.second)).to.equal('1 秒')
expect(Time.formatTime(Time.minute)).to.equal('1 分钟')
expect(Time.formatTime(Time.minute + 40 * Time.second)).to.equal('1 分钟 40 秒')
expect(Time.formatTime(Time.hour)).to.equal('1 小时')
expect(Time.formatTime(Time.hour + 50 * Time.minute)).to.equal('1 小时 50 分钟')
expect(Time.formatTime(Time.day)).to.equal('1 天')
expect(Time.formatTime(Time.day + 20 * Time.hour)).to.equal('1 天 20 小时')
})
it('format time interval', () => {
expect(Time.formatTimeInterval(date)).to.equal('2020-04-01 01:30:00')
expect(Time.formatTimeInterval(date, Time.day)).to.equal('每天 01:30')
Time.formatTimeInterval(date, Time.week) // make coverage happy
Time.formatTimeInterval(date, Time.hour) // make coverage happy
})
})
|
ae1e7d3688245d71895e8ea279cde8f04f02e1d6
|
TypeScript
|
danielsh28/actuali-front
|
/src/store/reducers/AppHeightReducer.ts
| 2.6875
| 3
|
import {
USER_NOT_LOGGED,
USER_LOGGED,
AppHeight,
LogUserActions,
ILogState,
} from "../types";
export const appHeightReducer = (
state: ILogState = { height: AppHeight.LANDING, isLogin: false },
action: LogUserActions
) => {
switch (action.type) {
case USER_LOGGED:
state = {
...state,
height: AppHeight.DASHBOARD,
isLogin: true,
};
break;
case USER_NOT_LOGGED:
state = {
...state,
height: AppHeight.LANDING,
};
break;
}
return state;
};
|
cb5d98e44d8a8497a826066d890f485f10ffd803
|
TypeScript
|
mcountryman/geotab-rx
|
/src/models/deferral_info.ts
| 2.75
| 3
|
/* eslint-disable @typescript-eslint/no-empty-interface */
import { DutyStatusDeferralType } from "./duty_status_deferral_type";
/**
* RestInfo.
*
* @deprecated
*/
export interface IDeferralInfo {
/**
* Gets or sets a value indicating whether the day two log required. Tells the driver
* if they are required to add another deferral exemption log today.
*/
dayTwoLogRequired: boolean;
/** Gets or sets the Deferral Status, DayOne or DayTwo. */
status: DutyStatusDeferralType;
/** Gets or sets the amount of time deferred. */
time: Date;
}
|
464f7dbe1c2cfa2ec78ab1a614ee5d70f5ebde52
|
TypeScript
|
JassiSidhu/Comp397-Game
|
/Comp397-Game/Scripts/objects/button.ts
| 2.6875
| 3
|
/// <reference path="../managers/assets.ts" />
module objects {
//BUTTON CLASS..........
export class Button extends createjs.Bitmap {
//CONSTRUCTOR.........
constructor(imageString: string, x: number, y: number, centered: boolean) {
super(imageString);
this.regX = this.getBounds().width / 2;
this.regY = this.getBounds().height / 2;
this.x = x;
this.y = y;
this.setButtonListeners();
}
//PUBLIC METHODS
public setButtonListeners() {
this.cursor = 'pointer';
this.on('rollover', this.onButtonOver);
this.on('rollout', this.onButtonOut);
}
public onButtonOver() {
this.alpha = 0.8;
}
public onButtonOut() {
this.alpha = 1;
}
}
}
|
c67df8353cce804afcfbc45c3ff0e035af2cd5e9
|
TypeScript
|
malekylik/angular-mentoring
|
/src/app/store/actions/courses.actions.ts
| 2.6875
| 3
|
import { Course } from 'src/app/modules/course/models/course.model';
import { CoursesReqParams } from 'src/app/modules/course/models/courses-req-params';
import { ActionPayload } from 'src/app/modules/course/models/action-payload';
import { CoursesDeletePayload } from 'src/app/models/courses-delete-action-payload';
export enum CoursesActionTypes {
GetCourses = '[Courses] GetCourses',
StoreCourses = '[Courses] StoreCourses',
ResetCourses = '[Courses] ResetCourses',
DeleteCourses = '[Courses] DeleteCourses',
AddCourse = '[Courses] AddCourse',
EditCourse = '[Courses] EditCourse',
Error = '[Courses] Error',
}
export class CoursesActions {
public static getCourses(payload: CoursesReqParams): ActionPayload<CoursesReqParams> {
return new ActionPayload(CoursesActionTypes.GetCourses, payload);
}
public static storeCourses(courses: Course[]): ActionPayload<Course[]> {
return new ActionPayload(CoursesActionTypes.StoreCourses, courses);
}
public static resetCourses(): ActionPayload<void> {
return new ActionPayload(CoursesActionTypes.ResetCourses);
}
public static deleteCourses(payload: CoursesDeletePayload): ActionPayload<CoursesDeletePayload> {
return new ActionPayload(CoursesActionTypes.DeleteCourses, payload);
}
public static addCourse(course: Course): ActionPayload<Course> {
return new ActionPayload(CoursesActionTypes.AddCourse, course);
}
public static editCourse(course: Course): ActionPayload<Course> {
return new ActionPayload(CoursesActionTypes.EditCourse, course);
}
public static error(payload: any): ActionPayload<any> {
return new ActionPayload(CoursesActionTypes.Error, payload);
}
}
|
a9d281b64932279404653f02e0ceccb218c013d1
|
TypeScript
|
ywarezk/angular-advanced-by
|
/ng-workspace/projects/redux-tutorial/src/app/actions/hello.actions.ts
| 2.640625
| 3
|
import { Action } from '@ngrx/store';
export enum HelloActionTypes {
SetMessage = '[Hello] Set Message',
}
export class SetMessage implements Action {
readonly type = HelloActionTypes.SetMessage;
constructor(public message : string) {}
}
export type HelloActions = SetMessage;
|
acc603b5c0db5cd81bc02ad5c367ead7c227a01c
|
TypeScript
|
patrickmichalina/typescript-monads
|
/src/reader/reader.spec.ts
| 3.1875
| 3
|
import { reader } from './reader.factory'
import { IReader } from './reader.interface'
describe('reader', () => {
it('should of', () => {
const greet = reader<string, string>(ctx => ctx + '_HelloA')
const greet2 = greet.of(ctx => ctx + '_HelloB')
expect(greet.run('Test')).toEqual('Test_HelloA')
expect(greet2.run('Test')).toEqual('Test_HelloB')
})
it('should map', () => {
const greet = reader<string, string>(ctx => ctx + '_HelloA')
const greet2 = greet.map(s => s + '_Mapped123')
expect(greet.run('Test')).toEqual('Test_HelloA')
expect(greet2.run('Test')).toEqual('Test_HelloA_Mapped123')
})
it('should flatMap', () => {
const greet = (name: string): IReader<string, string> => reader<string, string>(ctx => ctx + ', ' + name)
const end = (str: string): IReader<string, string> => reader<string, boolean>(a => a === 'Hello')
.flatMap(isH => isH ? reader(() => str + '!!!') : reader(() => str + '.'))
expect(greet('Tom').flatMap(end).run('Hello')).toEqual('Hello, Tom!!!')
expect(greet('Jerry').flatMap(end).run('Hi')).toEqual('Hi, Jerry.')
})
})
|
668287cbb0ec2dcc798babb952bd6c55daf0ed8d
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/use-global-hook/use-global-hook-tests.ts
| 3.265625
| 3
|
import Immer from "immer";
import useStore, { InitializerFunction, Options, Store } from "use-global-hook";
interface stateType {
value: string;
}
type setFunc = (value: string) => void;
interface associatedActionsType {
setValue: setFunc;
}
const initializer: InitializerFunction<stateType, associatedActionsType> = (
store: Store<stateType, associatedActionsType>,
) => {
store.actions.setValue("");
store.state.value;
store.setState({ value: "string" });
};
const options: Options<stateType, associatedActionsType> = {
Immer,
initializer,
};
// with options
const store = useStore<stateType, associatedActionsType>({ value: "" }, {}, options);
// default
store(); // $ExpectType [stateType, associatedActionsType]
// works without passing expected type when using state filter
store((state: stateType) => state.value); // $ExpectType [string, associatedActionsType]
store<string>((state: stateType) => state.value); // $ExpectType [string, associatedActionsType]
// works without passing expected type when using only action filter
store(undefined, (action: associatedActionsType) => action.setValue); // $ExpectType [stateType, setFunc]
// returns expected type if passed types
store<setFunc>(undefined, (action: associatedActionsType) => action.setValue); // $ExpectType [stateType, setFunc]
// works without passing expected type when using both state and action filters
// $ExpectType [string, setFunc]
store(
(state: stateType) => state.value,
(actions: associatedActionsType) => actions.setValue,
);
// $ExpectType [string, setFunc]
store<string, setFunc>(
(state: stateType) => state.value,
(actions: associatedActionsType) => actions.setValue,
);
// without options
useStore<stateType, associatedActionsType>({ value: "" }, {});
useStore<stateType, associatedActionsType>({ value: "" }, {}, {});
// with options
useStore<stateType, associatedActionsType>({ value: "" }, {}, { Immer });
useStore<stateType, associatedActionsType>({ value: "" }, {}, { initializer });
// with initializer (backward compatibility with 0.1.2)
useStore<stateType, associatedActionsType>({ value: "" }, {}, initializer);
|
02b2057d5fa9bc9395333e53d74e95ed9764bb41
|
TypeScript
|
samwaters/nChat
|
/server/messages/text.message.ts
| 2.921875
| 3
|
import {IMessage, MessageTypes} from './message.interface';
export class TextMessage implements IMessage {
private _message:string;
private _from:string;
constructor(from:string, message:string) {
this._from = from;
this._message = message;
}
public asString() {
return JSON.stringify({
type: MessageTypes.MESSAGE,
message: this._message,
username: this._from
});
}
public get from() {
return this._from;
}
public get message() {
return this._message;
}
}
|
e5e881670466e3df562f73e7451faac6cdeb4629
|
TypeScript
|
SachinBargal11/Midas
|
/web-ui/src/models/user.ts
| 2.6875
| 3
|
import { Record } from 'immutable';
import moment from 'moment';
import { Address } from './address';
import { Contact } from './contact';
import { UserType } from './enums/user-type';
import { Gender } from './enums/Gender';
const UserRecord = Record({
id: 0,
name: '',
userType: UserType.Owner,
accountId: '',
userName: '',
firstName: '',
middleName: '',
lastName: '',
gender: Gender.MALE,
imageLink: '',
address: null, //Address
contact: null, //Contact
dateOfBirth: moment(), //Moment
isDeleted: 0,
createByUserId: 0,
updateByUserId: 0,
// createDate: null, //Moment
// updateDate: null //Moment
});
export class User extends UserRecord {
id: number;
name: string;
userType: UserType;
accountId: number;
userName: string;
firstName: string;
middleName: string;
lastName: string;
gender: Gender;
imageLink: string;
address: Address;
contact: Contact;
dateOfBirth: moment.Moment;
isDeleted: boolean;
createByUserId: number;
updateByUserId: number;
// createDate: moment.Moment;
// updateDate: moment.Moment;
constructor(props) {
super(props);
}
get userTypeLabel(): string {
return User.getUserTypeLabel(this.userType);
}
get displayName(): string {
return this.firstName + ' ' + this.lastName;
}
static getUserTypeLabel(userType: UserType): string {
switch (userType) {
case UserType.Admin:
return 'Admin';
case UserType.Owner:
return 'Owner';
case UserType.Doctor:
return 'Doctor';
case UserType.Patient:
return 'Patient';
case UserType.Attorney:
return 'Attorney';
case UserType.Adjuster:
return 'Adjuster';
case UserType.Accounts:
return 'Accounts';
}
}
}
|
d1b3a28d8cac7b19ab4b77be7c90ff34e500a3dc
|
TypeScript
|
allanfenx/pulser
|
/src/controller/CategoryController.ts
| 2.890625
| 3
|
import { Request, Response } from "express";
import { getRepository } from "typeorm";
import Category from "../models/Category";
import slugify from "slugify";
import CategoryView from "../view/CategoryView";
class CategoryController {
async index(request: Request, response: Response) {
const categories = await getRepository(Category).find();
return response.json(CategoryView.renderMany(categories));
}
async store(request: Request, response: Response) {
const { title } = request.body;
if (!title || typeof title == undefined || title == null) return response.status(404).json({ erro: "O titulo é obrigatório" });
if (title.length > 49) return response.status(401).json({ erro: "O campo titulo nã pode ter mais que 50 caractres" });
const repository = getRepository(Category);
let category = await repository.findOne({ where: { title } });
if (category) return response.status(401).json({ erro: "Esse titulo já existe!" });
category = repository.create({ title, slug: slugify(title) });
try {
await repository.save(category);
return response.json(category);
} catch (error) {
return response.status(400).json({ erro: "Falha ao salvar categoria" });
}
}
async show(request: Request, response: Response) {
const { id } = request.params;
if (isNaN(Number(id))) return response.status(404).json({ erro: "Id invalido" });
const category = await getRepository(Category).findOne({ where: { id } });
if (!category) return response.status(404).json({ erro: "Categoria não encontrada" });
return response.json(CategoryView.render(category));
}
async update(request: Request, response: Response) {
const { id } = request.params;
if (isNaN(Number(id))) return response.status(404).json({ erro: "Id invalido" });
const { title } = request.body;
if (!title || title == null || typeof title == undefined) return response.status(401).json({ erro: "O campo titulo é obrigatório" });
if (title.length > 49) return response.status(401).json({ erro: "O campo titulo nã pode ter mais que 50 caractres" });
const repository = getRepository(Category);
const category = await repository.findOne(id);
if (!category) return response.status(404).json({ erro: "Category not found" });
try {
await repository.update(id, { title, slug: slugify(title) });
return response.json({ category: title });
} catch (error) {
return response.status(400).json({ erro: "Falha ao atualizar categoria" });
}
}
async destroy(request: Request, response: Response) {
const { id } = request.params;
if (isNaN(Number(id))) return response.status(404).json({ erro: "Id invalido" });
const repository = getRepository(Category);
const category = await repository.findOne(id);
if (!category) return response.status(404).json({ erro: "Categoria não encontrada" });
try {
await repository.remove(category);
return response.json();
} catch (error) {
return response.status(400).json({ erro: "Falha ao deletar categoria" });
}
}
}
export default new CategoryController();
|
8a3bee0a22137055484c40402261c7ba9ddb2e66
|
TypeScript
|
Bastianus/Case_BPM3
|
/Frontend/src/app/Componenten/Bestand toevoegen/bestand-toevoegen.component.ts
| 2.625
| 3
|
import { Component, OnInit } from '@angular/core';
import { CursusService } from 'src/app/Services/cursus.service';
import { Cursus } from '../../Models/Cursus'
import { CursusParserService } from '../../Services/cursus-parser.service';
@Component({
selector: 'app-bestand-toevoegen',
templateUrl: './bestand-toevoegen.component.html',
styleUrls: ['./bestand-toevoegen.component.css']
})
export class BestandToevoegenComponent implements OnInit {
bestand: any;
bestandCursussen : Cursus[];
uploadedCursussen : Array<Cursus>;
foutmeldingen : string[];
AantalInstantiesUploaded : number;
AantalCursussenUploaded : number;
AantalDuplicaten : number = 0;
erZijnFoutmeldingen : boolean = false;
erZijnGeenFoutmeldingen : boolean = false;
erIsTenminsteEenTabelGeupload : boolean = false;
erWordtGeupload : boolean = false;
erIsGeupload : boolean = false;
erWarenDuplicaten : boolean = false;
constructor(private parserService: CursusParserService,
private cursusService: CursusService) { }
ngOnInit(): void {
}
bestandGekozen(ruwBestand)
{
this.erIsGeupload = false;
this.erWordtGeupload = false;
let fileReader = new FileReader();
this.bestand = ruwBestand.target.files[0];
this.bestandNakijken(fileReader)
fileReader.readAsText(this.bestand)
}
async uploadDocument()
{
let teUploadedenCursussen = this.bestandCursussen;
this.erZijnFoutmeldingen = false;
this.erZijnGeenFoutmeldingen = false;
this.erIsGeupload = false;
this.erWordtGeupload = true;
this.erIsTenminsteEenTabelGeupload = false;
//resetten van de tabellen
this.uploadedCursussen = new Array<Cursus>();
this.bestandCursussen = new Array<Cursus>();
//resetten van de tellers
this.AantalInstantiesUploaded = 0;
this.AantalCursussenUploaded = 0;
//uploaden, respons geeft de hoeveelheden geuploade cursussen en instanties
let answer = await this.cursusService.PushCursussen(teUploadedenCursussen)
this.erWordtGeupload = false;
this.erIsGeupload = true;
let data = answer[0];
this.AantalCursussenUploaded = data[1];
this.AantalInstantiesUploaded = data[0];
this.AantalDuplicaten = teUploadedenCursussen.length - this.AantalInstantiesUploaded;
if(this.AantalDuplicaten > 0)
{
this.erWarenDuplicaten = true;
}
this.uploadedCursussen = answer[1];
if(this.uploadedCursussen.length>0)
{
this.erIsTenminsteEenTabelGeupload = true;
}
}
bestandNakijken(fileReader : FileReader)
{
let rawBestandCursusArray : Cursus[] = new Array<Cursus>();
fileReader.onload = () =>
{
//Filereader resultaat omzetten zodat het altijd een string is
let result : string;
if( fileReader.result instanceof ArrayBuffer){
const enc = new TextDecoder();
result = enc.decode(fileReader.result);
}
else{
result = fileReader.result;
}
//ingelezen bestand converteren naar cursussen. Als er errors waren, krijk je een string array (de foutmeldingen) i.p.v. een cursus array.
let parseResult: Cursus[] | string[] = this.parserService.parseTextToCursusArray(result);
//nakijken of het nou een string of cursus array is. Moet per regel, omdat anders typescript nog niet weet wat het is.
let foutmeldingen : string[] = new Array<string>();
for(let i=0;i<parseResult.length;i++){
let current = parseResult[i];
if(current instanceof Cursus)
{
rawBestandCursusArray.push(current);
}
else
{
foutmeldingen.push(current);
}
}
if(foutmeldingen.length>0)
{
this.erZijnFoutmeldingen = true;
this.erZijnGeenFoutmeldingen = false;
this.foutmeldingen = foutmeldingen;
}
else
{
this.erZijnFoutmeldingen = false;
this.erZijnGeenFoutmeldingen = true;
this.bestandCursussen = this.parserService.SortCursusArrayByStartDate(rawBestandCursusArray)
}
}
}
}
|
c579a3cb742b55147bcb0574b1b3856d6f09bcd8
|
TypeScript
|
cyberabis/ng-training
|
/marks-form/src/app/user.service.ts
| 2.796875
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class UserService {
//Shared attribute
userName: string;
//Initialize data
constructor(public http: HttpClient){
//this.userName = 'Anonymous User';
http.get('https://jsonplaceholder.typicode.com/users/1')
.subscribe(response => {
this.userName = response['name'];
console.log('Response: ', JSON.stringify(response));
});
console.log('Service created');
}
//Shared method
changeUserName(userName: string): void {
this.userName = userName;
}
}
|
454da7b79c5f072d77f97b01a7c3f2297b77f072
|
TypeScript
|
hhy5277/miniprogram-adapter
|
/src/XMLHttpRequest.ts
| 2.5625
| 3
|
import EventTarget from "./EventTarget";
declare let my: any;
const _requestHeader = new Map();
const _responseHeader = new Map();
const _requestTask = new Map();
const contentTypes = {
json: "application/json",
text: "application/text",
arraybuffer: "application/octet-stream"
};
function _triggerEvent(type, event = { target: this }) {
if (typeof this[`on${type}`] === "function") {
this[`on${type}`].call(this, event);
}
}
function _changeReadyState(readyState, event = { readyState }) {
this.readyState = readyState;
_triggerEvent.call(this, "readystatechange", event);
}
export class XMLHttpRequest extends EventTarget {
static UNSEND: number;
static OPENED: number;
static HEADERS_RECEIVED: number;
static LOADING: number;
static DONE: number;
onabort: any;
onerror: any;
onload: any;
onloadstart: any;
onprogress: any;
ontimeout: any;
onloadend: any;
onreadystatechange: any;
readyState: number;
response: any;
responseText: any;
_responseType: string;
responseXML: any;
status: number;
statusText: string;
upload: any;
withCredentials: boolean;
timeout: number;
_url: string;
_method: string;
constructor() {
super();
this.onabort = null;
this.onerror = null;
this.onload = null;
this.onloadstart = null;
this.onprogress = null;
this.ontimeout = null;
this.onloadend = null;
this.onreadystatechange = null;
this.readyState = 0;
this.response = null;
this.responseText = null;
this._responseType = "text";
this.responseXML = null;
this.status = 0;
this.statusText = "";
this.upload = {};
this.withCredentials = false;
_requestHeader.set("requestHeader", {
"content-type": "application/x-www-form-urlencoded"
});
}
set responseType(type: string) {
this._responseType = type;
}
abort() {
const myRequestTask = _requestTask.get("requestTask");
if (myRequestTask) {
myRequestTask.abort();
}
}
getAllResponseHeaders() {
const responseHeader = _responseHeader.get("responseHeader");
return Object.keys(responseHeader)
.map((header) => {
return `${header}: ${responseHeader[header]}`;
})
.join("\n");
}
getResponseHeader(header) {
return _responseHeader.get("responseHeader")[header];
}
open(method, url /* GET/POST*/) {
this._method = method;
this._url = url;
_changeReadyState.call(this, XMLHttpRequest.OPENED);
}
overrideMimeType() {}
send(data = "") {
if (this.readyState !== XMLHttpRequest.OPENED) {
throw new Error("Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.");
} else {
const url = this._url;
const header = _requestHeader.get("requestHeader");
const responseType = this._responseType;
if (contentTypes[responseType]) {
header["content-type"] = contentTypes[responseType];
}
delete this.response;
this.response = null;
const onSuccess = ({ data, status, headers }) => {
status = status === undefined ? 200 : status;
try {
if (data == null || (data instanceof ArrayBuffer && data.byteLength == 0)) {
status = 404;
}
} catch (e) {}
this.status = status;
if (headers) {
_responseHeader.set("responseHeader", headers);
}
_triggerEvent.call(this, "loadstart");
_changeReadyState.call(this, XMLHttpRequest.HEADERS_RECEIVED);
_changeReadyState.call(this, XMLHttpRequest.LOADING);
this.response = data;
if (data instanceof ArrayBuffer) {
//TODO temporary solution, fix native gc error.
this.response = data.slice(0);
Object.defineProperty(this, "responseText", {
enumerable: true,
configurable: true,
get: function () {
throw "InvalidStateError : responseType is " + this._responseType;
}
});
} else {
this.responseText = data;
}
_changeReadyState.call(this, XMLHttpRequest.DONE);
_triggerEvent.call(this, "load");
_triggerEvent.call(this, "loadend");
};
const onFail = (e) => {
const errMsg = e.message || e.errorMessage;
// TODO 规范错误
if (!errMsg) {
return;
}
if (errMsg.indexOf("abort") !== -1) {
_triggerEvent.call(this, "abort", {
message: errMsg + this._url
});
} else {
_triggerEvent.call(this, "error", {
message: errMsg + this._url
});
}
_triggerEvent.call(this, "loadend");
};
let requestTask = my.request({
data,
url,
method: this._method,
timeout: this.timeout ? this.timeout : 30000,
headers: header,
dataType: responseType,
success: onSuccess,
fail: onFail
});
_requestTask.set("requestTask", requestTask);
}
}
setRequestHeader(header, value) {
const myHeader = _requestHeader.get("requestHeader");
myHeader[header] = value;
_requestHeader.set("requestHeader", myHeader);
}
addEventListener(type, listener) {
if (typeof listener !== "function") {
return;
}
this["on" + type] = (event: any = {}) => {
event.target = event.target || this;
listener.call(this, event);
};
}
removeEventListener(type, listener) {
if (this["on" + type] === listener) {
this["on" + type] = null;
}
}
}
// TODO 没法模拟 HEADERS_RECEIVED 和 LOADING 两个状态
XMLHttpRequest.UNSEND = 0;
XMLHttpRequest.OPENED = 1;
XMLHttpRequest.HEADERS_RECEIVED = 2;
XMLHttpRequest.LOADING = 3;
XMLHttpRequest.DONE = 4;
|
b71cac001772551f40238ca030459abb4b7d54d4
|
TypeScript
|
wepyjs/wepy-templates
|
/templates/todolist/template/src/common/lib/stringOperation.ts
| 3.078125
| 3
|
export class String {
private static readonly regexNumber = /{(\d+(:\w*)?)}/g;
private static readonly regexObject = /{(\w+(:\w*)?)}/g;
public static Empty: string = '';
public static IsNullOrWhiteSpace(value: string): boolean {
try {
if (value == null || value == 'undefined')
return true;
return value.toString().replace(/\s/g, '').length < 1;
}
catch (e) {
console.log(e);
return false;
}
}
public static Join(delimiter: string, ...args: (string | object | Array<any>)[]): string {
try {
let firstArg = args[0];
if (Array.isArray(firstArg) || firstArg instanceof Array) {
let tempString = String.Empty;
let count = 0;
for (let i = 0; i < firstArg.length; i++) {
let current = firstArg[i];
if (i < firstArg.length - 1)
tempString += current + delimiter;
else
tempString += current;
}
return tempString;
}
else if (typeof firstArg === 'object') {
let tempString = String.Empty;
let objectArg = firstArg;
let keys = Object.keys(firstArg); //get all Properties of the Object as Array
keys.forEach(element => { tempString += (<any>objectArg)[element] + delimiter; });
tempString = tempString.slice(0, tempString.length - delimiter.length); //remove last delimiter
return tempString;
}
let stringArray = <string[]>args;
return String.join(delimiter, ...stringArray);
}
catch (e) {
console.log(e);
return String.Empty;
}
}
public static Format(format: string, ...args: any[]): string {
try {
if (format.match(String.regexNumber))
return String.format(String.regexNumber, format, args);
if (format.match(String.regexObject))
return String.format(String.regexObject, format, args, true);
return format;
}
catch (e) {
console.log(e);
return String.Empty;
}
}
private static format(regex: any, format: string, args: any, parseByObject: boolean = false): string {
return format.replace(regex, function (match, x) { //0
let s = match.split(':');
if (s.length > 1) {
x = s[0].replace('{', '');
match = s[1].replace('}', ''); //U
}
let arg;
if (parseByObject)
arg = args[0][x];
else
arg = args[x];
if (arg == null || arg == undefined || match.match(/{\d+}/))
return arg;
arg = String.parsePattern(match, arg);
return typeof arg != 'undefined' && arg != null ? arg : String.Empty;
});
}
private static parsePattern(match: 'L' | 'U' | 'd' | 's' | 'n' | string, arg: string | Date | number | any): string {
switch (match) {
case 'L':
arg = arg.toLowerCase();
return arg;
case 'U':
arg = arg.toUpperCase();
return arg;
case 'd':
if (typeof (arg) === 'string') {
return String.getDisplayDateFromString(arg);
}
else if (arg instanceof Date) {
return String.Format('{0:00}.{1:00}.{2:0000}', arg.getDate(), arg.getMonth(), arg.getFullYear());
}
break;
case 's':
if (typeof (arg) === 'string') {
return String.getSortableDateFromString(arg);
}
else if (arg instanceof Date) {
return String.Format('{0:0000}-{1:00}-{2:00}', arg.getFullYear(), arg.getMonth(), arg.getDate());
}
break;
case 'n': //Tausender Trennzeichen
if (typeof (arg) !== "string")
arg = arg.toString();
let replacedString = arg.replace(/,/g, '.');
if (isNaN(parseFloat(replacedString)) || replacedString.length <= 3)
break;
let numberparts = replacedString.split(/[^0-9]+/g);
let parts = numberparts;
if (numberparts.length > 1) {
parts = [String.join('', ...(numberparts.splice(0, numberparts.length - 1))), numberparts[numberparts.length - 1]];
}
let integer = parts[0];
var mod = integer.length % 3;
var output = (mod > 0 ? (integer.substring(0, mod)) : String.Empty);
var firstGroup = output;
var remainingGroups = integer.substring(mod).match(/.{3}/g);
output = output + '.' + String.Join('.', remainingGroups);
arg = output + (parts.length > 1 ? ',' + parts[1] : '');
return arg;
default:
break;
}
if ((typeof (arg) === 'number' || !isNaN(arg)) && !isNaN(+match) && !String.IsNullOrWhiteSpace(arg))
return String.formatNumber(arg, match);
return arg;
}
private static getDisplayDateFromString(input: string): string {
let splitted: string[];
splitted = input.split('-');
if (splitted.length <= 1)
return input;
let day = splitted[splitted.length - 1];
let month = splitted[splitted.length - 2];
let year = splitted[splitted.length - 3];
day = day.split('T')[0];
day = day.split(' ')[0];
return `${day}.${month}.${year}`;
}
private static getSortableDateFromString(input: string): string {
let splitted = input.replace(',', '').split('.');
if (splitted.length <= 1)
return input;
let times = splitted[splitted.length - 1].split(' ');
let time = String.Empty;
if (times.length > 1)
time = times[times.length - 1];
let year = splitted[splitted.length - 1].split(' ')[0];
let month = splitted[splitted.length - 2];
let day = splitted[splitted.length - 3];
let result = `${year}-${month}-${day}`
if (!String.IsNullOrWhiteSpace(time) && time.length > 1)
result += `T${time}`;
else
result += "T00:00:00";
return result;
}
private static formatNumber(input: number, formatTemplate: string): string {
let count = formatTemplate.length;
let stringValue = input.toString();
if (count <= stringValue.length)
return stringValue;
let remainingCount = count - stringValue.length;
remainingCount += 1; //Das Array muss einen Eintrag mehr als die benötigten Nullen besitzen
return new Array(remainingCount).join('0') + stringValue;
}
private static join(delimiter: string, ...args: string[]): string {
let temp = String.Empty;
for (let i = 0; i < args.length; i++) {
if ((typeof args[i] == 'string' && String.IsNullOrWhiteSpace(args[i])) || (typeof args[i] != "number" && typeof args[i] != "string"))
continue;
let arg = "" + args[i];
temp += arg;
for (let i2 = i + 1; i2 < args.length; i2++) {
if (String.IsNullOrWhiteSpace(args[i2]))
continue;
temp += delimiter;
i = i2 - 1;
break;
}
}
return temp;
}
}
export class StringBuilder {
public Values: string[] = [];
constructor(value: string = String.Empty) {
this.Values = new Array(value);
}
public ToString() {
return this.Values.join('');
}
public Append(value: string) {
this.Values.push(value);
}
public AppendFormat(format: string, ...args: any[]) {
this.Values.push(String.Format(format, ...args));
}
public Clear() {
this.Values = [];
}
}
|
5125dbaace379174a28db2badef79c5e636101ee
|
TypeScript
|
NiyazNz/ng-favicon
|
/projects/ng-favicon/src/lib/color.utils.spec.ts
| 2.640625
| 3
|
import {ColorUtils, RgbColor} from './color.utils';
const color: RgbColor = {
red: parseInt('cc', 16),
green: parseInt('ff', 16),
blue: parseInt('33', 16),
alpha: parseInt('ff', 16),
};
describe('ColorUtils', () => {
it('should convert hex', () => {
expect(ColorUtils.hexToRgba('#ccff33')).toEqual(color);
});
it('should convert hex with alpha', () => {
expect(ColorUtils.hexToRgba('#ccff33ff')).toEqual(color);
});
it('should convert short hex', () => {
expect(ColorUtils.hexToRgba('#cf3')).toEqual(color);
});
it('should convert short hex with alpha', () => {
expect(ColorUtils.hexToRgba('#cf3f')).toEqual(color);
});
});
|
9b01b65f94548a994c1b58543a3012cd72300374
|
TypeScript
|
island-is/island.is
|
/libs/judicial-system/message/src/lib/test/random.ts
| 3.3125
| 3
|
// eslint-disable-next-line @typescript-eslint/ban-types
export function randomEnum<T extends {}>(anEnum: T): T[keyof T] {
const enumValues = (Object.keys(anEnum) as unknown) as T[keyof T][]
const randomIndex = Math.floor(Math.random() * enumValues.length)
const randomEnumValue = enumValues[randomIndex]
return randomEnumValue
}
|
748afde7b6f5f9d6e9a1d6fd27b0f279e3bd8795
|
TypeScript
|
jereef/mmRTLS
|
/ctrlSrv/app/src/streams/markers/types.ts
| 2.734375
| 3
|
import type { Beacon } from '$src/interfaces/beacon.interface';
import type { NavDevice } from '$src/interfaces/nav-device.interface';
export enum MarkerType {
BEACON = 'BEACON',
NAVDEV = 'NAVDEV',
DEFAULT = 'DEFAULT'
}
export interface Marker {
id: string;
type: MarkerType;
icon?: string;
x: number;
y: number;
}
export type Position = Pick<Marker, 'x' | 'y'>;
type WithId<T> = { id: number } & T;
export type NavDeviceInfo = WithId<Omit<NavDevice, 'navId' | 'positions'>>;
export type BeaconInfo = WithId<Omit<Beacon, 'beaconId' | 'x' | 'y'>>;
export type MarkerInfo = BeaconInfo | NavDeviceInfo;
export interface MarkerOf<T extends MarkerInfo> extends Marker {
data: T;
}
export interface MarkerEvents {
onClick?(id: Marker['id']): void;
onDrag?(id: Marker['id'], postion: Pick<Marker, 'x' | 'y'>): void;
}
|
590f4e02d73c7c768c8df0cc32008263f16db7f2
|
TypeScript
|
ismaelalvesgit/angular4-loja
|
/src/app/carrinho.service.ts
| 2.90625
| 3
|
import { Carrinho } from './shared/carrinho.model';
import { Oferta } from './shared/ofertas.model';
export class CarrinhoService{
public items: Carrinho[] = []
constructor(){}
public exibirItems(): Carrinho[] {
return this.items
}
public itemsCarrinho(oferta: Oferta):void{
let carrinho: Carrinho = new Carrinho(
oferta.id,
oferta.imagens[0],
oferta.titulo,
oferta.descricao_oferta,
oferta.valor,
1
)
let carrinhoIgual = this.items.find((items:Carrinho) => items.id == carrinho.id)
if(carrinhoIgual){
carrinhoIgual.quantidade += 1
}else{
this.items.push(carrinho)
}
}
public totalCarrinho():number{
let total:number = 0
this.items.map((items:Carrinho) =>
total = total + ( items.valor * items.quantidade )
)
return total
}
public adicionarQuantidade(itens:Carrinho):void{
let adicinar = this.items.find((items:Carrinho) => items.id == itens.id)
if(adicinar){
adicinar.quantidade += 1
}
}
public diminuirQuantidade(itens:Carrinho):void{
let diminuir = this.items.find((items:Carrinho) => items.id == itens.id)
if(diminuir){
diminuir.quantidade -= 1
if( diminuir.quantidade == 0){
this.items.splice(this.items.indexOf(diminuir), 1)
}
}
}
}
|
f835ae717c7fd5e4181af1627215498d6a8bc02e
|
TypeScript
|
yckao/kubernetes-models-ts
|
/utils/read-input/src/read.ts
| 2.5625
| 3
|
import getStdin from "get-stdin";
import { readFile } from "fs";
import { promisify } from "util";
import { httpGet } from "./http";
const readFileAsync = promisify(readFile);
const urlRegex = /^https?:\/\//;
export async function readInput(path: string): Promise<string> {
if (path === "-") {
return getStdin();
}
if (urlRegex.test(path)) {
return httpGet(path);
}
return readFileAsync(path, "utf8");
}
|
7994fc473ed29243b4767b15b3f8771b73b54939
|
TypeScript
|
Antekirta/tabulas
|
/server/router/REST/collections.ts
| 2.515625
| 3
|
import express from 'express'
import {modelsManager} from "../../../db/utils/models-manager";
import {ISchema} from "../../../db/interfaces/mongoose";
import {QUERY_PARAMS} from "../../../shared/registry/QUERY_PARAMS";
export interface ICollectionRoute {
modelPrettyName: string
urlParam: string
}
export const getCollectionsRoutes = async (req: express.Request, res: express.Response) => {
const collectionsRoutes: Array<ICollectionRoute> = []
modelsManager.getSchemas().forEach((schema: ISchema) => {
collectionsRoutes.push({
modelPrettyName: schema.options.modelPrettyName,
urlParam: schema.options.collection
})
})
res.status(200).send(collectionsRoutes)
}
export const getCollectionSchema = async (req: express.Request, res: express.Response) => {
const modelName = req.query[QUERY_PARAMS.MODEL_NAME]
const schema = modelsManager.getModelSchema(modelName)
if (schema) {
res.status(200).send(schema)
} else {
res.status(404).send(`There is no schema called ${modelName}`)
}
}
|
b59a4df690119da4bef52db78ccd700cf7deba18
|
TypeScript
|
IamRajatBadjatya/Angular-Boilerplate
|
/src/app/reacitve-form-assignment/validatePassword.validator.ts
| 2.609375
| 3
|
import { AbstractControl, ValidationErrors } from '@angular/forms';
export class ValidatePassword{
static validateOldPassword(control: AbstractControl): Promise<ValidationErrors | null> {
return new Promise(
(resolve,reject) => {
setTimeout(()=>{
if(control.value !== "rajat")
resolve({invalidPassword : true})
else
resolve(null)
},2000)
}
);
}
static validateConfirmPassword(control: AbstractControl): ValidationErrors | null{
if(control.get('newPassword').value !== control.get('confirmPassword').value){
return {
invalidConfirmPassword : true
}
}
return null;
}
}
|
8689b51ffbb876b8decc313b6c67c5945024b911
|
TypeScript
|
sharifbubuka/course-data-structures-and-algorithms
|
/tests/data-structures/linear/stack/stack.test.ts
| 3.625
| 4
|
import ArrayStack from "../../../../src/data-structures/linear/stack/array-implementation-of-stack";
import SinglyLinkedListStack from "../../../../src/data-structures/linear/stack/singly-linked-list-implementation-of-stack";
describe('Stack Tests', () => {
let arrayStack: ArrayStack;
let singlyLinkedListStack: SinglyLinkedListStack;
beforeEach(() => {
arrayStack = new ArrayStack();
singlyLinkedListStack = new SinglyLinkedListStack();
});
describe('initializes', () => {
it('should initialize an empty stack', () => {
expect(arrayStack).toBeInstanceOf(ArrayStack);
expect(singlyLinkedListStack).toBeInstanceOf(SinglyLinkedListStack);
})
});
describe('push()', () => {
it('should add an item to the top of the stack', () => {
arrayStack.push('item');
expect(arrayStack.peek()).toBe('item');
expect(arrayStack.size()).toEqual(1);
singlyLinkedListStack.push('item');
expect(singlyLinkedListStack.peek()).toBe('item');
expect(singlyLinkedListStack.size()).toBe(1);
})
});
describe('pop()', () => {
it('should return an error on popping on an empty stack', () => {
expect(arrayStack.pop()).toBeInstanceOf(Error);
expect(singlyLinkedListStack.pop()).toBeInstanceOf(Error);
})
it('should pop top most item of a non empty stack', () => {
arrayStack.push(2);
expect(arrayStack.pop()).not.toBeInstanceOf(Error);
expect(arrayStack.size()).toEqual(0);
singlyLinkedListStack.push(2);
expect(singlyLinkedListStack.pop()).not.toBeInstanceOf(Error);
expect(singlyLinkedListStack.size()).toEqual(0);
})
});
describe('isEmpty()', () => {
it('should return true for an empty stack', () => {
expect(arrayStack.isEmpty()).toBe(true);
expect(singlyLinkedListStack.isEmpty()).toBe(true);
})
it('should return false for a non empty stack', () => {
arrayStack.push(2);
expect(arrayStack.isEmpty()).toBe(false);
singlyLinkedListStack.push(2);
expect(singlyLinkedListStack.isEmpty()).toBe(false);
})
});
describe('peek()', () => {
it('should return an error on peeking an empty stack', () => {
expect(arrayStack.peek()).toBeInstanceOf(Error);
expect(singlyLinkedListStack.peek()).toBeInstanceOf(Error);
})
it('should return the top most element of the stack', () => {
arrayStack.push(1);
expect(arrayStack.peek()).toEqual(1);
singlyLinkedListStack.push(1);
expect(singlyLinkedListStack.peek()).toEqual(1);
})
});
describe('size()', () => {
it('should return the size of an empty stack', () => {
expect(arrayStack.size()).toEqual(0);
expect(singlyLinkedListStack.size()).toEqual(0);
});
it('should return the size of a non empty stack', () => {
arrayStack.push(1);
expect(arrayStack.size()).toEqual(1);
singlyLinkedListStack.push(1);
expect(singlyLinkedListStack.size()).toEqual(1);
})
});
describe('change()', () => {
it('should return an error if the index is out of bounds', () => {
expect(arrayStack.change(2, 10)).toBeInstanceOf(Error);
arrayStack.push(2);
expect(arrayStack.change(2, 10)).toBeInstanceOf(Error);
})
it('should change the item at in-bound index given of a non empty error', () => {
arrayStack.push(2);
expect(arrayStack.change(0, 4)).not.toBeInstanceOf(Error);
expect(arrayStack.peek()).toEqual(4);
})
});
describe('search()', () => {
it('should return true when item is in stack', () => {
arrayStack.push(3); arrayStack.push(5);
expect(arrayStack.search(5)).toBe(true);
singlyLinkedListStack.push(3); singlyLinkedListStack.push(5);
expect(singlyLinkedListStack.search(5)).toBe(true);
});
it('should return false when item is not in stack', () => {
arrayStack.push(3); arrayStack.push(5);
expect(arrayStack.search(1)).toBe(false);
singlyLinkedListStack.push(3); singlyLinkedListStack.push(5);
expect(singlyLinkedListStack.search(1)).toBe(false);
});
});
describe('display()', () => {
it('should return a display string stating that stack is empty for an empty stack', () => {
expect(arrayStack.display()).toBe('Stack is empty!');
expect(singlyLinkedListStack.display()).toBe('Stack is empty!');
})
it('should return a display string representation of a non empty stack', () => {
arrayStack.push(1); arrayStack.push(3); arrayStack.push(6);
expect(arrayStack.display()).toEqual('[1, 3, 6]');
singlyLinkedListStack.push(1); singlyLinkedListStack.push(3); singlyLinkedListStack.push(6);
expect(arrayStack.display()).toEqual('[1, 3, 6]');
})
});
})
|
17f569740b05cff3810babec27626270cdd4e3ca
|
TypeScript
|
SethDavenport/ng2-redux
|
/src/components/sub-store.spec.ts
| 2.65625
| 3
|
import { NgZone } from '@angular/core';
import { async } from '@angular/core/testing'
import { NgRedux } from './ng-redux';
class MockNgZone { run = fn => fn() }
describe('Substore', () => {
const defaultReducer = (state, action) => state;
const ngRedux = new NgRedux(new MockNgZone() as NgZone);
ngRedux.configureStore(defaultReducer, {
foo: {
bar: { wat: { quux: 3 } },
}
});
const basePath = ['foo', 'bar'];
const subStore = ngRedux.configureSubStore(basePath, defaultReducer);
it('adds a key to actions it dispatches', () =>
expect(subStore.dispatch({ type: 'MY_ACTION' }))
.toEqual({
type: 'MY_ACTION',
'@angular-redux::fractalkey': '["foo","bar"]'
}));
it('gets state rooted at the base path', () =>
expect(subStore.getState()).toEqual({ wat: { quux: 3 } }));
it('selects based on base path', async(() =>
subStore.select('wat').subscribe(wat =>
expect(wat).toEqual({ quux: 3 }))));
it('can create its own sub-store', async() => {
const subSubStore = subStore.configureSubStore(['wat'], defaultReducer);
expect(subSubStore.getState()).toEqual({ quux: 3 });
subSubStore.select('quux').subscribe(quux =>
expect(quux).toEqual(3));
expect(subSubStore.dispatch({ type: 'MY_ACTION' }))
.toEqual({
type: 'MY_ACTION',
'@angular-redux::fractalkey': '["foo","bar","wat"]'});
});
});
|
7170bcbf87c0557fc883b8c3a997425121053904
|
TypeScript
|
NemoTravel/flights.search.widget
|
/src/__tests__/utils.spec.ts
| 2.640625
| 3
|
import { getAltLayout, encodeURLParams } from '../utils';
/* global describe */
/* global it */
/* global expect */
describe('utils', () => {
describe('getAltLayout', () => {
it('should return `vjcrdf` when `москва` passed', () => {
expect(getAltLayout('москва')).toBe('vjcrdf');
});
it('should return `москва` when `vjcrdf` passed', () => {
expect(getAltLayout('vjcrdf')).toBe('москва');
});
});
describe('encodeURLParams', () => {
it('should return `a=1` when `{ a: 1 }` passed', () => {
expect(encodeURLParams({ a: 1 })).toBe('a=1');
});
it('should return `a=1&b=2` when `{ a: 1, b: 2 }` passed', () => {
expect(encodeURLParams({ a: 1, b: 2 })).toBe('a=1&b=2');
});
it('should return `` when `{}` or anything but object passed', () => {
expect(encodeURLParams({})).toBe('');
expect(encodeURLParams()).toBe('');
});
});
});
|
3127385f99b2b2c04fb7d2a917c42d618c8c0af4
|
TypeScript
|
rob-myers/rob-myers.github.io
|
/model/geom/vector.model.ts
| 3.46875
| 3
|
export class Vector {
constructor(
public x = 0,
public y = 0,
) {}
add(other: VectorJson) {
this.x += other.x;
this.y += other.y;
return this;
}
public get angle() {
return Math.atan2(this.y, this.x);
}
static average(vectors: Vector[]) {
return vectors.length
? vectors
.reduce((agg, v) => agg.translate(v.x, v.y), Vector.zero)
.scale(1 / vectors.length)
: Vector.zero;
}
clone() {
return new Vector(this.x, this.y);
}
get coord(): [number, number] {
return [this.x, this.y];
}
public copy(other: VectorJson) {
this.x = other.x;
this.y = other.y;
return this;
}
public distSquaredTo(other: VectorJson) {
return Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2)
}
public distTo(other: VectorJson) {
return Math.sqrt(this.distSquaredTo(other));
}
equals({ x, y }: VectorJson) {
return this.x === x && this.y === y;
}
static from(p: VectorJson | string) {
return typeof p === 'string'
// expect e.g. 4.5,3
? new Vector(...(p.split(',').map(Number) as [number, number]))
: new Vector(p.x, p.y);
}
get length() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
normalize(newLength = 1) {
if (this.length) {
return this.scale(newLength / this.length);
}
console.error(`Failed to normalize Vector '${this}' to length '${newLength}'`);
return this;
}
precision(digits = 2) {
this.x = Number(this.x.toFixed(digits));
this.y = Number(this.y.toFixed(digits));
return this;
}
round() {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
return this;
}
scale(amount: number) {
this.x *= amount;
this.y *= amount;
return this;
}
sub(other: VectorJson) {
this.x -= other.x;
this.y -= other.y;
return this;
}
toString() {
return `${this.x},${this.y}`;
}
translate(dx: number, dy: number): Vector {
this.x += dx;
this.y += dy;
return this;
}
static get zero() {
return new Vector(0, 0);
}
}
export type Coord = [number, number];
export interface VectorJson {
x: number;
y: number;
}
export class Edge {
constructor(
public src: Vector,
public dst: Vector,
) {}
get midpoint() {
return new Vector(
0.5 * (this.src.x + this.dst.x),
0.5 * (this.src.y + this.dst.y),
);
}
toString() {
return `${this.src} ${this.dst}`;
}
}
|
9855ad3b0d87a0b14b73081caedc3c08f01d2a55
|
TypeScript
|
thirdslipper/JenkinsBuild
|
/week4master/TypeScript/Bank/main.ts
| 2.9375
| 3
|
import { User } from './user';
import { Account } from './account';
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var users = [
new User('rorr', 'pass'),
new User('jamarius', 'pass'),
new User('seth', 'notpass'),
new User('steven', '1234'),
new User('collin', 'soul'),
new User('joseph', 'design pattern')
];
users.forEach((user)=>{
user.accounts = [];
user.accounts.push(new Account(
Math.random()*1001, 'Checking'));
user.accounts.push(new Account(
Math.random()*100001, 'Savings'));
});
var username;
var password;
var loggedUser;
var account;
main();
function main () {
printUsers();
getUsername();
}
function printUsers() {
users.forEach((user) => {console.log(user);});
let maxMoney = 0;
let maxUser;
users.forEach((user) => {
let money = 0;
//console.log(user);
user.accounts.forEach((acct) => {money+=acct.balance});
if (maxMoney < money){
maxMoney=money;
maxUser = user.username;
}
});
console.log(`The user with the most money is ${maxUser} with ${maxMoney}`);
}
function getUsername() {
rl.question("Input your username: ('q' to quit) ",
(answer) => {
if(answer === 'q') {
exit();
} else {
username = answer;
getPassword();
}
});
}
function getPassword() {
rl.question("Input your password: ",
(answer) => {
password = answer;
login();
});
}
function login() {
loggedUser = users.find((user) => user.login(username, password));
if (loggedUser) {
options();
} else {
getUsername();
}
}
function options() {
loggedUser.accounts.forEach((acc) => {
console.log(acc.type);
});
rl.question("Choose an account: ('q' to quit) ", (answer) => {
if (answer === 'q') {
exit();
} else {
account = loggedUser.accounts.find((acc) => acc.type === answer);
if (account) {
operations();
} else {
options();
}
}
});
function operations() {
console.log("Current Balance: " + account.balance);
rl.question("'w' for withdraw, 'd' for deposit: ", (answer) => {
if (answer === 'w') {
rl.question("Amount: ", (answer) => {
account.withdraw(+answer);
console.log("Current Balance: " + account.balance);
console.log("Logging out");
getUsername();
});
} else {
if (answer === 'd') {
rl.question("Amount: ", (answer) => {
account.deposit(+answer);
console.log("Current Balance: " + account.balance);
console.log("Logging out");
getUsername();
});
}
else {
operations();
}
}
});
}
}
function exit() {
rl.close();
process.exit();
}
|
b7a68bcf154024d7b8732e79d8a22589dc982eaf
|
TypeScript
|
alexeiskachykhin/fxaudio
|
/sources/components/effects/overdrive/overdriveCircuit.ts
| 2.59375
| 3
|
/// <reference path="../../../_references.ts" />
namespace FXAudio {
'use strict';
export class OverdriveCircuit extends Circuit {
private _waveShaperNode: WaveShaperNode;
private _lowPassFilterNode: BiquadFilterNode;
private _gainNode: GainNode;
private _drive: number;
public get gainNode(): GainNode {
return this._gainNode;
}
public get lowPassFilterNode(): BiquadFilterNode {
return this._lowPassFilterNode;
}
constructor(context: Context) {
Contract.isNotNullOrUndefined(context, 'context');
super(context);
this._createOverdriveComponents();
this._connectOverdriveComponents();
this._publishOverdriveComponents();
}
public getDrive(): number {
return this._drive;
}
public setDrive(value: number): void {
Contract.isPositiveOrZero(value, 'value');
const k: number = value;
const deg: number = Math.PI / 180;
const sampleRate: number = this.context.sampleRate;
const shapingCurve = new Float32Array(sampleRate);
for (let i: number = 0; i < sampleRate; i += 1) {
const x: number = i * 2 / sampleRate - 1;
shapingCurve[i] = (3 + k) * x * 20 * deg / (Math.PI + k * Math.abs(x));
}
this._waveShaperNode.curve = shapingCurve;
this._drive = value;
}
private _createOverdriveComponents(): void {
Contract.isNotNullOrUndefined(this.context, 'context');
const audioContext: AudioContext = this.context.audioContext;
this._lowPassFilterNode = audioContext.createBiquadFilter();
this._lowPassFilterNode.type = BiquadFilterType.lowpass;
this._lowPassFilterNode.frequency.value = 3000;
this._waveShaperNode = audioContext.createWaveShaper();
this.setDrive(120);
this._gainNode = audioContext.createGain();
}
private _connectOverdriveComponents(): void {
Contract.isNotNullOrUndefined(this._lowPassFilterNode, '_lowPassFilterNode');
Contract.isNotNullOrUndefined(this._waveShaperNode, '_waveShaperNode');
Contract.isNotNullOrUndefined(this._gainNode, '_gainNode');
AudioUtilities.WebAudioAPI.routeLinear(this._lowPassFilterNode, this._waveShaperNode, this._gainNode);
}
private _publishOverdriveComponents(): void {
Contract.isNotNullOrUndefined(this._lowPassFilterNode, '_lowPassFilterNode');
Contract.isNotNullOrUndefined(this._gainNode, '_gainNode');
this._publishInputComponent(this._lowPassFilterNode);
this._publishOutputComponent(this._gainNode);
}
}
}
|
7c358e674d580f63c3bb3f61af4f31273a306a6b
|
TypeScript
|
seanadipose/mediashare
|
/apps/mediashare/src/state/modules/media-items/index.ts
| 2.53125
| 3
|
import { createAsyncThunk, createReducer } from '@reduxjs/toolkit';
import { makeEnum } from '../../core/factory';
import * as reducers from '../../core/reducers';
import { ApiService } from '../../apis';
import { CreateMediaItemDto, UpdateMediaItemDto } from '../../../api';
const MEDIA_ITEM_ACTIONS = ['GET_MEDIA_ITEM', 'ADD_MEDIA_ITEM', 'UPDATE_MEDIA_ITEM', 'SHARE_MEDIA_ITEM', 'REMOVE_MEDIA_ITEM'] as const;
const MEDIA_ITEMS_ACTIONS = ['FIND_MEDIA_ITEMS'] as const;
export const mediaItemActionTypes = makeEnum(MEDIA_ITEM_ACTIONS);
export const mediaItemsActionTypes = makeEnum(MEDIA_ITEMS_ACTIONS);
export const getMediaItemById = createAsyncThunk(mediaItemActionTypes.getMediaItem, async (id: string, { extra }) => {
const { api } = extra as { api: ApiService };
const response = await api.mediaItems.mediaItemControllerFindOne({ mediaId: id });
return response && response.status === 200 ? response.data : undefined;
});
export const addMediaItem = createAsyncThunk(mediaItemActionTypes.addMediaItem, async (item: CreateMediaItemDto, { extra }) => {
const { api } = extra as { api: ApiService };
const response = await api.mediaItems.mediaItemControllerCreate({ createMediaItemDto: item });
return response && response.status === 200 ? response.data : undefined;
});
export const updateMediaItem = createAsyncThunk(mediaItemActionTypes.updateMediaItem, async (item: UpdateMediaItemDto, { extra }) => {
const { api } = extra as { api: ApiService };
const response = await api.mediaItems.mediaItemControllerUpdate({ mediaId: item._id, updateMediaItemDto: item });
return response && response.status === 200 ? response.data : undefined;
});
export const shareMediaItem = createAsyncThunk(
mediaItemActionTypes.shareMediaItem,
async (args: { id: string; userId: string; item: CreateMediaItemDto }, { extra }) => {
const { api } = extra as { api: ApiService };
const response = await api.mediaItems.mediaItemControllerShare({ mediaId: args.id, userId: args.userId, createMediaItemDto: args.item });
return response && response.status === 200 ? response.data : undefined;
}
);
export const removeMediaItem = createAsyncThunk(mediaItemActionTypes.updateMediaItem, async (id: string, { extra }) => {
const { api } = extra as { api: ApiService };
const response = await api.mediaItems.mediaItemControllerRemove({ mediaId: id });
return response && response.status === 200 ? response.data : undefined;
});
export const findMediaItems = createAsyncThunk(mediaItemsActionTypes.findMediaItems, async (opts: {} | undefined, { extra }) => {
const { api } = extra as { api: ApiService };
// @ts-ignore
const response = await api.user.userControllerGetMediaItems({ query: {}, headers: {} });
return response && response.status === 200 ? response.data : [];
});
const initialState = {};
export const MEDIA_ITEMS_STATE_KEY = 'mediaItems';
const mediaItemReducer = createReducer(
initialState,
(builder) =>
builder
.addCase(getMediaItemById.fulfilled, reducers.addItem(MEDIA_ITEMS_STATE_KEY))
.addCase(addMediaItem.fulfilled, reducers.addItem(MEDIA_ITEMS_STATE_KEY))
.addCase(updateMediaItem.fulfilled, reducers.updateItem(MEDIA_ITEMS_STATE_KEY))
.addCase(shareMediaItem.fulfilled, reducers.updateItem(MEDIA_ITEMS_STATE_KEY))
// .addCase(removeMediaItem.fulfilled, reducers.removeItem(MEDIA_ITEMS_STATE_KEY))
);
const mediaItemsReducer = createReducer(initialState, (builder) => builder.addCase(findMediaItems.fulfilled, reducers.loadItems(MEDIA_ITEMS_STATE_KEY)));
export { mediaItemReducer, mediaItemsReducer };
|
2695ba475c3dbe166511dd3c9272e4a36b40689c
|
TypeScript
|
AnastasiiaReida/html5_css3
|
/src/validator-selector.ts
| 2.71875
| 3
|
/// <reference path="validator-strategies.ts" />
namespace Validation {
export class ValidatorSelector {
private static validators: { [id: string]: Validation.ValidationStrategy } = {}
static initialize() {
ValidatorSelector.validators["required"] = new RequiresValidator();
ValidatorSelector.validators["number"] = new NumberValidator();
ValidatorSelector.validators["email"] = new EmailValidators();
ValidatorSelector.initialize = () => { }; // для избежания повторной инициализации
}
static select(name: string): ValidationStrategy {
let validator: ValidationStrategy = ValidatorSelector.validators[name];
if (validator) {
return validator;
}
else {
throw new Error("Не найден валидатор " + name);
}
}
}
}
|
91fc2bc7a55866fa309346727abeef9fe5ca1bf0
|
TypeScript
|
Heiyuan/firing_balls
|
/assets/src/common/localStorage/LocalStorage.ts
| 2.8125
| 3
|
import SingletonClass from "../base/SingletonClass";
export class LocalStorage extends SingletonClass {
public static ins() {
return super.ins() as LocalStorage
}
private _game_key = 'nonstop_balls_tt_'
public setLocal(key: string, value) {
try {
if (typeof value == 'object')
value = JSON.stringify(value)
cc.sys.localStorage.setItem(this.str_encrypt(this._game_key + key), this.str_encrypt(value, this._game_key + key))
} catch (e) {
}
}
public getLocal(key: string, defaultValue?) {
try {
let result = cc.sys.localStorage.getItem(this.str_encrypt(this._game_key + key));
if (result == null) {
return defaultValue
}
result = this.str_decrypt(result, this._game_key + key);
switch (typeof defaultValue) {
case 'object': {
let ret = defaultValue;
try {
let parse = JSON.parse(result);
if (typeof parse === 'object') {
ret = parse;
}
} catch{
}
return ret;
}
case "boolean": {
return (result === "true")
}
case "number": {
return Number(result) || defaultValue;
}
}
return result
} catch (e) {
return defaultValue
}
}
/**
* 加密函数
* @param str 待加密字符串
* @returns {string}
*/
private str_encrypt(str: string, pwd: string = this._game_key) {
let pwd_length = 0;
for (let index = 0, len = pwd.length; index < len; index++) {
pwd_length += pwd.charCodeAt(index);
}
str = str.toString()
str += pwd;
let c = String.fromCharCode(str.charCodeAt(0) + str.length * pwd_length);
for (let i = 1; i < str.length; i++) {
c += String.fromCharCode(str.charCodeAt(i) + str.charCodeAt(i - 1));
}
return encodeURIComponent(c);
}
/**
* 解密函数
* @param str 待解密字符串
* @returns {string}
*/
private str_decrypt(str: string, pwd: string = this._game_key) {
let pwd_length = 0;
for (let index = 0, len = pwd.length; index < len; index++) {
pwd_length += pwd.charCodeAt(index);
}
str = str.toString()
str = decodeURIComponent(str);
let c = String.fromCharCode(str.charCodeAt(0) - str.length * pwd_length);
for (let i = 1; i < str.length; i++) {
c += String.fromCharCode(str.charCodeAt(i) - c.charCodeAt(i - 1));
}
return c.slice(0, c.length - pwd.length);
}
}
export const CONST_STORAGE_KEY = {
KEY_MUSIC_VOLUME: `KEY_MUSIC_VOLUME`,
KEY_SOUND_VOLUME: `KEY_SOUND_VOLUME`,
KEY_SOUND_IS_MUTE: `KEY_SOUND_IS_MUTE`,
KEY_MUSIC_IS_MUTE: `KEY_MUSIC_IS_MUTE`,
}
|
0edcc3b4ea6543fbeafd126da22d9217adcf3539
|
TypeScript
|
gungorbudak/composer
|
/src/app/auth/model/auth-credentials.ts
| 2.765625
| 3
|
import { User } from "../../../../electron/src/sbg-api-client/interfaces/user";
import { UserPlatformIdentifier } from "./user-platform-identifier";
interface PlatformEntry {
name: string;
shortName: string;
platformURL: string;
}
export class AuthCredentials implements UserPlatformIdentifier {
static readonly URL_VALIDATION_REGEXP = "^(https:\/\/)(.+)(\.sbgenomics\.com)$";
static readonly TOKEN_VALIDATION_REGEXP = "^[0-9a-f]{8}[0-9a-f]{4}[0-9a-f]{4}[0-9a-f]{4}[0-9a-f]{12}$";
static readonly platformLookupByAPIURL: { [key: string]: PlatformEntry } = {
"https://api.sbgenomics.com": {
"name": "Seven Bridges",
"shortName": "SBG",
"platformURL": "https://igor.sbgenomics.com"
},
"https://eu-api.sbgenomics.com": {
"name": "Seven Bridges (EU)",
"shortName": "SBG-EU",
"platformURL": "https://eu.sbgenomics.com"
},
"https://api.sb.biodatacatalyst.nhlbi.nih.gov": {
"name": "BioData Catalyst",
"shortName": "BDCatalyst",
"platformURL": "https://platform.sb.biodatacatalyst.nhlbi.nih.gov/developer/#token"
},
"https://cgc-api.sbgenomics.com": {
"name": "Cancer Genomics Cloud",
"shortName": "CGC",
"platformURL": "https://cgc.sbgenomics.com"
},
"https://cavatica-api.sbgenomics.com": {
"name": "Cavatica",
"shortName": "CAVATICA",
"platformURL": "https://cavatica.sbgenomics.com"
},
"https://api.sevenbridges.cn": {
"name": "Seven Bridges (China)",
"shortName": "SBG-CN",
"platformURL": "https://platform.sevenbridges.cn/developer#token"
},
};
static readonly platformDevTokenPath = "/developer#token";
id: string;
user: User;
url: string;
token: string;
constructor(url: string, token: string, user: User) {
// this.ensureValidURL(url);
// this.ensureValidToken(token);
this.url = url;
this.token = token;
this.user = user;
this.id = this.getHash();
}
static isValidToken(token: string): boolean {
return new RegExp(AuthCredentials.TOKEN_VALIDATION_REGEXP).test(token);
}
static isValidURL(url: string): boolean {
return new RegExp(AuthCredentials.URL_VALIDATION_REGEXP).test(url);
}
static getSubdomain(url: string): string {
return url.slice(8, url.length - 15);
}
static getPlatformShortName(url: string): string {
return AuthCredentials.getPlatformPropertyValue(url, "shortName");
}
static getPlatformLabel(url: string): string {
return AuthCredentials.getPlatformPropertyValue(url, "name");
}
static from(obj?: UserPlatformIdentifier): AuthCredentials | undefined {
if (!obj) {
return undefined;
}
return new AuthCredentials(obj.url, obj.token, obj.user);
}
/**
* Checks whether a pair of credentials contain the same user.
* It differs from the {@link AuthCredentials.equals} method in that x and y can be undefined.
*
* @see {@link AuthCredentials.equals} Instance method for comparing equality to another instance
*/
static isSimilar(x?: AuthCredentials, y?: AuthCredentials): boolean {
const onlyXExists = x !== undefined && y === undefined;
const onlyYExists = y !== undefined && x === undefined;
const neitherExist = x === undefined && y === undefined;
if (onlyXExists || onlyYExists) {
return false;
}
if (neitherExist) {
return true;
}
return x.equals(y);
}
getHash(): string {
const subdomain = AuthCredentials.getSubdomain(this.url);
return `${subdomain}_${this.user.username}`;
}
/**
* Checks whether given credentials are considered equal to this one.
* Equality is based on API endpoint and username associated with the token.
*
* @see {@link AuthCredentials.isSimilar} Static function for pair comparison
*/
equals(credentials: AuthCredentials): boolean {
if (!credentials) {
return false;
}
return this.getHash() === credentials.getHash();
}
updateToMatch(credentials: AuthCredentials): void {
this.url = credentials.url;
this.token = credentials.token;
this.user = credentials.user;
}
private ensureValidToken(token: string): void {
if (AuthCredentials.isValidToken(token) === false) {
throw new Error("Given token is not valid: " + token);
}
}
private ensureValidURL(url: string): void {
if (AuthCredentials.isValidURL(url) === false) {
throw new Error("Invalid platform URL: " + url);
}
}
private static getPlatformPropertyValue(url: string, property: keyof PlatformEntry): string {
const platform = this.platformLookupByAPIURL[url];
const subdomain = AuthCredentials.getSubdomain(url);
return platform ? platform[property]
: (subdomain.indexOf("vayu") === -1 ? subdomain : subdomain.split(".")[0]);
}
}
|
dfe5da1d0e26a8f97064a0b9d5d29d945af07973
|
TypeScript
|
liuxinglu/wuziqi
|
/src/app/qipan/model/DataHandler.ts
| 2.640625
| 3
|
module app {
export class DataHandler{
public constructor() {
}
public sendMessageToServer(vd:Object) {
let tempvd = lxl.Tool.copyObject(vd);
let o:Object = {action:'publicMessage', data:tempvd};
lxl.Tool.callJS("sendMsg", o);
}
/**
* 由老师端设置用户列表 然后学生端通过getUserList获取
*/
public setUserList(arr:Array<UserInfo>) {
let tempArr = lxl.Tool.copyObject(arr);
let obj = {type:'getUserList', data:tempArr};
this.sendMessageToServer(obj);
}
public selDefender(token:string) {
let obj = {type:'selDefender', data:token};
this.sendMessageToServer(obj);
}
public chessMove(gridData:GridMap) {
let gd = lxl.Tool.copyObject(gridData);
let obj = {type:'chessMove', data:gd};
this.sendMessageToServer(obj);
}
private _getUserList(data:any) {
lxl.CDispatcher.getInstance().dispatch(new lxl.CEvent(lxl.CEvent.GET_USER_LIST, data))
}
private _getDefender(data:any) {
lxl.CDispatcher.getInstance().dispatch(new lxl.CEvent(lxl.CEvent.SEL_DEFENDER, data));
}
private _getChessMove(data:any) {
lxl.CDispatcher.getInstance().dispatch(new lxl.CEvent(lxl.CEvent.CHESS_MOVE, data));
}
public getMessageFromServer(data:any) {
lxl.logs.log("getMessageFromServer " + data);
switch(data.type) {
case "getUserList":
this._getUserList(data.data);
break;
case "selDefender":
this._getDefender(data.data);
break;
case "chessMove":
this._getChessMove(data.data);
break;
}
}
public setStudentsFromServer(data:any) {
lxl.logs.log("students:" + data);
lxl.CDispatcher.getInstance().dispatch(new lxl.CEvent(lxl.CEvent.GET_STUDENTS_FROM_SERVER, data));
}
public setTeacherFromServer(data:any) {
lxl.logs.log("teacher:" + data);
lxl.CDispatcher.getInstance().dispatch(new lxl.CEvent(lxl.CEvent.GET_TEACHER_FROM_SERVER, data));
}
public getWordsFromServer() {
}
}
}
|
adcaa913d22b936d34e7ea03ad4e419c1557332b
|
TypeScript
|
mattiash/purple-tape
|
/lib/xunit.ts
| 2.96875
| 3
|
import { PurpleTapeTest } from './purple-tape-test'
export type TestEntryResult = {
name: string
durationMs: number
assertions: number
status: 'success' | 'failed' | 'error' | 'skipped'
message: string | undefined // Details for failed or error status
}
export type TestReport = {
name: string
startTime: Date
entries: Array<PurpleTapeTest | undefined>
}
function attr(v: string) {
return v.replace(/&/g, '&').replace(/"/g, '"').replace(/</, '<')
}
export function generateXunit(tr: TestReport) {
let r = ''
r += '<?xml version="1.0" encoding="UTF-8"?>'
let tests = 0
let skipped = 0
let errors = 0
let failures = 0
let durationMs = 0
const testEntries = tr.entries
.filter((t) => !!t)
.map((t) => (t as PurpleTapeTest).testResult())
for (let test of testEntries) {
tests++
durationMs += test.durationMs
switch (test.status) {
case 'error':
errors++
break
case 'skipped':
skipped++
break
case 'failed':
failures++
break
}
}
r += `<testsuites tests="${tests}" skipped="${skipped}" errors="${errors}" failures="${failures}" name="${attr(
tr.name
)}" time="${(durationMs / 1000).toFixed(3)}">`
r += `<testsuite tests="${tests}" skipped="${skipped}" errors="${errors}" failures="${failures}" name="${attr(
tr.name
)}" time="${(durationMs / 1000).toFixed(
3
)}" timestamp="${tr.startTime.toISOString()}">`
for (let test of testEntries) {
r += `<testcase name="${attr(test.name)}" classname="${attr(
tr.name
)}" assertions="${test.assertions}" status="${test.status}" time="${(
test.durationMs / 1000
).toFixed(3)}">`
if (test.status === 'failed') {
r += `<failure message="not used" type="notUsed"><![CDATA[${test.message}]]></failure>`
} else if (test.status === 'error') {
r += `<error message="not used" type="notUsed"><![CDATA[${test.message}]]></error>`
} else if (test.status === 'skipped') {
r += '<skipped/>'
}
r += `</testcase>`
}
r += '</testsuite>'
r += '</testsuites>'
return r
}
export function prematureXunit(name: string, startTime: Date) {
return `<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" skipped="0" errors="1" failures="0" name="${attr(
name
)}" time="0">
<testsuite tests="1" skipped="0" errors="1" failures="0" name="${attr(
name
)}" time="0" timestamp="${startTime.toISOString()}">
<testcase name="no premature exit" classname="${attr(
name
)}" assertions="1" status="error" time="0">
<error message="not used" type="notUsed"><![CDATA[Test exited without writing a proper xml-file]]></error>
</testcase>
</testsuite>
</testsuites>`
}
|
a40d9738f4425fbc82b92177b90c749a0cc9004b
|
TypeScript
|
hokimcuc0202/kintone-ui-component
|
/src/js/Text/__tests__/setValue.test.ts
| 2.796875
| 3
|
/* eslint-disable @typescript-eslint/no-empty-function */
import '@testing-library/jest-dom/extend-expect';
import Text from '../index';
const messages = {
INVALID_ARGUMENT: 'Error: invalid function arguments'
};
describe('[JS] Text', () => {
beforeEach(() => {
jest.spyOn(console, 'error');
// @ts-ignore
console.error.mockImplementation(() => { });
});
afterEach(() => {
// @ts-ignore
console.error.mockRestore();
});
test('should setValue() and getValue() successfully', ()=>{
const value = 'hello';
const text = new Text({value: undefined});
expect(text.render()).toHaveValue('');
text.setValue(value);
expect(text.getValue()).toBe(value);
});
test('should setValue() null for rerender successfully', ()=>{
const text = new Text({value: 'kintone'});
// @ts-ignore
text.setValue(null);
expect(text.render()).toHaveValue('');
});
test('should setValue() throw error when setValue is called without parameters ', ()=>{
try {
const text = new Text();
// @ts-ignore
text.setValue();
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect(error.message).toBe(messages.INVALID_ARGUMENT);
}
});
});
|
95eebd717302e5dea999b8ccfc5015f0cd8ae7e4
|
TypeScript
|
pongo/xpepisode_fuse
|
/src/Scorer.ts
| 3.375
| 3
|
export default class Scorer {
private itsThrows: number[] = Array(21);
private itsCurrentThrow: number = 0;
private ball: number = 0;
addThrow(pins: number): void {
this.itsThrows[this.itsCurrentThrow] = pins;
this.itsCurrentThrow += 1;
}
scoreForFrame(theFrame: number): number {
this.ball = 0;
let score: number = 0;
for (let currentFrame = 0; currentFrame < theFrame; currentFrame += 1) {
if (this.strike()) {
score += 10 + this.nextTwoBalls();
} else if (this.spare()) {
score += 10 + this.nextBall();
} else {
score += this.twoBallsInFrame();
}
}
return score;
}
private nextBall(): number {
return this.itsThrows[this.ball];
}
private strike(): boolean {
if (this.itsThrows[this.ball] === 10) {
this.ball += 1;
return true;
}
return false;
}
private nextTwoBalls(): number {
return this.itsThrows[this.ball] + this.itsThrows[this.ball + 1];
}
private spare(): boolean {
if (this.itsThrows[this.ball] + this.itsThrows[this.ball + 1] === 10) {
this.ball += 2;
return true;
}
return false;
}
private twoBallsInFrame(): number {
const score = this.itsThrows[this.ball] + this.itsThrows[this.ball + 1];
this.ball += 2;
return score;
}
}
|
6e18cb91cca8f6ecefff1d0173762e9f2c3be29b
|
TypeScript
|
asfernandes/node-firebird-drivers
|
/packages/node-firebird-driver/src/lib/impl/date-time.ts
| 2.75
| 3
|
/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2013-2016 Hajime Nakagami
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/
// These functions was adapted from https://github.com/nakagami/firebirdsql
/** Decode a date. */
export function decodeDate(date: number) {
let nday = date + 678882;
const century = Math.trunc((4 * nday - 1) / 146097);
nday = 4 * nday - 1 - 146097 * century;
let day = Math.trunc(nday / 4);
nday = Math.trunc((4 * day + 3) / 1461);
day = 4 * day + 3 - 1461 * nday;
day = Math.trunc((day + 4) / 4);
let month = Math.trunc((5 * day - 3) / 153);
day = 5 * day - 3 - 153 * month;
day = Math.trunc((day + 5) / 5);
let year = 100 * century + nday;
if (month < 10)
month += 3;
else {
month -= 9;
year += 1;
}
return { year, month, day };
}
/** Encode a date. */
export function encodeDate(year: number, month: number, day: number): number {
const i = month + 9;
let jy = year + Math.trunc(i / 12) - 1;
const jm = i % 12;
const c = Math.trunc(jy / 100);
jy -= 100 * c;
const j = Math.trunc((146097 * c) / 4) + Math.trunc((1461 * jy) / 4) + Math.trunc((153 * jm + 2) / 5) + day - 678882;
return j;
}
/** Descode a time. */
export function decodeTime(time: number) {
let seconds = Math.trunc(time / 10000);
let minutes = Math.trunc(seconds / 60);
const hours = Math.trunc(minutes / 60);
minutes = minutes % 60;
seconds = seconds % 60;
const fractions = time % 10000;
return { hours, minutes, seconds, fractions };
}
/** Encode a time. */
export function encodeTime(hours: number, minutes: number, seconds: number, fractions: number): number {
return (hours * 3600 + minutes * 60 + seconds) * 10000 + fractions;
}
|
ecb516a5d0ed085c11125c9c6a6d29554fd43f8c
|
TypeScript
|
pascalwhoop/steak-web
|
/src/app/administration/admin-day-offers-card/admin-day-offers-card.component.ts
| 2.59375
| 3
|
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Offer} from '../../shared/model/Offer';
import {EditMode, STANDARD_DESCRIPTIONS, STANDARD_TIMES} from '../../core/util/util.service';
import {OfferFormDialogComponent} from '../offer-form-dialog/offer-form-dialog.component';
import {MdDialog, MdDialogRef} from '@angular/material';
@Component({
selector: 'steak-admin-day-offers-card',
templateUrl: './admin-day-offers-card.component.html',
styleUrls: ['./admin-day-offers-card.component.scss'],
})
export class AdminDayOffersCardComponent implements OnInit {
@Input()
date: Date;
@Input()
offers: Offer[];
@Output('offerChange')
offerEventEmitter: EventEmitter<Offer> = new EventEmitter();
@Output('offerDelete')
offerDeleteEmitter: EventEmitter<Offer> = new EventEmitter();
constructor(public dialog: MdDialog) {
}
ngOnInit() {
}
/**
* create a new offer and add it to the list when it has been created
* @param date
*/
createNewFor(date: Date) : MdDialogRef<OfferFormDialogComponent>{
let ref = this.dialog.open(OfferFormDialogComponent, {data: {date: date, editMode: EditMode.CREATE}});
ref.afterClosed().subscribe((offer) => {
if (offer) this.onOfferChange(offer);
});
return ref;
}
/**
* method that gets called when a child has been changed and it needs to be changed in the array
* just bubbling it up the food chain though
* @param offer
*/
onOfferChange(offer: Offer) {
this.offerEventEmitter.emit(offer);
}
/**
* method to call when a child has been deleted and we need to remove it from the array of offers
* just bubbling it up the food chain though
* @param offer
*/
onOfferDelete(offer: Offer) {
this.offerDeleteEmitter.emit(offer);
}
/**
* Checks if a day has all the necessary offers to make it 'complete'
* A day should have
* - breakfast
* - lunch
* - 1x main vegetarian meal
* - 1x main veggie or non veggie meal
* - salad offers (large, small)
* - soup offer
* @param offers
*/
dayIsComplete(offers: Offer[]): boolean {
if (!offers || offers.length == 0) return false;
return (this.containBreakfast(offers) &&
this.containVegetarianLunch(offers) &&
this.containSoup(offers) &&
this.containSalad(offers) &&
this.containTwoMainMeals(offers));
}
containBreakfast(offers: Offer[]): boolean {
let cereal = false;
let bWithCer = false;
let bWithoutCer = false;
//if offers contain all three core breakfast elements, breakfast is completed
for (let off of offers) {
if (off.time == STANDARD_TIMES.BREAKFAST) {
if (off.description == STANDARD_DESCRIPTIONS.BREAKFAST_WITHOUT_CEREAL) bWithoutCer = true;
if (off.description == STANDARD_DESCRIPTIONS.BREAKFAST_WITH_CEREAL) bWithCer = true;
if (off.description == STANDARD_DESCRIPTIONS.CEREAL) cereal = true;
}
}
return cereal && bWithCer && bWithoutCer;
}
containSoup(offers: Offer[]): boolean {
//if one of the offers is soup, it contains soup
for (let off of offers) {
if (off.description.toLowerCase().indexOf(STANDARD_DESCRIPTIONS.SOUP) >= 0 && !off.main_offer) return true;
}
return false;
}
private containSalad(offers: Offer[]): boolean {
let smallSalad = false;
let largeSalad = false;
//if offers contain all three core breakfast elements, breakfast is completed
for (let off of offers) {
if (off.time == STANDARD_TIMES.LUNCH) {
if (off.description == STANDARD_DESCRIPTIONS.LARGE_SALAD) smallSalad = true;
if (off.description == STANDARD_DESCRIPTIONS.SMALL_SALAD) largeSalad = true;
}
}
return smallSalad && largeSalad;
}
private containVegetarianLunch(offers: Offer[]): boolean {
//if one of the offers is veggi and main offer
for (let off of offers) {
if (off.vegetarian && off.main_offer) return true;
}
return false;
}
private containTwoMainMeals(offers: Offer[]) {
let mainOfferCount = 0;
offers.forEach((offer) => {
if (offer.main_offer) mainOfferCount++;
});
return mainOfferCount >= 2;
}
}
|
0ae541ab822c17e9667c7bbf6f29afbcf17c407d
|
TypeScript
|
firmoholanda/studying
|
/turing.com/validParentheses.ts
| 4.15625
| 4
|
// given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// An input string is valid if:
// Open brackets must be closed by the same type of brackets.
// Open brackets must be closed in the correct order.
//
//
// Example 1:
// Input: s = "()"
// Output: true
//
// Example 2:
// Input: s = "()[]{}
// An input string is valid if:
// Open brackets must be closed by the same type of brackets.
// Open brackets must be closed in the correct order.
function isValid(s: string): boolean {
const stack: string[] = [];
const map = new Map([
['(', ')'],
['{', '}'],
['[', ']'],
]);
for (let i = 0; i < s.length; i++) {
if (map.has(s[i])) {
stack.push(s[i]);
} else {
if (map.get(stack.pop()) !== s[i]) {
return false;
}
}
}
return stack.length === 0;
}
const res = isValid('()[]{}');
console.log('res', res);
|
2efd04b6291dc54c2dc56fdf582a72f24be67b1e
|
TypeScript
|
indifferentghost/milo
|
/src/EventEmitter.ts
| 3.015625
| 3
|
import UnorderedMap from "./#{target}/UnorderedMap";
import IUnorderedMap from "./IUnorderedMap";
import { EventListenerCallback } from "./types";
interface EventConnection {
listener: EventListenerCallback;
once: true;
};
type EventConnectionType = EventConnection | EventListenerCallback;
export default class EventEmitter {
constructor() {
this.listenerMap = new UnorderedMap();
}
addListener(event: string, listener: EventListenerCallback): this {
return this.add(event, listener, false);
}
addOnceListener(event: string, listener: EventListenerCallback): this {
return this.add(event, { listener, once: true }, false);
}
on(event: string, listener: EventListenerCallback): this {
return this.add(event, listener, false);
}
once(event: string, listener: EventListenerCallback): this {
return this.add(event, { listener, once: true }, false);
}
removeListener(event: string, listener: EventListenerCallback): this {
return this.off(event, listener);
}
off(event: string, listener: EventListenerCallback): this {
const connections = this.listenerMap.get(event);
if (!connections)
return this;
if (Array.isArray(connections)) {
for (let idx = 0; idx < connections.length; ++idx) {
const val = connections[idx];
let match;
if (typeof val === "object") {
match = val.listener === listener;
} else {
match = val === listener;
}
if (match) {
if (connections.length === 1) {
this.listenerMap.delete(event);
} else {
connections.splice(idx, 1);
}
break;
}
}
} else if (typeof connections === "function") {
if (connections === listener)
this.listenerMap.delete(event);
} else if (connections.listener === listener) {
this.listenerMap.delete(event);
}
return this;
}
removeAllListeners(event?: string): this {
if (event) {
this.listenerMap.delete(event);
} else {
this.listenerMap.clear();
}
return this;
}
listeners(event: string): EventListenerCallback[] {
const connections = this.listenerMap.get(event);
if (!connections)
return [];
if (Array.isArray(connections)) {
return connections.map(l => {
if (typeof l === "function")
return l;
return l.listener;
});
} else if (typeof connections === "function") {
return [connections];
} else {
return [connections.listener];
}
}
emit(event: string, ...args: any[]): boolean {
const connections = this.listenerMap.get(event);
if (!connections) {
return false;
}
if (Array.isArray(connections)) {
let idx = 0;
while (idx < connections.length) {
let conn = connections[idx];
if (typeof conn === "function") {
++idx;
} else { // once
connections.splice(idx, 1);
conn = conn.listener;
}
try {
conn.apply(this, args);
} catch (err) {
this.unarray(event, connections);
throw err;
}
}
this.unarray(event, connections);
} else if (typeof connections === "function") {
connections.apply(this, args);
} else { // once
this.listenerMap.delete(event);
connections.listener.apply(this, args);
}
return true;
}
hasListener(event: string): boolean {
return this.listenerMap.has(event);
}
listenerCount(event: string): number {
const connections = this.listenerMap.get(event);
if (!connections) {
return 0;
}
if (Array.isArray(connections)) {
return connections.length;
}
return 1;
}
prependListener(event: string, listener: EventListenerCallback): this {
return this.add(event, listener, true);
}
prependOnceListener(event: string, listener: EventListenerCallback): this {
return this.add(event, { listener, once: true }, true);
}
eventNames(): string[] {
return this.listenerMap.keys();
}
private add(event: string, conn: EventConnectionType, prepend: boolean): this {
const connections = this.listenerMap.get(event);
if (connections) {
if (Array.isArray(connections)) {
if (prepend) {
connections.unshift(conn);
} else {
connections.push(conn);
}
} else {
this.listenerMap.set(event, prepend ? [conn, connections] : [connections, conn]);
}
} else {
this.listenerMap.set(event, conn);
}
return this;
}
private unarray(event: string, conns: EventConnectionType[]): void {
switch (conns.length) {
case 0:
this.listenerMap.delete(event);
break;
case 1:
this.listenerMap.set(event, conns[0]);
break;
default:
break;
}
}
private listenerMap: IUnorderedMap<string, EventConnectionType[] | EventConnectionType>;
}
|
8541115a4782a0d4960fbaa682a133858c4567ab
|
TypeScript
|
RaulROR/angular-e4ss
|
/src/app/gservice.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class GserviceService {
constructor(private cliente:HttpClient) { };
get(nombreLibro:String){
console.log('Criterio de busqueda:'+nombreLibro);
const volumes: object[] = [];
const titulos: string[] = [];
const url = 'https://www.googleapis.com/books/v1/volumes?q=intitle:';
this.cliente.get(url + nombreLibro).subscribe( (data: object[]) => {
for(let i = 0; i < data['items'].length; i++) {
console.log('VolumenInfo: '+data['items'][i]['volumeInfo']);
console.log('Title: '+data['items'][i]['volumeInfo']['title']);
// volumes.push(data['items'][i]['volumeInfo']);
// titulos.push(data['items'][i]['volumeInfo']['title']);
}
}
);
}
}
|
4dc22ec62bc92fc30c39c37c78344cb31dd77017
|
TypeScript
|
jeremytrigano/codewars-typescript
|
/findTheParityOutlier/findTheParityOutlier.sol.ts
| 3.28125
| 3
|
export function findOutlier(integers: number[]): number {
if (integers.slice(0, 3).filter((i) => i % 2 !== 0).length > 1) {
return integers.find((v) => v % 2 === 0) || 0;
} else {
return integers.find((v) => v % 2 !== 0) || 0;
}
}
|
64885b07d8200a4f8c84917b042143ba60665478
|
TypeScript
|
Chandehehe/fermenter-app
|
/service/api/src/persistence/fermentation-table.ts
| 2.578125
| 3
|
import { Fermentation, FermentationModel } from '../domain';
import { postgresClient } from './postgres-db';
const tableName = 'fermentations';
export const FermentationTable = {
create: async (userId: Fermentation['userId'], params: Partial<Fermentation>): Promise<void> => {
const { name, active, targetTemperature } = params;
await postgresClient.query<Fermentation>(
`INSERT INTO ${tableName} ("userId", name, active, "targetTemperature", "createdAt", "updatedAt") VALUES ($1, $2, $3, $4, now(), now())`,
[userId, name, active, targetTemperature],
);
},
find: async (): Promise<FermentationModel[]> => {
const result = await postgresClient.query<Fermentation>(`SELECT * FROM ${tableName}`);
return result.rows.map((r) => new FermentationModel(r));
},
findOne: async (id: Fermentation['id']): Promise<FermentationModel> => {
const result = await postgresClient.query<Fermentation>(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
const { rows } = result;
return new FermentationModel(rows[0]);
},
findByUserId: async (userId: Fermentation['userId']): Promise<FermentationModel[]> => {
const result = await postgresClient.query<Fermentation>(`SELECT * FROM ${tableName} WHERE "userId" = $1`, [userId]);
return result.rows.map((r) => new FermentationModel(r));
},
update: async (params: Partial<Fermentation>): Promise<FermentationModel[]> => {
const { id, name, targetTemperature } = params;
const result = await postgresClient.query<Fermentation>(
`UPDATE ${tableName} SET "name" = $1, "targetTemperature" = $2 WHERE id = $3`,
[name, targetTemperature, id],
);
return result.rows.map((r) => new FermentationModel(r));
},
};
|
1ab889af2759530995426f8333a167761996a663
|
TypeScript
|
RichardMViGEM/angular-json-schema-form-layout
|
/src/app/change-information/change-information.component.ts
| 2.59375
| 3
|
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-change-information',
templateUrl: './change-information.component.html',
styleUrls: ['./change-information.component.css']
})
/**
* use this component in any other component of the app
* pass boolean values to indicate which information label is to be displayed. Order does not matter
* parameters:
* - restartRecording (default: false)
* - restartSystem (default: false)
*
* example use in a component template:
* <app-change-information [restartSystem]='true' [restartRecording]='true'></app-change-information>
*/
export class ChangeInformationComponent implements OnInit {
@Input() restartRecording: boolean = false;
@Input() restartSystem: boolean = false;
constructor() { }
ngOnInit() { }
}
|
3ce93ce2635db4fdb7a68fbb64bcc1276d13893c
|
TypeScript
|
ZhouZhiW/egret-game-library
|
/egret_h5/egret_消除/src/data/MapControl.ts
| 2.890625
| 3
|
class MapControl {
public constructor() {
}
/**
* 创建全地图元素
*/
public createElementAllMap(){
this.createAllMap();
}
/**
* 创建全部地图元素
* 游戏开始时调用
*/
public createAllMap(){
let len:number = GameData.MaxColumn * GameData.MaxRow;
let type:string = "";
let haveLink:boolean =true;
let id:number =0;
let ztype:string ="";
let htype:string="";
for (let i = 0; i < GameData.MaxRow; i++) {
for (let t = 0; t < GameData.MaxColumn; t++) {
if(GameData.mapData[i][t]!=-1)
{
while(haveLink){
type = this.createType();
if(i>1&& GameData.mapData[i-1][t]!=-1 && GameData.mapData[i-2][t]!=-1 ){
if(GameData.elements[GameData.mapData[i-1][t]].type ==GameData.elements[GameData.mapData[i-2][t]].type){
ztype = GameData.elements[GameData.mapData[i-1][t]].type;
}
}
if(t>1&& GameData.mapData[i][t-1]!=-1 && GameData.mapData[i][t-2]!=-1 ){
if(GameData.elements[GameData.mapData[i][t-1]].type ==GameData.elements[GameData.mapData[i][t-2]].type){
htype = GameData.elements[GameData.mapData[i][t-1]].type;
}
}
if(type!=ztype&&type!=htype)
{
haveLink = false;
}
}
//console.log(type);
id = GameData.unusedElements[0];
GameData.elements[id].type =type;
GameData.elements[id].location = i*GameData.MaxRow+t;
GameData.mapData[i][t]=id;
GameData.unusedElements.shift();
haveLink=true;
ztype="";
htype="";
//console.log( GameData.mapData[i][t],GameData.elements[id].location);
}
}
}
}
/**
* 随机创建一个类型元素
*/
private createType():string{
return GameData.elementTypes[Math.floor(Math.random()*GameData.elementTypes.length)].toString();
}
/**
* 针对某一个数据元素更新它得类型
*/
public changeTypeByID(id:number)
{
GameData.elements[id].type = this.createType();
console.log(id,GameData.elements[id].type );
}
/**
* 根据当前删除得地图元素,刷新所有元素得位置
*/
public updateMapLocation()
{
//ID 去重
let ids:number[] = new Array();
let len:number = LinkLogic.lines.length;
for(let i=0;i<len;i++){
let l = LinkLogic.lines[i].length;
for(let t=0;t<l;t++){
// console.log(ids.indexOf(LinkLogic.lines[i][t]));
if(ids.indexOf(LinkLogic.lines[i][t])==-1)//如果找到则返回找到的索引值,如果没有找到,则返回-1.
{
this.changeTypeByID(LinkLogic.lines[i][t]);//定制新的类型
ids.push(LinkLogic.lines[i][t]);
}
}
}
//ids是此次被删除得元素ID,要更新其他得元素位置
len = ids.length;
let colArr:number[] = new Array();//存储列编号得数据,记录共有几列需要移动位置
for(let i=0;i<len;i++)
{
let col = GameData.elements[ids[i]].location%GameData.MaxColumn;
if(colArr.indexOf(col)==-1){
colArr.push(col);
}
}
//重新得到当前这列ID的排序
len = colArr.length;
for(let i=0;i<len;i++)
{
let removeIds:number[] = new Array();
let newColIds:number[] = new Array();
for(let t=GameData.MaxRow-1;t>=0;t--)//按行 下->上
{
//console.log(ids.indexOf(GameData.mapData[t][colArr[i]]));
if(ids.indexOf(GameData.mapData[t][colArr[i]])==-1){
if(GameData.mapData[t][colArr[i]]!=-1)
{
newColIds.push(GameData.mapData[t][colArr[i]]);
}
}
else
{
removeIds.push(GameData.mapData[t][colArr[i]]);
}
}
//合并两个数组
newColIds = newColIds.concat(removeIds);
//将元素重新放入map中,并改变元素Location
for(let t=GameData.MaxRow-1;t>=0;t--)
{
if(GameData.mapData[t][colArr[i]]!=-1)
{
GameData.mapData[t][colArr[i]] = newColIds[0];
//console.log(t,GameData.elements[newColIds[0]].type);
GameData.elements[newColIds[0]].location = t*GameData.MaxRow+colArr[i];
newColIds.shift();
}
}
}
}
}
|
29f1823a49383db0172a999ed3bdfe49255b9264
|
TypeScript
|
vanessanova/EIA2
|
/Aufgabe5/skier.ts
| 3.140625
| 3
|
namespace Aufgabe5 {
export class Skier{ //export macht klassen ber datei hinweg grenzen nutzbar
x: number;
y: number;
colorHead: string;
colorBody: string;
constructor () { //constructor nimmt infos entgegen, so kann beim konstruieren des objekts
//infos bergeben werden
this.setStart(); //verweist auf eigenshaften des objekts setStart
this.colorBody = "hsl(" + Math.random() * 360 + ", 45%, 65%)";
this.colorHead = "#ff9f9f";
}
moveanddraw(): void {
this.move();
this.draw();
}
move(): void {
this.x += Math.random() * 2 + 2.5;
this.y += Math.random() * 2 + 3;
}
setStart(): void{
this.x= Math.random()*290;
this.y= 230;
}
draw() : void {
crc2.beginPath();
crc2.moveTo(this.x, this.y);
crc2.lineTo(this.x + 20, this.y + 10);
crc2.strokeStyle = "#400000";
crc2.stroke();
crc2.beginPath();
crc2.moveTo(this.x, this.y);
crc2.lineTo(this.x + 15, this.y + 15);
crc2.strokeStyle = "#400000";
crc2.stroke();
//K�rper
crc2.fillStyle = this.colorBody;
crc2.fillRect(this.x, this.y - 10, 10, 15);
//Kopf
crc2.beginPath();
crc2.arc(this.x + 5, this.y - 15, 7, 0, 2 * Math.PI);
crc2.fillStyle = this.colorHead;
crc2.fill();
}
}
}
|
60ee6c16d989d03688c83e112093c6815a9aa779
|
TypeScript
|
adrianhunter/essence
|
/src/tests/parser.ts
| 2.921875
| 3
|
import { lex } from '../lexer'
import { parse } from '../parser'
describe('Parser', () => {
describe('Expressions', () => {
it('should parse identifiers', () => {
let input = `identifier`
let output = [{
nodeType: 'Identifier',
content: 'identifier',
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse "true" literals', () => {
let input = `true`
let output = [{
nodeType: 'Value',
type: 'Bool',
value: true,
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse "false" literals', () => {
let input = `false`
let output = [{
nodeType: 'Value',
type: 'Bool',
value: false,
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse empty string literals', () => {
let input = `''`
let output = [{
nodeType: 'Value',
type: 'String',
value: '',
members: {},
position: {
line: 1,
column: 2,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse filled string literals', () => {
let input = `'string'`
let output = [{
nodeType: 'Value',
type: 'String',
value: 'string',
members: {},
position: {
line: 1,
column: 2,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse simple number literals', () => {
let input = `123`
let output = [{
nodeType: 'Value',
type: 'Number',
value: '123',
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse simple number literals with underscores', () => {
let input = `1_000`
let output = [{
nodeType: 'Value',
type: 'Number',
value: '1000',
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse float number literals', () => {
let input = `1.5`
let output = [{
nodeType: 'Value',
type: 'Number',
value: '1.5',
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse float number literals with underscores', () => {
let input = `1_000.5`
let output = [{
nodeType: 'Value',
type: 'Number',
value: '1000.5',
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse empty function literals', () => {
let input = `() -> Type {}`
let output = [{
nodeType: 'Value',
type: 'Function',
value: {
nodeType: 'FunctionDefinition',
parameters: [],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
position: {
line: 1,
column: 6,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 1,
column: 12,
},
},
position: {
line: 1,
column: 1,
},
},
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse empty function literals with some linebreaks', () => {
let input = `() -> Type {
}`
let output = [{
nodeType: 'Value',
type: 'Function',
value: {
nodeType: 'FunctionDefinition',
parameters: [],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
position: {
line: 1,
column: 6,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 1,
column: 12,
},
},
position: {
line: 1,
column: 1,
},
},
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse empty function literals with one parameter', () => {
let input = `(parameter Type) -> Type {}`
let output = [{
nodeType: 'Value',
type: 'Function',
value: {
nodeType: 'FunctionDefinition',
parameters: [{
nodeType: 'Parameter',
name: 'parameter',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 12,
},
},
position: {
line: 1,
column: 12,
},
},
position: {
line: 1,
column: 2,
},
}],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 21,
},
},
position: {
line: 1,
column: 21,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 1,
column: 27,
},
},
position: {
line: 1,
column: 1,
},
},
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse empty function literals with two parameters', () => {
let input = `(parameter Type, parameter2 Type) -> Type {}`
let output = [{
nodeType: 'Value',
type: 'Function',
value: {
nodeType: 'FunctionDefinition',
parameters: [{
nodeType: 'Parameter',
name: 'parameter',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 12,
},
},
position: {
line: 1,
column: 12,
},
},
position: {
line: 1,
column: 2,
},
}, {
nodeType: 'Parameter',
name: 'parameter2',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 30,
},
},
position: {
line: 1,
column: 30,
},
},
position: {
line: 1,
column: 18,
},
}],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 39,
},
},
position: {
line: 1,
column: 39,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 1,
column: 45,
},
},
position: {
line: 1,
column: 1,
},
},
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse empty function literals with more than two parameters', () => {
let input = `(parameter Type, parameter2 Type, parameter3 Type) -> Type {}`
let output = [{
nodeType: 'Value',
type: 'Function',
value: {
nodeType: 'FunctionDefinition',
parameters: [{
nodeType: 'Parameter',
name: 'parameter',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 12,
},
},
position: {
line: 1,
column: 12,
},
},
position: {
line: 1,
column: 2,
},
}, {
nodeType: 'Parameter',
name: 'parameter2',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 30,
},
},
position: {
line: 1,
column: 30,
},
},
position: {
line: 1,
column: 18,
},
}, {
nodeType: 'Parameter',
name: 'parameter3',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 48,
},
},
position: {
line: 1,
column: 48,
},
},
position: {
line: 1,
column: 36,
},
}],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 57,
},
},
position: {
line: 1,
column: 57,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 1,
column: 63,
},
},
position: {
line: 1,
column: 1,
},
},
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse function literals with statements', () => {
let input = `() -> Type {
<- identifier
}`
let output = [{
nodeType: 'Value',
type: 'Function',
value: {
nodeType: 'FunctionDefinition',
parameters: [],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
position: {
line: 1,
column: 6,
},
},
body: {
nodeType: 'Block',
nodes: [{
nodeType: 'ReturnStatement',
expression: {
nodeType: 'Identifier',
content: 'identifier',
position: {
line: 2,
column: 7,
},
},
position: {
line: 2,
column: 1,
},
}],
position: {
line: 1,
column: 12,
},
},
position: {
line: 1,
column: 1,
},
},
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse function invocations without arguments', () => {
let input = `invocation()`
let output = [{
nodeType: 'FunctionInvocation',
name: {
nodeType: 'Identifier',
content: 'invocation',
position: {
line: 1,
column: 1,
},
},
arguments: [],
position: {
line: 1,
column: 12,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse function invocations with one argument', () => {
let input = `invocation(argument)`
let output = [{
nodeType: 'FunctionInvocation',
name: {
nodeType: 'Identifier',
content: 'invocation',
position: {
line: 1,
column: 1,
},
},
arguments: [{
nodeType: 'Identifier',
content: 'argument',
position: {
line: 1,
column: 13,
},
}],
position: {
line: 1,
column: 12,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse function invocations with two arguments', () => {
let input = `invocation(argument, argument2)`
let output = [{
nodeType: 'FunctionInvocation',
name: {
nodeType: 'Identifier',
content: 'invocation',
position: {
line: 1,
column: 1,
},
},
arguments: [{
nodeType: 'Identifier',
content: 'argument',
position: {
line: 1,
column: 13,
},
}, {
nodeType: 'Identifier',
content: 'argument2',
position: {
line: 1,
column: 23,
},
}],
position: {
line: 1,
column: 12,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse function invocations with more than two arguments', () => {
let input = `invocation(argument, argument2, argument3)`
let output = [{
nodeType: 'FunctionInvocation',
name: {
nodeType: 'Identifier',
content: 'invocation',
position: {
line: 1,
column: 1,
},
},
arguments: [{
nodeType: 'Identifier',
content: 'argument',
position: {
line: 1,
column: 13,
},
}, {
nodeType: 'Identifier',
content: 'argument2',
position: {
line: 1,
column: 23,
},
}, {
nodeType: 'Identifier',
content: 'argument3',
position: {
line: 1,
column: 35,
},
}],
position: {
line: 1,
column: 12,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse anonymous empty type constructors', () => {
let input = `{}`
let output = [{
nodeType: 'Value',
type: null,
value: null,
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse anonymous type constructors with a KeyValuePair', () => {
let input = `{ key = value, }`
let output = [{
nodeType: 'Value',
type: null,
value: null,
members: {
key: {
nodeType: 'Identifier',
content: 'value',
position: {
line: 1,
column: 8,
},
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse anonymous type constructors with multiple KeyValuePairs', () => {
let input = `{ key = value, key2 = value2, }`
let output = [{
nodeType: 'Value',
type: null,
value: null,
members: {
key: {
nodeType: 'Identifier',
content: 'value',
position: {
line: 1,
column: 8,
},
},
key2: {
nodeType: 'Identifier',
content: 'value2',
position: {
line: 1,
column: 23,
},
}
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse named empty type constructors', () => {
let input = `Type{}`
let output = [{
nodeType: 'Value',
type: 'Type',
value: null,
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse named type constructors with a KeyValuePair', () => {
let input = `Type{ key = value, }`
let output = [{
nodeType: 'Value',
type: 'Type',
value: null,
members: {
key: {
nodeType: 'Identifier',
content: 'value',
position: {
line: 1,
column: 13,
},
}
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse named type constructors with multiple KeyValuePairs', () => {
let input = `Type{ key = value, key2 = value2, }`
let output = [{
nodeType: 'Value',
type: 'Type',
value: null,
members: {
key: {
nodeType: 'Identifier',
content: 'value',
position: {
line: 1,
column: 13,
},
},
key2: {
nodeType: 'Identifier',
content: 'value2',
position: {
line: 1,
column: 28,
},
}
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse simple lookup', () => {
let input = `lookup.member`
let output = [{
nodeType: 'Lookup',
base: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 1,
},
},
member: {
nodeType: 'Identifier',
content: 'member',
position: {
line: 1,
column: 9,
},
},
position: {
line: 1,
column: 8,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse simple lookup with invocation', () => {
let input = `lookup.member()`
let output = [{
nodeType: 'FunctionInvocation',
name: {
nodeType: 'Lookup',
base: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 1,
},
},
member: {
nodeType: 'Identifier',
content: 'member',
position: {
line: 1,
column: 9,
},
},
position: {
line: 1,
column: 8,
},
},
arguments: [],
position: {
line: 1,
column: 16,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse complex lookup', () => {
let input = `lookup.member1.member2`
let output = [{
nodeType: 'Lookup',
base: {
nodeType: 'Lookup',
base: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 1,
},
},
member: {
nodeType: 'Identifier',
content: 'member1',
position: {
line: 1,
column: 9,
},
},
position: {
line: 1,
column: 8,
},
},
member: {
nodeType: 'Identifier',
content: 'member2',
position: {
line: 1,
column: 18,
},
},
position: {
line: 1,
column: 17,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse raw method lookups', () => {
let input = `lookup::member`
let output = [{
nodeType: 'MethodLookup',
base: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 1,
},
},
member: {
nodeType: 'Identifier',
content: 'member',
position: {
line: 1,
column: 10,
},
},
position: {
line: 1,
column: 8,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse method lookups with invocation', () => {
let input = `lookup::member()`
let output = [{
nodeType: 'MethodInvocation',
name: {
nodeType: 'MethodLookup',
base: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 1,
},
},
member: {
nodeType: 'Identifier',
content: 'member',
position: {
line: 1,
column: 10,
},
},
position: {
line: 1,
column: 8,
},
},
arguments: [],
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse multiple method lookups with invocation', () => {
let input = `lookup::member()::member()`
let output = [{
nodeType: 'MethodInvocation',
name: {
nodeType: 'MethodLookup',
base: {
nodeType: 'MethodInvocation',
name: {
nodeType: 'MethodLookup',
base: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 1,
},
},
member: {
nodeType: 'Identifier',
content: 'member',
position: {
line: 1,
column: 10,
},
},
position: {
line: 1,
column: 8,
},
},
arguments: [],
position: {
line: 1,
column: 1,
},
},
member: {
nodeType: 'Identifier',
content: 'member',
position: {
line: 1,
column: 21,
},
},
position: {
line: 1,
column: 19,
},
},
arguments: [],
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should not parse complex raw method lookups', () => {
let input = `lookup::member1::member2`
let output = [{
nodeType: 'MethodLookup',
base: {
nodeType: 'MethodLookup',
base: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 1,
},
},
member: 'member1',
position: {
line: 1,
column: 8,
},
},
member: 'member2',
position: {
line: 1,
column: 18,
},
}]
expect(() => parse(lex(input))).toThrow()
})
it('should not parse native prefix without identifier', () => {
let input = `__`
let output = []
expect(() => parse(lex(input))).toThrow()
})
it('should not parse native lookups without second identifier', () => {
let input = `__lookup.`
let output = []
expect(() => parse(lex(input))).toThrow()
})
it('should parse native function invocation without parameters', () => {
let input = `__lookup()`
let output = [{
nodeType: 'NativeFunctionInvocation',
name: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 3,
},
},
arguments: [],
position: {
line: 1,
column: 10,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse native function invocation without parameters after lookup', () => {
let input = `__lookup.member()`
let output = [{
nodeType: 'NativeFunctionInvocation',
name: {
nodeType: 'NativeLookup',
base: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 3,
},
},
member: {
nodeType: 'Identifier',
content: 'member',
position: {
line: 1,
column: 11,
},
},
position: {
line: 1,
column: 11,
},
},
arguments: [],
position: {
line: 1,
column: 18,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse native function invocation with single argument', () => {
let input = `__lookup(argument)`
let output = [{
nodeType: 'NativeFunctionInvocation',
name: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 3,
},
},
arguments: [{
nodeType: 'Identifier',
content: 'argument',
position: {
line: 1,
column: 11,
},
}],
position: {
line: 1,
column: 10,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse native function invocation with multiple arguments', () => {
let input = `__lookup(argument, argument2)`
let output = [{
nodeType: 'NativeFunctionInvocation',
name: {
nodeType: 'Identifier',
content: 'lookup',
position: {
line: 1,
column: 3,
},
},
arguments: [{
nodeType: 'Identifier',
content: 'argument',
position: {
line: 1,
column: 11,
},
}, {
nodeType: 'Identifier',
content: 'argument2',
position: {
line: 1,
column: 21,
},
}],
position: {
line: 1,
column: 10,
},
}]
expect(parse(lex(input))).toEqual(output)
})
})
describe('Statements', () => {
it('should parse return statements', () => {
let input = `<- identifier`
let output = [{
nodeType: 'ReturnStatement',
expression: {
nodeType: 'Identifier',
content: 'identifier',
position: {
line: 1,
column: 3,
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse if statements', () => {
let input = `if (identifier) {}`
let output = [{
nodeType: 'IfStatement',
condition: {
nodeType: 'Identifier',
content: 'identifier',
position: {
line: 1,
column: 5,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 1,
column: 17,
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse if else statements', () => {
let input = `if (identifier) {} else {}`
let output = [{
nodeType: 'IfElseStatement',
condition: {
nodeType: 'Identifier',
content: 'identifier',
position: {
line: 1,
column: 5,
},
},
trueBody: {
nodeType: 'Block',
nodes: [],
position: {
line: 1,
column: 17,
},
},
falseBody: {
nodeType: 'Block',
nodes: [],
position: {
line: 1,
column: 26,
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse if else if statements', () => {
let input = `if (identifier) {} else if (identifier2) {}`
let output = [{
nodeType: 'IfElseStatement',
condition: {
nodeType: 'Identifier',
content: 'identifier',
position: {
line: 1,
column: 5,
},
},
trueBody: {
nodeType: 'Block',
nodes: [],
position: {
line: 1,
column: 17,
},
},
falseBody: {
nodeType: 'Block',
nodes: [{
nodeType: 'IfStatement',
condition: {
nodeType: 'Identifier',
content: 'identifier2',
position: {
line: 1,
column: 30,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 1,
column: 43,
},
},
position: {
line: 1,
column: 26,
},
}],
position: {
line: 1,
column: 20,
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse declaration statements without typeDeclaration', () => {
let input = `let identifier = ''`
let output = [{
nodeType: 'DeclarationStatement',
name: {
nodeType: 'Identifier',
content: 'identifier',
position: {
line: 1,
column: 5,
},
},
type: null,
value: {
nodeType: 'Value',
type: 'String',
value: '',
members: {},
position: {
line: 1,
column: 19,
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse declaration statements with typeDeclaration', () => {
let input = `let identifier Type = ''`
let output = [{
nodeType: 'DeclarationStatement',
name: {
nodeType: 'Identifier',
content: 'identifier',
position: {
line: 1,
column: 5,
},
},
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 16,
},
},
position: {
line: 1,
column: 16,
},
},
value: {
nodeType: 'Value',
type: 'String',
value: '',
members: {},
position: {
line: 1,
column: 24,
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse assignment statements', () => {
let input = `identifier = ''`
let output = [{
nodeType: 'AssignmentStatement',
name: {
nodeType: 'Identifier',
content: 'identifier',
position: {
line: 1,
column: 1,
},
},
value: {
nodeType: 'Value',
type: 'String',
value: '',
members: {},
position: {
line: 1,
column: 15,
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse empty typeDefinition statements', () => {
let input = `type Type {}`
let output = [{
nodeType: 'TypeDefinitionStatement',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
properties: {},
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse typeDefinition statements with one property', () => {
let input = `type Type {
property Type
}`
let output = [{
nodeType: 'TypeDefinitionStatement',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
properties: {
property: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 2,
column: 14,
},
},
position: {
line: 2,
column: 14,
},
},
},
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse typeDefinition statements with multiple properties', () => {
let input = `type Type {
property Type
property2 Type
}`
let output = [{
nodeType: 'TypeDefinitionStatement',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
properties: {
property: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 2,
column: 14,
},
},
position: {
line: 2,
column: 14,
},
},
property2: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 3,
column: 15,
},
},
position: {
line: 3,
column: 15,
},
},
},
members: {},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse typeDefinition statements with one empty method', () => {
let input = `type Type {
method() -> Type {}
}`
let output = [{
nodeType: 'TypeDefinitionStatement',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
properties: {},
members: {
method: {
nodeType: 'Value',
type: 'Method',
value: {
nodeType: 'FunctionDefinition',
parameters: [],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 2,
column: 17,
},
},
position: {
line: 2,
column: 17,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 2,
column: 23,
},
},
position: {
line: 2,
column: 12,
},
},
members: {},
position: {
line: 2,
column: 1,
},
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse typeDefinition statements with multiple empty methods', () => {
let input = `type Type {
method() -> Type {}
method2() -> Type {}
}`
let output = [{
nodeType: 'TypeDefinitionStatement',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
properties: {},
members: {
method: {
nodeType: 'Value',
type: 'Method',
value: {
nodeType: 'FunctionDefinition',
parameters: [],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 2,
column: 17,
},
},
position: {
line: 2,
column: 17,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 2,
column: 23,
},
},
position: {
line: 2,
column: 12,
},
},
members: {},
position: {
line: 2,
column: 1,
},
},
method2: {
nodeType: 'Value',
type: 'Method',
value: {
nodeType: 'FunctionDefinition',
parameters: [],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 3,
column: 18,
},
},
position: {
line: 3,
column: 18,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 3,
column: 24,
},
},
position: {
line: 3,
column: 13,
},
},
members: {},
position: {
line: 3,
column: 1,
},
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse typeDefinition statements with one nonempty method', () => {
let input = `type Type {
method(parameter ParameterType) -> Type {}
}`
let output = [{
nodeType: 'TypeDefinitionStatement',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
properties: {},
members: {
method: {
nodeType: 'Value',
type: 'Method',
value: {
nodeType: 'FunctionDefinition',
parameters: [{
nodeType: 'Parameter',
name: 'parameter',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'ParameterType',
position: {
line: 2,
column: 23,
},
},
position: {
line: 2,
column: 23,
},
},
position: {
line: 2,
column: 13,
},
}],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 2,
column: 41,
},
},
position: {
line: 2,
column: 41,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 2,
column: 47,
},
},
position: {
line: 2,
column: 12,
},
},
members: {},
position: {
line: 2,
column: 1,
},
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse typeDefinition statements with multiple nonempty methods', () => {
let input = `type Type {
method(parameter ParameterType) -> Type {}
method2(parameter ParameterType) -> Type {}
}`
let output = [{
nodeType: 'TypeDefinitionStatement',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
properties: {},
members: {
method: {
nodeType: 'Value',
type: 'Method',
value: {
nodeType: 'FunctionDefinition',
parameters: [{
nodeType: 'Parameter',
name: 'parameter',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'ParameterType',
position: {
line: 2,
column: 23,
},
},
position: {
line: 2,
column: 23,
},
},
position: {
line: 2,
column: 13,
},
}],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 2,
column: 41,
},
},
position: {
line: 2,
column: 41,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 2,
column: 47,
},
},
position: {
line: 2,
column: 12,
},
},
members: {},
position: {
line: 2,
column: 1,
},
},
method2: {
nodeType: 'Value',
type: 'Method',
value: {
nodeType: 'FunctionDefinition',
parameters: [{
nodeType: 'Parameter',
name: 'parameter',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'ParameterType',
position: {
line: 3,
column: 24,
},
},
position: {
line: 3,
column: 24,
},
},
position: {
line: 3,
column: 14,
},
}],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 3,
column: 42,
},
},
position: {
line: 3,
column: 42,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 3,
column: 48,
},
},
position: {
line: 3,
column: 13,
},
},
members: {},
position: {
line: 3,
column: 1,
},
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse typeDefinition statements with empty & nonempty methods', () => {
let input = `type Type {
method(parameter ParameterType) -> Type {}
method2() -> Type {}
}`
let output = [{
nodeType: 'TypeDefinitionStatement',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
properties: {},
members: {
method: {
nodeType: 'Value',
type: 'Method',
value: {
nodeType: 'FunctionDefinition',
parameters: [{
nodeType: 'Parameter',
name: 'parameter',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'ParameterType',
position: {
line: 2,
column: 23,
},
},
position: {
line: 2,
column: 23,
},
},
position: {
line: 2,
column: 13,
},
}],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 2,
column: 41,
},
},
position: {
line: 2,
column: 41,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 2,
column: 47,
},
},
position: {
line: 2,
column: 12,
},
},
members: {},
position: {
line: 2,
column: 1,
},
},
method2: {
nodeType: 'Value',
type: 'Method',
value: {
nodeType: 'FunctionDefinition',
parameters: [],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 3,
column: 18,
},
},
position: {
line: 3,
column: 18,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 3,
column: 24,
},
},
position: {
line: 3,
column: 13,
},
},
members: {},
position: {
line: 3,
column: 1,
},
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
it('should parse typeDefinition statements with methods and properties', () => {
let input = `type Type {
property PropertyType
method(parameter ParameterType) -> Type {}
}`
let output = [{
nodeType: 'TypeDefinitionStatement',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 1,
column: 6,
},
},
properties: {
property: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'PropertyType',
position: {
line: 2,
column: 14,
},
},
position: {
line: 2,
column: 14,
},
},
},
members: {
method: {
nodeType: 'Value',
type: 'Method',
value: {
nodeType: 'FunctionDefinition',
parameters: [{
nodeType: 'Parameter',
name: 'parameter',
type: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'ParameterType',
position: {
line: 3,
column: 23,
},
},
position: {
line: 3,
column: 23,
},
},
position: {
line: 3,
column: 13,
},
}],
returnType: {
nodeType: 'TypeDeclaration',
name: {
nodeType: 'Identifier',
content: 'Type',
position: {
line: 3,
column: 41,
},
},
position: {
line: 3,
column: 41,
},
},
body: {
nodeType: 'Block',
nodes: [],
position: {
line: 3,
column: 47,
},
},
position: {
line: 3,
column: 12,
},
},
members: {},
position: {
line: 3,
column: 1,
},
},
},
position: {
line: 1,
column: 1,
},
}]
expect(parse(lex(input))).toEqual(output)
})
})
})
|
def3374d6922b959f744f6f26add0a2ff73661b6
|
TypeScript
|
itsbth/webgl2-term
|
/src/TermWriter.ts
| 3.015625
| 3
|
import runes = require("runes");
import GlTerminal from "./GlTerminal";
type Color = [number, number, number, number];
export default class TermWriter {
private fg: Color = [1, 1, 1, 1];
private bg: Color = [0, 0, 0, 0];
private col: number;
private row: number;
private pendingFlush: boolean = false;
constructor(private term: GlTerminal, private autoFlush: boolean = false) {
this.col = 0;
this.row = term.rows - 1;
}
public write(what: string): this {
for (const ch of runes(what)) {
if (this.col >= this.term.cols - 1 || ch === "\n") {
this.term.scroll(1);
this.col = 0;
if (ch === "\n") {
if (this.autoFlush) {
this.term.render();
}
continue;
}
}
if (ch === "\r") {
this.col = 0;
continue;
}
this.term.setChar(this.col, this.row, ch, this.fg, this.bg);
this.col += 1;
}
return this;
}
public writeLine(what: string): this {
this.write(what + "\n");
return this;
}
public backspace(n: number): this {
this.col = Math.max(0, this.col - n);
return this;
}
public setFg(col: Color): this {
this.fg = col;
return this;
}
public setBg(col: Color): this {
this.bg = col;
return this;
}
public flip(): this {
const tmp = this.fg;
this.fg = this.bg;
this.bg = tmp;
return this;
}
public flush(): this {
if (!this.pendingFlush) {
this.pendingFlush = true;
requestAnimationFrame(() => {
this.pendingFlush = false;
this.term.render();
});
}
return this;
}
}
|
b6e7a90c8425ffeb7c599183286095e3d86fb696
|
TypeScript
|
rsuite/rsuite
|
/src/utils/useClickOutside.ts
| 2.96875
| 3
|
import { useEffect, useRef } from 'react';
export interface UseClickOutsideOptions {
enabled?: boolean;
isOutside: (event: MouseEvent) => boolean;
handle: (event: MouseEvent) => void;
}
export default function useClickOutside({
enabled = true,
isOutside,
handle
}: UseClickOutsideOptions) {
const isOutsideRef = useRef<((event: MouseEvent) => boolean) | null>(isOutside);
const handleRef = useRef<((event: MouseEvent) => void) | null>(handle);
useEffect(() => {
isOutsideRef.current = isOutside;
handleRef.current = handle;
}, [isOutside, handle]);
useEffect(() => {
if (enabled) {
const eventHandler = (event: MouseEvent) => {
if (isOutsideRef.current?.(event)) {
handleRef.current?.(event);
}
};
window.addEventListener('mousedown', eventHandler);
return () => {
window.removeEventListener('mousedown', eventHandler);
};
}
}, [enabled]);
}
|
392934c374ad95d4e2183e07e3a33c8a95be0f01
|
TypeScript
|
ayeressian/db-viewer-component
|
/src/types/column.ts
| 2.6875
| 3
|
import Table from "../table";
export interface Fk {
table: Table;
column: ColumnNoneFk;
}
export interface ColumnNoneFk {
name: string;
elem?: HTMLTableRowElement;
pk?: boolean;
uq?: boolean;
nn?: boolean;
type: string;
}
export interface ColumnFk extends Omit<ColumnNoneFk, "type"> {
fk?: Fk;
}
export type Column = ColumnFk | ColumnNoneFk;
export const isColumnFk = (column: Column): column is ColumnFk => {
return (column as ColumnFk).fk !== undefined;
};
|
b89f74c7fccb2f75f2318fabde61d1d06c836c4d
|
TypeScript
|
alexandraveres7/Tic-Tac-Toe
|
/src/app/square/square.component.ts
| 2.640625
| 3
|
import { Component, Input} from '@angular/core';
@Component({
selector: 'app-square',
template: `
<button nbButton *ngIf="!value" [disabled]="!!playGame">{{ value }} </button>
<button id="myX" nbButton hero status="success" *ngIf="value == 'X'" [disabled]="!!playGame">{{ value }} </button>
<button id="myY" nbButton hero status="info" *ngIf="value == 'O'" [disabled]="!!playGame">{{ value }}</button>
`,
styles: [
'button { width: 100%; height: 100%; font-size: 5em !important; }',
'#myX {background-color: green;}'
]
})
export class SquareComponent {
@Input() value: 'X' | 'O';
@Input() playGame: boolean;
@Input() pos: number;
@Input() winState: Array<any>;
f() {
return this.winState.includes(this.pos);
}
}
|
a137bfd7a57f34e143ade9aece6b3a9f2ae871f3
|
TypeScript
|
andresgutgon/instagram-graph-api-lib
|
/src/main/Constants.ts
| 2.609375
| 3
|
/**
* Class containing Constants used throughout the project.
*
* @author Tiago Grosso <tiagogrosso99@gmail.com>
* @since 0.1.0
*/
export class Constants {
/**
* The URL of the api.
*/
static readonly API_URL: string = 'https://graph.facebook.com';
}
|
ab0f424906c830ba89cd8dcead01621ebec853ae
|
TypeScript
|
kgolezardi/Performance-Review-Web
|
/src/shared/hooks/useSortBy.ts
| 3.328125
| 3
|
import { useState } from 'react';
type Order = 'asc' | 'desc';
function descendingComparator<T>(a: T, b: T, orderBy: keyof T) {
if (b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
}
export function getComparator<Key extends keyof any>(
order: Order,
orderBy: Key,
): (a: { [key in Key]: number | string }, b: { [key in Key]: number | string }) => number {
return order === 'desc'
? (a, b) => descendingComparator(a, b, orderBy)
: (a, b) => -descendingComparator(a, b, orderBy);
}
export function stableSort<T>(array: T[], comparator: (a: T, b: T) => number) {
const stabilizedThis = array.map((el, index) => [el, index] as [T, number]);
stabilizedThis.sort((a, b) => {
const order = comparator(a[0], b[0]);
if (order !== 0) return order;
return a[1] - b[1];
});
return stabilizedThis.map((el) => el[0]);
}
export const useSortBy = <T extends Record<string | number, any>>() => {
const [order, setOrder] = useState<Order>('asc');
const [orderBy, setOrderBy] = useState<keyof T>();
const onPropertySort = (event: React.MouseEvent<unknown>, property: keyof T) => {
const isAsc = orderBy === property && order === 'asc';
setOrder(isAsc ? 'desc' : 'asc');
setOrderBy(property);
};
const sortRows = (rows: T[]) => {
if (orderBy) {
return stableSort<T>(rows, getComparator<keyof T>(order, orderBy));
}
return rows;
};
return { order, orderBy, onPropertySort, sortRows };
};
|
41dd10aecf1630b5f48b8402527c4dfd1055938f
|
TypeScript
|
Z-HNAN/taro-redux-saga-seed
|
/src/pages/index/reducer.js
| 2.890625
| 3
|
const INITIAL_STATE = {
num: 0
}
export default function counter (state = INITIAL_STATE, action) {
switch (action.type) {
case 'ADD':
return {
...state,
num: state.num + 1
}
case 'MINUS':
return {
...state,
num: state.num - 1
}
default:
return state
}
}
|
72c02048a2072ae27c18da3b0dcbc9b03ccf7f54
|
TypeScript
|
mickaelvieira/webcam-demo
|
/src/editor/download.ts
| 2.5625
| 3
|
export default class Download {
filename = "download.png";
button: HTMLAnchorElement;
constructor(button: HTMLAnchorElement) {
this.button = button;
this.button.download = this.filename;
}
update(data: string): void {
this.button.href = data;
}
}
|
66c2c1e830832a8a85d3327d6f6f212f5c412588
|
TypeScript
|
test-belbina/test_belbina
|
/src/store/blocks/reducer.ts
| 2.6875
| 3
|
import { Map } from "immutable";
import { ActionTypesInfer } from "src/store/actionTypes";
import * as types from "./types";
import * as actions from "./actions";
import Block from "src/models/block";
export type TStoreBlock = Map<Block["id"], Block>;
const reducer = (state: TStoreBlock = Map(), action: ActionTypesInfer<typeof actions>) => {
switch (action.type) {
case types.LOAD_BLOCKS_SUCCESS:
action.blocks.forEach((block: Block) => {
if (!state.has(block.id)) {
state = state.set(block.id, block);
}
});
return state;
default:
return state;
}
};
export default reducer;
|
d20a10700e21402bfcbf44fab81eb397b0d0d432
|
TypeScript
|
tomek401273/webshop
|
/src/app/model/directory-titles.ts
| 2.625
| 3
|
export class DirectoryTitles {
private _titles: String[];
constructor() {
}
get titles(): String[] {
return this._titles;
}
set titles(value: String[]) {
this._titles = value;
}
}
|
cfc002567cbde423f14ca8708126437cd0ebb7bd
|
TypeScript
|
plusxp/nstarter-ts-express
|
/template/src/utils/utils.common.ts
| 2.6875
| 3
|
export class CommonUtils {
public static getName() {
return;
}
public static async sleep (timeMs: number) {
return new Promise((r) => setTimeout(r, timeMs));
}
}
|
9e12d7760cd974e2a20338aee97016801b479af9
|
TypeScript
|
ethanfann/leetcode
|
/src/70/70.test.ts
| 2.734375
| 3
|
import climbStairs from './70'
test('expects 0 stairs to return 1', () => {
expect(climbStairs(0)).toEqual(1)
})
test('expects 1 stair to return 1', () => {
expect(climbStairs(1)).toEqual(1)
})
test('expects 2 stairs to return 2', () => {
expect(climbStairs(2)).toEqual(2)
})
test('expects 3 stairs to return 3', () => {
expect(climbStairs(3)).toEqual(3)
})
test('expects 4 stairs to return 5', () => {
expect(climbStairs(4)).toEqual(5)
})
test('expects 5 stairs to return 8', () => {
expect(climbStairs(5)).toEqual(8)
})
|
07ddb5f589a3a31e15b0cc6f758dbdf1e17e82cf
|
TypeScript
|
meacer/deasciifier
|
/src/typescript/benchmark/cleanup.ts
| 3.375
| 3
|
// Cleans up Turkish text.
//
// Skips characters that are not Latin or Turkish and drops certain characters
// such as combining dot above.
import * as deasciifier from '../deasciifier'
import * as fs from "fs";
import * as process from "process"
if (process.argv.length <= 2) {
throw "Usage: cleanup <input_file> <optional_output_file>";
}
let input_path = process.argv[2];
let output_path = (process.argv.length > 3) ? process.argv[3] : null;
console.log("Processing ", input_path);
let text = fs.readFileSync(input_path, "utf8");
console.log("File read, cleaning up...");
function isLatinOrTurkish(c: string) : boolean {
// TODO: Use something more intelligent here.
return (c.charCodeAt(0) >=32 && c.charCodeAt(0) <= 126) ||
c == '\n' || c == '\t' || c == '\r' ||
c == '’' || c == '“' || c == '”' || c == '´' || c == '–' ||
c == 'â' || c == 'î' || c == 'û' ||
c == 'é' || c == 'à' || c == 'ë' || c == 'ô' || c == 'œ' || c == 'ê' ||
c == 'è' ||
c == 'ç' || c == 'ğ' || c == 'ı' || c == 'ö' || c == 'ş' || c == 'ü';
}
var positions = [];
var output = [];
for (var i = 0; i < text.length; i++) {
let c = text.charAt(i);
if (c.charCodeAt(0) == 0x0307) { // Combining dot above
continue;
}
if (isLatinOrTurkish(c)) {
output.push(c);
continue;
}
positions.push(i);
}
console.log("Found %d odd characters", positions.length);
if (output_path) {
fs.writeFile(output_path, output.join(""), function(err) {
if (err) {
throw err;
} else {
console.log("Wrote cleaned text at %s", output_path);
}
});
}
|
c32102f7d9688a845836af29cf276c8ccce9b2eb
|
TypeScript
|
wilsonmoraes/Yaeeh-Utils
|
/TypeScript/validators.ts
| 3.140625
| 3
|
private validarCPF(cpf: string) {
cpf = cpf.replace(/[^\d]+/g, '');
if (cpf == '') {
return false;
}
let CPFinvalidosConhecidos = {
'00000000000': true,
'11111111111': true,
'22222222222': true,
'33333333333': true,
'44444444444': true,
'55555555555': true,
'66666666666': true,
'77777777777': true,
'88888888888': true,
'99999999999': true,
'12345678909': true
};
// Elimina CPFs invalidos conhecidos
if (cpf.length != 11 || CPFinvalidosConhecidos['cpf']) {
return false;
}
// Valida 1o digito
let add: number = 0;
for (let i = 0; i < 9; i++) {
add += parseInt(cpf.charAt(i)) * (10 - i);
}
let rev: number = 11 - (add % 11);
if (rev == 10 || rev == 11) {
rev = 0;
}
if (rev != parseInt(cpf.charAt(9))) {
return false;
}
// Valida 2o digito
add = 0;
for (let i = 0; i < 10; i++) {
add += parseInt(cpf.charAt(i)) * (11 - i);
}
rev = 11 - (add % 11);
if (rev == 10 || rev == 11) {
rev = 0;
}
if (rev != parseInt(cpf.charAt(10))) {
return false;
} else {
return true;
}
}
/**
*
* @param nascimento receive: 'dd/mm/yyyy'
* @returns {boolean}
*/
private validarNascimentoDDMMYYYY(nascimento: string) {
nascimento = nascimento.replace(/[^\d]+/g, '');
if (nascimento.length != 8) {
return false;
}
let dia: string = nascimento.substring(0, 2);
let mes: string = nascimento.substring(2, 4);
let ano: string = nascimento.substring(4, 8);
let nascimentoDate: Date = new Date(parseInt(ano), parseInt(mes), parseInt(dia));
if (new Date() < nascimentoDate) {
return false;
}
return true;
}
/**
*
* @param telefone
* @returns {boolean}
*/
private validarTelefone(telefone: string) {
//retira todos os caracteres menos os numeros
telefone = telefone.replace(/\D/g, '');
//verifica se tem a qtde de numero correto
if (!(telefone.length >= 10 && telefone.length <= 11)) {
return false;
}
//Se tiver 11 caracteres, verificar se começa com 9 o celular
if (telefone.length == 11 && parseInt(telefone.substring(2, 3)) != 9) {
return false;
}
//verifica se não é nenhum numero digitado errado (propositalmente)
for (let n = 0; n < 10; n++) {
//um for de 0 a 9.
//estou utilizando o metodo Array(q+1).join(n) onde "q" é a quantidade e n é o
//caractere a ser repetido
if (telefone == new Array(11).join(`${n}`) || telefone == new Array(12).join(`${n}`)) {
return false;
}
}
//DDDs validos
let codigosDDD = [11, 12, 13, 14, 15, 16, 17, 18, 19,
21, 22, 24, 27, 28, 31, 32, 33, 34,
35, 37, 38, 41, 42, 43, 44, 45, 46,
47, 48, 49, 51, 53, 54, 55, 61, 62,
64, 63, 65, 66, 67, 68, 69, 71, 73,
74, 75, 77, 79, 81, 82, 83, 84, 85,
86, 87, 88, 89, 91, 92, 93, 94, 95,
96, 97, 98, 99];
//verifica se o DDD é valido (sim, da pra verificar rsrsrs)
if (codigosDDD.indexOf(parseInt(telefone.substring(0, 2))) == -1) {
return false;
}
// E por ultimo verificar se o numero é realmente válido.
if (telefone.length == 10 && [2, 3, 4, 5, 7].indexOf(parseInt(telefone.substring(2, 3))) == -1) {
return false;
}
//se passar por todas as validações acima, então está tudo certo
return true;
}
|
9518e1bbb32c89356d69d4b8c5dc4078047ca48c
|
TypeScript
|
theredhead/formatByteSize
|
/tests/formatByteSize.simple.test.ts
| 2.84375
| 3
|
/** @format */
import { formatByteSize } from "../src/formatByteSize";
describe("formatByteSize", () => {
it("can handle some known values", () => {
expect(formatByteSize(100)).toBe("100B");
expect(formatByteSize(1024)).toBe("1KB");
expect(formatByteSize(1024 * 1024 * 1024 * 1.2)).toBe("1.20GB");
});
it("can can handle kilo meaning 1000", () => {
expect(formatByteSize(100, { kilo: 1000 })).toBe("100B");
expect(formatByteSize(1024, { kilo: 1000 })).toBe("1.02KB");
});
});
|
ecbbe0929612127f5318002e2228db0f26af4b4f
|
TypeScript
|
lbwa/docs-server
|
/src/generator/base.ts
| 2.796875
| 3
|
const glob = require('glob')
const path = require('path')
const fs = require('fs')
function createError () {
console.error('[Error]: This function should be implemented by subclass')
}
export = class BaseGenerator {
cwd: string
constructor () {}
/**
* get All markdown files paths
* @return {Promise<void>}
*/
async parser () {
let paths: string[]
try {
paths = await this.scanner()
} catch (e) {
console.error(e)
}
await this.iterator(paths)
}
/**
* get All markdown content Promises wrapper
* @return {Promise<{origin: string, content: string}>[]}
*/
async iterator (paths: string[]) {
createError()
}
/**
* get All markdown files paths
* @return {Promise<path[]>}
*/
async scanner () {
let paths: string[] = []
try {
paths = await this.getPaths()
} catch (err) {
console.error(`[Scanner error]: ${err}`)
}
return paths
}
getPaths (): Promise<string[]> {
return new Promise((resolve, reject) => {
glob('*/**/*.md', {
cwd: this.cwd,
ignore: 'node_modules/**/*',
nodir: true
}, (err: null | Error, paths: string[]) => {
err ? reject(err) : resolve(paths)
})
})
}
getContent (origin: string): Promise<{origin: string, content: string}> {
return new Promise((resolve, reject) => {
fs.readFile(
path.resolve(process.cwd(), `./${origin}`),
'utf8',
(err: Error, content: string) => {
err ? reject(err) : resolve({
origin,
content
})
}
)
})
}
}
|
cf1f7f77085edbb08002feba586d803b4e97dd32
|
TypeScript
|
RioloGiuseppe/byte-serializer
|
/dist/interfaces/crc.d.ts
| 2.875
| 3
|
/// <reference types="node" />
import { CrcLength } from './../enums/crcLength';
/**
* Define the interface for CRC algorithm injection
*/
export interface CRC {
compute(data: Array<number>): Buffer;
}
/**
* Define metadata for crc
*/
export interface CRCMetadata {
/**
* Define the position of the first byte of the output array to compute crc
*/
startByte: number;
/**
* Define the position of the last byte of the output array to compute crc
*/
stopByte: CrcLength;
/**
* Define the length of crc
*/
length: number;
/**
* Define the name of the property of type CRC to compute crc
* @see {@link CRC}
*/
name: string;
}
|
64869b65db0d2cc684324dc790ad487963dfbe87
|
TypeScript
|
cristianTertuliano/zen-api
|
/src/core/entity/user/user.entity.ts
| 2.546875
| 3
|
import { Column, Entity, OneToOne, RelationId, OneToMany, Unique, Index, JoinColumn } from "typeorm";
import {
IsBoolean,
IsEmail,
IsEnum,
IsNotEmpty,
IsOptional,
IsString,
MaxLength,
MinLength,
} from 'class-validator';
import { BaseResourceEntity } from "@core/base/base-entity";
import { Email } from '@core/entity/email/email.entity';
import { Account } from "@core/entity/account/account.entity";
import { UserSession } from "@core/entity/user/user-session.entity";
import { UserProfessional } from "@core/entity/user/user-professional.entity";
import { Schedule } from "@core/entity/schedule/schedule.entity";
import { Scheduling } from "@core/entity/schedule/scheduling.entity";
export enum TypeUser {
Professional = 'professional',
Patient = 'patient',
}
export enum GenderUser {
Female = 'female',
Male = 'male',
NotBinary = 'not_binary',
}
@Entity()
@Unique(['email'])
export class User extends BaseResourceEntity {
// Relations One to One
@OneToOne(() => Account, account => account.user)
@JoinColumn()
account: Account;
@OneToOne(() => UserProfessional, userProfessional => userProfessional.user)
@JoinColumn()
professional: UserProfessional;
// Relations One to many
@OneToMany(() => Email, email => email.creator)
emails: Email[]
@OneToMany(() => UserSession, session => session.user)
sessions: UserSession[];
@OneToMany(() => Schedule, schedule => schedule.user)
schedules: Schedule[]
@OneToMany(() => Scheduling, scheduling => scheduling.patient)
schedulingsPatient: Scheduling[]
@OneToMany(() => Scheduling, scheduling => scheduling.professional)
schedulingsProfessional: Scheduling[]
// Columns
@Column()
@IsNotEmpty()
@IsString()
@RelationId((user: User) => user.account)
accountId: string;
@Column({ nullable: true })
@IsString()
@RelationId((user: User) => user.professional)
professionalId: string;
@Column()
@IsOptional()
@IsString()
@MinLength(3)
@MaxLength(50)
firstName: string;
@Column()
@IsOptional()
@IsString()
@MinLength(3)
@MaxLength(50)
lastName: string;
@Column()
@IsOptional()
@IsString()
@MaxLength(250)
fullName: string;
@Column()
@IsNotEmpty()
@IsString()
@IsEmail()
@MaxLength(255)
email: string;
@Column({ select: false })
@IsNotEmpty()
@MinLength(6)
password: string;
@Index()
@Column('enum', { enum: TypeUser })
@IsNotEmpty()
@IsEnum(TypeUser)
type: TypeUser;
@Index()
@Column('enum', { enum: GenderUser })
@IsNotEmpty()
@IsEnum(GenderUser)
gender: GenderUser;
@Column({ select: false })
@IsNotEmpty()
salt: string;
@Column({ default: true })
@IsOptional()
@IsBoolean()
isActive: boolean;
}
|
db702ee79dffe8eaf630129b3aae94ce5dc7ad2c
|
TypeScript
|
christianhg/match-match
|
/src/index.ts
| 2.578125
| 3
|
import { Card } from './game/card';
import { createGame } from './game/game';
import { createImageService } from './game/image-service';
import { getPixabayImages } from './pixabay';
const cardContainer = document.querySelector('#cards')!;
createGame({
imageService: createImageService('match', {
getImages: getPixabayImages,
converter: ({ webformatURL }) => ({ src: webformatURL }),
}),
numberOfPairs: 14,
onInit: cards => {
cards.forEach(card => {
cardContainer.appendChild(createCardElement(card));
});
},
onUpdate: cards => {
cards.forEach(card => {
const existingCard = cardContainer.querySelector<HTMLElement>(
`#${card.id}`,
)!;
existingCard.dataset.state = card.state;
});
},
});
function createCardElement(card: Card): HTMLElement {
const cardElement = document.createElement('li');
const front = document.createElement('span');
const back = document.createElement('span');
const img = document.createElement('img');
cardElement.setAttribute('class', 'card');
cardElement.id = card.id;
cardElement.dataset.state = card.state;
front.setAttribute('class', 'front');
back.setAttribute('class', 'back');
back.addEventListener(
'mouseenter',
() => {
card.getImage().then(image => {
img.src = image.src;
});
},
{ once: true },
);
back.addEventListener('click', card.reveal);
front.appendChild(img);
cardElement.appendChild(front);
cardElement.appendChild(back);
return cardElement;
}
|
060d0bcf709168b77a8e975d8ccc6a4f0e3ef94f
|
TypeScript
|
craciuncezar/visx
|
/packages/visx-scale/test/createScale.test.ts
| 2.984375
| 3
|
import { createScale } from '../src';
describe('createScale()', () => {
it('linear', () => {
const scale = createScale({ type: 'linear', domain: [0, 10], range: [2, 4] });
expect(scale(5)).toEqual(3);
});
it('fallbacks to linear if type is not defined', () => {
const scale = createScale({ domain: [0, 10], range: [2, 4] });
expect(scale(5)).toEqual(3);
});
it('log', () => {
const scale = createScale({
type: 'log',
base: 2,
domain: [2, 8],
range: [1, 3],
});
expect(scale(4)?.toFixed(2)).toEqual('2.00');
});
it('pow', () => {
const scale = createScale({ type: 'pow', exponent: 2, domain: [1, 3], range: [2, 18] });
expect(scale(2)).toEqual(8);
});
it('sqrt', () => {
const scale = createScale({ type: 'sqrt', domain: [1, 9], range: [1, 3] });
expect(scale(4)).toEqual(2);
});
it('symlog', () => {
const scale = createScale({ type: 'symlog', domain: [1, 9], range: [1, 3], constant: 2 });
expect(scale(4)?.toFixed(2)).toEqual('2.07');
});
it('time', () => {
const scale = createScale({
type: 'time',
domain: [new Date(2020, 0, 1), new Date(2020, 0, 10)],
range: [1, 10],
});
expect(scale(new Date(2020, 0, 4))).toEqual(4);
});
it('utc', () => {
const scale = createScale({
type: 'utc',
domain: [new Date(Date.UTC(2020, 0, 1)), new Date(Date.UTC(2020, 0, 10))],
range: [1, 10],
});
expect(scale(new Date(Date.UTC(2020, 0, 4)))).toEqual(4);
});
it('quantile', () => {
const scale = createScale({ type: 'quantile', domain: [1, 3, 5, 7], range: [0, 10] });
expect(scale(2)).toEqual(0);
});
it('quantize', () => {
const scale = createScale({ type: 'quantize', domain: [1, 10], range: ['red', 'green'] });
expect(scale(2)).toEqual('red');
expect(scale(6)).toEqual('green');
});
it('threshold', () => {
const scale = createScale({
type: 'threshold',
domain: [0, 1] as number[],
range: ['red', 'white', 'green'],
});
expect(scale(-1)).toEqual('red');
expect(scale(0)).toEqual('white');
expect(scale(0.5)).toEqual('white');
expect(scale(1)).toEqual('green');
expect(scale(1000)).toEqual('green');
});
it('ordinal', () => {
const scale = createScale({ type: 'ordinal', domain: ['pig', 'cat'], range: ['red', 'green'] });
expect(scale('pig')).toEqual('red');
expect(scale('cat')).toEqual('green');
});
it('point', () => {
const scale = createScale({
type: 'point',
domain: ['a', 'b', 'c'],
range: [1.1, 3.5],
round: true,
});
expect(scale('a')).toEqual(1);
expect(scale('b')).toEqual(2);
expect(scale('c')).toEqual(3);
});
it('band', () => {
const scale = createScale({
type: 'band',
domain: ['a', 'b', 'c'],
range: [1.1, 3.5],
round: false,
});
expect(scale('a')).toEqual(1.1);
expect(scale('b')).toEqual(1.9);
expect(scale('c')).toEqual(2.7);
});
it('invalid type', () => {
// @ts-ignore
expect(createScale({ type: 'invalid' })).toBeDefined();
});
});
|
819b732affdf31d18fedb0d0840fbaabb8dc82b4
|
TypeScript
|
DevRobert/psycollect-ui
|
/src/model/AuthenticationApi.ts
| 2.78125
| 3
|
import { apiBaseUri } from "./ApiHelpers";
interface LoginResponse {
token: string
}
export async function login(email: string, password: string): Promise<LoginResponse> {
const requestUri = apiBaseUri + 'login'
const response = await fetch(requestUri, {
method: 'POST',
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
}),
body: JSON.stringify({
email,
password
})
})
const responseData = await response.json()
if(!response.ok) {
throw new Error(responseData.error)
}
return responseData
}
|
ef9763491971f73a5912c9ca7832d4e5c6ae0f9f
|
TypeScript
|
Stentroll/AutoFilerTS
|
/TSclasses/DaySecCalculator.ts
| 3.109375
| 3
|
class DaySecCalculator {
mainDiv: HTMLDivElement;
secDiv: HTMLDivElement;
dayDiv: HTMLDivElement;
secLabel: HTMLLabelElement;
dayLabel: HTMLLabelElement;;
dayInput: HTMLInputElement;
secInput: HTMLInputElement;
constructor() {
this.mainDiv = document.createElement("div");
this.secDiv = document.createElement("div");
this.dayDiv = document.createElement("div");
this.secLabel = document.createElement("label");
this.dayLabel = document.createElement("label");
this.secInput = document.createElement("input");
this.dayInput = document.createElement("input");
this.mainDiv.appendChild(this.secDiv);
this.mainDiv.appendChild(this.dayDiv);
this.secDiv.appendChild(this.secLabel);
this.secDiv.appendChild(this.secInput);
this.dayDiv.appendChild(this.dayLabel);
this.dayDiv.appendChild(this.dayInput);
this.secLabel.innerHTML = "Seconds:";
this.dayLabel.innerHTML = "Days:";
this.secInput.type = "text";
this.secInput.value = "0";
this.secInput.id = "txtSeconds";
this.dayInput.type = "text";
this.dayInput.value = "0";
this.dayInput.id = "txtDays";
this.dayInput.onclick = () => this.dayInput.select();
this.secInput.onclick = () => this.secInput.select();
this.dayInput.onkeyup = () => this.UpdateCalculator(this.dayInput);
this.secInput.onkeyup = () => this.UpdateCalculator(this.secInput);
}
UpdateCalculator(input) {
if (input.id === "txtSeconds") {
var val: number = input.value / (24 * 60 * 60);
this.dayInput.value = val.toFixed(3).toString();
}
else if (input.id === "txtDays") {
var val: number = input.value * 24 * 60 * 60;
this.secInput.value = val.toString();
}
}
Build(): HTMLDivElement{
return this.mainDiv;
}
}
|
1d77efd91ce4221926643e920c3dc1f5c61cfb11
|
TypeScript
|
luomus/laji
|
/projects/laji/src/app/shared/local-db/local-db.abstract.ts
| 2.703125
| 3
|
import * as localForage from 'localforage';
import { from as ObservableFrom, Observable, of as ObservableOf } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
export abstract class LocalDb<T> {
protected db: LocalForage;
protected constructor(dbName = 'cache', protected isPlatformBrowser = true) {
this.db = localForage.createInstance({
name: dbName
});
}
setItem(key: string, value: T): Observable<T> {
if (!this.isPlatformBrowser) {
return ObservableOf(value);
}
return ObservableFrom(this.db.setItem(key, value)).pipe(
map<any, T>(v => v),
catchError(() => ObservableOf<T>(value))
);
}
getItem(key: string): Observable<T> {
if (!this.isPlatformBrowser) {
return ObservableOf(null);
}
return ObservableFrom(this.db.getItem<T>(key)).pipe(
catchError(() => ObservableOf(null))
);
}
}
|
b5bf470d7b5ce686ea8e15ac772b8eeff6369bb6
|
TypeScript
|
awhipple/giraphql
|
/packages/core/test/examples/starwars/schema/droid.ts
| 2.609375
| 3
|
import Character from './character';
import builder from '../builder';
export default builder.createObjectType('Droid', {
description: 'A mechanical creature in the Star Wars universe.',
implements: [Character],
isType: item => item.type === 'Droid',
shape: t => ({
primaryFunction: t.string({
description: 'The primary function of the droid.',
resolve: o => o.primaryFunc || 'N/A',
}),
}),
});
|
11680cd1657defec8dc08beb17f79bebc1595d42
|
TypeScript
|
AndreyArthur/park-server
|
/src/tests/app/adapters/Encrypter.spec.ts
| 2.859375
| 3
|
import { Encrypter } from '@/application/adapters';
import { randomString } from '@/tests/helpers/generators';
describe('Encrypter Adapter', () => {
// To avoid jest coverage bugs with static methods
it('should create an instance of Encrypter', () => {
const encrypter = new Encrypter();
expect(encrypter).toBeInstanceOf(Encrypter);
});
it('should hash text successfully', async () => {
const textToBeHashed = randomString(8);
const hash = await Encrypter.encrypt(textToBeHashed);
expect(hash.length).toBe(60);
expect(hash !== textToBeHashed).toBe(true);
});
it('should compare a hash correctly', async () => {
const textToBeHashed = randomString(8);
const hashToBeCompared = await Encrypter.encrypt(textToBeHashed);
const secondHash = await Encrypter.encrypt(randomString(8));
expect(await Encrypter.compare(textToBeHashed, hashToBeCompared))
.toBe(true);
expect(await Encrypter.compare(textToBeHashed, secondHash)).toBe(false);
});
});
|
f82740452f18b69b4c7d3512baefccd01d560586
|
TypeScript
|
vladfind/data-knu-v-1
|
/client/src/types.ts
| 3
| 3
|
export interface User {
name: string;
workNumber: string;
mobileNumber: string;
birthday: string;
email: string;
category: string;
location: string;
note: string;
}
export interface Cat {
text: string;
}
type KeysEnum<T> = { [p in keyof Required<T>]: string };
export const engToRusField: KeysEnum<User> = {
name: "ФИО",
workNumber: "НомСтацТелеф",
mobileNumber: "НомМобилТелеф",
birthday: "Дата рождения",
email: "Электронный адрес",
category: "Категория_абонента",
location: "Домашний адрес",
note: "Примечание",
} as const;
type test = keyof User;
export const fieldNamesEng = Object.keys(engToRusField) as test[];
|
e6cd546de8e9576256ca98e0913a6624eeb02a0b
|
TypeScript
|
zealves/angular7-basic-example
|
/src/app/customers/customer.model.ts
| 2.8125
| 3
|
export class Customer {
public name: string
public age: number
public subscriptions = []
constructor(name: string, age: number, subscriptions: any) {
this.name = name
this.age = age
this.subscriptions = subscriptions
}
}
|
d4133a9b00b7684b7db29adb42b8e7214bdea34b
|
TypeScript
|
coyotte508/mongo-limiter
|
/index.ts
| 2.953125
| 3
|
import * as mongoose from "mongoose";
import actionSchema, { ActionLogDocument } from "./src/schema";
import MongoLimiterError from "./src/mongo-limiter-error";
type UserActions = mongoose.Model<ActionLogDocument>;
export interface Limit {
/** Maximum number of times the action can be done */
limit: number;
/** Duration in seconds of the period for which the limit is effective */
duration: number;
}
export interface Limits {
[action: string]: Limit;
}
class MongoLimiter {
private UserActions: UserActions = null;
public limits: Limits = {};
public init(connection: mongoose.Connection, limits?: Limits) {
this.UserActions = connection.model('UserActions', actionSchema);
if (limits) {
this.setLimits(limits);
}
}
private checkInit() {
if (!this.UserActions) {
throw new MongoLimiterError("You must initialize mongo-limiter with a mongoose connection");
}
}
public setLimits(limits: Limits) {
this.limits = limits;
}
/**
* Remaining number of times the user can do the action without going over the limit
*
* @param user The user identifier (id, username, ip)
* @param action The action we're querying about
*/
public async remainingUses(user: string, action: string) {
await this.checkInit();
if (!(action in this.limits)) {
return Infinity;
}
const {duration, limit} = this.limits[action];
const count = await this.UserActions.count({user, action, createdAt: {$gt: Date.now() - duration * 1000}}).limit(limit);
return limit - count;
}
public async possible(user: string, action: string) {
return (await this.remainingUses(user, action)) > 0;
}
/**
* Tells MongoLimiter that user did action.
*
* @param user The user identifier (id, username, ip)
* @param action The action done by the user
* @param data Optional. The data to be logged with the action
*/
public async action(user: string, action: string, data?: any) {
await this.checkInit();
return new this.UserActions({user, action, data}).save();
}
/**
* Checks if the user can do the action, and if so, logs the action
*
* @param user
* @param action
* @param data
*
* @returns An object with the remaining number of times user can do the action, or
* false if the action can't be done
*/
public async attempt(user: string, action: string, data?: any) {
const remaining = await this.remainingUses(user, action);
if (remaining <= 0) {
return false;
}
await this.action(user, action, data);
return {
user,
action,
remaining: remaining - 1
};
}
/**
* Show the logs for the specified action/user/both
*
* @param options options.limit is the maximum number of entries, 50 by default
*/
public async logs(options: {user?: string, action?: string, limit?: number}) {
const search: {user?: string, action?: string} = {};
const limit = "limit" in options ? options.limit : 50;
if (options.user) {
search.user = options.user;
}
if (options.action) {
search.action = options.action;
}
return await this.UserActions.find(search).sort({$natural: -1}).limit(limit);
}
}
export default new MongoLimiter();
export {MongoLimiterError, ActionLogDocument};
|
171ca68be778257f89b6340973ce723d56b2b24f
|
TypeScript
|
elrafapc/Unit-JUpiter-TypeScript
|
/spec/ShoppingCartTest.spec.ts
| 2.90625
| 3
|
import { Book } from "../src/Book";
import { ShoppingCart } from "../src/ShoppingCart";
const cart: ShoppingCart = new ShoppingCart();
describe("Testing Functions From ShoppingCart", () =>{
it("Verifying the count items from cart", () =>{
cart.addBook(new Book("Book1", 10, "1"));
cart.addBook(new Book("Book2", 20, "2"));
expect(cart.countItems()).toBe(2);
})
it("Verifying the total Value from cart", () =>{
cart.addBook(new Book("Book1", 10, "1"));
cart.addBook(new Book("Book2", 20, "2"));
expect(cart.getTotal()).toBe(30);
})
it("Verifying clear cart", () =>{
cart.addBook(new Book("Book1", 10, "1"));
cart.addBook(new Book("Book2", 20, "2"));
cart.clear();
expect(cart.countItems()).toBe(0);
expect(cart.getTotal()).toBe(0);
})
})
|
80a8328a280cdb473fd640b61eab077e53522377
|
TypeScript
|
Covisource/covisource-api
|
/src/validators/categoryValidator.ts
| 2.78125
| 3
|
import express from "express";
import categoryModel from "../models/categoryModel";
export const newCategoryValidator = async (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
const { name, extraParameters } = req.body;
const { user } = req as any;
if (!name) {
return next({
statusCode: 400,
code: "bad_data",
message: "Make sure the data is valid.",
});
}
if (!user.admin) {
return next({
statusCode: 401,
code: "unauthorized",
message: "You aren't authorized to perform this action",
});
}
if (extraParameters) {
// make sure the extra parameters for the category are valid
try {
let isOkay = true;
extraParameters.forEach((extraParam: any) => {
if (!extraParam.name || !extraParam.icon || !extraParam.type) {
isOkay = false
}
})
if (!isOkay) {
return next({
message: "Make sure all the fields are valid.",
statusCode: 500,
code: "params_insufficient",
});
}
} catch (err) {
return next({
message: err.message,
statusCode: 500,
code: "server_err",
});
}
}
try {
const queryRes = await categoryModel.findOne({ name });
if (queryRes) {
return next({
statusCode: 400,
code: "resource_exists",
message: "This resource already exists",
});
}
} catch (err) {
return next({
message: err.message,
statusCode: 500,
code: "mongo_err",
});
}
// validation succeeds, continue to next middleware
next();
};
|
9951a6957e42c6b66ae52ab2d40d29b06b5eb4c9
|
TypeScript
|
havelessbemore/dastal
|
/src/collection/index.ts
| 3.140625
| 3
|
import { Collection } from './collection';
export * from './collection';
/**
* Check if a value is a {@link Collection}.
*
* @param obj - The value to check.
*
* @returns - `true` if obj is a Collection, `false` otherwise.
*/
export function isCollection(obj: any): obj is Collection<unknown> {
return (
obj != null && typeof obj['size'] === 'number' && typeof obj[Symbol.iterator] === 'function'
);
}
|
483553e5a44849ea795676c640ba932c95fa1b32
|
TypeScript
|
dudubs/fullstack-template
|
/src/server/tests/setupTests.ts
| 2.671875
| 3
|
import { createConnection } from "typeorm";
import { Session } from "../entities/Session";
import { User } from "../entities/User";
import { encryptPassword } from "../utils/encryptPassword";
export const testUser = {
entity: null as null | User,
password: "123",
};
export const testUsersEntities: User[] = [];
beforeAll(async () => {
await createConnection({
type: "sqlite",
name: "default",
database: ":memory:",
synchronize: true,
entities: [User, Session],
});
const encrypedPassword = encryptPassword(testUser.password);
testUser.entity = await User.save(createUser("Barak Obama"));
testUsersEntities.push(
testUser.entity,
...(await User.save([createUser("Bill Gates")])),
...(await User.save([createUser("Aki Avni")])),
...(await User.save([createUser("David Ben Simon")]))
);
function createUser(fullName: string) {
const [firstName] = fullName.split(" ", 1);
const lastName = fullName.slice(firstName.length + 1).trim();
return User.create({
encrypedPassword,
firstName,
lastName,
loginName: (firstName + lastName).toUpperCase(),
});
}
});
|
9bcf00e1b6f26c01cb6af0188c81f97c491bb842
|
TypeScript
|
textlint/textlint
|
/packages/@textlint/types/src/Rule/TextlintRuleOptions.ts
| 2.71875
| 3
|
/**
* textlint rule option values is object or boolean.
* if this option value is false, disable the rule.
*/
import { TextlintRuleSeverityLevel } from "./TextlintRuleSeverityLevel";
export type TextlintRuleOptions<T extends object = {}> = {
[index: string]: any;
severity?: TextlintRuleSeverityLevel;
} & T;
|
1f4f4acf603a7e36a066bcc7f499d2931c9f6c8f
|
TypeScript
|
Tasse00/VisualComDev
|
/src/components/Editor/Providers/Editor/actions.ts
| 2.546875
| 3
|
interface ActCreateInstance {
type: 'create-instance';
payload: {
parentId: string;
comId: string;
position?: number; // 插入位置
};
}
interface ActMoveInstnce {
type: 'move-instance';
payload: {
parentId: string;
instanceId: string;
position?: number; // 插入位置
};
}
interface ActDelInstance {
type: 'delete-instance';
payload: {
instanceId: string;
};
}
interface ActSelectInstance {
type: 'select-instance';
payload: {
instanceId: string;
};
}
interface ActHoverIntance {
type: 'hover-instance';
payload: {
instanceId: string;
};
}
interface ActUpdateInstanceProperty {
type: 'update-instance-property';
payload: {
instanceId: string;
field: string;
value: string;
};
}
interface ActUpdateInstanceName {
type: 'update-instance-name';
payload: {
instanceId: string;
name: string;
};
}
interface ActLoadTree {
type: 'load-tree';
payload: {
tree: VCD.ComponentInstanceTree;
size?: VCD.EditorSize;
};
}
interface ActStoreInstanceDom {
type: 'store-instance-dom';
payload: {
instanceId: string;
dom: Element;
};
}
interface ActUpdateInstanceListeners {
type: 'update-instance-listeners';
payload: {
instanceId: string;
listeners: VCD.InstanceListener[];
};
}
interface ActRedo {
type: 'redo';
}
interface ActUndo {
type: 'undo';
}
interface ActUpdateContainerAttribs {
type: 'update-container-attribs';
payload: {
left: number;
top: number;
width: number;
height: number;
scrollTop: number;
scrollLeft: number;
};
}
interface ActInitEditor {
type: 'init-editor';
payload: {
comId: string; //根节点容器
name: string; // 根节点名称
};
}
interface ActInsertInstanceTree {
type: 'insert-instance-tree';
payload: {
tree: VCD.ComponentInstanceTree;
parentId: string;
position?: number;
};
}
interface ActSetSizeMode {
type: 'set-size-mode';
payload: {
width: string;
height: string;
allowOverHeight: boolean;
};
}
export type AvailableActions =
| ActCreateInstance
| ActMoveInstnce
| ActDelInstance
| ActSelectInstance
| ActHoverIntance
| ActUpdateInstanceProperty
| ActUpdateInstanceName
| ActLoadTree
| ActStoreInstanceDom
| ActUpdateInstanceListeners
| ActRedo
| ActUndo
| ActUpdateContainerAttribs
| ActInitEditor
| ActInsertInstanceTree
| ActSetSizeMode;
|
484a5cde4cbaafc14f8312a998d72638920652ca
|
TypeScript
|
MouseLightProject/pipeline-scheduler
|
/server/data-access/sequelize/project-connectors/adjacentTileStageConnector.ts
| 2.515625
| 3
|
import {Instance, Model} from "sequelize";
import {generatePipelineCustomTableName, IToProcessTileAttributes, StageTableConnector} from "./stageTableConnector";
export interface IAdjacentTileAttributes {
relative_path: string,
adjacent_relative_path: string;
adjacent_tile_name: string;
}
export interface IAdjacentTile extends Instance<IAdjacentTileAttributes>, IAdjacentTileAttributes {
}
function generatePipelineStageAdjacentTileTableName(pipelineStageId: string) {
return generatePipelineCustomTableName(pipelineStageId, "Adjacent");
}
export class AdjacentTileStageConnector extends StageTableConnector {
private _adjacentTileModel: Model<IAdjacentTile, IAdjacentTileAttributes> = null;
public async loadAdjacentTile(id: string): Promise<IAdjacentTile> {
return this._adjacentTileModel.findOne({where: {relative_path: id}});
}
public async loadAdjacentTiles(): Promise<IAdjacentTile[]> {
return this._adjacentTileModel.findAll();
}
public async insertAdjacent(toProcess: IToProcessTileAttributes[]) {
return StageTableConnector.bulkCreate(this._adjacentTileModel, toProcess);
}
public async deleteAdjacent(toDelete: string[]) {
if (!toDelete || toDelete.length === 0) {
return;
}
return this._adjacentTileModel.destroy({where: {relative_path: {$in: toDelete}}});
}
protected defineTables() {
super.defineTables();
this._adjacentTileModel = this.defineAdjacentTileModel();
}
private defineAdjacentTileModel(): any {
return this._connection.define(generatePipelineStageAdjacentTileTableName(this._tableBaseName), {
relative_path: {
primaryKey: true,
unique: true,
type: this._connection.Sequelize.TEXT
},
adjacent_relative_path: {
type: this._connection.Sequelize.TEXT,
defaultValue: null
},
adjacent_tile_name: {
type: this._connection.Sequelize.TEXT,
defaultValue: null
}
}, {
timestamps: true,
createdAt: "created_at",
updatedAt: "updated_at",
paranoid: false
});
}
}
|
a10818f949c379236025e74fd43dba7e50ff04c5
|
TypeScript
|
henry-alakazhang/pokemon-autochess
|
/src/objects/pokemon.object.ts
| 2.9375
| 3
|
import { Status } from '../core/game.model';
import { Pokemon, pokemonData, PokemonName } from '../core/pokemon.model';
import { generateId, getBaseTexture } from '../helpers';
import { boundRange } from '../math.helpers';
import { Coords, getTurnDelay } from '../scenes/game/combat/combat.helpers';
import { FloatingText } from './floating-text.object';
import { PokemonCard } from './pokemon-card.object';
interface SpriteParams {
readonly scene: Phaser.Scene;
readonly x: number;
readonly y: number;
readonly name: PokemonName;
readonly frame?: string | number;
readonly side: 'player' | 'enemy';
}
/**
* Stat changes, calculated as stages like Pokemon
* Each stage is worth 25% more/less
*
* ```
* 8 = 12/4 (300%)
* 4 = 8/4 (200%)
* 2 = 6/4 (150%)
* 0 = 4/4 (100%)
* -2 = 4/6 (66%)
* -4 = 4/8 (50%)
* -8 = 4/12 (33%)
* ```
*/
type StatChange =
| -8
| -7
| -6
| -5
| -4
| -3
| -2
| -1
| 0
| 1
| 2
| 3
| 4
| 5
| 6
| 7
| 8;
type ModifiableStat =
| 'attack'
| 'defense'
| 'specAttack'
| 'specDefense'
| 'speed';
export type PokemonAnimationType = 'left' | 'right' | 'up' | 'down';
export class PokemonObject extends Phaser.Physics.Arcade.Sprite {
public static readonly Events = {
Dead: 'dead',
Damage: 'damage',
} as const;
/**
* A hacky little way of adding an outline to a Pokemon.
* Draws a second, slightly larger sprite which serves as the outline.
*/
outlineSprite: Phaser.GameObjects.Sprite;
isOutlined = false;
name: PokemonName;
/**
* The Pokemon that "owns" this one.
* Used for referencing a Pokemon that summoned another
*/
owner?: PokemonObject;
/**
* The "base" Pokemon for an object.
* Used for external access to combat stats, move, and other things.
*/
basePokemon: Pokemon;
/**
* The original basePokemon object, reffed straight from the Pokemon data.
* Used alongside stat changes to calculate the actual basePokemon stats.
*/
private rawBasePokemon: Pokemon;
/** HP and PP bars above the Pokemon */
bars: Phaser.GameObjects.Graphics;
blindIcon: Phaser.GameObjects.Image;
sleepIcon: Phaser.GameObjects.Sprite;
pokemonTooltip: Phaser.GameObjects.DOMElement;
currentHP: number;
maxHP: number;
currentPP: number;
maxPP?: number;
evasion = 0;
critRate = 0;
critDamage = 1.5;
/* some combat specific stuff */
id: string;
side: 'player' | 'enemy';
// todo: remove and just use moveState for everything
consecutiveAttacks = 0;
moveState: string | number;
currentTarget?: PokemonObject;
status: {
[k in Status]?: {
value?: number;
duration: number;
};
} = {};
/**
* Stat changes, calculated as stages like Pokemon (see: StatChanges type def)
*/
statChanges: { [k in ModifiableStat]: StatChange } = {
attack: 0,
defense: 0,
specAttack: 0,
specDefense: 0,
speed: 0,
};
/**
* Stat changes, calcualted as flat additions before stage multiplication
*/
flatStatChanges: { [k in ModifiableStat]: number } = {
attack: 0,
defense: 0,
specAttack: 0,
specDefense: 0,
speed: 0,
};
/**
* State stored for synergies. Each synergy stores whatever it needs to track.
*/
synergyState: {
/** Number of Speed stacks */
sweeper: number;
/** Number of Attack stacks */
revengeKiller: number;
/** Total stage value of Mech */
pivot: number;
} = { sweeper: 0, revengeKiller: 0, pivot: 0 };
attachments: Phaser.GameObjects.Components.Visible[] = [];
/** Active things the Pokemon is doing that can be cancelled by CC or death */
cancellableEvents: {
timer: Phaser.Time.TimerEvent;
onCancel?: Function;
}[] = [];
// TODO: clean up messiness in model
constructor(params: SpriteParams) {
super(
params.scene,
params.x,
params.y,
getBaseTexture(params.name),
params.frame
);
// generate a random ID
this.id = generateId();
this.name = params.name;
this.rawBasePokemon = pokemonData[params.name];
this.basePokemon = this.rawBasePokemon;
// load data from Pokemon data
this.maxHP = this.basePokemon.maxHP;
this.currentHP = this.maxHP;
if (this.basePokemon.move?.type === 'active') {
this.maxPP = this.basePokemon.move.cost;
this.currentPP = this.basePokemon.move.startingPP;
}
this.side = params.side;
this.outlineSprite = this.scene.add
.sprite(this.x, this.y, this.texture.key, params.frame)
.setOrigin(0.5, 0.5)
.setDisplaySize(this.width + 8, this.height + 8)
.setTintFill(0xffffff)
.setVisible(false);
this.attach(this.outlineSprite);
this.blindIcon = this.scene.add
.image(this.x, this.y - 20, 'blind')
.setDepth(2)
.setVisible(false);
this.attach(this.blindIcon);
this.sleepIcon = this.scene.add
.sprite(this.x + 10, this.y - 20, 'sleep')
.setScale(0.5, 0.5)
.setDepth(2)
.play('sleep')
.setVisible(false);
this.attach(this.sleepIcon);
// FIXME: Should probably just create one and reuse it between Pokemon
this.pokemonTooltip = this.scene.add
.existing(new PokemonCard(this.scene, this.x, this.y, this.basePokemon))
.setVisible(false);
this.attach(this.pokemonTooltip);
// default state is facing the player
this.playAnimation('down');
this.bars = this.scene.add
.graphics({
x: this.x,
y: this.y,
})
.setDepth(1);
this.redrawBars();
// larger sprites need to be shifted slightly
if (this.displayHeight === 128) {
this.setOrigin(0.5, 0.75);
}
this.setInteractive().on(
Phaser.Input.Events.POINTER_DOWN,
(event: Phaser.Input.Pointer) => {
if (event.rightButtonDown()) {
this.pokemonTooltip.setPosition(event.x, event.y);
this.pokemonTooltip.setVisible(true);
}
}
);
this.scene.input.on(
Phaser.Input.Events.POINTER_DOWN,
(event: Phaser.Input.Pointer) => {
// hide if clicked outside...
// bruh there has to be a better way of handling this
if (
event.leftButtonDown() ||
Math.abs(event.x - this.x) > 35 ||
Math.abs(event.y - this.y) > 35
) {
this.pokemonTooltip.setVisible(false);
}
}
);
}
initPhysics() {
// set collision to be a small block in the center
this.body.setSize(32, 32, true);
}
setPosition(x: number, y: number) {
super.setPosition(x, y);
if (this.outlineSprite) {
this.outlineSprite.setPosition(x, y);
}
if (this.bars) {
this.bars.setPosition(x, y);
}
return this;
}
setVisible(visible: boolean) {
this.bars.setVisible(visible);
this.outlineSprite.setVisible(visible && this.isOutlined);
return super.setVisible(visible);
}
/** Attaches a visible GameObject so it moves with the PokemonObject */
attach(object: Phaser.GameObjects.Components.Visible) {
this.attachments.push(object);
}
/** Detaches an attached GameObject */
detach(object: Phaser.GameObjects.Components.Visible) {
this.attachments = this.attachments.filter(item => item === object);
}
addCancellableEvent(event: {
timer: Phaser.Time.TimerEvent;
onCancel?: Function;
}) {
this.cancellableEvents.push(event);
}
destroy() {
// Only destroy if not part of the scene being destroyed.
// Otherwise Phaser can throw errors trying to destroy the same thing twice.
// https://github.com/photonstorm/phaser/issues/5520
if (
this.scene &&
this.scene.scene.settings.status !== Phaser.Scenes.SHUTDOWN
) {
this.outlineSprite.destroy();
this.pokemonTooltip.destroy();
this.bars.destroy();
}
super.destroy();
}
redrawBars() {
this.bars.clear();
// The stat bars section is 10px tall
// 1px of top border
// 5px of hp bar
// 1px of inner border
// 2px of pp bar
// 1 px of bottom border
// bar background
const backgroundColor = this.status.paralyse ? 0x666600 : 0x000000;
this.bars.fillStyle(backgroundColor, 1);
this.bars.fillRect(-this.width / 2, -this.height / 2, this.width, 10);
// hp bar
const hpBarColor =
this.side === 'player'
? 0x32cd32 // player: green
: 0xdc143c; // enemy: red
this.bars.fillStyle(hpBarColor, 1);
this.bars.fillRect(
-this.width / 2 + 1,
-this.height / 2 + 1,
this.width * (this.currentHP / this.maxHP) - 2,
5
);
// add little pips in the HP bar every 250 HP
this.bars.lineStyle(1, 0x000000, 1);
const width = Math.round((250 / this.maxHP) * (this.width - 2));
if (width <= 0) {
// if we accidentally end up with a negative HP or a 0 width for each bar,
// the for loop below is going to go infinite. throw instead
throw new Error(
`Cannot draw HP bars for Pokemon ${this.name}, expected width of bars is ${width}`
);
}
for (let x = width; x < this.width - 2; x += width) {
// full height bars for 1000 increments
const y = (x / width) % 4 === 0 ? 6 : 4;
this.bars.strokeLineShape(
new Phaser.Geom.Line(
-this.width / 2 + x,
-this.height / 2,
-this.width / 2 + x,
-this.height / 2 + y
)
);
}
// pp bar
this.bars.fillStyle(0x67aacb, 1); // sky blue
this.bars.fillRect(
-this.width / 2 + 1,
-this.height / 2 + 7, // offset by 6 to put below the HP bar
this.maxPP
? Math.max(0, this.width * (this.currentPP / this.maxPP) - 2) // use current PP if available
: 0, // empty if no PP
2
);
this.blindIcon.setVisible(!!this.status.blind);
this.sleepIcon.setVisible(!!this.status.sleep);
}
/**
* Rerenders the Pokemon info card.
* Don't use this too much; it's probably not very performant.
*/
redrawCard() {
this.pokemonTooltip.destroy();
this.pokemonTooltip = this.scene.add
.existing(new PokemonCard(this.scene, this.x, this.y, this.basePokemon))
.setVisible(false);
}
public playAnimation(type: PokemonAnimationType) {
this.play(`${this.texture.key}--${type}`);
this.outlineSprite.play(`${this.texture.key}--${type}`);
}
public move(
{ x, y }: Coords,
{
onComplete,
duration,
ease = 'Quad',
}: { onComplete?: Function; duration?: number; ease?: string } = {}
) {
this.scene.add.tween({
targets: [this, this.bars, ...this.attachments],
duration: duration ?? getTurnDelay(this.basePokemon) * 0.75,
// add delta so the bars / attachments / etc move properly too
x: `+=${x - this.x}`,
y: `+=${y - this.y}`,
ease,
onComplete: () => {
this.setPosition(x, y);
if (onComplete) {
onComplete();
}
},
});
}
/**
* Cause this pokemon to heal health
*/
public heal(amount: number) {
if (amount < 0 || this.currentHP <= 0) {
return;
}
const mult = 1 - (this.status.healReduction?.value ?? 0);
this.currentHP = Math.min(
this.maxHP,
Math.round(this.currentHP + amount * mult)
);
this.redrawBars();
}
/**
* Cause this pokemon to deal damage
* Triggers effects that happen on attack, such as mana generation
*/
public dealDamage(
amount: number,
{ isAttack = false }: { isAttack?: boolean } = {}
) {
if (isAttack) {
// 5% of damage, capped at 2
this.addPP(Math.min(2, amount * 0.05));
this.redrawBars();
}
}
/**
* Cause this pokemon to take damage
*/
public takeDamage(
amount: number,
{
triggerEvents = true,
crit = false,
tint = 0xdddddd, // slight darken
}: {
triggerEvents?: boolean;
crit?: boolean;
/** Color change on hit. Defaults to slightly dark */ tint?: number;
} = {}
) {
if (amount < 0 || this.currentHP <= 0) {
return;
}
// trigger on-hit events like mana
if (triggerEvents) {
this.emit(PokemonObject.Events.Damage, amount);
this.addPP(Math.min(5, amount * 0.015));
}
const actualDamage = Math.min(this.currentHP, amount);
this.currentHP -= actualDamage;
this.redrawBars();
// display damage text
this.scene.add.existing(
new FloatingText(
this.scene,
this.x,
this.y,
`${amount}${crit ? '!' : ''}`,
crit ? 'large' : 'small'
)
);
// play flash effect
this.scene.add.tween({
targets: this,
duration: 66,
alpha: 0.9,
onStart: () => this.setTint(tint),
onComplete: () => this.clearTint(),
});
// TODO: move this somewhere more appropriate?
if (this.currentHP === 0) {
// destroy UI elements first
this.bars.destroy();
this.blindIcon.destroy();
this.sleepIcon.destroy();
this.emit(PokemonObject.Events.Dead);
// add fade-out animation
this.scene.add.tween({
targets: [this, this.attachments],
duration: 600,
ease: 'Exponential.Out',
alpha: 0,
onComplete: () => {
// disable and hide
// don't destroy because if any leftover events
// try to manipulate the Pokemon or object,
// they might crash the game
this.setActive(false);
this.setVisible(false);
// hide all attachments
this.attachments.forEach(object => object.setVisible(false));
// and all active timers
this.cancellableEvents.forEach(event => event.timer.remove());
// and any tweens that are running on this
this.scene.tweens
.getTweensOf(this, true)
.forEach(tween => tween.stop());
},
callbackScope: this,
});
}
}
public addPP(amount: number): this {
// move is active - can't gain PP
if (this.status.moveIsActive) {
return this;
}
if (this.maxPP && this.currentPP < this.maxPP) {
const mult = 1 - (this.status.ppReduction?.value ?? 0);
this.currentPP = Math.min(this.maxPP, this.currentPP + amount * mult);
}
return this;
}
public toggleOutline(): this {
this.isOutlined = !this.isOutlined;
this.outlineSprite.setVisible(this.isOutlined);
return this;
}
/**
* Adjust any of a Pokemon's stats by a provided %
*/
public changeStats(
changes: {
[k in ModifiableStat]?: StatChange;
},
duration?: number
) {
// apply any changes that are provided
(Object.entries(changes) as [ModifiableStat, StatChange][]).forEach(
([stat, change]) => {
this.statChanges[stat] = boundRange(
this.statChanges[stat] + change,
-8,
8
) as StatChange;
}
);
this.recalculateStats();
// if doesn't last forever, set the inverse after some time
if (duration) {
this.scene.time.addEvent({
delay: duration,
callback: () => {
this.changeStats({
attack: (changes.attack ? -changes.attack : 0) as StatChange,
defense: (changes.defense ? -changes.defense : 0) as StatChange,
specAttack: (changes.specAttack
? -changes.specAttack
: 0) as StatChange,
specDefense: (changes.specDefense
? -changes.specDefense
: 0) as StatChange,
speed: (changes.speed ? -changes.speed : 0) as StatChange,
});
},
});
}
}
/**
* Adjust any of a Pokemon's stats by a provided flat amount
*/
public addStats({
maxHP = 0,
attack = 0,
defense = 0,
specAttack = 0,
specDefense = 0,
speed = 0,
}: {
maxHP?: number;
attack?: number;
defense?: number;
specAttack?: number;
specDefense?: number;
speed?: number;
}) {
this.flatStatChanges.attack += attack;
this.flatStatChanges.defense += defense;
this.flatStatChanges.specAttack += specAttack;
this.flatStatChanges.specDefense += specDefense;
this.flatStatChanges.speed += speed;
// update max and current HP immediately
this.maxHP += maxHP;
this.currentHP += maxHP;
this.recalculateStats();
}
/**
* Recalculates the Pokemon's base stats based on their raw base stats,
* flat stat adjustments and stat multiplier stages
*/
private recalculateStats() {
/**
* Returns % change for a given stat stage
*
* stage + 4 / 4 for positive (ie. each boost gives a flat 25% increase)
* 4 / stage - 4 for negative (ie. each drop gives a 1/1.25 decrease)
*/
const getChange = (stage: StatChange) => {
// unaffected by stat reductions if immune to negative statuses
if (this.status.statusImmunity && stage < 0) {
return 1;
}
return stage > 0 ? (stage + 4) / 4 : 4 / Math.abs(stage - 4);
};
this.basePokemon = {
...this.basePokemon,
maxHP: this.maxHP,
attack:
(this.rawBasePokemon.attack + this.flatStatChanges.attack) *
getChange(this.statChanges.attack),
defense:
(this.rawBasePokemon.defense + this.flatStatChanges.defense) *
getChange(this.statChanges.defense),
specAttack:
(this.rawBasePokemon.specAttack + this.flatStatChanges.specAttack) *
getChange(this.statChanges.specAttack),
specDefense:
(this.rawBasePokemon.specDefense + this.flatStatChanges.specDefense) *
getChange(this.statChanges.specDefense),
speed:
(this.rawBasePokemon.speed + this.flatStatChanges.speed) *
getChange(this.statChanges.speed),
};
}
/**
* Add a status with a given duration
*
* @param status Name of the status
* @param duration Duration (overrides existing ones)
* @param value Some associated value. Either a number, or a modifier function
* @returns
*/
public addStatus(
status: Status,
duration: number,
value?: number | ((prev?: number) => number)
): this {
if (
// FIXME: don't hardcode bad statuses
(status === 'blind' ||
status === 'immobile' ||
status === 'paralyse' ||
status === 'poison' ||
status === 'sleep') &&
this.status.statusImmunity
) {
return this;
}
// disabling statuses can interrupt stuff
if (status === 'paralyse' || status === 'sleep') {
this.cancellableEvents.forEach(event => {
event.timer.remove();
event.onCancel?.();
});
}
this.status[status] = {
value:
typeof value === 'number' ? value : value?.(this.status[status]?.value),
duration,
};
this.redrawBars();
return this;
}
public updateStatuses(timeElapsed: number) {
if (this.status.poison) {
this.takeDamage(
Math.floor((this.maxHP * (this.status.poison?.value ?? 0)) / 100),
{
triggerEvents: false,
// purple flash for poison damage
tint: 0xc060c0,
}
);
}
// reduce the duration of each status
(Object.keys(this.status) as Status[]).forEach((s: Status) => {
const statusValue = this.status[s];
if (statusValue) {
statusValue.duration -= timeElapsed;
if (statusValue.duration <= 0) {
this.status[s] = undefined;
}
}
});
this.redrawBars();
}
}
|
35563daef505c07a111afc2d6635c461ed467813
|
TypeScript
|
robmillersoftware/encounter-manager
|
/src/networking/p2p/p2pmessage.ts
| 3.1875
| 3
|
export enum P2PTypes {
MESSAGE,
JOIN,
LEAVE,
BROADCAST,
DISCOVERED,
SYNC,
CONNECTED
}
interface P2PMessageData {
type: P2PTypes,
sourceAddress?: string,
message?: string
}
export class P2PMessage {
public source: string;
public message: string;
public type: P2PTypes;
constructor(data: P2PMessageData) {
this.source = data.sourceAddress ? data.sourceAddress : null;
this.message = data.message ? data.message : null;
this.type = data.type;
}
}
function parseJson(json: string): P2PMessage {
let obj: any = JSON.parse(json);
switch(+obj.type) {
case P2PTypes.MESSAGE:
return P2PMessageFactory.createMessage(obj.source, obj.message);
case P2PTypes.JOIN:
return P2PMessageFactory.createJoinMessage(obj.source);
case P2PTypes.LEAVE:
return P2PMessageFactory.createLeaveMessage(obj.source);
case P2PTypes.DISCOVERED:
return P2PMessageFactory.createDiscoveredMessage(obj.source, obj.message);
case P2PTypes.BROADCAST:
return P2PMessageFactory.createBroadcastMessage(obj.message, obj.s);
case P2PTypes.SYNC:
return P2PMessageFactory.createSyncMessage(obj.message);
case P2PTypes.CONNECTED:
return P2PMessageFactory.createConnectedMessage(obj.source);
}
}
export class P2PMessageFactory {
public static createMessage(src: string, msg: string): P2PMessage {
return new P2PMessage({sourceAddress: src, message: msg, type: P2PTypes.MESSAGE});
}
public static createJoinMessage(src: string): P2PMessage {
return new P2PMessage({sourceAddress: src, type: P2PTypes.JOIN});
}
public static createLeaveMessage(src: string): P2PMessage {
return new P2PMessage({sourceAddress: src, message: null, type: P2PTypes.LEAVE});
}
public static createDiscoveredMessage(src: string, msg: string): P2PMessage {
return new P2PMessage({sourceAddress: src, message: msg, type: P2PTypes.DISCOVERED});
}
public static createBroadcastMessage(msg: string, src: string): P2PMessage {
return new P2PMessage({sourceAddress: src, message: msg, type: P2PTypes.BROADCAST});
}
public static createSyncMessage(msg: string) {
return new P2PMessage({sourceAddress: null, message: msg, type: P2PTypes.SYNC});
}
public static createConnectedMessage(src: string): P2PMessage {
return new P2PMessage({sourceAddress: src, message: null, type: P2PTypes.CONNECTED});
}
public static createJoinJson(src: string): string {
return JSON.stringify(P2PMessageFactory.createJoinMessage(src));
}
public static createMessageJson(src: string, msg: string): string {
return JSON.stringify(P2PMessageFactory.createMessage(src, msg));
}
public static createBroadcastJson(msg: string, src: string): string {
return JSON.stringify(P2PMessageFactory.createBroadcastMessage(msg, src));
}
public static createSyncJson(msg: string): string {
return JSON.stringify(P2PMessageFactory.createSyncMessage(msg));
}
public static fromJSON(json: string): P2PMessage {
return parseJson(json);
}
public static toJSON(msg: P2PMessage): string {
return JSON.stringify(msg);
}
}
|
c4321f51d1f89a36bbf892067be76d67ca8a009e
|
TypeScript
|
namtx/reactshop
|
/src/ProductReducers.ts
| 2.84375
| 3
|
import { Reducer } from "redux"
import { IProductsState, ProductsActions, ProductsActionTypes } from "./ProductsTypes"
const initialProductsState: IProductsState = {
products: [],
productsLoading: false
}
export const productsReducer: Reducer<IProductsState, ProductsActions> = (state = initialProductsState, action) => {
switch (action.type) {
case ProductsActionTypes.LOADING: {
return {
...state,
productsLoading: true
}
}
case ProductsActionTypes.GETALL: {
return {
...state,
products: action.products,
productsLoading: false
}
}
}
return state;
}
|
80a899a8824a72438c360e54c603166f04136be2
|
TypeScript
|
Percegaroli/outboxup
|
/src/styles/theme.ts
| 2.515625
| 3
|
const colors = {
primary: '#AC6DDE',
lightGrey:'#F5F5F6',
dark: '#181820'
}
export const theme: ThemeInterface = {
typography: {
colors:{
primary: colors.primary,
light: colors.lightGrey
},
size: {
lg: '4.2rem',
md: '2.6rem',
sm: '1.6rem'
}
},
background: {
color: colors.dark
},
button: {
colors: {
primary: colors.primary
}
},
breakpoints: {
desktop: '1024px'
}
}
export interface ThemeInterface {
typography: {
colors: {
primary: string,
light: string;
},
size: {
lg: string;
md: string;
sm: string;
}
},
background: {
color: string;
}
button: {
colors: {
primary: string;
}
},
breakpoints: {
desktop: string ;
}
}
|
64a7a6f667cfce3fb4fbf29626d2120e9b4398c6
|
TypeScript
|
MariaCassandra/angular-basic
|
/src/app/contact/contact.component.ts
| 2.515625
| 3
|
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
contactForm: FormGroup = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(2)]),
email: new FormControl('', [Validators.required, Validators.email]),
subject: new FormControl('', Validators.required),
message: new FormControl('', [ Validators.required, Validators.minLength(10), Validators.maxLength(100) ]),
});
constructor() { }
ngOnInit(): void {}
get name() {
return this.contactForm.get('name');
}
get email() {
return this.contactForm.get('email');
}
get subject() {
return this.contactForm.get('subject');
}
get message() {
return this.contactForm.get('message');
}
get nameNotValid(){
return this.contactForm.get('name')?.invalid && this.contactForm.get('name')?.touched
}
get emailNotValid() {
return this.contactForm.get('email')?.invalid && this.contactForm.get('email')?.touched
}
get subjectNotValid() {
return this.contactForm.get('subject')?.invalid && this.contactForm.get('subject')?.touched
}
get messageNotValid() {
return this.contactForm.get('message')?.invalid && this.contactForm.get('message')?.touched
}
onSubmit(){
if( this.contactForm.invalid) {
return Object.values(this.contactForm.controls).forEach(control => {
control.markAsTouched();
});
} else if (this.contactForm.valid) {
alert ("Your message has been sent");
this.contactForm.reset();
}
}
}
|
35e965a73b79640113fadbe97f2479ed15d1a27f
|
TypeScript
|
vundev/Snake
|
/src/view/layout/SpriteSheet.ts
| 2.765625
| 3
|
///<reference path="IMovieClip.ts"/>
/**
* Created by Atanas Vasilev at avant.vasilev@gmail.com.
*/
namespace layout {
import MovieClip = PIXI.extras.MovieClip;
import Texture = PIXI.Texture;
export class SpriteSheet extends MovieClip implements IMovieClip {
protected _frames: Array<Frame>
constructor(frames: Array<Frame>) {
this._frames = frames
super(this.frames())
}
private frames(): Array<Texture> {
const frames: Array<Texture> = []
const length: number = this._frames.length
for (var i = 0; i < length; i++)
frames[i] = this._frames[i].texture
return frames
}
public gotoAndStopToLabel(label: string): void {
const length: number = this._frames.length
for (var i = 0; i < length; i++) {
if (this._frames[i].label == label) {
this.gotoAndStop(i)
break
}
}
}
public dispose(): void {
const length: number = this._frames.length
for (var i = 0; i < length; i++)
this._frames[i].dispose()
this._frames.length = 0
}
}
export class Frame {
public texture: Texture
public label: string
constructor(texture: Texture, label?: string) {
this.texture = texture
this.label = label
}
public dispose(): void {
this.texture = null
}
}
}
|
20998f78cac6bf71ac598cded0a9f16a86ac0cde
|
TypeScript
|
spitfiremunguia/viaro_nodeks
|
/src/services/auth.service.ts
| 2.671875
| 3
|
import jsonwebtoken from 'jsonwebtoken';
import {Credentials} from '../models/Credentials'
import {AuthRepository} from '../repositories/auth.repository';
import * as dotenv from 'dotenv';
dotenv.config();
// Sign token
export class AuthService
{
private authRepository:AuthRepository;
constructor(authRepository:AuthRepository)
{
this.authRepository=authRepository;
}
public createAuthToken(accountid:string):string{
// uses HMAC SHA256 as default encryption algorithm
const token=jsonwebtoken.sign({accountid},process.env.JWT_SECRET,{expiresIn:'1h'});
return token;
}
public tokenValid(token:string):boolean{
try{
jsonwebtoken.verify(token,process.env.JWT_SECRET);
return true;
}
catch{
return false;
}
}
public async verifyCredentials(credentials:Credentials)
{
try{
const result=await this.authRepository.VerifyCredentials(credentials);
// result is an array
if(result){
// create token
const newToken=this.createAuthToken(result.Id);
return {
accountid:result.Id,
token:newToken
}
}
return null;
}
catch(e){
console.log(`ERROR AT SERVICE: ${e}`);
}
}
}
|
cf52c89e27bc839a973f676a30a4548b9ce127af
|
TypeScript
|
aga555/chart-api
|
/src/app/components/chartjs-utils.ts
| 2.625
| 3
|
// npm install chartjs --save
import * as Chart from 'chart.js';
// npm install chart.piecelabel.js --save
import 'chart.piecelabel.js';
/**
* this is simply used to init our chartjs
*
*/
export function initChart() {
const fontFamily = 'Work Sans, sans-serif';
// set defaults
Chart.defaults.global.defaultFontFamily = fontFamily;
Chart.defaults.global.tooltips.titleFontSize = 14;
Chart.defaults.global.tooltips.titleMarginBottom = 4;
Chart.defaults.global.tooltips.displayColors = false;
Chart.defaults.global.tooltips.bodyFontSize = 12;
Chart.defaults.global.tooltips.xPadding = 10;
Chart.defaults.global.tooltips.yPadding = 8;
Chart.defaults.global.tooltips.enabled = true;
}
/**
* this is used to render our chart on the passed in canvas
* @param canvas
* @param options
*/
export function pieChart(canvas: HTMLCanvasElement, options: {
labels: string[],
dataset: {data: number[],
backgroundColor?: string[],
hoverBackgroundColor?: string[],
borderColor?: string,
borderWidth: number
}
}) {
canvas.setAttribute('height', '340');
const data = {
labels: options.labels,
datasets: [{
...options.dataset,
borderColor: '#ffffff',
borderWidth: 2
}]
};
return new Chart(canvas, {
type: 'doughnut',
data: data,
options: {
legend: {
display: true,
position: 'right',
fullWidth: true,
labels: {
boxWidth: 10
}
},
tooltips: {
enabled: true,
mode: 'point'
},
animation: {
animateScale: true
},
responsive: true,
}
});
}
|