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
|
|---|---|---|---|---|---|---|
6b3357476515d008cc215d15b458702398bb90c1
|
TypeScript
|
d0rianb/RunAndGun
|
/src/grid.ts
| 3.515625
| 4
|
interface NeihboorObject {
top?: Cell
right?: Cell
bottom?: Cell
left?: Cell
}
class Grid {
rows: number
cols: number
cells: Array<Cell>
constructor(cols: number, rows: number) {
this.rows = rows
this.cols = cols
this.cells = []
this.createCells()
this.defineNeighboors()
}
createCells(): void {
for (let col = 0; col < this.cols; col++) {
for (let row = 0; row < this.rows; row++) {
this.cells.push(new Cell(row, col))
}
}
}
getCell(x: number, y: number): Cell {
let cell = this.cells.filter(cell => {
return cell.x === x && cell.y === y
})
if (cell.length !== 0) {
return cell[0]
} else {
console.error(`La cellule (x: ${x}, y: ${y}) n'existe pas`)
}
}
updateCell(newCell: Cell): void {
if (!this.cells.includes(newCell)) return
console.log(newCell)
this.defineNeighboors()
this.cells[this.cells.indexOf(newCell)] = newCell
}
defineNeighboors(): void {
this.cells.forEach(cell => {
cell.neighboor.top = cell.y >= 1 ? this.cells.filter(othercell => othercell.x <= cell.x && othercell.x + othercell.width > cell.x && othercell.y === cell.y - cell.height)[0] : null
cell.neighboor.bottom = cell.y <= this.rows - 1 ? this.cells.filter(othercell => othercell.x <= cell.x && othercell.x + othercell.width > cell.x && othercell.y === cell.y + cell.height)[0] : null
cell.neighboor.left = cell.x >= 1 ? this.cells.filter(othercell => othercell.y <= cell.y && othercell.y + othercell.height > cell.y && othercell.x === cell.x - cell.width)[0] : null
cell.neighboor.right = cell.x <= this.rows - 1 ? this.cells.filter(othercell => othercell.y <= cell.y && othercell.y + othercell.height > cell.y && othercell.x === cell.x + cell.width)[0] : null
})
}
}
class Cell {
x: number
y: number
width: number
height: number
neighboor: NeihboorObject
active: boolean
constructor(x: number, y: number, width = 1, height = 1) {
this.x = x
this.y = y
this.width = width
this.height = height
this.neighboor = {}
this.active = false
}
toggleActive(bool?: boolean): void {
if (bool) {
this.active = bool
} else {
this.active = !this.active
}
}
}
export { Grid, Cell }
|
7d7a2fbd4dd124e76e291d051e6d1d1b30e46df9
|
TypeScript
|
just-do-halee/rusultts
|
/src/rusultts.ts
| 3.8125
| 4
|
// (c) 2021 just-do-halee(=Hwakyeom Kim)
/**
* kind of internal subject(ok or err)
*/
export type ResultObject<T> = {
readonly error?: Error;
readonly value: T;
};
/**
* international interface
*/
export interface IResult<T, E> {
readonly isOk: boolean;
readonly isErr: boolean;
// Returning internal value or Throw an error
unwrap(): T | never;
unwrap_or(inputValue: T): T;
unwrap_or_else(op: (innerValue: E) => T): T;
unwrap_err(): E | never;
}
/**
* ## Examples
*```ts
* function divide(a: number, b: number): ResultBox<number, number> {
* if (b === 0) {
* return Err.new(`b cannot be 0.`, b);
* }
* return Ok.new(a / b);
* }
*
* const ok = divide(4, 2).unwrap() === 2; // true
* const err = divide(4, 0);
* console.log(err.isErr); // true
*
* try {
*
* err.unwrap();
*
* } catch(e) {
* const value = Err.eSplit(e)[1]; // "0"
* }
*```
*/
export abstract class ResultBox<T, E> implements IResult<T, E> {
readonly isOk: boolean;
readonly isErr: boolean;
protected constructor(protected readonly val: ResultObject<T | E>) {
this.isOk = val.error === undefined;
this.isErr = !this.isOk;
}
/**
*
* @returns if isErr is true, throw new `Error` with `${message}:--> ${JSON.stringify(value<E>)}` or returns `value<T>`
* @that `Error` (this can be splited by eSplit)
*/
unwrap(): T | never {
if (this.val.error) {
this.val.error.message += ':--> ' + JSON.stringify(this.val.value);
throw this.val.error;
} else {
return this.val.value as T;
}
}
/**
*
* @param inputValue
* @returns if isErr is true, returns `inputValue<T>` or stored `value<T>`
*/
unwrap_or(inputValue: T): T {
if (this.isErr) {
return inputValue;
} else {
return this.val.value as T;
}
}
/**
*
* @param {callback} op - callback (innerValue: `E`) => `T`
* @returns if isOk is true, returns `value<T>` or computes it from a operating function, contained `value<E> to specific T value`
*/
unwrap_or_else(op: (innerValue: E) => T): T {
if (this.val.error) {
return op(this.val.value as E);
} else {
return this.val.value as T;
}
}
/**
*
* @returns if isOk is true, throw new `Error` or `value<E>`
* @that `Error` === 'this is not an Error:--> ' + JSON.stringify(`value<T>`) (this can be splited by eSplit)
*/
unwrap_err(): E | never {
if (this.val.error) {
return this.val.value as E;
} else {
throw new Error(
'this is not an Error:--> ' + JSON.stringify(this.val.value)
);
}
}
}
/**
* ## Examples
*```ts
* function divide(a: number, b: number): ResultBox<number, number> {
* if (b === 0) {
* return Err.new(`b cannot be 0.`, b);
* }
* return Ok.new(a / b);
* }
*
* const ok = divide(4, 2).unwrap() === 2; // true
* const err = divide(4, 0);
* console.log(err.isErr); // true
*
* try {
*
* err.unwrap();
*
* } catch(e) {
* const value = Err.eSplit(e)[1]; // "0"
* }
*```
*/
export class Ok<T, E> extends ResultBox<T, E> {
private constructor(value: T) {
super({ value });
}
static new<T, E>(val: T) {
return new Ok<T, E>(val);
}
}
/**
* ## Examples
*```ts
* function divide(a: number, b: number): ResultBox<number, number> {
* if (b === 0) {
* return Err.new(`b cannot be 0.`, b);
* }
* return Ok.new(a / b);
* }
*
* const ok = divide(4, 2).unwrap() === 2; // true
* const err = divide(4, 0);
* console.log(err.isErr); // true
*
* try {
*
* err.unwrap();
*
* } catch(e) {
* const value = Err.eSplit(e)[1]; // "0"
* }
*```
*/
export class Err<T, E> extends ResultBox<T, E> {
private constructor(message: string, value: E) {
super({ error: new Error(message), value });
}
static new<T, E>(msg: string, val: E) {
return new Err<T, E>(msg, val);
}
/**
*
* @param e Error | unknown
* @returns [`error.message`, `value<E>`] or ***[`string`, null] (not found)***
*/
static eSplit<E>(e: Error | unknown): [string, E | null] {
if (!(e instanceof Error)) {
return ['', null];
}
let val: string[] = e.message.split(':--> ', 2);
if (val.length !== 2) {
return [val[0] || '', null];
}
return [val[0], JSON.parse(val[1])];
}
}
/**
* easy one, has value of Error as `null`
*/
export type Result<T> = ResultBox<T, null>;
/**
* error's message pair object
* ## Example
* ```ts
* const mp: MessagePair = {
* notFound: 'not found',
* somethingWrong: 'something wrong...',
* wrongHeader: 'please fix your header.'
* }
* ```
*/
export type MessagePair = { [key: string]: string };
/**
* creates errors that have already been set.
* ## Example
* ```ts
* const err = createErrorSet({
* notFound: 'not found',
* somethingWrong: 'something wrong...',
* wrongHeader: 'please fix your header.'
* });
*
* err.new('wrongHeader'); // === Err.new('please fix your header.', null)
* ```
*/
export class ErrSet<M extends MessagePair> {
constructor(public readonly messagePair: M) {}
/**
* creates and return the error that have already been set.
*/
new<T, E>(errorMessageType: keyof M): Err<T, null>;
new<T, E>(errorMessageType: keyof M, val: E): Err<T, E>;
new<T>(errorMessageType: keyof M, val?: any): Err<T, any> {
return Err.new(
this.messagePair[errorMessageType],
val === undefined ? null : val
);
}
/**
*
* @param {Error} e the error in the scope of try~catch.
* @param {MessagePair} errorMessageType in the MessagePair.
* @returns if `e` is not Error type, return Err<, Type>, or returns Ok<string | undefined,> which means `e` equals the error of errorMessageType then returns `error value<E>` or `undefined`.
*
* ## Example
*```ts
* const test = divide(4, 0);
* try {
* test.unwrap();
* } catch (e) {
* const val = err.match(e, 'dividedByZero').unwrap();
* if(val) {
* return val; // = 0 <- number type
* } else {
* return 'unexpected error.';
* }
* }
* ```
*/
match<E>(
e: Error | unknown,
errorMessageType: keyof M
): ResultBox<E | undefined, unknown> {
if (!(e instanceof Error)) {
return Err.new(`e is unknown type:`, e);
}
const [message, value] = Err.eSplit(e);
return Ok.new(
message === this.messagePair[errorMessageType] ? (value as E) : undefined
);
}
}
/**
* creates errors that have already been set.
* ## Example
* ```ts
* const err = createErrorSet({
* notFound: 'not found',
* somethingWrong: 'something wrong...',
* wrongHeader: 'please fix your header.'
* });
*
* err.new('wrongHeader'); // === Err.new('please fix your header.', null)
* ```
*/
export const createErrorSet = <M extends MessagePair>(
messagePair: M
): ErrSet<M> => {
return new ErrSet(messagePair);
};
|
a0124133d2e1a9dc930abfc4c9dff0a5f8e24713
|
TypeScript
|
oliwheeler/lage
|
/src/logger/TaskLogger.ts
| 2.71875
| 3
|
import { Logger } from "./Logger";
import { TaskData } from "./LogEntry";
export class TaskLogger {
logger: Logger;
constructor(private pkg: string, private task: string) {
this.logger = new Logger();
}
info(msg: string, data?: TaskData) {
this.logger.info(msg, { package: this.pkg, task: this.task, ...data });
}
warn(msg: string, data?: TaskData) {
this.logger.warn(msg, { package: this.pkg, task: this.task, ...data });
}
error(msg: string, data?: TaskData) {
this.logger.error(msg, { package: this.pkg, task: this.task, ...data });
}
verbose(msg: string, data?: TaskData) {
this.logger.verbose(msg, { package: this.pkg, task: this.task, ...data });
}
silly(msg: string, data?: TaskData) {
this.logger.silly(msg, { package: this.pkg, task: this.task, ...data });
}
getLogs() {
return this.logger.logs;
}
}
|
3bcfe5f1277c2ebb789a13dfdac409788254ac24
|
TypeScript
|
keptn-contrib/notification-service
|
/src/subscribers/subscriber.service.ts
| 2.5625
| 3
|
import { Injectable, Inject } from '@nestjs/common';
import { ISubscription } from './subscriber.type';
import { Logger } from 'winston';
import { Slack } from './subscription/slack';
import { Teams } from './subscription/teams';
import { WebexTeams } from './subscription/webexTeams';
import { InjectConfig, ConfigService } from 'nestjs-config';
@Injectable()
export class SubscriberService {
private readonly subscribers: ISubscription[] = [];
constructor(
@Inject('winston') private readonly logger: Logger,
@InjectConfig() private readonly config: ConfigService,
) {
this.logger.debug('SubscriberService constructor. Loading subscribers');
const slackUrl = this.config.get('url.slack');
this.logger.info(`The slack URL is ${slackUrl}`);
if (slackUrl) {
this.subscribers.push(new Slack(logger, slackUrl));
}
const teamsUrl = this.config.get('url.teams');
this.logger.info(`The teams URL is ${teamsUrl}`);
if (teamsUrl) {
this.subscribers.push(new Teams(logger, teamsUrl));
}
const webexTeamsUrl = this.config.get('url.webexTeams');
this.logger.info(`The WebexTeams URL is ${webexTeamsUrl}`);
if (webexTeamsUrl) {
this.subscribers.push(new WebexTeams(logger, webexTeamsUrl));
}
this.logger.debug(
`SubscriberService constructor. Finished loading ${this.subscribers.length} subscribers`,
);
}
getSubscribers(): ISubscription[] {
return this.subscribers;
}
}
|
e62b447b3c0f34e7818288b351d55b293f5f5a48
|
TypeScript
|
data-driven-forms/react-forms
|
/packages/react-form-renderer/src/data-types/data-types.d.ts
| 2.703125
| 3
|
export type DataType = 'integer'|'float'|'number'|'boolean'|'string';
interface IdataTypes {
INTEGER: 'integer';
FLOAT: 'float';
NUMBER: 'number';
BOOLEAN: 'boolean';
STRING: 'string';
}
declare const dataTypes: IdataTypes;
export default dataTypes;
|
b6a0ef0d12960440db9720463ea80290697a0029
|
TypeScript
|
DevOstium/paginacao-ng-bootstrap
|
/src/app/pages/usuarios/usuarioADs/pipe/fitrarPorNome.pipe.ts
| 2.65625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { Usuario } from '../../domain/usuario.model';
@Pipe({name : 'filtroPorNome'})
export class FiltroPorNome implements PipeTransform {
transform(usuariosAD: Usuario[], nomeUsuario : string) {
nomeUsuario = this.removerAcentos(nomeUsuario.toLowerCase());
if(nomeUsuario){
return usuariosAD.filter( usuario => this.removerAcentos(usuario.name.toLowerCase()).includes(nomeUsuario) );
} else {
return usuariosAD;
}
}
removerAcentos( s : string ) {
return s.normalize('NFD').replace(/[\u0300-\u036f|\u00b4|\u0060|\u005e|\u007e]/g, "")
}
}
|
16ade24a78625451e0702e49de8c3b47dee2a40b
|
TypeScript
|
IHateWait/HateWait-Web
|
/src/lib/utils/businessHourModule.ts
| 2.96875
| 3
|
import React from 'react';
function businessHourModule(
same: boolean,
monBreak: string,
tueBreak: string,
wedBreak: string,
thuBreak: string,
friBreak: string,
satBreak: string,
sunBreak: string,
startTime: string,
endTime: string,
monStartTime: string,
monEndTime: string,
tueStartTime: string,
tueEndTime: string,
wedStartTime: string,
wedEndTime: string,
thuStartTime: string,
thuEndTime: string,
friStartTime: string,
friEndTime: string,
satStartTime: string,
satEndTime: string,
sunStartTime: string,
sunEndTime: string,
){
if(same === true){
let breakDays = '';
if(monBreak === 'break'){
breakDays += "월";
}
if(tueBreak === 'break'){
breakDays += ", "+"화";
}
if(wedBreak === 'break'){
breakDays += ", "+"수";
}
if(thuBreak === 'break'){
breakDays += ", "+"목";
}
if(friBreak === 'break'){
breakDays += ", "+"금";
}
if(satBreak === 'break'){
breakDays += ", "+"토";
}
if(sunBreak === 'break'){
breakDays += ", "+"일";
}
return(`${startTime} - ${endTime} (휴무 요일: ${breakDays})`);
}
else{
let businessHour = "";
let breakDays = "";
if(monBreak === ''){
businessHour += `월요일:${monStartTime} - ${monEndTime}\n`;
}
else{
breakDays += "월, ";
}
if(tueBreak === ''){
businessHour += `화요일:${tueStartTime} - ${tueEndTime}\n`;
}
else{
breakDays += "화, ";
}
if(wedBreak === ''){
businessHour += `수요일:${wedStartTime} - ${wedEndTime}\n`;
}
else{
breakDays += "수, ";
}
if(thuBreak === ''){
businessHour += `목요일:${thuStartTime} - ${thuEndTime}\n`;
}
else{
breakDays += "목, ";
}
if(friBreak === ''){
businessHour += `금요일:${friStartTime} - ${friEndTime}\n`;
}
else{
breakDays += "금, ";
}
if(satBreak === ''){
businessHour += `토요일:${satStartTime} - ${satEndTime}\n`;
}
else{
breakDays += "토, ";
}
if(sunBreak === ''){
businessHour += `일요일:${sunStartTime} - ${sunEndTime}\n`;
}
else{
breakDays += "일";
}
return(`${businessHour} (휴무 요일: ${breakDays})`)
}
}
export default businessHourModule;
|
d68f94dbdfc857c07bd65cd10dabff7ec37a00b1
|
TypeScript
|
DavidKk/goaseasy
|
/@goaseasy/workweixin-robot/types/robot.ts
| 2.6875
| 3
|
export interface Settings {
apikey: string
}
export type MessageType = 'text' | 'markdown' | 'news'
export type SendMessageParams<T extends MessageType> = T extends 'text'
? {
msgtype: T
text: {
mentioned_list?: string[]
mentioned_mobile_list?: string[]
content: string
}
}
: T extends 'markdown'
? {
msgtype: T
markdown: {
content: string
}
}
: T extends 'news'
? {
msgtype: T
articles: Array<{
title: string
description?: string
url: string
picurl?: string
}>
}
: null
|
18b7b8af9901f3ce09f26a9108c8004b8879bd18
|
TypeScript
|
NanoWorkspace/core
|
/src/app/Embed.ts
| 2.703125
| 3
|
import Discord from "discord.js"
import bot from "../globals/bot"
import Logger from "./Logger"
Logger.load("file", __filename)
export interface EmbedTemplates {
default: Discord.MessageEmbedOptions
success: Discord.MessageEmbedOptions
error: Discord.MessageEmbedOptions
log: Discord.MessageEmbedOptions
[k: string]: Discord.MessageEmbedOptions
}
export default class Embed extends Discord.MessageEmbed {
static templates = bot.embedTemplates || ({} as EmbedTemplates)
// static byMessageEmbed(embed: Discord.MessageEmbed): Embed {
//
// }
static log(description?: string) {
return new Embed().setTemplate("log", description)
}
static error(description?: string) {
return new Embed().setTemplate("error", description)
}
static success(description?: string) {
return new Embed().setTemplate("success", description)
}
static default(description?: string) {
return new Embed(description)
}
constructor(description?: string) {
super()
this.setTemplate("default", description)
}
setAuthorName(name: Discord.StringResolvable): this {
return super.setAuthor(name, this.author?.iconURL, this.author?.url)
}
setFooterText(text: Discord.StringResolvable): this {
return super.setFooter(text, this.footer?.iconURL)
}
setTemplate(templateName: string, description?: string): this {
const template = Embed.templates[templateName.toLowerCase()]
if (template) {
const Globals = require("./Globals")
const templatingRegex = /\{\{\s*(.+)\s*}}/g
const templatingReplacer = (fm: string, g: string) => eval(g)
Object.entries(template).forEach(([name, value]) => {
// @ts-ignore
const method = this[`set${name[0].toUpperCase() + name.slice(1)}`]
if (value === null) {
method.bind(this)()
} else if (typeof value === "string") {
method.bind(this)(value.replace(templatingRegex, templatingReplacer))
} else if (Array.isArray(value)) {
if (name === "fields") {
// fields
value.forEach((field: Discord.EmbedFieldData) => {
this.addField(
field.name.replace(templatingRegex, templatingReplacer),
field.value.replace(templatingRegex, templatingReplacer),
field.inline
)
})
} else {
// files
this.attachFiles(value)
}
} else if (value && typeof value === "object") {
if (name === "author") {
this.setAuthor(
// @ts-ignore
value.name?.replace(templatingRegex, templatingReplacer) ||
this.author?.name,
// @ts-ignore
value.iconURL?.replace(templatingRegex, templatingReplacer) ||
this.author?.iconURL,
// @ts-ignore
value.url || this.author?.url
)
} else {
// footer
this.setFooter(
// @ts-ignore
value.text.replace(templatingRegex, templatingReplacer) ||
this.footer?.text,
// @ts-ignore
value.iconURL?.replace(templatingRegex, templatingReplacer) ||
this.footer?.iconURL
)
}
}
})
}
if (description) this.setDescription(description)
return this
}
}
|
79b33ebc7363f1a2c6e045f047907b8cdae08d56
|
TypeScript
|
luania/Canvas-TypeScript
|
/6-FrictionForce/script/Ball.ts
| 3
| 3
|
import { PVector } from "./PVector";
export class Ball {
color: string = "rgba(0, 0, 0, 0.5)";
position: PVector = new PVector(10, 10);
speed: PVector = new PVector(0, 0);
acceleration: PVector = new PVector(0, 0);
size: number = 1;
mass: number = 1;
step() {
this.speed.add(this.acceleration);
this.position.add(this.speed);
}
checkBounds(canvas: HTMLCanvasElement) {
if (this.position.x > canvas.width - this.size || this.position.x < this.size) {
this.speed.x *= -1;
this.position.add(this.speed);
}
if (this.position.y > canvas.height - this.size || this.position.y < this.size) {
this.speed.y *= -1;
this.position.add(this.speed);
}
}
applyForce(force: PVector) {
this.acceleration.add(PVector.div(force, this.mass));
return this;
}
}
|
c81f3538a87de20a34ec99b316a723e342efd18b
|
TypeScript
|
Pintec10/Angular_math-speed-game
|
/src/app/answer-highlight.directive.ts
| 2.59375
| 3
|
import { Directive, ElementRef } from '@angular/core';
import { NgControl } from '@angular/forms';
import { map, filter } from 'rxjs/operators';
@Directive({
selector: '[appAnswerHighlight]'
})
export class AnswerHighlightDirective {
constructor(
private el: ElementRef, //by dependency injection, gives a ref to the element the directive is applied to
private controlName: NgControl //gives ref to a FormControlName object, which has a copy of the content of the FormControl of the element to which the directive is applied
) { }
//if answer is correct, the input box will have a green background
ngOnInit() {
this.controlName.control?.parent?.valueChanges
.pipe(
map(({ firstNumber, secondNumber, answer }) => (firstNumber + secondNumber === parseInt(answer))),
)
.subscribe((value) => {
if (value === true) {
this.el.nativeElement.classList.add('correct');
} else {
this.el.nativeElement.classList.remove('correct');
}
});
}
}
|
c712f6fbbe352c50039c65848d2ad6c5a01aaa3b
|
TypeScript
|
mixrich/scripts
|
/src/utils/duration/duration.ts
| 3.3125
| 3
|
export function duration(timeInSeconds: number): string {
const seconds = timeInSeconds % 60;
const res: string[] = [];
if (seconds) {
res.push(`${seconds}sec`);
}
const minutes = Math.floor(timeInSeconds / 60) % 60;
if (minutes) {
res.push(`${minutes}min`);
}
const hours = Math.floor(timeInSeconds / 60 / 60);
if (hours) {
res.push(`${hours}h`);
}
return res.reverse().join(' ');
}
|
52930b227e3ac0767561f545801e24975a07f64d
|
TypeScript
|
suconghou/code-snippet
|
/js/fnv1a.ts
| 3.390625
| 3
|
// modified from https://github.com/sindresorhus/fnv1a
const base62Map = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// fnv1a 64 to base62
export default (str: string) => {
return base62(Number(fnv1a64(str)));
}
export const base62 = (num: number): string => {
const arr: Array<string> = [];
while (true) {
const i = num % 62
arr.unshift(base62Map.charAt(i))
num = Math.floor(num / 62)
if (num <= 0) {
break
}
}
return arr.join('')
}
export const fnv1a64 = (str: string): bigint => {
let hash = 14_695_981_039_346_656_037n;
const fnvPrime = 1_099_511_628_211n;
const bytes = (new TextEncoder()).encode(str)
for (let index = 0; index < bytes.length; index++) {
const characterCode = bytes[index];
hash ^= BigInt(characterCode);
hash = BigInt.asUintN(64, hash * fnvPrime);
}
return hash;
}
export const fnv1a32 = (str: string): number => {
let hash = 2_166_136_261;
const bytes = (new TextEncoder()).encode(str)
for (let index = 0; index < bytes.length; index++) {
const characterCode = bytes[index];
hash = (hash ^ characterCode) >>> 0; // 每一步的结果都要转化为 uint32
hash = (hash + (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24)) >>> 0; // 使用加法而不是乘法才没问题
}
return hash;
}
|
132b16d29181e5ef5018e0f2ad6a39232cd56556
|
TypeScript
|
mareksl/ts-backend-playground
|
/src/models/contact.model.ts
| 3.140625
| 3
|
import { Document, Schema, Model, model, SchemaDefinition } from 'mongoose';
import validator from 'validator';
export interface IContact extends Document {
type: string;
firstName?: string;
lastName?: string;
title?: string;
email?: string;
phone?: string;
link?: string;
}
// HACK
interface ContactSchema {
type: { [key: string]: any };
firstName?: { [key: string]: any };
lastName?: { [key: string]: any };
title?: { [key: string]: any };
email?: { [key: string]: any };
phone?: { [key: string]: any };
link?: { [key: string]: any };
}
const contactSchema = new Schema(<SchemaDefinition & ContactSchema>{
type: {
type: String,
required: true,
trim: true,
enum: ['person', 'general']
},
firstName: {
type: String,
required: function() {
return this.type === 'person';
},
trim: true
},
lastName: {
type: String,
trim: true
},
title: {
type: String,
trim: true,
required: function() {
return this.type === 'general';
}
},
email: {
type: String,
trim: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
},
required: function() {
return !(this.phone || this.link);
}
},
phone: {
type: String,
trim: true,
validate: {
validator: (val: string) => validator.isMobilePhone(val, 'any'),
message: '{VALUE} is not a valid phone number'
},
required: function() {
return !(this.email || this.link);
}
},
link: {
type: String,
trim: true,
validate: {
validator: validator.isURL,
message: '{VALUE} is not a valid URL'
},
required: function() {
return !(this.email || this.phone);
}
}
});
const Contact: Model<IContact> = model<IContact>('Contact', contactSchema);
export default Contact;
|
b9cc5da69fd3e1913217fcd9be4dbafd2d69e7ee
|
TypeScript
|
kouz75/jovo-framework
|
/jovo-platforms/jovo-platform-twilioautopilot/test/AutopilotResponse.test.ts
| 2.5625
| 3
|
import { AutopilotResponse } from '../src/core/AutopilotResponse';
process.env.NODE_ENV = 'UNIT_TEST';
describe('test hasSessionEnded()', () => {
let response: AutopilotResponse;
beforeEach(() => {
response = new AutopilotResponse();
});
test('action contains Listen action', () => {
response.actions = [
{
listen: true,
},
];
expect(response.hasSessionEnded()).toBe(false);
});
test('action contains Redirect action', () => {
response.actions = [
{
redirect: 'test',
},
];
expect(response.hasSessionEnded()).toBe(false);
});
test('action contains Collect action', () => {
response.actions = [
{
collect: {}, // actual content of the action is not important
},
];
expect(response.hasSessionEnded()).toBe(false);
});
test('action does not contain Listen, Redirect, or Collect action', () => {
response.actions = [
{
say: 'hello World',
},
];
expect(response.hasSessionEnded()).toBe(true);
});
});
|
b0a3fcb3a53bb339c617fc6d2abe349c356c3a94
|
TypeScript
|
TrendingTechnology/sunrise-1
|
/src/interfaces/Deref.test.ts
| 3.328125
| 3
|
import { isDereferencable, deref } from './Deref'
describe('Deref', () => {
test('isDereferencable should check if the value satisfyes the Dereferencable interface', () => {
const x = { deref: () => 1 }
const y = 1
const z = { a: 1 }
expect(isDereferencable(x)).toBe(true)
expect(isDereferencable(y)).toBe(false)
expect(isDereferencable(z)).toBe(false)
})
describe('deref', () => {
test('should return the inner value of the dereferenced object', () => {
const x = { deref: () => 1 }
expect(deref(x)).toBe(1)
})
test('should return the value itself if not dereferencable', () => {
const x = { a: 'just a value' }
expect(deref(x)).toBe(x)
})
})
})
|
0f0e76794c84711f31e6440c0f9e348884531fc5
|
TypeScript
|
ngnijland/adventofcode2020
|
/src/day9/index.ts
| 3.359375
| 3
|
import fs from "fs";
import assert from "assert";
import path from "path";
function validatePart(numbers: number[], sum: number): boolean {
for (let i = 0; i < numbers.length; i++) {
for (let j = i + 1; j < numbers.length; j++) {
const a = numbers[i];
const b = numbers[j];
if (a !== b && a + b === sum) {
return true;
}
}
}
return false;
}
function findWeakness(program: number[], preamble: number): number {
for (let i = preamble; i < program.length; i++) {
if (!validatePart(program.slice(i - preamble, i), program[i])) {
return program[i];
}
}
throw new Error("No weaknesses");
}
function contiguousSum(program: number[], sum: number): number[] {
for (let i = 0; i < program.length; i++) {
let total: number = 0;
const list: number[] = [];
while (total < sum) {
const number = program[i + list.length];
total = total + number;
list.push(number);
if (total === sum) {
return list;
}
}
}
throw new Error(`No contiguous list of numbers add up to ${sum}`);
}
const program = [
35,
20,
15,
25,
47,
40,
62,
55,
65,
95,
102,
117,
150,
182,
127,
219,
299,
277,
309,
576,
];
const weakness = 127;
assert.strictEqual(findWeakness(program, 5), weakness);
assert.deepStrictEqual(contiguousSum(program, weakness), [15, 25, 47, 40]);
fs.readFile(
path.join(__dirname, "..", "..", "src", "day9", "input"),
"utf8",
function (err: NodeJS.ErrnoException, data: string) {
if (err) throw err;
const input = data.split("\n").map(Number);
const solutionA = findWeakness(input, 25);
const weakness = contiguousSum(input, solutionA).sort((a, b) => a - b);
const solutionB = weakness[0] + weakness[weakness.length - 1];
console.log({ solutionA, solutionB });
}
);
|
ffb3422a39ceec536438fbe5d7edad676bdbef1c
|
TypeScript
|
Andret0701/GY521
|
/CurrentBestmain.ts
| 2.875
| 3
|
//let offSets: number[] = [2791,593,1065,122,-29,1] // GY-521
let offSets: number[] = [-2694,593,485,75,15,21] // MPU-6050
let selfCal: boolean = microbit_GY521.calibrate_Sensors(offSets); // required to increase accuracy of readings
if (!selfCal) {
basic.showLeds(`
# . . # .
# . # # #
# . . # .
# . # # #
# . . # .
`)
basic.pause(30000);
}
let y: number = 0
let speed: number = 0
// Motor state setup
// Use to trim motors if one is stronger than the other
let leftMotorBias = 0;
let rightMotorBias = 0;
// Manage baseline motor speed ie the value from which motor values have an affect
let motorMin = 140;
// PID state setup
let setPoint = -1;// Now set dynamically on start up
let Kp = 100; //102
let Ki = 76; //68
let Kd = 52; //60
let outMax = 1023;
let outMin = -1023;
let lastInput = 0;
let lastTime = 0;
let accumulative_error : number = 0
let last_error: number = 0
let Actuator_Output: number = 0
led.plotBarGraph(1000, 1023);
basic.pause(500)
led.plotBarGraph(750, 1023);
basic.pause(500)
led.plotBarGraph(500, 1023);
basic.pause(500)
led.plotBarGraph(250, 1023)
basic.pause(500)
basic.showLeds(`
. # . . .
# . . # .
# . . . .
# . . # .
. # . . .
`)
input.onButtonPressed(Button.A, () => {
setPoint -= 1;
});
input.onButtonPressed(Button.B, () => {
setPoint += 1;
});
let skipDebug : number = 0;
setPoint = microbit_GY521.computeY();
while (1) {
basic.pause(2); // keep to 200hz
y = microbit_GY521.computeY()
if (y > 360) {
basic.showLeds(`
# . . . .
. # . # .
. # . . .
. # . # .
# . . . .
`);
break;
}
speed = PID(y)
skipDebug++;
if (y > -80 && y < 80 ) {
// This prevents error in the PID from accumulating when robot laying down
motorController(speed)
} else {
motorStop()
}
}
function PID(input:number) : number
{
let now = game.currentTime(); // in milliseconds
let timeChange = (now - lastTime)/1000; //convert to seconds
/*
// PID algorithm
Actuator_Output =
Kp * (distance from goal)
+ Ki * (accumulative error)
+ Kd * (change in error)
*/
let distance_from_goal: number = (setPoint - input) // P
accumulative_error = accumulative_error + (distance_from_goal*timeChange) // I
let change_in_error = (distance_from_goal- last_error)/timeChange // D
last_error = distance_from_goal
Actuator_Output = Kp * distance_from_goal + Ki * accumulative_error + Kd * change_in_error
// A base motor speed to over come motor inertia
if (Actuator_Output < 0) {
Actuator_Output = Actuator_Output - motorMin;
}
else {
Actuator_Output = Actuator_Output + motorMin;
}
// Clamp actuator output to motor range
if (Actuator_Output > outMax) {
Actuator_Output = outMax
}
if (Actuator_Output < outMin) {
Actuator_Output = outMin
}
lastInput = input;
lastTime = now;
return Actuator_Output;
}
function motorStop() {
pins.digitalWritePin(DigitalPin.P13, 0)
pins.digitalWritePin(DigitalPin.P14, 0)
pins.digitalWritePin(DigitalPin.P15, 0)
pins.digitalWritePin(DigitalPin.P16, 0)
}
function motorController(speed: number)
{
if (speed > 0) {
pins.digitalWritePin(DigitalPin.P13, 1)
pins.digitalWritePin(DigitalPin.P14, 0)
pins.digitalWritePin(DigitalPin.P15, 1)
pins.digitalWritePin(DigitalPin.P16, 0)
}
if (speed < 0) {
pins.digitalWritePin(DigitalPin.P13, 0)
pins.digitalWritePin(DigitalPin.P14, 1)
pins.digitalWritePin(DigitalPin.P15, 0)
pins.digitalWritePin(DigitalPin.P16, 1)
}
pins.analogWritePin(AnalogPin.P0, Math.abs(speed + rightMotorBias))
pins.analogSetPeriod(AnalogPin.P0,2500)
pins.analogWritePin(AnalogPin.P1, Math.abs(speed + leftMotorBias))
pins.analogSetPeriod(AnalogPin.P1,2500)
}
|
0af800c75964d7830fedd8d742ac6f124962cd43
|
TypeScript
|
beenotung/shopping-cart-demo
|
/src/helpers.ts
| 2.859375
| 3
|
export type Product = {
id: number
name: string
}
export type SelectedProduct={
product:Product
quantity:number
}
const AllProducts: Product[] = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' },
]
export function getProducts(): Promise<Product[]> {
return new Promise(resolve => {
console.log('downloading product list...')
setTimeout(() => {
console.log('downloaded product list')
resolve(AllProducts)
}, 2000)
})
}
|
f2bf40c58c72e63180c4ed03a7c590f0046c5e15
|
TypeScript
|
jamescryer/kata
|
/src/004 array compare constant time/constanttime.test.ts
| 3.265625
| 3
|
import constanttime from './constanttime';
describe('hello', () => {
test('arrays are the same', () => {
const a = [121, 144, 19, 161, 19, 144, 19, 11];
const b = [121, 144, 19, 161, 19, 144, 19, 11];
expect(constanttime(a, b)).toEqual(true);
});
test('arrays are the similar but not the same', () => {
const a = [2, 3, 3];
const b = [3, 3, 2, 2];
expect(constanttime(a, b)).toEqual(false);
});
test('arrays are not the same length', () => {
const a = [121, 144, 19, 161, 19, 144, 19, 11];
const b = [121, 14641, 20736, 361, 25921];
expect(constanttime(a, b)).toEqual(false);
});
test('empty a', () => {
const a: number[] = [];
const b = [132, 14641, 20736, 361, 25921, 361, 20736, 361];
expect(constanttime(a, b)).toEqual(false);
});
test('empty b', () => {
const a = [121, 144, 19, 161, 19, 144, 19, 11];
const b: number[] = [];
expect(constanttime(a, b)).toEqual(false);
});
test('empty a & b', () => {
const a: number[] = [];
const b: number[] = [];
expect(constanttime(a, b)).toEqual(false);
});
test('large arrays', () => {
const large = new Array(10000000).fill(1);
expect(constanttime(large, large)).toEqual(true);
});
});
|
0ea466a52a910ebf7a4b36d8caf37e1454c0330e
|
TypeScript
|
cborac/node-discord
|
/lib/structures/message/MessageReaction.d.ts
| 2.625
| 3
|
import { Message } from './Message';
import Collection from '../../Collection';
import { ReactionUsersController } from '../../controllers/reaction';
import { Snowflake } from '../../types';
import { Emoji } from '../Emoji';
import { BaseStruct, GatewayStruct } from '../base';
import { Member } from '../member/Member';
/**
* Holds all users that reacted to a {@link Message} with a specific {@link Emoji}
*/
export declare class MessageReaction extends BaseStruct {
/**
* The message this reaction is attached to
*/
message: Message;
/**
* The times this emoji has been used to react
*/
count: number;
/**
* Whether the bot reacted using this emoji
*/
botReacted: boolean | undefined;
/**
* The reaction's users controller
*/
users: ReactionUsersController;
/**
* The members that added this reaction
*/
members: Collection<Snowflake, Member>;
/**
* The emoji this reaction used. This emoji is partial
*/
emoji: Emoji;
constructor(message: Message, reaction: GatewayStruct);
/**
* @ignore
* @param {GatewayStruct} reaction The reaction data
* @returns {this}
*/
init(reaction: GatewayStruct): this;
/**
* Deletes all reactions for this emoji.
* Requires the {@link Permission.ManageMessages} permission
* @returns {Promise<void>}
*/
delete(): Promise<void>;
/**
* The ID of the emoji this reaction stores
* Serves as an identifier for this reaction
* @type {string}
*/
get id(): string;
}
|
fbc50447d46ec64d270d3b1c662e96d3b2627a31
|
TypeScript
|
rodriguesl3/timesheet
|
/src/store/Login/reducer.ts
| 2.734375
| 3
|
import { Reducer } from 'redux';
import { LoginState, LOGIN_INITIAL_STATE, LoginTypes } from './types';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const loginReducer: Reducer<LoginState> = (state: LoginState = LOGIN_INITIAL_STATE, action: any) => {
switch (action.type) {
case LoginTypes.LOGIN_REQUEST:
return {
...state,
loginRequest: true,
loginFailure: false,
loginSuccess: true,
};
case LoginTypes.LOGIN_FAILURE:
return {
...state,
loginFailure: true,
loginRequest: false,
loginSuccess: false,
};
case LoginTypes.LOGIN_SUCCESS:
return {
...state,
credential: action.payload,
loginSuccess: true,
loginFailure: false,
loginRequest: false,
};
default:
return state;
}
};
export default loginReducer;
|
fa3de6a98ffc4d9cbbe584d660ca60f803bbdeb0
|
TypeScript
|
danielwerg/r6api.js
|
/src/methods/findById.ts
| 2.5625
| 3
|
import { getToken } from '../auth';
import fetch from '../fetch';
import { PlatformAllExtended, UUID, IOptionsDocs } from '../typings';
import { getURL, getAvatars } from '../utils';
export interface IProfile {
profileId: UUID;
userId: UUID;
idOnPlatform: UUID | string;
platformType: PlatformAllExtended;
nameOnPlatform: string;
}
export interface IApiResponse {
profiles: IProfile[];
}
export interface IOptions {
isUserId?: boolean;
}
export const optionsDocs: IOptionsDocs = [
[
'isUserId', '`boolean`', false, '`false`', 'Whether `id` is `userId` or not'
]
];
export default (platform: PlatformAllExtended, ids: UUID[] | string[], options?: IOptions) =>
getToken()
.then(
platform === 'all'
? options && options.isUserId
? fetch<IApiResponse>(getURL.BYUSERID(ids))
: fetch<IApiResponse>(getURL.BYPROFILEID(ids))
: fetch<IApiResponse>(getURL.BYIDONPLATFORM(platform, ids))
)
.then(res =>
res.profiles
.map(profile => ({
id: profile.profileId,
userId: profile.userId,
idOnPlatform: profile.idOnPlatform,
platform: profile.platformType,
username: profile.nameOnPlatform,
avatar: getAvatars(profile.userId)
}))
);
|
27996a0e3d9e9a865a1bb08bcc70c60469d8c280
|
TypeScript
|
zacharysnewman/minesweeper-console-typescript
|
/src/Typescript/tsTools.ts
| 3.3125
| 3
|
import { Tile } from "../State/Tile";
export const tileArrayEquals = (a: Tile[], b: Tile[]): Boolean =>
Array.isArray(a) &&
Array.isArray(b) &&
a.length === b.length &&
a.every((aTile, atTileIndex) => aTile.equals(b[atTileIndex]));
// export const tileArrayToTileMap = (tileArray: Tile[]): Tile[] => {
// // let x = JSON.stringify(Object.entries(tileArray));
// // console.log("TileArray: ", JSON.stringify(x));
// // console.log(JSON.stringify(new Tile[](x)));
// // const kvps = tileArray.map((tile) => [tile.coords, tile] as [Coords, Tile]);
// // console.log(
// // "KVP Array: ",
// // JSON.stringify(new Tile[](kvps).values)
// // );
// const iAmAMap = new Map( // Look Ma! No type annotations
// tileArray.map((x) => [x.coords, x] as [Coords, Tile])
// );
// // console.log(iAmAMap);
// return iAmAMap;
// };
// export const tileMapToTileArray = (tileMap: Tile[]): Tile[] => {
// return Array.from(tileMap, ([name, value]) => ({ name, value })).map(
// (x) => x.value
// );
// };
// export const compareMaps = <T, U>(
// map1: Map<T, U>,
// map2: Map<T, U>
// ): Boolean => {
// var testVal;
// if (map1.size !== map2.size) {
// return false;
// }
// for (var [key, val] of map1) {
// testVal = map2.get(key);
// // in cases of an undefined value, make sure the key
// // actually exists on the object so there are no false positives
// if (testVal !== val || (testVal === undefined && !map2.has(key))) {
// return false;
// }
// }
// return true;
// };
|
39ff9e3f906b5ae606d76d39856e46fb6da9cc47
|
TypeScript
|
jiameng123/entities
|
/src/decode.ts
| 2.828125
| 3
|
import htmlDecodeTree from "./generated/decode-data-html";
import xmlDecodeTree from "./generated/decode-data-xml";
import decodeCodePoint from "./decode_codepoint";
// Re-export for use by eg. htmlparser2
export { htmlDecodeTree, xmlDecodeTree };
const enum CharCodes {
NUM = 35, // "#"
SEMI = 59, // ";"
ZERO = 48, // "0"
NINE = 57, // "9"
LOWER_A = 97, // "a"
LOWER_F = 102, // "f"
LOWER_X = 120, // "x"
/** Bit that needs to be set to convert an upper case ASCII character to lower case */
To_LOWER_BIT = 0b100000,
}
export enum BinTrieFlags {
HAS_VALUE = 0b1000_0000_0000_0000,
BRANCH_LENGTH = 0b0111_1111_0000_0000,
MULTI_BYTE = 0b0000_0000_1000_0000,
JUMP_TABLE = 0b0000_0000_0111_1111,
}
export const JUMP_OFFSET_BASE = CharCodes.ZERO - 1;
function getDecoder(decodeTree: Uint16Array) {
return function decodeHTMLBinary(str: string, strict: boolean): string {
let ret = "";
let lastIdx = 0;
let strIdx = 0;
while ((strIdx = str.indexOf("&", strIdx)) >= 0) {
ret += str.slice(lastIdx, strIdx);
lastIdx = strIdx;
// Skip the "&"
strIdx += 1;
// If we have a numeric entity, handle this separately.
if (str.charCodeAt(strIdx) === CharCodes.NUM) {
// Skip the leading "&#". For hex entities, also skip the leading "x".
let start = strIdx + 1;
let base = 10;
let cp = str.charCodeAt(start);
if ((cp | CharCodes.To_LOWER_BIT) === CharCodes.LOWER_X) {
base = 16;
strIdx += 1;
start += 1;
}
while (
((cp = str.charCodeAt(++strIdx)) >= CharCodes.ZERO &&
cp <= CharCodes.NINE) ||
(base === 16 &&
(cp | CharCodes.To_LOWER_BIT) >= CharCodes.LOWER_A &&
(cp | CharCodes.To_LOWER_BIT) <= CharCodes.LOWER_F)
);
if (start !== strIdx) {
const entity = str.substring(start, strIdx);
const parsed = parseInt(entity, base);
if (str.charCodeAt(strIdx) === CharCodes.SEMI) {
strIdx += 1;
} else if (strict) {
continue;
}
ret += decodeCodePoint(parsed);
lastIdx = strIdx;
}
continue;
}
let result: string | null = null;
let excess = 1;
let treeIdx = 0;
let current = decodeTree[treeIdx];
for (; strIdx < str.length; strIdx++, excess++) {
treeIdx = determineBranch(
decodeTree,
current,
treeIdx + 1,
str.charCodeAt(strIdx)
);
if (treeIdx < 0) break;
current = decodeTree[treeIdx];
// If the branch is a value, store it and continue
if (current & BinTrieFlags.HAS_VALUE) {
// If we have a legacy entity while parsing strictly, just skip the number of bytes
if (strict && str.charCodeAt(strIdx) !== CharCodes.SEMI) {
// No need to consider multi-byte values, as the legacy entity is always a single byte
treeIdx += 1;
} else {
// If this is a surrogate pair, combine the higher bits from the node with the next byte
result =
current & BinTrieFlags.MULTI_BYTE
? String.fromCharCode(
decodeTree[++treeIdx],
decodeTree[++treeIdx]
)
: String.fromCharCode(decodeTree[++treeIdx]);
excess = 0;
}
}
}
if (result != null) {
ret += result;
lastIdx = strIdx - excess + 1;
}
}
return ret + str.slice(lastIdx);
};
}
export function determineBranch(
decodeTree: Uint16Array,
current: number,
nodeIdx: number,
char: number
): number {
if (current <= 128) {
return char === current ? nodeIdx : -1;
}
const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 8;
if (branchCount === 0) {
return -1;
}
if (branchCount === 1) {
return char === decodeTree[nodeIdx] ? nodeIdx + 1 : -1;
}
const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
if (jumpOffset) {
const value = char - JUMP_OFFSET_BASE - jumpOffset;
return value < 0 || value > branchCount
? -1
: decodeTree[nodeIdx + value] - 1;
}
// Binary search for the character.
let lo = nodeIdx;
let hi = lo + branchCount - 1;
while (lo <= hi) {
const mid = (lo + hi) >>> 1;
const midVal = decodeTree[mid];
if (midVal < char) {
lo = mid + 1;
} else if (midVal > char) {
hi = mid - 1;
} else {
return decodeTree[mid + branchCount];
}
}
return -1;
}
const htmlDecoder = getDecoder(htmlDecodeTree);
const xmlDecoder = getDecoder(xmlDecodeTree);
export function decodeHTML(str: string): string {
return htmlDecoder(str, false);
}
export function decodeHTMLStrict(str: string): string {
return htmlDecoder(str, true);
}
export function decodeXML(str: string): string {
return xmlDecoder(str, true);
}
|
64184bbbbddea2eae6ff947c68f033046b374ea3
|
TypeScript
|
kristinka-skl/Programming-Language-Benchmarks
|
/bench/algorithm/json-serde/1.ts
| 2.703125
| 3
|
import { createHash } from "https://deno.land/std/hash/mod.ts";
function printHash(data: any) {
const str = JSON.stringify(data);
const hasher = createHash('md5');
hasher.update(str);
console.log(hasher.toString());
}
async function main() {
let fileName = Deno.args[0] || "sample";
let n = +Deno.args[1] || 3;
const jsonStr = await Deno.readTextFile(`${fileName}.json`);
printHash(JSON.parse(jsonStr));
const array = [];
for (var i = 0; i < n; i++) {
array.push(JSON.parse(jsonStr));
}
printHash(array);
}
main();
|
0212b32878bfceab8d4730c0df6c574ae0be9ab4
|
TypeScript
|
fabiansdp/itfest-frontend-7.0
|
/api/checkout.ts
| 2.640625
| 3
|
import { AxiosInstance } from "axios";
import { MerchStoreItem } from "interfaces/merch-store";
import { ApiError, ApiResponse } from "interfaces/api";
import {
CheckoutErrorStatus,
} from "interfaces/checkout";
export async function checkout(
axios: AxiosInstance,
items: Array<MerchStoreItem>,
line?: string,
whatsapp?: string,
address?: string
): Promise<ApiResponse<void>> {
try {
const data = {
"lineContact": line,
"waContact": whatsapp,
"address": address,
"items": items
};
const response = await axios.post("/checkout", data);
return response.data;
} catch (e) {
if (e.response) {
const errorCode = e.response.data?.code;
if (errorCode === "insufficient-quantity") {
throw new ApiError<CheckoutErrorStatus>(
CheckoutErrorStatus.INSUFFICIENT_QUANTITY,
"Stok barang habis"
);
} else if (errorCode === "insufficient-point") {
throw new ApiError<CheckoutErrorStatus>(
CheckoutErrorStatus.INSUFFICIENT_POINT,
"Point tidak cukup"
);
} else if (errorCode === "incomplete-contact" || errorCode === "invalid-input") {
throw new ApiError<CheckoutErrorStatus>(
CheckoutErrorStatus.DATA_INCOMPLETE,
"Pastikan data anda benar"
);
} else if (errorCode === "item-not-found") {
throw new ApiError<CheckoutErrorStatus>(
CheckoutErrorStatus.INSUFFICIENT_QUANTITY,
"Stok barang habis"
);
}
}
throw new ApiError<CheckoutErrorStatus>(CheckoutErrorStatus.ERROR, e.message);
}
}
|
2f8e90cec8c459a853841bad5306446dcd43df4d
|
TypeScript
|
Heverton/newza-frontend
|
/src/app/menuitem.ts
| 2.84375
| 3
|
export class MenuItem {
nome: string;
descricao: string;
url: string;
icone: string;
constructor(nome, descricao, url, icone){
this.nome = nome;
this.descricao = descricao;
this.url = url;
this.icone = icone;
}
}
|
a322ce005332e4da24c641ab10ca9989f571171f
|
TypeScript
|
guoyu07/egret-target-bricks
|
/template/PublicBrickEngineGame/Res/script/core/render/spriteSheetCache.ts
| 2.765625
| 3
|
// class SheetSprite
// {
// __nativeObj : BK.Sprite;
// contentSprite : BK.Sprite;
// size : BK.Size = {width:0,height:0};
// textureInfo:BK.SheetTextureInfo;
// currTexturePath : string;
// //sprite format
// flipU:number = 0 ;
// flipV:number = 1;
// stretchX:number = 1;
// stretchY:number = 1;
// constructor(textureInfo:BK.SheetTextureInfo,width:number,height:number,flipU?:number,flipV?:number,stretchX?:number,stretchY?:number)
// {
// if (flipU) {
// this.flipU = flipU;
// }
// if (flipV) {
// this.flipV = flipV;
// }
// if(stretchX){
// this.stretchX = stretchX;
// }
// if (stretchY) {
// this.stretchY = stretchY;
// }
// if (width) {
// this.size.width = width;
// }
// if(height){
// this.size.height = height;
// }
// this.textureInfo = textureInfo;
// this.onInit(this.size.width,this.size.height);
// this.adjustWithTextureInfo(textureInfo);
// }
// onInit(width,height){
// this.createSprites(width,height);
// //redirect the properties to this object
// var names = Object.getOwnPropertyNames(this.__nativeObj);
// names.forEach(function (element) {
// var key = element;
// Object.defineProperty(this, key, {
// get: function () {
// return this.__nativeObj[key];
// },
// set: function (obj) {
// this.__nativeObj[key] = obj;
// }
// });
// }, this);
// Object.defineProperty(this,"size",{
// get:function () {
// return this.__nativeObj.size;
// },
// set:function(obj){
// this.__nativeObj.size = obj;
// this.displayFrame(this.currDisplayIdx);
// }
// });
// }
// adjustWithTextureInfo(textureInfo:BK.SheetTextureInfo)
// {
// if (textureInfo) {
// var tex = textureInfo.texture;
// var frameInfo = textureInfo.frameInfo;
// if (textureInfo.frameInfo.trimmed == true) {
// var x = textureInfo.frameInfo.spriteSourceSize.x;
// var y = textureInfo.frameInfo.spriteSourceSize.y;
// var w = textureInfo.frameInfo.spriteSourceSize.w;
// var h = textureInfo.frameInfo.spriteSourceSize.h;
// var srcSize = textureInfo.frameInfo.sourceSize;
// var currSize = this.__nativeObj.size;
// x = currSize.width * x/srcSize.w
// y = currSize.height * y/srcSize.h
// w = currSize.width * w/srcSize.w
// h = currSize.height * h/srcSize.h
// this.contentSprite.position = {x:x,y:y};
// this.contentSprite.size = {width:w,height:h};
// BK.Script.log(0,0,"textureInfo.frameInfo.trimmed == true");
// }else{
// this.contentSprite.size = this.__nativeObj.size;
// BK.Script.log(0,0,"textureInfo.frameInfo.trimmed != true");
// }
// BK.Script.log(1,-1,"this.currTexture != tex");
// this.currTexturePath = textureInfo.texturePath;
// var tex = new BK.Texture(this.currTexturePath)
// this.contentSprite.setTexture(tex);
// this.contentSprite.adjustTexturePosition(frameInfo.frame.x,frameInfo.frame.y,frameInfo.frame.w,frameInfo.frame.h,frameInfo.rotated);
// }
// }
// //redirect functions
// setTexture(tex:BK.Texture){
// this.__nativeObj.setTexture(tex);
// }
// dispose(){
// BK.Director.ticker.remove(this);
// this.__nativeObj.dispose();
// }
// removeChild(child:BK.Node){
// return this.__nativeObj.removeChild(child);
// }
// removeChildById(id:number,dispose:boolean){
// return this.__nativeObj.removeChildById(id,dispose);
// }
// removeChildByName(name:string,dispose:boolean){
// return this.__nativeObj.removeChildByName(name,dispose);
// }
// removeFromParent(){
// return this.__nativeObj.removeFromParent();
// }
// addChild(child:BK.Node,index?:number){
// return this.__nativeObj.addChild(child,index);
// }
// hittest(position){
// return this.__nativeObj.hittest(position);
// }
// convertToWorldSpace(position){
// return this.__nativeObj.convertToWorldSpace(position);
// }
// convertToNodeSpace(position){
// return this.__nativeObj.convertToNodeSpace(position);
// }
// createSprites(width,height){
// this.__nativeObj = new BK.Sprite(width,height,undefined,this.flipU,this.flipV,this.stretchX,this.stretchY);
// this.contentSprite = new BK.Sprite(width,height,undefined,this.flipU,this.flipV,this.stretchX,this.stretchY);
// this.__nativeObj.addChild(this.contentSprite);
// }
// }
// if (!BK.SheetSprite) {
// BK.SheetSprite = SheetSprite;
// }
// var SpriteSheetCache = (function () {
// function SpriteSheetCache() {
// this.sheets = {};
// this.jsonConfigs = {};
// }
// SpriteSheetCache.prototype.getFrameInfoByFilename = function (filename) {
// for (var texturePath in this.jsonConfigs) {
// if (this.jsonConfigs.hasOwnProperty(texturePath)) {
// var config = this.jsonConfigs[texturePath];
// var texture = this.sheets[texturePath];
// var frames = config.frames;
// var meta = config.meta;
// this.fullWidth = meta.size.w;
// this.fullHeight = meta.size.h;
// for (var index = 0; index < frames.length; index++) {
// var frm = frames[index];
// if (filename == frm.filename) {
// var frame = { x: 0, y: 1, w: 0, h: 0 };
// var rotated = frm.rotated;
// var trimmed = frm.trimmed;
// var spriteSourceSize = frm.spriteSourceSize;
// var sourceSize = frm.sourceSize;
// if (rotated) {
// frame.x = frm.frame.x;
// frame.y = this.fullHeight - frm.frame.y - frm.frame.w;
// frame.w = frm.frame.w;
// frame.h = frm.frame.h;
// }
// else {
// frame.x = frm.frame.x;
// frame.y = this.fullHeight - frm.frame.y - frm.frame.h;
// frame.w = frm.frame.w;
// frame.h = frm.frame.h;
// }
// spriteSourceSize.y = sourceSize.h - spriteSourceSize.y - spriteSourceSize.h;
// var retSheetFrame = {
// filename: filename,
// frame: frame,
// rotated: rotated,
// trimmed: trimmed,
// spriteSourceSize : spriteSourceSize,
// sourceSize :sourceSize
// };
// return retSheetFrame;
// }
// }
// }
// }
// return null;
// };
// SpriteSheetCache.prototype.getTexturePathByFilename = function (filename) {
// for (var texturePath in this.jsonConfigs) {
// if (this.jsonConfigs.hasOwnProperty(texturePath)) {
// var config = this.jsonConfigs[texturePath];
// var frames = config.frames;
// for (var index = 0; index < frames.length; index++) {
// var frame = frames[index];
// if (frame.filename == filename) {
// return texturePath;
// }
// }
// }
// }
// return null;
// };
// /**
// * 根据路径加载sheet
// *
// * @param {string} jsonPath
// * @param {string} texturePath
// * @memberof SpriteSheetCache
// */
// SpriteSheetCache.prototype.loadSheet = function (jsonPath, texturePath,format, minFilter, magFilter, uWrap, vWrap) {
// var buff = BK.FileUtil.readFile(jsonPath);
// var sheetJsonStr = buff.readAsString();
// if (sheetJsonStr) {
// var sheetObj = JSON.parse(sheetJsonStr);
// this.jsonConfigs[texturePath] = sheetObj;
// if (format === void 0) { format = 4; }
// if (minFilter === void 0) { minFilter = 1; }
// if (magFilter === void 0) { magFilter = 1; }
// if (uWrap === void 0) { uWrap = 1; }
// if (vWrap === void 0) { vWrap = 1; }
// var tex = new BK.Texture(texturePath,format, minFilter, magFilter, uWrap, vWrap);
// this.sheets[texturePath] = tex;
// }
// else {
// BK.Script.log(0, 0, "loadSheet Failed.Please check path");
// }
// };
// /**
// * 移除图集
// *
// * @param {any} jsonPath
// * @param {any} texturePath
// */
// SpriteSheetCache.prototype.removeSheet = function (jsonPath, texturePath)
// {
// if (this.jsonConfigs[texturePath]) {
// for (var key in this.jsonConfigs) {
// if (this.jsonConfigs.hasOwnProperty(key)) {
// var val = this.jsonConfigs[key];
// if (key==texturePath) {
// delete this.jsonConfigs[texturePath];
// BK.Script.log(0,0,"Delete jsonConfigs key:"+key + " val:"+val);
// }
// }
// }
// }
// if (this.sheets[texturePath]) {
// for (var key in this.sheets) {
// if (this.sheets.hasOwnProperty(key)) {
// var val = this.sheets[key];
// if (key==texturePath) {
// delete this.sheets[texturePath];
// BK.Script.log(0,0,"Delete sheets key:"+key + " val:"+val);
// }
// }
// }
// }
// }
// /**
// * 根据名字获取texture
// *
// * @param {string} filename
// * @returns {BK.Texture}
// * @memberof SpriteSheetCache
// */
// SpriteSheetCache.prototype.getTextureByFilename = function (filename) {
// var frameInfo = this.getFrameInfoByFilename(filename);
// var texturePath = this.getTexturePathByFilename(filename);
// if (frameInfo && texturePath) {
// var texture = new BK.Texture(texturePath);
// return texture;
// }
// else {
// BK.Script.log(0, 0, "getTexture Failed.Please check path");
// return null;
// }
// };
// /**
// *
// * @param filename
// * @param width
// * @param height;
// */
// SpriteSheetCache.prototype.getSprite = function (filename, width, height) {
// var textureInfo = this.getTextureFrameInfoByFileName(filename);
// if (textureInfo) {
// var frameInfo = textureInfo.frameInfo;//this.getFrameInfoByFilename(filename);
// var texturePath = textureInfo.texturePath;//this.getTexturePathByFilename(filename);
// var texture = new BK.Texture(texturePath);
// if(!width)
// {
// width = frameInfo.frame.w;
// }
// if(!height)
// {
// height = frameInfo.frame.h;
// }
// BK.Script.log(0, 0, "getSprite texture:" + texture + " width:" + width+ " height:" + height);
// if (frameInfo.trimmed) {
// var sprite = new BK.SheetSprite(textureInfo,width, height);
// return sprite;
// }else{
// var sprite = new BK.Sprite(width, height, texture, 0, 1, 1, 1);
// sprite.adjustTexturePosition(frameInfo.frame.x, frameInfo.frame.y, frameInfo.frame.w, frameInfo.frame.h, frameInfo.rotated);
// return sprite;
// }
// }
// else {
// return null;
// }
// };
// SpriteSheetCache.prototype.getTextureFrameInfoByFileName = function(filename)
// {
// var frameInfo = this.getFrameInfoByFilename(filename);
// var texturePath = this.getTexturePathByFilename(filename);
// if (frameInfo && texturePath) {
// var textureFrameInfo = {
// "frameInfo":frameInfo,
// "texturePath":texturePath
// }
// return textureFrameInfo;
// }else{
// return null;
// }
// }
// return SpriteSheetCache;
// }());
// var Sprite9 = (function () {
// /**
// *
// * @param texWidth
// * @param texHeight
// * @param texture
// * @param grid
// * @param offset
// * @param rotated
// */
// function Sprite9(texWidth, texHeight, texture, grid, offset, rotated) {
// if (offset === void 0) { offset = {
// x: 0,
// y: 0
// }; }
// this._size = { width: 0, height: 0 };
// this.__nativeObj = new BK.Node();
// this.onInit();
// this._grid = grid;
// this._size = { width: texHeight, height: texHeight };
// this._leftTop = new BK.Sprite(grid.left, grid.top, texture, 0, 1, 1, 1);
// this._leftTop.position = { x: 0, y: (texHeight - grid.top) };
// this._leftTop.zOrder = 99999;
// this._leftTop.name = "_leftTop";
// this.__nativeObj.addChild(this._leftTop);
// this._centerTop = new BK.Sprite(texWidth - grid.left - grid.right, grid.top, texture, 0, 1, 1, 1);
// this._centerTop.position = { x: grid.left, y: (texHeight - grid.top) };
// this._centerTop.zOrder = 99999;
// this._centerTop.name = "_centerTop";
// this.__nativeObj.addChild(this._centerTop);
// this._rightTop = new BK.Sprite(grid.right, grid.top, texture, 0, 1, 1, 1);
// this._rightTop.position = { x: texWidth - grid.right, y: texHeight - grid.top };
// this._rightTop.zOrder = 99999;
// this._rightTop.name = "_rightTop";
// this.__nativeObj.addChild(this._rightTop);
// this._leftCenter = new BK.Sprite(grid.left, texHeight - grid.top - grid.bottom, texture, 0, 1, 1, 1);
// this._leftCenter.position = { x: 0, y: grid.bottom };
// this._leftCenter.name = "_leftCenter";
// this.__nativeObj.addChild(this._leftCenter);
// this._centerCenter = new BK.Sprite(texWidth - grid.left - grid.right, texHeight - grid.top - grid.bottom, texture, 0, 1, 1, 1);
// this._centerCenter.position = { x: grid.left, y: grid.bottom };
// this._centerCenter.name = "_centerCenter";
// this.__nativeObj.addChild(this._centerCenter);
// this._rightCenter = new BK.Sprite(grid.right, texHeight - grid.bottom - grid.top, texture, 0, 1, 1, 1);
// this._rightCenter.position = { x: texWidth - grid.right, y: grid.bottom };
// this._rightCenter.name = "_rightCenter";
// this.__nativeObj.addChild(this._rightCenter);
// this._leftBottom = new BK.Sprite(grid.left, grid.bottom, texture, 0, 1, 1, 1);
// this._leftBottom.position = { x: 0, y: 0 };
// this._leftBottom.name = "_leftBottom";
// this.__nativeObj.addChild(this._leftBottom);
// this._centerBottom = new BK.Sprite(texWidth - grid.left - grid.right, grid.bottom, texture, 0, 1, 1, 1);
// this._centerBottom.position = { x: grid.left, y: 0 };
// this._centerBottom.name = "_centerBottom";
// this.__nativeObj.addChild(this._centerBottom);
// this._rightBottom = new BK.Sprite(grid.right, grid.bottom, texture, 0, 1, 1, 1);
// this._rightBottom.position = { x: texWidth - grid.right, y: 0 };
// this._rightBottom.name = "_rightBottom";
// this.__nativeObj.addChild(this._rightBottom);
// if (rotated == true) {
// this._leftTop.adjustTexturePosition(offset.x + (texHeight - grid.top), offset.y + (texWidth - grid.left), grid.left, grid.top, rotated);
// this._centerTop.adjustTexturePosition(offset.x + (texHeight - grid.top), offset.y + grid.right, texWidth - grid.left - grid.right, grid.top, rotated);
// this._rightTop.adjustTexturePosition(offset.x + (texHeight - grid.top), offset.y, grid.right, grid.top, rotated);
// this._leftCenter.adjustTexturePosition(offset.x + grid.bottom, offset.y + (texWidth - grid.left), grid.left, texHeight - grid.top - grid.bottom, rotated);
// this._centerCenter.adjustTexturePosition(offset.x + grid.bottom, offset.y + grid.right, texWidth - grid.left - grid.right, texHeight - grid.top - grid.bottom, rotated);
// this._rightCenter.adjustTexturePosition(offset.x + grid.bottom, offset.y, grid.right, texHeight - grid.bottom - grid.top, rotated);
// this._leftBottom.adjustTexturePosition(offset.x, offset.y + (texWidth - grid.left), grid.left, grid.bottom, rotated);
// this._centerBottom.adjustTexturePosition(offset.x, offset.y + grid.right, texWidth - grid.left - grid.right, grid.bottom, rotated);
// this._rightBottom.adjustTexturePosition(offset.x, offset.y, grid.right, grid.bottom, rotated);
// }
// else {
// this._leftTop.adjustTexturePosition(0 + offset.x, texHeight - grid.top + offset.y, grid.left, grid.top);
// this._centerTop.adjustTexturePosition(grid.left + offset.x, texHeight - grid.top + offset.y, texWidth - grid.left - grid.right, grid.top);
// this._rightTop.adjustTexturePosition(texWidth - grid.right + offset.x, texHeight - grid.top + offset.y, grid.right, grid.top);
// this._leftCenter.adjustTexturePosition(0 + offset.x, grid.bottom + offset.y, grid.left, texHeight - grid.top - grid.bottom);
// this._centerCenter.adjustTexturePosition(grid.left + offset.x, grid.bottom + offset.y, texWidth - grid.left - grid.right, texHeight - grid.top - grid.bottom);
// this._rightCenter.adjustTexturePosition(texWidth - grid.right + offset.x, grid.bottom + offset.y, grid.right, texHeight - grid.bottom - grid.top);
// this._leftBottom.adjustTexturePosition(0 + offset.x, 0 + offset.y, grid.left, grid.bottom);
// this._centerBottom.adjustTexturePosition(grid.left + offset.x, 0 + offset.y, texWidth - grid.left - grid.right, grid.bottom);
// this._rightBottom.adjustTexturePosition(texWidth - grid.right + offset.x, 0 + offset.y, grid.right, grid.bottom);
// }
// }
// Sprite9.prototype.onInit = function () {
// var names = Object.getOwnPropertyNames(this.__nativeObj);
// names.forEach(function (element) {
// var key = element;
// // log("name:"+key);
// Object.defineProperty(this, key, {
// get: function () {
// return this.__nativeObj[key];
// },
// set: function (obj) {
// this.__nativeObj[key] = obj;
// }
// });
// }, this);
// };
// Object.defineProperty(Sprite9.prototype, "alpha", {
// get: function () {
// return this._rightBottom.vertexColor.a;
// },
// set: function (num) {
// this._leftTop.vertexColor = { r: 1, g: 1, b: 1, a: num };
// this._centerTop.vertexColor = { r: 1, g: 1, b: 1, a: num };
// this._rightTop.vertexColor = { r: 1, g: 1, b: 1, a: num };
// this._leftCenter.vertexColor = { r: 1, g: 1, b: 1, a: num };
// this._centerCenter.vertexColor = { r: 1, g: 1, b: 1, a: num };
// this._rightCenter.vertexColor = { r: 1, g: 1, b: 1, a: num };
// this._leftBottom.vertexColor = { r: 1, g: 1, b: 1, a: num };
// this._centerBottom.vertexColor = { r: 1, g: 1, b: 1, a: num };
// this._rightBottom.vertexColor = { r: 1, g: 1, b: 1, a: num };
// },
// enumerable: true,
// configurable: true
// });
// Object.defineProperty(Sprite9.prototype, "size", {
// get: function () {
// return this._size;
// },
// set: function (contentSize) {
// this._size = contentSize;
// var tgtCenterWidth = contentSize.width - this._grid.left - this._grid.right;
// var tgtCenterHeight = contentSize.height - this._grid.top - this._grid.bottom;
// this._leftTop.position = { x: 0, y: contentSize.height - this._grid.top };
// this._leftCenter.size = { width: this._grid.left, height: tgtCenterHeight };
// this._leftCenter.position = { x: 0, y: this._grid.bottom };
// this._rightCenter.size = { width: this._grid.right, height: tgtCenterHeight };
// this._rightCenter.position = { x: contentSize.width - this._grid.right, y: this._grid.bottom };
// this._centerCenter.size = { width: tgtCenterWidth, height: tgtCenterHeight };
// this._centerTop.size = { width: tgtCenterWidth, height: this._grid.top };
// this._centerTop.position = { x: this._grid.left, y: contentSize.height - this._grid.top };
// this._centerBottom.size = { width: tgtCenterWidth, height: this._grid.bottom };
// this._centerBottom.position = { x: this._grid.left, y: 0 };
// this._rightCenter.size = { width: this._grid.right, height: tgtCenterHeight };
// this._rightCenter.position = { x: contentSize.width - this._grid.right, y: this._grid.bottom };
// this._rightBottom.position = { x: contentSize.width - this._grid.right, y: 0 };
// this._rightTop.position = { x: contentSize.width - this._grid.right, y: contentSize.height - this._grid.top };
// },
// enumerable: true,
// configurable: true
// });
// /**
// * 调整位置
// * @param postion
// */
// Sprite9.prototype.pos = function (x, y) {
// this.__nativeObj.position = { x: x, y: y };
// };
// //---------原始方法-------------
// /**
// * 销毁当前对象
// */
// Sprite9.prototype.dispose = function () {
// this.__nativeObj.dispose();
// };
// /**
// * 附着一个物理引擎中的刚体对象至当前节点
// * @param body 物理引擎中刚体对象
// */
// Sprite9.prototype.attachBody = function (body) {
// this.__nativeObj.attachComponent(body);
// };
// /**
// * 添加子节点
// * @param sonNode
// */
// Sprite9.prototype.addChild = function (sonNode) {
// this.__nativeObj.addChild(sonNode);
// };
// /**
// * 根据id移除子节点
// * @param id
// * @param isDispose 是否销毁当前节点
// */
// Sprite9.prototype.removeChildById = function (id, isDispose) {
// return this.__nativeObj.removeChildById(id, isDispose);
// };
// /**
// * 根据name移除子节点
// * @param name
// * @param isDispose 是否销毁当前节点
// */
// Sprite9.prototype.removeChildByName = function (name, isDispose) {
// return this.__nativeObj.removeChildByName(name, isDispose);
// };
// /**
// * 移除当前节点
// * 如果需要销毁,再调用dispose方法
// */
// Sprite9.prototype.removeFromParent = function () {
// return this.__nativeObj.removeFromParent();
// };
// /**
// * 判断是被点击
// * @param postion 待判断的位置 结构形如 {x:0,y:0}
// */
// Sprite9.prototype.hittest = function (position) {
// return this.__nativeObj.hittest(position);
// };
// return Sprite9;
// }());
// if (!BK.SpriteSheetCache) {
// BK.SpriteSheetCache = new SpriteSheetCache();
// }
// if (!BK.Sprite9) {
// BK.Sprite9 = Sprite9;
// }
|
c505c5f810719b887708a7926ee2d21ea62811bd
|
TypeScript
|
kemokemo/ts-worker-sample
|
/01-simple_worker/src/dom/main-thread.ts
| 2.65625
| 3
|
// Copy from the awesome book 'https://www.oreilly.co.jp/books/9784873119045/'
// This is my learning code. :-) kemokemo
var worker = new Worker("worker-thread.js");
worker.onmessage = (e) => processCommandFromWorkerThread(e.data);
window.onload = () => {
let postButton = document.getElementById("post-to-worker");
if (postButton) {
postButton.onclick = postToWorkerThread;
}
};
function postToWorkerThread() {
let message: string = "";
let msg = document.getElementById("message-01") as HTMLTextAreaElement;
if (msg != null) {
message = msg.value;
}
worker.postMessage({
type: "sendMessageToWorker",
data: [message],
});
}
function processCommandFromWorkerThread(wc: WChannel) {
switch (wc.type) {
case "receivedFromWorker":
let [message] = wc.data;
console.log(`This message is main thread log: ${message}`);
let msg = document.getElementById("message-02") as HTMLTextAreaElement;
if (msg) {
msg.value = message;
}
break;
default:
break;
}
}
|
70ff2949165b16c9667dd661ee47a51b0ca4f3f3
|
TypeScript
|
saefullohmaslul/Nodejs-DDD-Pattern
|
/src/database/seeds/user.seed.ts
| 2.546875
| 3
|
import faker from 'faker'
import { getRepository } from 'typeorm'
import { UserEntity } from 'database/entities'
import { log } from 'app/library/debug/debugger.lib'
export const userSeeder = () => {
return new Promise(async (res, rej) => {
const createdData: UserEntity[] = []
try {
const userRepository = getRepository(UserEntity)
for (const data of Array(10)) {
const user = await userRepository.save({
id: faker.random.uuid(),
username: faker.random.alphaNumeric(10),
first_name: faker.name.firstName(1),
last_name: faker.name.lastName(1),
is_active: faker.random.boolean(),
phone_number: faker.phone.phoneNumber('08##########')
})
createdData.push(user)
}
log.debugDB('success seed user table')
res(createdData)
} catch (error) {
rej(error)
}
})
}
|
d079989f9d1d455616f13a8b44bd0f629b2602d9
|
TypeScript
|
dpschen/languagetools
|
/packages/template-ast-types/src/stringify.ts
| 2.796875
| 3
|
import type {
AttributeNode,
DirectiveNode,
ElementNode,
Node,
RootNode,
SimpleExpressionNode,
TextNode,
} from '@vue/compiler-core'
import {
isAttributeNode,
isDirectiveNode,
isElementNode,
isInterpolationNode,
isRootNode,
isSimpleExpressionNode,
isTextNode,
isCommentNode,
} from './assert'
const selfClosingTag = [
'area',
'base',
'br',
'col',
'command',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr',
]
/**
* @public
*/
export interface StringifyOptions {
indent: number
initialIndent: number
directive: 'shorthand' | 'longhand'
replaceNodes: Map<Node, Node | null>
}
const defaults: StringifyOptions = {
indent: 2,
initialIndent: 0,
directive: 'shorthand',
replaceNodes: new Map<Node, Node | null>(),
}
/**
* Convert template AST to template code.
*
* @public
*/
export function stringify(
node: Node | Node[],
options?: Partial<StringifyOptions>,
): string {
const finalOptions = { ...defaults, ...options }
return genNode(
Array.isArray(node) ? ({ type: 0, children: node } as any) : node,
finalOptions.initialIndent * finalOptions.initialIndent,
finalOptions,
)
}
const shorthands = {
bind: ':',
on: '@',
slot: '#',
} as const
function genNode(
node: Node,
indent: number,
options: StringifyOptions,
): string {
if (options.replaceNodes.has(node)) {
const replaced = options.replaceNodes.get(node)
return replaced == null ? '' : genNode(replaced, indent, options)
} else if (isRootNode(node)) {
return genRootNode(node, indent, options)
} else if (isElementNode(node)) {
return genElementNode(node, indent, options)
} else if (isAttributeNode(node)) {
return genAttributeNode(node, indent, options)
} else if (isDirectiveNode(node)) {
return genDirectiveNode(node, indent, options)
} else if (isInterpolationNode(node)) {
return `{{ ${genNode(node.content, indent, options)} }}`
} else if (isSimpleExpressionNode(node)) {
return genExpressionNode(node, indent, options)
} else if (isTextNode(node)) {
return genTextNode(node, indent, options)
} else if (isCommentNode(node)) {
return (
' '.repeat(indent) +
'<!--' +
genMultilineText(node.content, indent, options) +
'-->'
)
} else {
throw new Error(`Unsupported node type: ${node.type}`)
}
}
function genExpressionNode(
node: SimpleExpressionNode,
indent: number,
options: StringifyOptions,
): string {
return genMultilineText(node.content, indent, options)
}
function genTextNode(
node: TextNode,
indent: number,
options: StringifyOptions,
): string {
return genMultilineText(node.content, indent, options)
}
function genMultilineText(
content: string,
indent: number,
options: StringifyOptions,
): string {
if (content.startsWith('\n')) {
content = content.trimStart()
}
if (content.includes('\n')) {
content = content
.split('\n')
.map((line) => line.trim())
.join('\n' + ' '.repeat(indent + options.indent))
}
return content
}
function genRootNode(
node: RootNode,
indent: number,
options: StringifyOptions,
): string {
return genChildren(node, indent, options)
}
function genElementNode(
node: ElementNode,
indent: number,
options: StringifyOptions,
): string {
const code: string[] = []
code.push(' '.repeat(indent), '<', node.tag)
let shouldIndentClosing = false
const props = applyReplaceNodes(node.props, options)
if (props.length > 0) {
if (props.length > 2) {
code.push('\n')
node.props.forEach((prop) => {
code.push(' '.repeat(indent + options.indent))
code.push(genNode(prop, indent + options.indent, options))
code.push('\n')
})
shouldIndentClosing = true
} else {
props.forEach((prop) => {
code.push(' ')
code.push(genNode(prop, indent, options))
})
}
}
if (shouldIndentClosing) code.push(' '.repeat(indent))
if (node.isSelfClosing) {
if (!shouldIndentClosing) code.push(' ')
code.push('/>')
} else {
if (selfClosingTag.find((k) => k === node.tag) != null) {
code.push(' ', '/>')
} else {
code.push('>', genChildren(node, indent, options), '</', node.tag, '>')
}
}
return code.join('')
}
function genChildren(
node: ElementNode | RootNode,
indent: number,
options: StringifyOptions,
): string {
const code: string[] = []
const children = applyReplaceNodes(node.children, options)
if (children.length > 0) {
const hasOnlyInlineChildren = children.every(
(child) => !isElementNode(child),
)
if (hasOnlyInlineChildren) {
children.forEach((child) => {
code.push(genNode(child, indent + options.indent, options))
})
} else {
let wasLastChildInline = true
children.forEach((child) => {
if (isTextNode(child) && child.content.trim() === '') return // Ignore empty text nodes.
const isThisChildInline = !isElementNode(child)
if (wasLastChildInline && isThisChildInline) {
// No need to put anything between inline children.
} else if (wasLastChildInline) {
code.push('\n')
} else if (isThisChildInline) {
code.push('\n', ' '.repeat(indent + options.indent))
} else {
code.push('\n')
}
code.push(genNode(child, indent + options.indent, options))
wasLastChildInline = isThisChildInline
})
code.push('\n', ' '.repeat(indent))
}
}
return code.join('')
}
function applyReplaceNodes(nodes: Node[], options: StringifyOptions): Node[] {
return nodes
.map((node) => {
if (options.replaceNodes.has(node)) return options.replaceNodes.get(node)
return node
})
.filter(Boolean) as Node[]
}
function genDirectiveNode(
node: DirectiveNode,
indent: number,
options: StringifyOptions,
): string {
const code: string[] = []
if (options.directive === 'shorthand' && node.name in shorthands) {
code.push(shorthands[node.name as 'bind' | 'on' | 'slot'])
} else {
code.push(`v-${node.name}`)
if (node.arg != null) code.push(':')
}
if (isSimpleExpressionNode(node.arg)) {
if (node.arg.isStatic) code.push(genNode(node.arg, indent, options))
else code.push('[', genNode(node.arg, indent, options), ']')
}
node.modifiers.forEach((modifier) => code.push('.', modifier))
if (isSimpleExpressionNode(node.exp)) {
code.push('="', genNode(node.exp, indent, options), '"')
}
return code.join('')
}
function genAttributeNode(
node: AttributeNode,
indent: number,
options: StringifyOptions,
): string {
return node.value != null
? `${node.name}="${genNode(node.value, indent, options)}"`
: node.name
}
|
145da03d77e676669a1e30391e6a826f6a9bda96
|
TypeScript
|
ninadingole/sls-typescript-api
|
/src/app.ts
| 2.546875
| 3
|
import express from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import HomeController from './controller/home.controller';
import BaseController from './core/base.interface';
export default class App {
public express: express.Application;
constructor(controllers: BaseController[]) {
this.express = express();
this.express.set('port', process.env.PORT || 3000);
this.initializeMiddlewares();
this.initializeRoutes(controllers);
console.log('Initialized done');
}
start(): void {
this.express.listen(this.express.get('port'), () => {
console.log('App is running at http://localhost:%d in %s mode', this.express.get('port'));
console.log(' Press CTRL-C to stop\n');
});
}
private initializeMiddlewares() {
this.express.use(compression());
this.express.use(bodyParser.json());
this.express.use(bodyParser.urlencoded({ extended: true }));
}
private initializeRoutes(controllers: BaseController[]) {
controllers.forEach(controller => {
this.express.use('/', controller.routes());
});
}
}
const app = new App([new HomeController()]);
export { app };
|
06fca884c3d93f9d125e7e6549ff73d17f2556e0
|
TypeScript
|
deathandmayhem/jolly-roger
|
/tests/unit/imports/lib/calendarTimeFormat.ts
| 2.671875
| 3
|
import { assert } from 'chai';
import { calendarTimeFormat } from '../../../../imports/lib/calendarTimeFormat';
describe('calendarTimeFormat', function () {
it('formats dates today correctly', function () {
const now = new Date(2021, 7, 6, 19, 26);
assert.match(calendarTimeFormat(now, now), /Today at 7:26\sPM/);
assert.match(calendarTimeFormat(new Date(2021, 7, 6, 11, 10), now), /Today at 11:10\sAM/);
assert.match(calendarTimeFormat(new Date(2021, 7, 6, 22, 50), now), /Today at 10:50\sPM/);
});
it('formats dates from the last week correctly', function () {
const now = new Date(2021, 7, 6, 19, 26);
assert.match(calendarTimeFormat(new Date(2021, 7, 4, 10, 5), now), /Wed 10:05\sAM/);
});
it('formats dates from more than a week ago long-format', function () {
const now = new Date(2021, 7, 6, 19, 26);
assert.match(calendarTimeFormat(new Date(2021, 6, 20, 15, 25), now), /7\/20\/2021, 3:25\sPM/);
// including the boundary condition, which is a bit odd but ok
assert.match(calendarTimeFormat(new Date(2021, 6, 31, 9, 40), now), /7\/31\/2021, 9:40\sAM/);
});
it('formats future dates in long-format', function () {
const now = new Date(2021, 7, 6, 19, 26);
assert.match(calendarTimeFormat(new Date(2021, 7, 7, 2, 27), now), /8\/7\/2021, 2:27\sAM/);
assert.match(calendarTimeFormat(new Date(2022, 0, 15, 16, 2), now), /1\/15\/2022, 4:02\sPM/);
});
});
|
2294fc2aa702077b267733cc1f8400a7ec3b0da1
|
TypeScript
|
eduardosm7/microhangry
|
/preference-service/src/config/database.ts
| 2.90625
| 3
|
import { createConnection, getRepository, Repository, ObjectType, EntitySchema } from 'typeorm';
/**
* @namespace Config
* @class DatabaseConfig
*/
export default class DatabaseConfig {
public static connectionName: string = `default`;
public static async connect() {
for (let i = 0; i < 5; i++) {
try {
await createConnection(DatabaseConfig.connectionName);
console.log(`Connected successfully to ${DatabaseConfig.connectionName.toUpperCase()}.`);
break;
} catch (e) {
console.log(`Couldn't connect to database: ${e.message}\n\nTrying again in 3 sec...`);
await new Promise(_ => setTimeout(_, 3000));
}
}
}
/**
* Gets repository for the given entity class.
*
* @param entity
*/
public static getRepository<T>(entity: ObjectType<T> | EntitySchema<T> | string): Repository<T> {
return getRepository(entity, DatabaseConfig.connectionName);;
}
}
|
e72a37ffd2ef052daa3f80418e3a9a20fe81ba75
|
TypeScript
|
efureev/mu
|
/src/object/select.ts
| 3.5
| 4
|
/**
* Get value by deep key in object(array)
*
* @example
* const obj = {
key : 0,
label: 'Root',
items: {
one: {
key : 1,
label : 'One',
val : 111,
items : {
two: {
key : 2,
label: 'Two',
val : 111,
items: {},
},
},
children: [{
key : 2,
label: 'Two',
val : 111,
items: {},
}, {
key : 4,
label: 'Four',
val : 444,
}],
},
},
}
* select(obj, 'items.one.children.1.key') // 4
* select(obj, 'items.one.children.3.key', 0) // 0
* select(obj, 'items/one/items/two/items',undefined,'/') // {}
* select({key:null}, 'key') // null
* select({key:''}, 'key') // ''
* select({key:undefined}, 'key', '111') // undefined
*
* @param {object} from
* @param {string} selector
* @param {string} defaultValue [divider=undefined]
* @param {string} divider [divider='.']
* @returns {*}
*/
export default function select(
from: Record<PropertyKey, any>,
selector: string,
defaultValue: any = undefined,
divider: string | RegExp = '.'
) {
return selector.split(divider).reduce(function (previous, current) {
if (previous && current in previous) {
return previous[current]
}
return defaultValue
}, from)
}
|
c07e59e315aa3a2d1ff44bf48de7af93ab316fc0
|
TypeScript
|
markglattback/finer-dev-test
|
/pages/api/createPerson.ts
| 2.625
| 3
|
import knex from 'knex';
import knexConfig from '../../config/knex';
import { FormFields, Gender } from "../../components/Form/types"
import validator from 'validator';
import createTable from '../../lib/createTable';
export default async (req, res) => {
const { body }: { body: FormFields } = req;
let sanitised: FormFields = {
firstName: '',
lastName: '',
email: '',
mobile: '',
gender: Gender.SELECT,
dob: '',
dobDay: '',
dobMonth: '',
dobYear: '',
comments: '',
};
for (const key in body) {
sanitised[key] = validator.escape(body[key]);
}
// connect to DB
const myKnex = knex(knexConfig);
// check table exists
await myKnex.schema.hasTable('person').then(function(exists) {
if (!exists) createTable(myKnex);
});
// insert new person
try {
myKnex('person').insert({
first_name: sanitised.firstName,
surname: sanitised.lastName,
email: sanitised.email,
mobile: sanitised.mobile,
gender: sanitised.gender,
date_of_birth: sanitised.dob,
comments: sanitised.comments
}).then(() => {
res.statusCode = 200
res.json({ message: 'success' });
}).catch(err => {throw Error(err)});
} catch (err) {
console.error(err);
res.statusCode = 500;
res.json({ message: 'failure' });
}
}
|
205d2813eef961ea90cdff074acbb24c61a6ac50
|
TypeScript
|
laijunlinfz/bookmarksync
|
/src/utils/treeUtils.ts
| 2.828125
| 3
|
/**
* 对比本地和服务器书签数据,找出需要更改的数据
*/
let delList: string[] = [];
let updateList: any[] = [];
let createList: any[] = [];
let createCloudList: any[] = [];
const checkDelList = (itemLocal: any, cloudList: any[] = [], recentBookmark: any[] = []): void => {
const { id = '' } = itemLocal || {};
// console.log('itemLocal --- ', itemLocal);
// console.log('cloudList --- ', cloudList);
// console.log('recentBookmark --- ', recentBookmark);
if (!cloudList.some((c) => c.id === id)) {
if (recentBookmark.some((r) => r.id === id)) {
createCloudList.push(itemLocal);
} else {
delList.push(id);
}
}
};
const checkCreateList = (itemCloud: any, localList: any[]): void => {
const { id } = itemCloud;
if (!localList.some((l) => l.id === id)) {
createList.push(itemCloud);
}
};
const checkUpdateList = (itemCloud: any, localList: any[]): void => {
const { id, url, title } = itemCloud;
localList.forEach(item => {
if (id === item.id && url !== item.url && title !== item.title) {
updateList.push(itemCloud);
}
})
};
export const merge = (localBookmark: any, cloudBookmark: any, recentBookmark: any) => {
delList = [];
updateList = [];
createList = [];
createCloudList = [];
if (!cloudBookmark) {
return localBookmark;
}
const recordChange = (localList: any[], cloudList: any[]): void => {
for (let i = 0; i < cloudList.length; i++) {
const itemCloud = cloudList[i];
const itemLocal = localList[i];
checkDelList(itemLocal, cloudList, recentBookmark);
checkCreateList(itemCloud, localList);
checkUpdateList(itemCloud, localList);
const hasNext = itemLocal && Array.isArray(itemLocal.children) && itemCloud && Array.isArray(itemCloud.children);
if (hasNext) {
recordChange(itemLocal.children, itemCloud.children);
}
}
};
recordChange(localBookmark, cloudBookmark);
return { delList, updateList, createList, createCloudList };
};
|
ef5b723826c1505799beef02260b3ee53e9d0f78
|
TypeScript
|
ra81/XioPorted
|
/XioTest/7_PageParserFunctions.ts
| 2.75
| 3
|
//
// Сюда все функции которые парсят данные со страниц
//
/**
* Пробуем оцифровать данные но если они выходят как Number.POSITIVE_INFINITY или 0, валит ошибку
* @param value строка являющая собой число больше 0
*/
function numberfyOrError(value: string) {
let n = numberfy(value);
if (n === Number.POSITIVE_INFINITY || n === 0)
throw new RangeError("Должны получить число > 0");
return n;
}
/**
* Из набора HTML элементов представляющих собой tr парсит subid. Ряды должны быть стандартного формата.
*/
function parseSubid(trList: HTMLTableRowElement[]): number[] {
if (trList == null)
throw new ArgumentNullError("trList");
let f = (i: number, e: Element) => numberfyOrError($(e).text());
return $(trList).find("td.unit_id").map(f).get() as any as number[];
}
/**
* Берет локальное хранилище и тащит оттуда все записи по юнитам. возвращает subid
*/
function parseAllSavedSubid(realm: string): number[] {
if (!realm || realm.length === 0)
throw new ArgumentNullError("realm");
let subids: number[] = [];
let rx = new RegExp("x" + realm + "\\d+");
for (let key in localStorage) {
if (!rx.test(key))
continue;
let m = key.match(/\d+/);
if (m != null)
subids.push(numberfy(m[0]));
}
return subids;
}
/**
* Парсит id компании со страницы
*/
function getCompanyId() {
let m = $(".dashboard a").attr("href").match(/\d+/);
if (m == null)
throw new ParseError("company id");
return numberfy(m[0]);
}
/**
* Парсинг главной страницы с юнитами.
* @param html
* @param url
*/
function parseUnitList(html: any, url: string): IUnitList {
let $html = $(html);
let $unitList = $html.find(".unit-list-2014");
try {
let _subids = $unitList.find("td:nth-child(1)").map((i, e) => numberfyOrError($(e).text())).get() as any as number[];
let _type = $unitList.find("td:nth-child(3)").map((i, e) => {
let s = $(e).attr("class").split("-")[1];
if (s == null)
throw new RangeError("class attribute doesn't contains type part.");
return s;
}).get() as any as string[];
return { subids: _subids, type: _type };
}
catch (err) {
throw new ParseError("unit list", url, err);
}
}
/**
* Парсит "/main/unit/view/ + subid + /sale" урлы
* @param html
* @param url
*/
function parseSale(html: any, url: string): ISale {
let $html = $(html);
try {
let _form = $html.find("[name=storageForm]") as JQuery;
let _policy = $html.find("select:even").map((i, e) => {
let f = $(e).find("[selected]").index();
if (f < 0)
throw new RangeError("policy index < 0");
return f;
}).get() as any as number[];
let _price = $html.find("input.money:even").map((i, e) => numberfyOrError($(e).val())).get() as any as number[];
let _incineratorMaxPrice = $html.find('span[style="COLOR: green;"]').map((i, e) => numberfyOrError($(e).text())).get() as any as number[];
let _outqual = $html.find("td:has('table'):nth-last-child(6) tr:nth-child(2) td:nth-child(2)").map((i, e) => numberfyOrError($(e).text())).get() as any as number[];
let _outprime = $html.find("td:has('table'):nth-last-child(6) tr:nth-child(3) td:nth-child(2)").map((i, e) => numberfyOrError($(e).text())).get() as any as number[];
let _stockqual = $html.find("td:has('table'):nth-last-child(5) tr:nth-child(2) td:nth-child(2)").map((i, e) => numberfyOrError($(e).text())).get() as any as number[];
let _stockprime = $html.find("td:has('table'):nth-last-child(5) tr:nth-child(3) td:nth-child(2)").map((i, e) => numberfyOrError($(e).text())).get() as any as number[];
// название продукта Спортивное питание, Маточное молочко и так далее
let _product = $html.find(".grid a:not([onclick])").map((i, e) => {
let t = $(e).text();
if (t.trim() === "")
throw new Error("product name is empty");
return t;
}).get() as any as string[];
// урл на продукт
let _productId = $html.find(".grid a:not([onclick])").map((i, e) => {
let m = $(e).attr("href").match(/\d+/);
if (m == null)
throw new Error("product id not found.");
return numberfyOrError(m[0]);
}).get() as any as number[];
// "Аттика, Македония, Эпир и Фессалия"
let _region = $html.find(".officePlace a:eq(-2)").text();
if (_region.trim() === "")
throw new Error("region not found");
// если покупцов много то появляется доп ссылка на страницу с контрактами. эта херь и говорит есть она или нет
let _contractpage = !!$html.find(".tabsub").length;
// данное поле существует только если НЕТ ссылки на контракты то есть в простом случае и здесь может быть такой хуйня
// ["Молоко", "$1.41", "$1.41", "$1.41", "Мясо", "$5.62"]
// идет категория, потом цены покупателей, потом снова категория и цены. И как бы здесь нет порядка
// Если покупателей нет, гарантируется пустой массив!
let _contractprice = ($html.find("script:contains(mm_Msg)").text().match(/(\$(\d|\.| )+)|(\[\'name\'\] = \"[a-zA-Zа-яА-ЯёЁ ]+\")/g) || []).map((e) => {
return e[0] === "[" ? e.slice(13, -1) : numberfy(e);
}) as any as string|number[];
return {
form: _form,
policy: _policy,
price: _price,
incineratorMaxPrice: _incineratorMaxPrice,
outqual: _outqual,
outprime: _outprime,
stockqual: _stockqual,
stockprime: _stockprime,
product: _product,
productId: _productId,
region: _region,
contractpage: _contractpage,
contractprice: _contractprice
};
}
catch (err) {
throw new ParseError("sale", url, err);
}
}
/**
* Парсит страницы вида "/main/unit/view/ + subid + /sale/product", а так же
* "/main/unit/view/" + subid + "/sale/product/ + productId"
* @param html
* @param url
*/
function parseSaleContracts(html: any, url: string): ISaleContract {
let $html = $(html);
// слегка дибильный подход. В объекте мы имеем цены покупцов для одной категории по url, но список категорий
// каждый раз забираем весь.
// TODO: перепилить. Сделать контракт как {url:string, ИмяТовара:string, prices: number[]}
// итоговая структура будет выглядеть так
/* $mapped[subid/sale/product] = {
categories: string[]; - список урлов категорий
}
а далее
$mapped[subid/sale/product/prodId] = {
prodName: string; - строковое имя продукта
buyerPrices: number[]; - массив цен покупцов данного товара
}
аналогично делать ISale. Вместо хуйни с string|number вставить туда сразу свойство
contracts: IDictionary<ISaleContract> содержащее инфу по всем товарам. ключом будет productId или его урл
*/
try {
// каждая категория представляет товар который продается со склада или производства. По факту берем ссыль через которую
// попадаем на список покупателей товара.
// если покупцов товара НЕТ, тогда данной категории не будет. То есть не может быть пустая категория
let _categorys = $html.find("#productsHereDiv a").map(function (i, e) { return $(e).attr("href"); }).get() as any as string[];
// здесь уже есть четкая гарантия что резалт будет вида
// ["Медицинский инструментарий", 534.46, 534.46, 534.46, 534.46]
// то есть первым идет название а потом цены покупателей
let _contractprices = ($html.find("script:contains(mm_Msg)").text().match(/(\$(\d|\.| )+)|(\[\'name\'\] = \"[a-zA-Zа-яА-ЯёЁ ]+\")/g) || []).map(function (e) { return e[0] === "[" ? e.slice(13, -1) : numberfy(e) }) as any as string | number[]
return { category: _categorys, contractprice: _contractprices };
}
catch (err) {
throw new ParseError("sale contracts", url, err);
}
}
/**
* Парсинг данных по страницы /main/unit/view/8004742/virtasement
* @param html
* @param url
*/
function parseAds(html: any, url: string): IAds {
let $html = $(html);
try {
// известность
let _celebrity = numberfy($html.find(".infoblock tr:eq(0) td:eq(1)").text());
// население города
let _pop = (() => {
let m = $html.find("script").text().match(/params\['population'\] = \d+/);
if (m == null)
throw new Error("population number not found.");
return numberfy(m[0].substring(23));
})();
// текущий бюджет, он может быть и 0
let _budget = numberfy($html.find(":text:not([readonly])").val());
// бюжет на поддержание известности
// ["не менее ©110.25 в неделю для ТВ-рекламы"] здесь может быть и $110.25
// данный бюжет тоже может быть 0 если известность 0
let _requiredBudget = numberfy($html.find(".infoblock tr:eq(1) td:eq(1)").text().split(/[$©]/g)[1]);
//if (_celebrity > 0 && _requiredBudget === 0) такое может быть при хреновой известности
// throw new Error("required budget can't be 0 for celebrity" + _celebrity);
return {
celebrity: _celebrity,
pop: _pop,
budget: _budget,
requiredBudget: _requiredBudget
};
}
catch (err) {
throw new ParseError("ads", url, err);
}
}
/**
* Парсим данные с формы зарплаты /window/unit/employees/engage/" + subid
* @param html
* @param url
*/
function parseSalary(html: any, url: string): ISalary {
let $html = $(html);
try {
let _form = $html.filter("form");
let _employees = numberfy($html.find("#quantity").val());
let _maxEmployees = numberfy($html.find("tr.even:contains('Максимальное количество')").find("td.text_to_left").text());
if (_maxEmployees <= 0)
throw new RangeError("Макс число рабов не может быть 0.");
let _salaryNow = numberfy($html.find("#salary").val());
let _salaryCity = numberfyOrError($html.find("tr:nth-child(3) > td").text().split(/[$©]/g)[1]);
let _skillNow = numberfy($html.find("#apprisedEmployeeLevel").text());
let _skillCity = (() => {
let m = $html.find("div span[id]:eq(1)").text().match(/[0-9]+(\.[0-9]+)?/);
if (m == null)
throw new Error("city skill not found.");
return numberfyOrError(m[0]);
})();
let _skillReq = (() => {
let m = $html.find("div span[id]:eq(1)").text().split(",")[1].match(/(\d|\.)+/);
if (m == null)
throw new Error("skill req not found.");
return numberfy(m[0]);
})();
return {
form: _form,
employees: _employees,
maxEmployees: _maxEmployees,
salaryNow: _salaryNow,
salaryCity: _salaryCity,
skillNow: _skillNow,
skillCity: _skillCity,
skillReq: _skillReq
};
}
catch (err) {
throw new ParseError("unit list", url, err);
}
}
/**
* /main/user/privat/persondata/knowledge
* @param html
* @param url
*/
function parseManager(html: any, url: string): ITopManager {
let $html = $(html);
try {
let _base = $html.find(".qual_item .mainValue").map((i, e) => numberfyOrError($(e).text())).get() as any as number[];
let _bonus = $html.find(".qual_item .bonusValue").map((i, e) => numberfy($(e).text())).get() as any as number[];
let _pic = $html.find(".qual_item img").map((i, e) => $(e).attr("src")).get() as any as string[];
return {
base: _base,
bonus: _bonus,
pic: _pic
};
}
catch (err) {
throw new ParseError("top manager", url, err);
}
}
/**
* /main/unit/view/ + subid
* @param html
* @param url
*/
function parseUnitMain(html: any, url: string): IMain {
let $html = $(html);
try {
let newInterf = $html.find(".unit_box").length > 0;
if (newInterf) {
let _employees = numberfy($html.find(".unit_box:has(.fa-users) tr:eq(0) td:eq(1)").text());
let _salaryNow = numberfy($html.find(".unit_box:has(.fa-users) tr:eq(2) td:eq(1)").text());
let _salaryCity = numberfy($html.find(".unit_box:has(.fa-users) tr:eq(3) td:eq(1)").text());
let _skillNow = numberfy($html.find(".unit_box:has(.fa-users) tr:eq(4) td:eq(1)").text());
let _skillReq = numberfy($html.find(".unit_box:has(.fa-users) tr:eq(5) td:eq(1)").text());
// TODO: в новом интерфейсе не все гладко. проверить как оборудование ищет
let _equipNum = numberfy($html.find(".unit_box:has(.fa-cogs) tr:eq(0) td:eq(1)").text());
let _equipMax = numberfy($html.find(".unit_box:has(.fa-cogs) tr:eq(1) td:eq(1)").text());
let _equipQual = numberfy($html.find(".unit_box:has(.fa-cogs) tr:eq(2) td:eq(1)").text());
let _equipReq = numberfy($html.find(".unit_box:has(.fa-cogs) tr:eq(3) td:eq(1)").text());
let _equipWearBlack = numberfy($html.find(".unit_box:has(.fa-cogs) tr:eq(4) td:eq(1)").text().split("(")[1]);
let _equipWearRed = $html.find(".unit_box:has(.fa-cogs) tr:eq(4) td:eq(1) span").length === 1;
let _managerPic = $html.find(".unit_box:has(.fa-user) ul img").attr("src");
let _qual = numberfy($html.find(".unit_box:has(.fa-user) tr:eq(1) td:eq(1)").text());
let _techLevel = numberfy($html.find(".unit_box:has(.fa-industry) tr:eq(3) td:eq(1)").text());
// общее число подчиненных по профилю
let _totalEmployees = numberfy($html.find(".unit_box:has(.fa-user) tr:eq(2) td:eq(1)").text());
let _img = $html.find("#unitImage img").attr("src").split("/")[4].split("_")[0];
let _size = numberfy($html.find("#unitImage img").attr("src").split("_")[1]);
let _hasBooster = !$html.find("[src='/img/artefact/icons/color/production.gif']").length;
let _hasAgitation = !$html.find("[src='/img/artefact/icons/color/politics.gif']").length;
let _onHoliday = !!$html.find("[href$=unset]").length;
let _isStore = !!$html.find("[href$=trading_hall]").length;
let _departments = numberfy($html.find("tr:contains('Количество отделов') td:eq(1)").text());
let _visitors = numberfy($html.find("tr:contains('Количество посетителей') td:eq(1)").text());
return {
employees: _employees,
totalEmployees: _totalEmployees,
employeesDemand: -1,
salaryNow: _salaryNow,
salaryCity: _salaryCity,
skillNow: _skillNow,
skillCity: -1,
skillReq: _skillReq,
equipNum: _equipNum,
equipMax: _equipMax,
equipQual: _equipQual,
equipReq: _equipReq,
equipBroken: -1,
equipWearBlack: _equipWearBlack,
equipWearRed: _equipWearRed,
managerPic: _managerPic,
qual: _qual,
techLevel: _techLevel,
img: _img,
size: _size,
hasBooster: _hasBooster,
hasAgitation: _hasAgitation,
onHoliday: _onHoliday,
isStore: _isStore,
departments: _departments,
visitors: _visitors
};
}
else {
let rxFloat = new RegExp(/\d+\.\d+/g);
let rxInt = new RegExp(/\d+/g);
let $block = $html.find("table.infoblock");
// Количество рабочих. может быть 0 для складов.
let empl = (() => {
// Возможные варианты для рабочих будут
// 10(требуется ~ 1)
// 10(максимум:1)
// 10 ед. (максимум:1) это уже не включать
let emplRx = new RegExp(/\d+\s*\(.+\d+.*\)/g);
let jq = $block.find("td.title:contains('Количество')").next("td").filter((i, el) => emplRx.test($(el).text()));
if (jq.length !== 1)
return ["-1", "-1"];
let m = jq.text().match(rxInt);
if (!m || m.length !== 2)
return ["-1", "-1"];
return m as string[];
})();
let _employees = numberfy(empl[0]);
let _employeesDemand = numberfy(empl[1]);
// общее число подчиненных по профилю
let _totalEmployees = numberfy($block.find("td:contains('Суммарное количество подчинённых')").next("td").text());
let salary = (() => {
//let rx = new RegExp(/\d+\.\d+.+в неделю\s*\(в среднем по городу.+?\d+\.\d+\)/ig);
let jq = $block.find("td.title:contains('Зарплата')").next("td");
if (jq.length !== 1)
return ["-1", "-1"];
let m = jq.text().match(rxFloat);
if (!m || m.length !== 2)
return ["-1", "-1"];
return m;
})();
let _salaryNow = numberfy(salary[0]);
let _salaryCity = numberfy(salary[1]);
let skill = (() => {
let jq = $block.find("td.title:contains('Уровень квалификации')").next("td");
if (jq.length !== 1)
return ["-1", "-1", "-1"];
// возможные варианты результата
// 10.63 (в среднем по городу 9.39, требуется по технологии 6.74)
// 9.30(в среднем по городу 16.62 )
let m = jq.text().match(rxFloat);
if (!m || m.length < 2)
return ["-1", "-1", "-1"];
return [m[0], m[1], m[2] || "-1"];
})();
let _skillNow = numberfy(skill[0]);
let _skillCity = numberfy(skill[1]);
let _skillReq = numberfy(skill[2]); // для лаб требования может и не быть
let equip = (() => {
let res = [-1, -1, -1, -1, -1, -1, -1];
// число оборудования тупо не ищем. гемор не надо
// качество оборудования и треб по технологии
let jq = $block.find("td.title:contains('Качество')").next("td");
if (jq.length === 1) {
// 8.40 (требуется по технологии 1.00)
// или просто 8.40 если нет требований
let m = jq.text().match(rxFloat);
if (m && m.length > 0) {
res[2] = parseFloat(m[0]) || -1;
res[3] = parseFloat(m[1]) || -1;
}
}
// красный и черный и % износа
// 1.28 % (25+1 ед.)
// 0.00 % (0 ед.)
jq = $block.find("td.title:contains('Износ')").next("td");
if (jq.length === 1) {
let rx = new RegExp(/(\d+\.\d+)\s*%\s*\((\d+)(?:\+(\d+))*.*\)/ig);
let m = rx.exec(jq.text());
if (m) {
// первым идет сама исходная строка
res[4] = parseFloat(m[1]); // 0 или float.
res[5] = parseInt(m[2]); // 0 или целое
res[6] = parseInt(m[3]) || -1; // красного может не быть будет undefined
}
}
return res;
})();
let _equipNum = equip[0];
let _equipMax = equip[1];
let _equipQual = equip[2];
let _equipReq = equip[3];
// % износа
let _equipBroken = equip[4];
// кол-во черного оборудования
let _equipWearBlack = equip[5];
// есть ли красное оборудование или нет
let _equipWearRed = equip[6] > 0;
let _managerPic = "";
let _qual = (() => {
let jq = $block.find("td.title:contains('Квалификация игрока')").next("td");
if (jq.length !== 1)
return -1;
return numberfy(jq.text());
})();
let _techLevel = (() => {
let jq = $block.find("td.title:contains('Уровень технологии')").next("td");
if (jq.length !== 1)
return -1;
return numberfy(jq.text());
})();
let _img = $html.find("#unitImage img").attr("src").split("/")[4].split("_")[0];
let _size = numberfy($html.find("#unitImage img").attr("src").split("_")[1]);
let _hasBooster = !$html.find("[src='/img/artefact/icons/color/production.gif']").length;
let _hasAgitation = !$html.find("[src='/img/artefact/icons/color/politics.gif']").length;
let _onHoliday = !!$html.find("[href$=unset]").length;
let _isStore = !!$html.find("[href$=trading_hall]").length;
let _departments = numberfy($html.find("tr:contains('Количество отделов') td:eq(1)").text()) || -1;
let _visitors = numberfy($html.find("tr:contains('Количество посетителей') td:eq(1)").text()) || -1;
return {
employees: _employees,
totalEmployees: _totalEmployees,
employeesDemand: _employeesDemand,
salaryNow: _salaryNow,
salaryCity: _salaryCity,
skillNow: _skillNow,
skillCity: _skillCity,
skillReq: _skillReq,
equipNum: _equipNum,
equipMax: _equipMax,
equipQual: _equipQual,
equipReq: _equipReq,
equipBroken: _equipBroken,
equipWearBlack: _equipWearBlack,
equipWearRed: _equipWearRed,
managerPic: _managerPic,
qual: _qual,
techLevel: _techLevel,
img: _img,
size: _size,
hasBooster: _hasBooster,
hasAgitation: _hasAgitation,
onHoliday: _onHoliday,
isStore: _isStore,
departments: _departments,
visitors: _visitors
};
}
}
catch (err) {
throw new ParseError("unit main page", url, err);
}
}
function parseX(html: any, url: string) {
}
|
6a72dd5433d9ecb4ce6fbab06525a24f6c07876f
|
TypeScript
|
keesey/simple-digraph
|
/src/isProperSubsetOf.ts
| 2.703125
| 3
|
import { VertexSet } from "./VertexSet";
export const isProperSubsetOf = (a: VertexSet, b: VertexSet): boolean => {
if (a.size >= b.size) {
return false;
}
return [...a].every((v) => b.has(v));
};
export default isProperSubsetOf;
|
d634ad19206213575578e207a1289602a77ee12b
|
TypeScript
|
lodz-university-of-technology-masi/Magenta
|
/web/src/app/metrics-processor/services/distance-calculator.service.ts
| 2.875
| 3
|
import {Injectable} from '@angular/core';
import {MousePosition} from "../../models/mouse-position";
@Injectable({
providedIn: 'root'
})
export class DistanceCalculatorService {
private positions: MousePosition[];
private isProcessing: boolean = false;
private scrollDistance: number = 0;
constructor() {
}
switchProcessing(interrupted?: boolean): void {
if (interrupted) {
this.isProcessing = false;
} else {
this.isProcessing = !this.isProcessing;
}
if (this.isProcessing) {
this.resetValues();
}
}
addPosition(event: MouseEvent): void {
if (this.isProcessing) {
this.positions.push(new MousePosition(event.clientX, event.clientY));
}
}
getDistance(): number {
return this.calculateDistance();
}
addScrollDistance(dst: number): void {
this.scrollDistance += dst;
}
private calculateDistance(): number {
if (this.positions.length) {
let distance = this.calcPointsDistance(new MousePosition(0, 0), this.positions.shift());
for (let i = 1; i < this.positions.length - 1; i++) {
distance += this.calcPointsDistance(this.positions[i], this.positions[i + 1]);
}
return distance;
}
}
private resetValues(): void {
this.positions = [];
this.scrollDistance = 0;
}
private calcPointsDistance(p1: MousePosition, p2: MousePosition): number {
return Math.sqrt(Math.pow(p2.getX - p1.getX, 2) + Math.pow(p2.getY - p1.getY, 2)) + this.scrollDistance;
}
}
|
166effdc6125fbc5902db0892de45f072f7ce04a
|
TypeScript
|
paolodenti/factoryjs
|
/index.ts
| 3.0625
| 3
|
import MyCounter from "./myCounter";
const main = async () => {
const c = MyCounter({ name: "some counter ..." });
c.setVal(3);
c.add();
c.sub(6);
console.log(`${c.getName()}: ${c.getVal()}`);
c.add(50);
setTimeout(c.log, 2000);
};
main().catch(err => {
console.log(err);
});
|
3c80b4ae8ef4934522d8ead61fe88ec6dba25d18
|
TypeScript
|
WooodHead/nest-mikro-crud
|
/src/utils/walk-path.func.ts
| 3
| 3
|
export function walkPath(
obj: Record<string, unknown>,
path: string,
callback?: (obj: Record<string, any>, key: string) => unknown
) {
/**The keys to approach the target object */
const keys = path.split(".");
/**The key to the value of the target object */
const key = keys.pop()!;
// approach the target object
keys.forEach((key) => (obj = (obj[key] as typeof obj) ?? (obj[key] = {})));
if (callback) callback(obj, key);
return obj[key];
}
|
280c6fd3eea5243fb549f348e00e5bafa204ac64
|
TypeScript
|
dhruvisompura/HappyIslandDesigner
|
/app/ui/loadingScreen.ts
| 2.546875
| 3
|
let element;
// this is a hack until React gets added
function createElement() {
let div = document.createElement("div");
div.id = 'bobContainer';
let img = document.createElement("img");
img.src = "static/gif/bob-loading.gif";
img.id = "bob";
let p = document.createElement("p");
p.style.fontFamily = "TTNorms";
p.style.color = "#726a5a";
p.textContent = "Please wait a bit...";
div.appendChild(img);
div.appendChild(p);
return div;
}
let hideTimeout;
export function showLoadingScreen(isShown) {
if (!element) {
element = createElement();
document.body.appendChild(element);
}
clearTimeout(hideTimeout);
if (isShown) {
element.style.display = 'block';
}
// for some reason it needs a frame before it will animate the opacity
setTimeout(() => element.style.opacity = isShown ? 1 : 0, 10);
if (!isShown) {
hideTimeout = setTimeout(() => element.style.display = 'none', 500);
}
}
|
606adf8d425d2e74beec2493c9594b371a21aeab
|
TypeScript
|
jelbaz-ledger/ui
|
/packages/native/src/components/Text/getTextStyle.ts
| 3.015625
| 3
|
export type TextTypes =
| "h1"
| "h2"
| "h3"
| "highlight"
| "emphasis"
| "body"
| "cta"
| "link"
| "tiny"
| "subTitle"
| "navigation"
| "tag";
export default function getTextStyle({
type,
bracket,
}: {
type: TextTypes;
bracket?: boolean;
}): {
fontFamily: string;
fontSize: number;
lineHeight: number;
fontWeight?: number;
textDecoration?: string;
paddingTop?: number;
} {
switch (type) {
case "h1":
return {
fontFamily: "Alpha",
fontSize: 36,
lineHeight: 43.2,
paddingTop: bracket ? 15 : 0,
};
case "h2":
return {
fontFamily: "Alpha",
fontSize: 28,
lineHeight: 33.6,
paddingTop: bracket ? 10 : 0,
};
case "h3":
return {
fontFamily: "Alpha",
fontSize: 20,
lineHeight: 24,
paddingTop: bracket ? 5 : 0,
};
case "highlight":
return {
fontFamily: "Inter",
fontSize: 16,
lineHeight: 19.36,
};
case "emphasis":
return {
fontFamily: "Inter",
fontSize: 14,
lineHeight: 20,
};
case "body":
return {
fontFamily: "Inter",
fontSize: 13,
lineHeight: 20,
};
case "cta":
return {
fontFamily: "Inter",
fontSize: 13,
lineHeight: 15.73,
fontWeight: 600,
};
case "link":
return {
fontFamily: "Inter",
fontSize: 13,
lineHeight: 16,
textDecoration: "underline",
};
case "tiny":
return {
fontFamily: "Inter",
fontSize: 12,
lineHeight: 16,
};
case "navigation":
return {
fontFamily: "Inter",
fontSize: 12,
lineHeight: 14.52,
fontWeight: 600,
};
case "subTitle":
return {
fontFamily: "Inter",
fontSize: 11,
lineHeight: 13.31,
fontWeight: 600,
};
case "tag":
return {
fontFamily: "Inter",
fontSize: 10,
lineHeight: 12.1,
fontWeight: 600,
};
default:
return {
fontFamily: "Inter",
fontSize: 13,
lineHeight: 20,
};
}
}
|
b6d3ea4c0ec2716a702918581267c4029a8bf631
|
TypeScript
|
justinlubin/ts-game
|
/systems/Input.ts
| 2.5625
| 3
|
class Input implements FixedSystem {
readonly requirements =
new Set<Component>([Component.PHYSICS, Component.USER_CONTROL]);
update(w: World, dt: number): void {
w.forall(this.requirements, e => {
let xVel = 0;
if (w.model.keys.has(Key.RIGHT)) {
xVel += w.physics[e].walkSpeed;
}
if (w.model.keys.has(Key.LEFT)) {
xVel -= w.physics[e].walkSpeed;
}
w.physics[e].velocity = new Vec(xVel, w.physics[e].velocity.y);
if (w.model.keys.has(Key.Z) && w.physics[e].grounded) {
w.physics[e].velocity =
w.physics[e].velocity.add(new Vec(0, -w.physics[e].jumpSpeed));
}
});
}
}
|
b44228faa7c79d0e8ef51700cf4b3141c4c04977
|
TypeScript
|
njaegergrassl/Haushaltsbuch
|
/src/providers/category/category.ts
| 2.640625
| 3
|
import { Injectable } from '@angular/core';
import firebase from 'firebase/app';
import {CategoryEntry} from "../../models/category-entry";
// this class is handling the categoriex in the firebase database
@Injectable()
export class CategoryProvider {
public categoryListRef: firebase.database.Reference;
// this constructor adds a function for updating local bookingListReference to the firebase changeAuthEvent
constructor() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.categoryListRef = firebase.database().ref(`/user/${user.uid}/categoryList`);
}
});
}
// this function returns the categoryList
getCategoryList() : firebase.database.Reference {
return this.categoryListRef;
}
// this function adds a Category to the categoryList and stores it to the database
addCategoryEntry(category: CategoryEntry): PromiseLike<any> {
return this.categoryListRef.push({
name: category.name
});
}
// this function updates a Category to the categoryList and stores it to the database
updateCategoryEntry(category: CategoryEntry): PromiseLike<any> {
return this.categoryListRef.child(category.key).set({
name: category.name
});
}
// this function delete a Category from the categoryList and deletes it on the database
removeCategoryEntry(category: CategoryEntry): PromiseLike<any> {
return this.categoryListRef.child(category.key).remove();
}
}
|
614f419a954ad4b37682db45a381dda508ae1a9c
|
TypeScript
|
khteh/Node.JSRestAPI
|
/src/webapi.core/Domain/Entities/Student.ts
| 2.78125
| 3
|
import { Entity, Column, ManyToMany, JoinTable } from "typeorm"
import { EntityBase } from "./EntityBase"
import { Teacher } from "./Teacher"
@Entity()
export class Student extends EntityBase {
@Column({ length: 256 })
public firstName: string
@Column({ length: 256 })
public lastName: string
@Column({ unique: true, length: 256 })
public email: string
@Column()
public isSuspended: boolean
@ManyToMany((type) => Teacher, (teacher) => teacher.students)
@JoinTable()
public teachers: Teacher[]
constructor(first: string, last: string, email: string, isSuspended?: boolean) {
super();
this.firstName = first;
this.lastName = last;
this.email = email;
this.isSuspended = isSuspended ?? false;
//this.teachers = []; TypeORM initialization failed! InitializedRelationError: Array initializations are not allowed in entity relations
}
}
//export type StudentDTO = Pick<Student, { [K in keyof Student]: Student[K] extends Function ? never : K }[keyof Student]>;
|
b94d753610d1077b24fa02fa4e5d557e9b677bba
|
TypeScript
|
RahulKwani/BasicApp
|
/src/app/components/user-form/user-form.component.ts
| 2.609375
| 3
|
import { Component } from '@angular/core';
import { FormControl,FormArray, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { FormsModule } from '@angular/forms';
import * as cloneDeep from 'lodash/cloneDeep';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
userForm: FormGroup;
jobTypes = [
{ id: 1, name: 'Onsite', value: "OS" },
{ id: 2, name: 'Partial Remote', value: "PR" },
{ id: 3, name: 'Full Time Remote', value: "FR" }
];
technologies = ['Front-end development', 'Back-end development', 'Full-stack developement','Data Science', 'DB Administrator'];
constructor(private formBuilder: FormBuilder) {
const controls = this.jobTypes.map(c => new FormControl(false));
controls[0].setValue(true); // Set the first checkbox to
this.userForm = this.createFormGroupWithBuilder(formBuilder , controls);
}
createFormGroupWithBuilder(formBuilder: FormBuilder, controls) {
return formBuilder.group({
firstName: ['' , Validators.required],
lastName: '',
city: ['' , Validators.required],
tech: '',
gender: ['' , Validators.required],
email: new FormControl('',[Validators.required , Validators.pattern("[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")]),
phoneNumber: new FormControl('',[Validators.required , Validators.minLength(8), Validators.pattern("[0-9]+")]),
message: '',
jobTypes: new FormArray(controls)
});
}
onSubmit(){
const result: any = Object.assign({}, this.userForm);
console.log('after submit');
console.log(result);
result.value.jobTypes = this.findJobType(this.userForm.value.jobTypes);
console.log(JSON.stringify(result.value));
alert('SUCCESS!! :-)\n\n' + JSON.stringify(result.value));
}
revert(){
this.userForm.reset(UserRequest);
}
findJobType(selectedJobs : string[]){
let jobTypes = [];
for(let job in selectedJobs){
jobTypes.push(this.jobTypes[job]['value']);
}
return jobTypes;
}
}
export class UserRequest {
firstName: string = '';
lastName: string = '';
city: string = '';
gender: string = '';
tech: string = '';
email: string = '';
phoneNumber: string = '';
message: string = '';
}
|
b33d66e7885d3d8bfd229b62a43ceeaf38043fba
|
TypeScript
|
doug-martin/nestjs-query
|
/packages/query-graphql/src/types/subscription-filter-input.type.ts
| 2.703125
| 3
|
import { Filter, Class } from '@nestjs-query/core';
import { Field, InputType } from '@nestjs/graphql';
import { ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
import { SubscriptionFilterType } from './query';
export interface SubscriptionFilterInputType<DTO> {
filter?: Filter<DTO>;
}
/**
* Input abstract type for all subscription filters.
* @param DTOClass - The DTO used to create a FilterType for the filter.
*/
// eslint-disable-next-line @typescript-eslint/no-redeclare -- intentional
export function SubscriptionFilterInputType<DTO>(DTOClass: Class<DTO>): Class<SubscriptionFilterInputType<DTO>> {
const F = SubscriptionFilterType(DTOClass);
@InputType({ isAbstract: true })
class SubscriptionFilterInput implements SubscriptionFilterInputType<DTO> {
@Field(() => F, {
description: 'Specify to filter the records returned.',
})
@ValidateNested()
@Type(() => F)
filter?: Filter<DTO>;
}
return SubscriptionFilterInput;
}
|
bd7368429c5b5f4395ba688a86f58507810148d7
|
TypeScript
|
TarunKhandelwal/application
|
/event_practice/src/main/emitter/event_emitter.ts
| 2.796875
| 3
|
import * as events from 'events';
import {EventType} from '../common/event_type';
export class CommonEventEmitter{
private eventEmitter: events.EventEmitter;
private static instance: CommonEventEmitter;
private constructor(){
this.eventEmitter = new events.EventEmitter();
}
public registerEvent(eventType:EventType, handler:any){
this.eventEmitter.on(EventType[eventType], handler);
}
public callEvent(eventType:EventType, eventValue:string){
this.eventEmitter.emit(EventType[eventType], eventValue);
}
public static getInstance(): CommonEventEmitter{
if(CommonEventEmitter.instance == null){
CommonEventEmitter.instance = new CommonEventEmitter();
}
return CommonEventEmitter.instance;
}
}
|
49bb4b4f16e79887b1acce004e19f4ad8b11fd6a
|
TypeScript
|
rajarshidatta007/novopay-assignment
|
/src/main/webapp/app/shared/model/wallet.model.ts
| 2.578125
| 3
|
export interface IWallet {
id?: number;
balance?: number;
owenerId?: number;
passbookId?: number;
}
export class Wallet implements IWallet {
constructor(public id?: number, public balance?: number, public owenerId?: number, public passbookId?: number) {}
}
|
fe214a840f97d34a236e1e69a1478ff48759766a
|
TypeScript
|
kuzzleio/kourou
|
/test/commands/instance/list.test.ts
| 2.515625
| 3
|
import { expect, test } from "@oclif/test";
import { execSync } from "child_process";
const TEST_TIMEOUT = 50000;
const PRINT_STDOUT = false;
const checkStackDetails = (
stdout: string,
line: number,
expectedValues: any
) => {
const splittedOutput: string[] = stdout.split("\n");
const stackLine: string[] = splittedOutput[6 + line]
.split(/[ ]{1,}/)
.join("")
.split("│");
expect(stackLine[1]).to.contain(expectedValues.index);
expect(stackLine[2]).to.contain(expectedValues.name);
expect(stackLine[3]).to.match(expectedValues.status);
expect(stackLine[4]).to.contain(expectedValues.kuzzleVersion);
expect(stackLine[5]).to.contain(expectedValues.kuzzlePort);
expect(stackLine[6]).to.contain(expectedValues.esVersion);
expect(stackLine[7]).to.contain(expectedValues.esPort);
expect(stackLine[8]).to.contain(expectedValues.redisVersion);
expect(stackLine[9]).to.contain(expectedValues.redisPort);
};
xdescribe("instance:list", () => {
test
.timeout(TEST_TIMEOUT)
.stdout({ print: PRINT_STDOUT })
.do(() => {
execSync("./bin/run instance:spawn -v 2");
})
.command(["instance:list"])
.finally(() => {
execSync("docker stop $(docker ps -aq)");
})
.it("Lists a kuzzle v2", (ctx, done) => {
checkStackDetails(ctx.stdout, 0, {
index: "0",
name: "stack-0",
status:
/'Up(Lessthanasecond|(\d{1,3}(second|seconds|minute|minutes)'))/,
kuzzleVersion: "2",
kuzzlePort: "7512",
esVersion: "7",
esPort: "9200",
redisVersion: "5",
redisPort: "6379",
});
done();
});
test
.timeout(TEST_TIMEOUT)
.stdout({ print: PRINT_STDOUT })
.do(() => {
execSync("./bin/run instance:spawn -v 1");
})
.command(["instance:list"])
.finally(() => {
execSync("docker stop $(docker ps -aq)");
})
.it("Lists a kuzzle v1", (ctx, done) => {
checkStackDetails(ctx.stdout, 0, {
index: "0",
name: "stack-0",
status:
/'Up(Lessthanasecond|(\d{1,3}(second|seconds|minute|minutes)'))/,
kuzzleVersion: "1",
kuzzlePort: "7512",
esVersion: "5",
esPort: "9200",
redisVersion: "5",
redisPort: "6379",
});
done();
});
test
.timeout(TEST_TIMEOUT)
.stdout({ print: PRINT_STDOUT })
.do(() => {
execSync("./bin/run instance:spawn -v 2");
execSync("./bin/run instance:spawn -v 2");
})
.command(["instance:list"])
.finally(() => {
execSync("docker stop $(docker ps -aq)");
})
.it("Lists some kuzzle v2", (ctx, done) => {
checkStackDetails(ctx.stdout, 0, {
index: "0",
name: "stack-0",
status:
/'Up(Lessthanasecond|(\d{1,3}(second|seconds|minute|minutes)'))/,
kuzzleVersion: "2",
kuzzlePort: "7512",
esVersion: "7",
esPort: "9200",
redisVersion: "5",
redisPort: "6379",
});
checkStackDetails(ctx.stdout, 1, {
index: "1",
name: "stack-1",
status:
/'Up(Lessthanasecond|(\d{1,3}(second|seconds|minute|minutes)'))/,
kuzzleVersion: "2",
kuzzlePort: "7513",
esVersion: "7",
esPort: "9201",
redisVersion: "5",
redisPort: "6379",
});
done();
});
test
.timeout(TEST_TIMEOUT)
.stdout({ print: PRINT_STDOUT })
.do(() => {
execSync("./bin/run instance:spawn -v 1");
execSync("./bin/run instance:spawn -v 1");
})
.command(["instance:list"])
.finally(() => {
execSync("docker stop $(docker ps -aq)");
})
.it("Lists some kuzzle v1", (ctx, done) => {
checkStackDetails(ctx.stdout, 0, {
index: "0",
name: "stack-0",
status:
/'Up(Lessthanasecond|(\d{1,3}(second|seconds|minute|minutes)'))/,
kuzzleVersion: "1",
kuzzlePort: "7512",
esVersion: "5",
esPort: "9200",
redisVersion: "5",
redisPort: "6379",
});
checkStackDetails(ctx.stdout, 1, {
index: "1",
name: "stack-1",
status:
/'Up(Lessthanasecond|(\d{1,3}(second|seconds|minute|minutes)'))/,
kuzzleVersion: "1",
kuzzlePort: "7513",
esVersion: "5",
esPort: "9201",
redisVersion: "5",
redisPort: "6379",
});
done();
});
test
.timeout(TEST_TIMEOUT)
.stdout({ print: PRINT_STDOUT })
.do(() => {
execSync("./bin/run instance:spawn -v 2");
execSync("./bin/run instance:spawn -v 1");
execSync("./bin/run instance:spawn -v 2");
})
.command(["instance:list"])
.finally(() => {
execSync("docker stop $(docker ps -aq)");
})
.it("Lists some kuzzle v1 and v2", (ctx, done) => {
checkStackDetails(ctx.stdout, 0, {
index: "0",
name: "stack-0",
status:
/'Up(Lessthanasecond|(\d{1,3}(second|seconds|minute|minutes)'))/,
kuzzleVersion: "2",
kuzzlePort: "7512",
esVersion: "7",
esPort: "9200",
redisVersion: "5",
redisPort: "6379",
});
checkStackDetails(ctx.stdout, 1, {
index: "1",
name: "stack-1",
status:
/'Up(Lessthanasecond|(\d{1,3}(second|seconds|minute|minutes)'))/,
kuzzleVersion: "1",
kuzzlePort: "7513",
esVersion: "5",
esPort: "9201",
redisVersion: "5",
redisPort: "6379",
});
checkStackDetails(ctx.stdout, 2, {
index: "2",
name: "stack-2",
status:
/'Up(Lessthanasecond|(\d{1,3}(second|seconds|minute|minutes)'))/,
kuzzleVersion: "2",
kuzzlePort: "7514",
esVersion: "7",
esPort: "9202",
redisVersion: "5",
redisPort: "6379",
});
done();
});
});
|
1bd9a8e11669ecb3ac480ff98a9a20a3aea47649
|
TypeScript
|
classroomMisiones/proyecto-fs-grupo5-g5m
|
/PILMoney/src/app/Modelos/localidad.model.ts
| 2.5625
| 3
|
export class Localidad {
public Id_localidad : number
public Nombre : string
public Id_provincia : number
constructor(
// _Id_localidad : number,
// _Nombre : string,
// _Id_provincia : number
)
{
this.Id_localidad = 0;
this.Nombre = "";
this.Id_provincia = 0;
// this.Id_localidad = _Id_localidad;
// this.Nombre = _Nombre;
// this.Id_provincia = _Id_provincia;
}
}
|
2f8eec62ac3860e73cd8eef2be468107b3ac4678
|
TypeScript
|
looker-open-source/components
|
/packages/components/lib/DataTable/getNextFocus.d.ts
| 2.75
| 3
|
/**
* Returns the next focusable inside an element in a given direction
* @param direction 1 for forward -1 for reverse
* @param element the container element
*/
export declare const getNextFocus: (direction: 1 | -1, element: HTMLElement, vertical?: boolean | undefined) => HTMLElement | null;
|
af3f6f156590cdaac9bd692ec2c13b6de45642b2
|
TypeScript
|
My42/RRS-skeleton
|
/test/commandLines.test.ts
| 2.734375
| 3
|
import * as chai from "chai";
import * as chaiAsPromised from "chai-as-promised";
import exec, { cp, yarn, mkdir } from '../src/CommandLines';
import { readFile as _readFile, unlink,readdir as _readdir } from 'fs';
import { remove } from 'fs-extra';
import { promisify } from 'util';
import YarnCommands from "../src/enums/YarnCommands";
const { expect } = chai;
const readFile = promisify(_readFile);
const readdir = promisify(_readdir);
before(() => {
chai.should();
chai.use(chaiAsPromised);
});
describe('Exec command', () => {
it('should return a CommandLineResult', async () => {
const message = 'Hello World';
const result = await exec(`echo ${message}`);
expect(result).to.have.all.keys(['stdout', 'stderr']);
expect(result.stdout).to.be.equal(`${message}\r\n`);
});
it('should throw an error when the command is bad', async () => {
return expect(exec('bad command')).to.be.rejectedWith(Error);
});
});
describe('cp command', () => {
it('should copy a file', async () => {
const srcPath = 'test/commandLines.test.ts';
const tmpPath = 'test/tmp';
await cp(srcPath, tmpPath);
const srcContent = await readFile(srcPath, 'utf8');
const tmpContent = await readFile(tmpPath, 'utf8');
expect(srcContent).to.be.equal(tmpContent, 'expected the content of src file be equal to the content of dest file');
unlink(tmpPath, (err) => { if (err) console.log("Couldn't remove test/tmp file") });
});
it ('should throw an error when src path is bad', async () => {
const srcPath = 'INVALID_PATH';
const tmpPath = 'tmp';
return expect(cp(srcPath, tmpPath)).to.be.rejectedWith(Error);
});
});
describe('yarn command', () => {
const dependencyName = 'is-obj';
it('should give the version', async () => {
return yarn(YarnCommands.VERSION, [], './');
});
it('should add a dependency', async () => {
await yarn(YarnCommands.ADD, [dependencyName], './');
const { dependencies } = JSON.parse(await readFile('package.json', 'utf8'));
return expect(dependencies).to.include.all.keys(['is-obj']);
});
it('should remove a dependency', async () => {
await yarn(YarnCommands.REMOVE, [dependencyName], './');
const { dependencies } = JSON.parse(await readFile('package.json', 'utf8'));
return expect(dependencies).to.not.include.all.keys(['is-obj']);
});
});
describe('mkdir command', () => {
it('should create 1 directories', async () => {
await mkdir(['tmp']);
const files = await readdir('./');
await remove('./tmp');
return expect(files).to.include.members(['tmp']);
});
it('should create 2 directories', async () => {
await mkdir(['tmp', 'tmp2']);
const files = await readdir('./');
await remove('./tmp');
await remove('./tmp2');
return expect(files).to.include.members(['tmp', 'tmp2']);
});
});
|
a1f6e57149841020d8098851c1d6073d901ba7f8
|
TypeScript
|
karol7531/Link-Collection-App
|
/Main/ClientApp/src/Infrastructure/CustomReactHooks.ts
| 2.9375
| 3
|
import Cookies from "js-cookie";
import { useState } from "react";
export function useCookie<T>(
cookieName: string,
defaultValue: T
): [T, (newValue: T) => void] {
let value = Cookies.getJSON(cookieName) as T;
if (value === undefined) {
Cookies.set(cookieName, JSON.stringify(defaultValue));
value = defaultValue;
}
const [cookieVal, setCookieVal] = useState(value);
const onChange = (newValue: T): void => {
Cookies.set(cookieName, JSON.stringify(newValue));
setCookieVal(newValue);
};
return [cookieVal, onChange];
}
|
3c8194e547fa8d970b86cc5f0c2a33945c82597e
|
TypeScript
|
AdanDuM/INE5421
|
/src/SyntaxTree.ts
| 3.640625
| 4
|
export type SingleExprOperator = {
type: 'star' | 'plus' | 'optional';
value: DoubleExprOperator | SingleExprOperator | string;
};
export type DoubleExprOperator = {
type: 'concat' | 'or';
left: DoubleExprOperator | SingleExprOperator | string;
right: DoubleExprOperator | SingleExprOperator | string;
};
export type SyntaxTree = SingleExprOperator['value'];
const singleExprOperatorSymbols: { [k: string]: SingleExprOperator['type'] } = {
'*': 'star',
'+': 'plus',
'?': 'optional',
};
const doubleExprOperatorSymbols: { [k: string]: DoubleExprOperator['type'] } = {
'.': 'concat',
'|': 'or',
};
const operatorSymbols = {
...singleExprOperatorSymbols,
...doubleExprOperatorSymbols,
};
function getParentesisStart(
expression: string,
closingParentesis: number,
): number {
const stack: string[] = [')'];
let i = closingParentesis - 1;
for (; i >= 0; i--) {
const currChar = expression.charAt(i);
// Cada fechamento de parentesis aumenta stack
if (currChar === ')') {
stack.push(')');
continue;
}
// Cada abertura de parentesis diminui a stack
if (currChar === '(') stack.pop();
// Stack vazia, a expressao dentro do parentesis acabou
if (stack.length === 0) break;
}
// Caso ainda existam parentesis a serem fechados, retorna erro
if (stack.length !== 0)
throw new Error(
`Couldn't fully close the parentesis at ${closingParentesis}`,
);
return i;
}
// Quebra uma expressao na menor possivel à direita + restante à esquerda,
// considerando parentesis
function safeSplitExpr(expression: string): { left: string; right: string } {
let right = expression.substr(-1);
const left = expression.substring(0, expression.length - 1);
// Não é possível abrir um parentesis e nao fechar
if (right === '(') throw new Error(`Parentesis without it's closing twin`);
// Temos um parentesis como primeira expressão à direita e o resto como esquerda
if (right === ')') {
const parentesisStart = getParentesisStart(
expression,
expression.length - 1,
);
// Caso a parte de dentro do parentesis seja vazia, erro
right = expression.substring(parentesisStart + 1, expression.length - 1);
if (!right) throw new Error('Empty parentesis are not allowed');
return {
left: expression.substring(0, parentesisStart),
right,
};
}
return { left, right };
}
export function NewSyntaxTree(expression: string): SyntaxTree {
// Se a string estiver vazia, erro
if (!expression) throw new Error('Empty expression');
// Caso a expressao tenha tamanho 1, é o fundo de alguma recursao
if (expression.length === 1) {
// Caso seja um operador, erro (pois falta o simbolo/expressao)
if (operatorSymbols[expression])
throw new Error('Operator without symbol/expression');
// Senao, retorna o simbolo, apenas
return expression;
}
// Procura um "or" no primeiro nivel, que divida a expressao em dois lados
for (let i = expression.length - 1; i >= 0; i--) {
let currChar = expression.charAt(i);
// Pula o interior de qualquer parentesis, considera apenas o nivel mais alto
while (currChar === ')') {
i = getParentesisStart(expression, i) - 1;
// Se i for negativo, entao não existem "or" à esquerda
if (i < 0) break;
// Atualiza o char atual
currChar = expression.charAt(i);
}
// Se i for negativo, entao não existem "or" à esquerda
if (i < 0) break;
// Não é possível abrir um parentesis e nao fechar
if (currChar === '(')
throw new Error(`Parentesis without it's closing twin`);
// Encontrou um "or", então divide a expressao em duas, ligadas por um nodo
// "or"
if (operatorSymbols[currChar] === 'or') {
const rightExpr = expression.substring(i + 1);
const leftExpr = expression.substring(0, i);
if (!rightExpr || !leftExpr)
throw new Error('"or" operator without its two symbols/expressions');
return {
right: NewSyntaxTree(rightExpr),
left: NewSyntaxTree(leftExpr),
type: 'or',
};
}
}
// Sabemos que a expressao não pode ser dividida em duas por um "or"
// no primeiro nivel, portanto dividiremos entre expressao à extrema
// direita concatenada com restante à esquerda
const { left, right } = safeSplitExpr(expression);
// Caso nao tenha sobrado nada à esquerda, retorna arvore à direita
if (!left) return NewSyntaxTree(right);
// Caso à direita não exista um operador, retorna as arvores da esquerda
// e direita, concatenadas
if (!operatorSymbols[right])
return {
right: NewSyntaxTree(right),
left: NewSyntaxTree(left),
type: 'concat',
};
// Garante que nao vai ter um "or" aqui (loop do inicio deveria pegar)
// ou um concat
if (doubleExprOperatorSymbols[right])
throw new Error(`Illegal '${right}' operator usage`);
// Caso seja um operador, divide a esquerda novamente
const { left: newLeft, right: operand } = safeSplitExpr(left);
const rightTree = {
value: NewSyntaxTree(operand),
type: singleExprOperatorSymbols[right],
};
// Caso nao tenha sobrado nada à esquerda, retorna arvore à direita
if (!newLeft) return rightTree;
// Caso ainda exista algo à esquerda, concatena com a direita
return {
right: rightTree,
left: NewSyntaxTree(newLeft),
type: 'concat',
};
}
|
6c989e03923051523dd000fd3b6f33ca4d8a0556
|
TypeScript
|
Jocelyn10/vue-app-netlify
|
/src/assets/rules.ts
| 3.203125
| 3
|
export const Rules = {
required: (value: string) => !!value || "Required",
alphabeticOnly: (value: string) => {
if (value) {
const pattern = /^([a-zA-Z ' ` ~ ñ á é ü ô č]*)$/;
return pattern.test(value) || "Must contain only letters";
}
return true;
},
email: (value: string) => {
if (value) {
const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return pattern.test(value) || "Invalid e-mail.";
}
return true;
},
maxValue: (value: string, length: number) => {
if (value) {
return (
(value.length > 0 && value.length < length) ||
"Should not have more than " + ": " + length + " " + "characters"
);
}
return true;
},
max60: (value: string) => {
return Rules.maxValue(value, 60);
},
max100: (value: string) => {
return Rules.maxValue(value, 100);
},
max255: (value: string) => {
return Rules.maxValue(value, 255);
},
};
|
a211c2261715cbcef3ec486f7c7ca9494edbd904
|
TypeScript
|
clctianya/SFramework_LayaAir
|
/manager/timer/timer-interval.ts
| 2.828125
| 3
|
/**
* @author Sun
* @time 2019-08-10 20:02
* @project SFramework_LayaAir
* @description 定时执行
*
*/
export class TimerInterval {
private m_interval_time: number;//毫秒
private m_now_time: number;
constructor() {
this.m_now_time = 0;
}
/**
* 初始化定时器
* @param interval 触发间隔
* @param first_frame 是否第一帧开始执行
*/
public init(interval: number, first_frame: boolean): void {
this.m_interval_time = interval;
if (first_frame) this.m_now_time = this.m_interval_time;
}
public reset(): void {
this.m_now_time = 0;
}
public update(elapse_time: number): boolean {
this.m_now_time += elapse_time;
if (this.m_now_time >= this.m_interval_time) {
this.m_now_time -= this.m_interval_time;
return true;
}
return false;
}
}
|
6cedc0bad5c708b7b1a90feba053514922f0b2d0
|
TypeScript
|
iLunts/vstroyke-invoice
|
/src/app/pipes/summ-to-string.pipe.ts
| 2.609375
| 3
|
import {
Pipe,
PipeTransform
} from '@angular/core';
@Pipe({
name: 'summToString'
})
export class SummToStringPipe implements PipeTransform {
// money: any;
// price: any;
// rub: any;
// kop: any;
// litera = '';
// sotny = '';
// desatky = '';
// edinicy = '';
// minus = '';
// k = 0;
// i = 0;
// j = 0;
// N: any[] = ['', 'один', 'два', 'три', 'четыре', 'пять', 'шесть', 'семь', 'восемь', 'девять',
// '', 'одиннадцать', 'двенадцать', 'тринадцать', 'четырнадцать', 'пятнадцать', 'шестнадцать',
// 'семнадцать', 'восемнадцать', 'девятнадцать',
// '', 'десять', 'двадцать', 'тридцать', 'сорок', 'пятьдесят', 'шестьдесят', 'семьдесят', 'восемьдесят', 'девяносто',
// '', 'сто', 'двести', 'триста', 'четыреста', 'пятьсот', 'шестьсот', 'семьсот', 'восемьсот', 'девятьсот',
// 'тысяч', 'тысяча', 'тысячи', 'тысячи', 'тысячи', 'тысяч', 'тысяч', 'тысяч', 'тысяч', 'тысяч',
// 'миллионов', 'миллион', 'миллиона', 'миллиона', 'миллиона', 'миллионов', 'миллионов', 'миллионов', 'миллионов', 'миллионов',
// 'миллиардов', 'миллиард', 'миллиарда', 'миллиарда', 'миллиарда', 'миллиардов', 'миллиардов',
// 'миллиардов', 'миллиардов', 'миллиардов'];
// M: any[] = new Array(10);
// R: any[] = new Array('рублей', 'рубль', 'рубля', 'рубля', 'рубля', 'рублей', 'рублей', 'рублей', 'рублей', 'рублей');
// K: any[] = new Array('копеек', 'копейка', 'копейки', 'копейки', 'копейки', 'копеек', 'копеек', 'копеек', 'копеек', 'копеек');
// constructor() {}
// transform(value: any, ...args: any[]): any {
// for (this.j = 0; this.j < 10; ++this.j) {
// this.M[this.j] = new Array(this.N.length);
// }
// for (this.i = 0; this.i < this.N.length; this.i++) {
// for (this.j = 0; this.j < 10; this.j++) {
// this.M[this.j][this.i] = this.N[this.k++];
// }
// }
// return this.num2str(value);
// }
// // num2str(money, target) {
// num2str(money) {
// this.rub = '', this.kop = '';
// money = money.replace(',', '.');
// if (isNaN(money)) {
// return 'Не числовое значение';
// }
// if (money.substr(0, 1) === '-') {
// money = money.substr(1);
// this.minus = 'минус ';
// } else {
// this.minus = '';
// }
// money = Math.round(money * 100) / 100 + '';
// if (money.indexOf('.') !== -1) {
// this.rub = money.substr(0, money.indexOf('.'));
// this.kop = money.substr(money.indexOf('.') + 1);
// if (this.kop.length === 1) {
// this.kop += '0';
// }
// } else {
// this.rub = money;
// }
// if (this.rub.length > 12) {
// return 'Слишком большое число';
// }
// debugger;
// const ru = this.propis(this.price = this.rub, this.R);
// debugger;
// const ko = this.propis(this.price = this.kop, this.K);
// // const ru = this.propis(this.rub, this.R);
// // const ko = this.propis(this.kop, this.K);
// let res = '';
// ko !== '' ? res = ru + ' ' + ko : res = ru;
// ru === 'Ноль ' + this.R[0] && ko !== '' ? res = ko : 0;
// this.kop === 0 ? res += ' ноль ' + this.K[0] : 0;
// return (this.minus + res).substr(0, 1).toUpperCase() + (this.minus + res).substr(1);
// }
// propis(price, D) {
// debugger;
// let litera = '';
// for (let i = 0; i < price.length; i += 3) {
// this.sotny = this.desatky = this.edinicy = '';
// if (this.n(i + 2, 2) > 10 && this.n(i + 2, 2) < 20) {
// this.edinicy = ' ' + this.M[this.n(i + 1, 1)][1] + ' ' + this.M[0][i / 3 + 3];
// i === 0 ? this.edinicy += D[0] : 0;
// } else {
// this.edinicy = this.M[this.n(i + 1, 1)][0];
// (this.edinicy === 'один' && (i === 3 || D === this.K)) ? this.edinicy = 'одна' : 0;
// (this.edinicy === 'два' && (i === 3 || D === this.K)) ? this.edinicy = 'две' : 0;
// i === 0 && this.edinicy !== '' ? 0 : this.edinicy += ' ' + this.M[this.n(i + 1, 1)][i / 3 + 3];
// this.edinicy === ' ' ? this.edinicy = '' : (this.edinicy === ' ' + this.M[this.n(i + 1, 1)][i / 3 + 3]) ? 0 : this.edinicy = ' ' + this.edinicy;
// i === 0 ? this.edinicy += ' ' + D[this.n(i + 1, 1)] : 0;
// (this.desatky = this.M[this.n(i + 2, 1)][2]) !== '' ? this.desatky = ' ' + this.desatky : 0;
// }
// (this.sotny = this.M[this.n(i + 3, 1)][3]) !== '' ? this.sotny = ' ' + this.sotny : 0;
// if (price.substr(price.length - i - 3, 3) === '000' && this.edinicy === ' ' + this.M[0][i / 3 + 3]) { this.edinicy = ''; }
// litera = this.sotny + this.desatky + this.edinicy + litera;
// }
// if (litera === ' ' + this.R[0]) {
// return 'ноль' + litera;
// } else {
// return litera.substr(1);
// }
// }
// n(start, len) {
// if (start > this.price.length) {
// return 0;
// } else {
// return Number(this.price.substr(this.price.length - start, len));
// }
// }
constructor() {}
transform(value: any, ...args: any[]): any {
return value;
}
}
|
979f39376caaf15f02917027fa8e479ab6989f83
|
TypeScript
|
wolfcoder/tutorial-social-login-vue
|
/packages/server/src/controller/auth/dialogs-controller.ts
| 2.515625
| 3
|
import {
FacebookDialogProvider,
GitHubDialogProvider,
GoogleDialogProvider,
oAuthDialogEndPoint,
} from "@plumier/social-login"
import Tokens from "csrf"
import { authorize, bind, response } from "plumier"
//this controller provide social media auth endpoint that will be opened by a browser dialog
//create CSRF secret token for each session, send the secret to the client cookie as an identity.
//this identity will be used to verify if current user is the authentic user requests the login.
@authorize.public()
export class DialogsController {
//retrieve the csrf token secret as an identity
identity() {
return response.json({})
.setCookie("csrf:key", new Tokens().secretSync())
}
@oAuthDialogEndPoint(new FacebookDialogProvider("/auth/facebook", process.env.FACEBOOK_CLIENT_ID))
//GET /auth/dialogs/facebook
facebook(@bind.cookie("csrf:key") secret: string) {
return { state: new Tokens().create(secret) }
}
@oAuthDialogEndPoint(new GoogleDialogProvider("/auth/google", process.env.GOOGLE_CLIENT_ID))
//GET /auth/dialogs/google
google(@bind.cookie("csrf:key") secret: string) {
return { state: new Tokens().create(secret) }
}
@oAuthDialogEndPoint(new GitHubDialogProvider("/auth/github", process.env.GITHUB_CLIENT_ID))
//GET /auth/dialogs/github
github(@bind.cookie("csrf:key") secret: string) {
return { state: new Tokens().create(secret) }
}
}
|
9268c85bb92fb6a5861359c2afbd9fa87e964753
|
TypeScript
|
jbagaresgaray/dev-test-nodejs
|
/src/api/auth/validator/authenticate.ts
| 2.515625
| 3
|
import { NextFunction, Request, Response } from 'express'
import { body as checkBody, validationResult } from 'express-validator/check'
import HttpStatus from 'http-status-codes'
import isEmpty from 'lodash/isEmpty'
const validateLogin = (req: Request, res: Response, next: NextFunction) => {
const auth = req.headers.authorization
const uname = {
param: 'username',
message: 'Please provide your Username',
}
const pword = {
param: 'password',
message: 'Please provide your Password',
}
if (!auth) {
res.status(HttpStatus.BAD_REQUEST).send({
result: [uname, pword],
message: '',
success: false,
})
} else if (auth) {
const tmp = auth.split(' ')
const buf = new Buffer(tmp[1], 'base64')
const plain_auth = buf.toString()
const creds = plain_auth.split(':')
const username = creds[0]
const password = creds[1]
if (isEmpty(username) && isEmpty(password)) {
res.status(HttpStatus.BAD_REQUEST).send({
result: [uname, pword],
message: '',
success: false,
})
} else if (isEmpty(username) && !isEmpty(password)) {
res.status(HttpStatus.BAD_REQUEST).send({
result: [uname],
message: '',
success: false,
})
} else if (!isEmpty(username) && isEmpty(password)) {
res.status(HttpStatus.BAD_REQUEST).send({
result: [pword],
message: '',
success: false,
})
} else if (username === 'undefined' && password === 'undefined') {
res.status(HttpStatus.BAD_REQUEST).send({
result: [uname, pword],
message: '',
success: false,
})
} else if (!isEmpty(username) && password === 'undefined') {
res.status(HttpStatus.BAD_REQUEST).send({
result: [pword],
message: '',
success: false,
})
} else if (username === 'undefined' && !isEmpty(password)) {
res.status(HttpStatus.BAD_REQUEST).send({
result: [uname],
message: '',
success: false,
})
} else {
next()
}
}
}
export default {
validateLogin,
}
|
1b7b09e72a8062067bb8c067bed0e188f26dbdfc
|
TypeScript
|
web-scrobbler/web-scrobbler
|
/src/core/object/pipeline/coverartarchive/coverartarchive.ts
| 2.78125
| 3
|
import Song from '@/core/object/song';
import { MusicBrainzSearch } from './coverartarchive.types';
import { debugLog } from '@/core/content/util';
/**
* Fetch coverart from MusicBrainz archive.
* @param song - Song instance
*/
export async function process(song: Song): Promise<void> {
if (song.parsed.trackArt) {
debugLog('Using local/parsed artwork');
return;
} else if (song.metadata.trackArtUrl) {
debugLog('Found album artwork via LastFM');
return;
} else if (song.isEmpty()) {
return;
}
const endpoints = ['release', 'release-group'];
for (const endpoint of endpoints) {
let mbId = song.metadata.albumMbId;
let coverArtUrl = null;
try {
if (!mbId) {
mbId = await getMusicBrainzId(endpoint, song);
}
coverArtUrl = await checkCoverArt(mbId);
} catch (e) {
continue;
}
if (coverArtUrl) {
debugLog('Found album artwork via MusicBrainz');
song.metadata.trackArtUrl = coverArtUrl;
return;
}
}
}
/**
* Get track or album MusicBrainz ID.
* Search API docs:
* https://musicbrainz.org/doc/Development/XML_Web_Service/Version_2/Search
* Query syntax docs:
* https://lucene.apache.org/core/4_3_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package_description
*
* @param endpoint - Endpoint
* @param song - Song object
* @returns MusicBrainz ID
*/
async function getMusicBrainzId(endpoint: string, song: Song) {
const artist = song.getArtist();
const track = song.getTrack();
if (artist === null || track === null) {
throw new TypeError('artist or track is null');
}
const url =
`https://musicbrainz.org/ws/2/${endpoint}?fmt=json&query=` +
`title:+"${track ?? ''}"^3 ${track ?? ''} artistname:+"${
artist ?? ''
}"^4${artist ?? ''}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('Unable to fetch MusicBrainz ID');
}
const musicbrainz = (await response.json()) as MusicBrainzSearch;
if (musicbrainz.count === 0) {
throw new Error('Unable to fetch MusicBrainz ID');
}
if ('releases' in musicbrainz) {
return musicbrainz.releases[0].id;
}
if ('release-groups' in musicbrainz) {
return musicbrainz['release-groups'][0].id;
}
return '';
}
/**
* Check if cover art is accessible.
* @param mbid - MusicBrainz ID of track or album
* @returns Cover art URL
*/
async function checkCoverArt(mbid: string) {
const coverArtUrl = `https://coverartarchive.org/release/${mbid}/front-500`;
const response = await fetch(coverArtUrl, { method: 'HEAD' });
if (response.ok) {
return coverArtUrl;
}
throw new Error('Unable to fetch cover art from MusicBrainz');
}
|
004bf3efa9179aba8ec59b30e3896c9e8459a457
|
TypeScript
|
itziarZG/FirstStepsWithAngular
|
/Module1 Exercices/typescript-importer/src/classes/xmen.class.ts
| 2.703125
| 3
|
export class Xmen {
constructor(public nombre: string, public clave: string) {}
imprimir() {
console.log(`${this.nombre} es ${this.clave}`);
}
}
|
2169401f7a25618ac6b0b330c6cedc900853d79d
|
TypeScript
|
ansteh/sec-data
|
/cockpit/src/app/market/lib/commit.ts
| 3
| 3
|
import * as _ from 'lodash';
const POSITION = { trade: null, count: 0, invested: 0, net: 0, balance: 0, avgPricePerShare: 0, history: [] };
const PROPERTIES = _.keys(POSITION);
const getAvgPrice = (series) => {
return _
.chain(series)
.map('price')
.mean()
.round(2)
.value()
};
export const long = (position, quote, amount) => {
position.trade = 'long';
if(_.isNumber(amount) && _.isNaN(amount) == false && amount !== 0) {
const value = amount * quote.close;
position.count += amount;
position.invested += value;
position.history.push({ amount, price: quote.close, value, date: quote.date });
}
position.avgPricePerShare = getAvgPrice(position.history);
position.net = position.count * quote.close;
position.balance = position.net - position.invested;
return position;
};
export const short = (position, quote, amount) => {
position.trade = 'short';
if(_.isNumber(amount) && _.isNaN(amount) == false && amount !== 0) {
const value = amount * quote.close;
position.count += amount;
position.net += value;
position.history.push({ amount, price: quote.close, value, date: quote.date });
}
position.avgPricePerShare = getAvgPrice(position.history);
position.invested = position.count * quote.close;
position.balance = position.net - position.invested;
return position;
};
export const trade = (position, quote, amount) => {
if(!position.trade) {
position.trade = amount >= 0 ? 'long' : 'short';
}
if(position.trade === 'long') {
if(amount > 0 || position.count + amount >= 0) {
long(position, quote, amount);
} else {
const adjustedAmount = position.count + amount;
long(position, quote, -position.count);
close(position);
short(_.assign(position, POSITION), quote, adjustedAmount);
}
setTotals(position);
return position;
}
if(position.trade === 'short') {
if(amount < 0 || position.count + amount <= 0) {
short(position, quote, amount);
} else {
const adjustedAmount = position.count + amount;
short(position, quote, -position.count);
close(position);
long(_.assign(position, POSITION), quote, adjustedAmount);
}
setTotals(position);
return position;
}
};
const close = (position) => {
const snapshot = _.assign({}, _.pick(position, PROPERTIES));
position.trades = position.trades || [];
position.trades.push(snapshot);
};
const setTotals = (position) => {
position.total = {
balance: sum('balance', position),
invested: sum('invested', position),
net: sum('net', position),
};
};
const sum = (property, position) => {
const trades = position.trades || [];
const values = [position[property] || 0, ...trades.map(trade => trade[property])];
return _
.chain(values)
.sum()
.round(2)
.value()
};
export const createPosition = () => {
return _.clone(POSITION);
};
const audit = (positions) => {
const [ losers, winners ] = _.partition(positions, (position) => {
return (_.get(position, 'total.balance') || 0) < 0;
});
return {
count: positions.length,
losers: losers.length,
winners: winners.length,
balance: _.sumBy(positions, 'total.balance'),
invested: _.sumBy(positions, 'total.invested'),
net: _.sumBy(positions, 'total.net'),
// fail: _
// .chain(losers)
// .sortBy('total.balance')
// .first()
// .value()
};
};
// const position = _.cloneDeep(POSITION);
//
// long(position, { close: 5 }, 100);
// console.log(position);
//
// long(position, { close: 5 }, -50);
// console.log(position);
//
// long(position, { close: 6 }, -25);
// console.log(position);
//
// long(position, { close: 2 }, -25);
// console.log(position);
const simulateSellOnLong = (price, amount) => {
const position = _.cloneDeep(POSITION);
long(position, { close: _.round(_.random(price.min, price.max), 2) }, amount);
console.log(position);
do {
const move = -_.random(1, amount);
long(position, { close: _.round(_.random(price.min, price.max), 2) }, move);
console.log(position);
amount += move;
} while (amount > 0);
};
// simulateSellOnLong({ min: 2, max: 6 }, 100);
// export const test = () => {
// const position = _.cloneDeep(POSITION);
//
// trade(position, { close: 5 }, 100);
// console.log(position);
//
// trade(position, { close: 5 }, -50);
// console.log(position);
//
// trade(position, { close: 6 }, -25);
// console.log(position);
//
// trade(position, { close: 2 }, -75);
// console.log(position);
//
// trade(position, { close: 1 }, -25);
// console.log(position);
//
// trade(position, { close: 3 }, 75);
// console.log(position);
// };
export const test = () => {
const position = _.cloneDeep(POSITION);
trade(position, { close: 5 }, -50);
console.log(position);
trade(position, { close: 5 }, 100);
console.log(position);
};
|
67977cf73d82a771b8dd70105df95ef0c20422df
|
TypeScript
|
roblox-ts/roblox-ts
|
/src/Project/functions/cleanup.ts
| 2.65625
| 3
|
import fs from "fs-extra";
import path from "path";
import { tryRemoveOutput } from "Project/functions/tryRemoveOutput";
import { PathTranslator } from "Shared/classes/PathTranslator";
function cleanupDirRecursively(pathTranslator: PathTranslator, dir: string) {
if (fs.pathExistsSync(dir)) {
for (const name of fs.readdirSync(dir)) {
const itemPath = path.join(dir, name);
if (fs.statSync(itemPath).isDirectory()) {
if (name === ".git") {
continue;
}
cleanupDirRecursively(pathTranslator, itemPath);
}
tryRemoveOutput(pathTranslator, itemPath);
}
}
}
export function cleanup(pathTranslator: PathTranslator) {
const outDir = pathTranslator.outDir;
if (fs.pathExistsSync(outDir)) {
cleanupDirRecursively(pathTranslator, outDir);
}
}
|
8863acccab23ac3bda94a4a6bd98956266f6667c
|
TypeScript
|
blmhemu/rustor
|
/sapper/src/components/Metadata.ts
| 2.765625
| 3
|
import { writable } from 'svelte/store';
export type Metadata = { name: string; is_dir: boolean; path: string };
function createSelected() {
const { subscribe, set, update } = writable(new Set<Metadata>());
let add = (item: Metadata) => update(f => { f.add(item); return f });
let reset = () => set(new Set<Metadata>());
let addOrRemove = (item: Metadata) => update(f => {
if (f.has(item)) { f.delete(item); }
else { f.add(item); }
return f
});
return {
subscribe,
reset,
smartadd: (event: MouseEvent, item: Metadata) => {
if (event.ctrlKey || event.metaKey) {
addOrRemove(item);
} else {
reset();
add(item);
}
}
}
};
export const selected = createSelected();
|
168fadc5afdf1588f8c117f4cddf82a794fee052
|
TypeScript
|
KhiaLech/InterfaceProgramming_2019_Sem2
|
/Week 3 Exersise/index.ts
| 2.828125
| 3
|
import axios from 'axios';
var url = "";
interface PostInterface {
userId: number;
id:number;
title:string;
body:string;
}
axios.get<PostInterface[]>('http://jsonplaceholder.typicode.com/posts')
.then(function(response){
let data = response.data;
for(var i = 0; i<data.length;i++){
let _id=data[i].id;
let _title = data[i].title
console.log(_id);
console.log(_title);
}
})
|
076e96c194b7b279a4f09fab57e145199624d6ea
|
TypeScript
|
AdrianPrzychodzien/fit_Calculator
|
/src/redux/circum/circum.reducer.ts
| 2.71875
| 3
|
import { CircumActionTypes } from './circum.types';
import { addNewMeasurement } from '../utils';
import {
CircumReducer,
SetBodyFatCircumAction,
SetCircumferencesAction
} from '../../interfaces/interfaces';
const INITIAL_STATE = {
waist: 0,
hips: 0,
neck: 0,
circumferences: []
};
type CircumReducerActionTypes =
| SetBodyFatCircumAction
| SetCircumferencesAction;
const circumReducer = (
state: CircumReducer = INITIAL_STATE,
action: CircumReducerActionTypes
) => {
switch (action.type) {
case CircumActionTypes.SET_BODY_FAT_CIRCUM:
return {
...state,
waist: action.payload.waist,
hips: action.payload.hips,
neck: action.payload.neck
};
case CircumActionTypes.SET_CIRCUMFERENCES:
return {
...state,
circumferences: addNewMeasurement(state.circumferences, action.payload)
};
default:
return state;
}
};
export default circumReducer;
|
8016ec34e8d48cb05fbeba98e2b35374bdf72df0
|
TypeScript
|
serenity-js/serenity-js
|
/packages/core/src/events/RetryableSceneDetected.ts
| 2.75
| 3
|
import type { JSONObject } from 'tiny-types';
import { ensure, isDefined } from 'tiny-types';
import { CorrelationId } from '../model';
import { Timestamp } from '../screenplay';
import { DomainEvent } from './DomainEvent';
/**
* Indicates that the test runner will retry running the test scenario upon failure.
*
* @group Events
*/
export class RetryableSceneDetected extends DomainEvent {
/**
* Deserialises the event from a JSONObject
*
* @param o
*/
static fromJSON(o: JSONObject): RetryableSceneDetected {
return new RetryableSceneDetected(
CorrelationId.fromJSON(o.sceneId as string),
Timestamp.fromJSON(o.timestamp as string),
);
}
/**
* @param sceneId
* @param [timestamp]
*/
constructor(
public readonly sceneId: CorrelationId,
timestamp?: Timestamp,
) {
super(timestamp);
ensure('sceneId', sceneId, isDefined());
}
}
|
df091b0b9796386cdb69bdafa30485db3bdff8ad
|
TypeScript
|
ofk8vb/Typescript-Oldschool-Web-Framework
|
/src/models/Model.ts
| 3.46875
| 3
|
import { AxiosPromise, AxiosResponse } from 'axios';
interface ModelAttributes<T> {
set(value: T): void;
getAll(): T;
get<K extends keyof T>(key: K): T[K];
}
interface Sync<T> {
fetch(id: number): AxiosPromise;
save(data: T): AxiosPromise;
}
interface Events {
// () => void means callback function
on(eventName: string, callback: () => void): void;
trigger(eventName: string): void;
}
interface HasId {
id?: number;
}
export class Model<T extends HasId> {
constructor(
private attributes: ModelAttributes<T>,
private events: Events,
private sync: Sync<T>
) {}
// returns a reference to the on method defined in Eventing class
// ie user.on() is equal to user.events.on();
// get on() {
// return this.events.on;
// }
// These are executed after the constructor initializing, so this type of passthrough cannot be used if
// classes are being initialized inside constructor function. Works if classes are initialized in constructor arguments though!
on = this.events.on;
trigger = this.events.trigger;
get = this.attributes.get;
// get trigger() {
// return this.events.trigger;
// }
// get get() {
// return this.attributes.get;
// }
// sets the current values(attributes) of the User instance this method is being called on
set(update: T): void {
this.attributes.set(update);
// this event trigger will tell other parts of our application something changed if they listen to event called 'change'
this.events.trigger('change');
}
// gets the id of the user this function is being called on.
// then makes an axios request to DB with that id, then sets (updates) the
// value of the User instance (user) to the fetch value inside it
fetch(): void {
const id = this.get('id');
if (typeof id !== 'number') {
throw new Error('Cannot fetch without an id');
}
this.sync.fetch(id).then((response: AxiosResponse): void => {
this.set(response.data);
});
}
save(): void {
const data = this.attributes.getAll();
this.sync
.save(data)
.then((response: AxiosResponse): void => {
// this event trigger will run when a data is successfully saved
this.trigger('save');
})
.catch(() => {
this.trigger('error');
});
}
}
|
87ab55a2d64a47bc4c08a5b672fa54f897747fc0
|
TypeScript
|
JakeDame/Employee-Search-Application
|
/Employee Search Application/ClientApp/src/app/models/employee.ts
| 2.515625
| 3
|
import * as moment from 'moment';
export interface Employee {
firstName: string;
lastName: string;
jobTitle: string;
age: moment.Moment;
startDate: moment.Moment;
endDate: moment.Moment;
}
|
92ca7173c963a79c98f2b0a92f1cfb77fadbf773
|
TypeScript
|
ezolla/linear-style
|
/src/core/app-themes.ts
| 2.640625
| 3
|
export const appThemeNames = ["dark"] as const;
export type AppTheme = {
colors: {
background: string;
text: string;
lighterBackground: string;
};
};
export const appThemes: Record<typeof appThemeNames[number], AppTheme> = {
dark: {
colors: {
background: "#121212",
text: "#cccccc",
lighterBackground: "#1b1c1d",
},
},
};
|
e85af85afe110600f619f16da09fe3d57bfcf0d4
|
TypeScript
|
littlebitselectronics/pxt
|
/pxtblocks/fields/field_utils.ts
| 2.71875
| 3
|
namespace pxtblockly {
export namespace svg {
export function hasClass(el: SVGElement, cls: string): boolean {
return pxt.BrowserUtils.containsClass(el, cls);
}
export function addClass(el: SVGElement, cls: string) {
pxt.BrowserUtils.addClass(el, cls);
}
export function removeClass(el: SVGElement, cls: string) {
pxt.BrowserUtils.removeClass(el, cls);
}
}
export function parseColour(colour: string | number): string {
const hue = Number(colour);
if (!isNaN(hue)) {
return Blockly.hueToRgb(hue);
} else if (goog.isString(colour) && (colour as string).match(/^#[0-9a-fA-F]{6}$/)) {
return colour as string;
} else {
return '#000';
}
}
/**
* Converts a bitmap into a square image suitable for display. In light mode the preview
* is drawn with no transparency (alpha is filled with background color)
*/
export function bitmapToImageURI(frame: pxtsprite.Bitmap, sideLength: number, lightMode: boolean) {
const colors = pxt.appTarget.runtime.palette.slice(1);
const canvas = document.createElement("canvas");
canvas.width = sideLength;
canvas.height = sideLength;
// Works well for all of our default sizes, does not work well if the size is not
// a multiple of 2 or is greater than 32 (i.e. from the decompiler)
const cellSize = Math.min(sideLength / frame.width, sideLength / frame.height);
// Center the image if it isn't square
const xOffset = Math.max(Math.floor((sideLength * (1 - (frame.width / frame.height))) / 2), 0);
const yOffset = Math.max(Math.floor((sideLength * (1 - (frame.height / frame.width))) / 2), 0);
let context: CanvasRenderingContext2D;
if (lightMode) {
context = canvas.getContext("2d", { alpha: false });
context.fillStyle = "#dedede";
context.fillRect(0, 0, sideLength, sideLength);
}
else {
context = canvas.getContext("2d");
}
for (let c = 0; c < frame.width; c++) {
for (let r = 0; r < frame.height; r++) {
const color = frame.get(c, r);
if (color) {
context.fillStyle = colors[color - 1];
context.fillRect(xOffset + c * cellSize, yOffset + r * cellSize, cellSize, cellSize);
}
else if (lightMode) {
context.fillStyle = "#dedede";
context.fillRect(xOffset + c * cellSize, yOffset + r * cellSize, cellSize, cellSize);
}
}
}
return canvas.toDataURL();
}
}
|
401c4598a74f53ed70f8b9827c3220f7adcf5b98
|
TypeScript
|
dakom/pure3d-typescript
|
/src/lib/exports/common/array/Array.ts
| 2.6875
| 3
|
import {mat4, quat} from "gl-matrix";
export const createVec2 = () => new Float64Array(2);
export const createVec4 = () => new Float64Array(4);
export const createVec3 = () => new Float64Array(3);
export const createMat4 = () => {
const data = new Float64Array(16);
mat4.identity(data);
return data;
}
export const createQuat = () => {
const data = new Float64Array(4);
quat.identity(data);
return data;
}
export const createFill = (size:number) => (value:number) => {
const data = new Float64Array(size);
data.fill(value);
return data;
}
|
a1babf2327a9498ef8a4956dd4cda265cb2bf515
|
TypeScript
|
teytattze/nestjs-microservices
|
/libs/shared/src/utils/objects.util.ts
| 2.859375
| 3
|
export const deleteObjectField = <T = Record<string, any>>(
value: T | T[],
field: keyof T,
) => {
if (Array.isArray(value)) {
return value.map((obj) => {
delete obj[field];
return obj;
});
}
delete value[field];
return value;
};
|
b9eaef05fe8f9aa05e18699ac5e1d414b234af35
|
TypeScript
|
pnp/sp-dev-fx-webparts
|
/samples/react-multilist-grid/src/webparts/spfxReactGrid/reducers/SiteReducer.ts
| 2.828125
| 3
|
import {
GOT_WEBS,
GET_LISTSFORWEB_SUCCESS,
GET_FIELDSFORLIST_SUCCESS
} from "../constants";
import * as _ from "lodash";
import { Site } from "../model/Site";
const INITIAL_STATE: Array<Site> = [];
function gotWebs(state: Array<Site> = INITIAL_STATE, action: any = { type: "" }): Array<Site> {
let site: Site = new Site(action.payload.siteUrl);
site.webs = action.payload.webs;
let result: Array<Site> = _.union(state, new Array<Site>(site));
return result;
}
function siteReducer(state: Array<Site> = INITIAL_STATE, action: any = { type: "" }): Array<Site> {
switch (action.type) {
case GOT_WEBS:
return gotWebs(state, action);
case GET_LISTSFORWEB_SUCCESS:
let newState = _.clone(state);
//find the site and add the lists to it
for (const site of newState) {
for (const web of site.webs) {
if (web.url === action.payload.webUrl) {
web.lists = action.payload.lists;
web.listsFetched = true;
}
}
}
return newState;
case GET_FIELDSFORLIST_SUCCESS:
let newState2 = _.clone(state);
//find the site and add the lists to it
for (const site of newState2) {
for (const web of site.webs) {
if (web.url === action.payload.webUrl) {
for (const list of web.lists) {
if (list.id === action.payload.listId) {
list.fields = action.payload.fields;
list.fieldsFetched = true;
}
}
}
}
}
return newState2;
default:
return state;
}
}
export default siteReducer;
|
ee13398ad4edb4f1f74cfda52f803733ba58ecb0
|
TypeScript
|
Vheissu/ssr-engine
|
/src/transformers/title.ts
| 2.71875
| 3
|
import {replaceString} from './utils';
import {RenderOptions, TransformerContext} from '../interfaces';
/**
* Copy style content of the title from the aurelia instance DOM to the rendered HTML
* @param {string} html
* @param {TransformerContext} transformerCtx
* @param {RenderOptions} options
* @returns {string}
*/
export default function(html: string, transformerCtx: TransformerContext, options?: RenderOptions) {
const title = transformerCtx.document.head.querySelector('title');
if (title) {
return replaceString(html, /<title>((.|[\n\r])*)<\/title>/im, title.outerHTML);
}
return html;
};
|
89fb35aa90ea378179bfda7c214e29ad1b70ad7b
|
TypeScript
|
nehctuk/Casino-TypeScript
|
/ts/CardGames.ts
| 2.96875
| 3
|
abstract class CardGames {
protected player: Player;
protected deck: Deck;
public CardGames(aPlayer: Player) {
this.deck = new Deck();
this.deck.shuffle();
}
public getPlayer(): Player {
return this.player;
}
public setPlayer(player: Player): void {
this.player = player;
}
public getDeck(): Deck {
return this.deck;
}
public setDeck(deck: Deck): void {
this.deck = deck;
}
public dealCard(playerToReceiveCard: Player): void{
let card: Card = this.getDeck().getCard();
playerToReceiveCard.addToHand(card);
}
}
|
bfdf22797698de2d55b19bfc4945c681a8107d18
|
TypeScript
|
nbarrett/ng-ekwg
|
/server/serenity-js/screenplay/tasks/ramblers/common/requestParameterExtractor.ts
| 2.71875
| 3
|
import { PerformsActivities, Task } from "@serenity-js/core";
import { Log } from "../../common/log";
import { WalkRequestParameters } from "../../../../models/walkRequestParameters";
const ramblersDeleteWalks = "RAMBLERS_DELETE_WALKS";
const ramblersWalkCount = "RAMBLERS_WALKCOUNT";
const ramblersFileName = "RAMBLERS_FILENAME";
export class ExtractTask implements Task {
performAs(actor: PerformsActivities): Promise<void> {
const extractedParameters: WalkRequestParameters = RequestParameterExtractor.extract();
console.log("extractedParameters", extractedParameters);
return actor.attemptsTo(
Log.message(`parameters supplied were ${JSON.stringify(extractedParameters)}`),
);
}
}
export class RequestParameterExtractor {
static extract(): WalkRequestParameters {
const walkDeletionsString: string = process.env[ramblersDeleteWalks] || "";
const walkDeletions: string[] = walkDeletionsString.length > 1 ? walkDeletionsString.split(",").map(walkId => walkId) : [];
const fileName: string = process.env[ramblersFileName];
const walkCount: number = +process.env[ramblersWalkCount];
return {
walkDeletions,
fileName,
walkCount,
};
}
static extractTask = () => new ExtractTask();
}
|
d7bc5269639999d37dd7ce22f456e04265498ec3
|
TypeScript
|
gmfe/gm-pc
|
/packages/react/src/component/grid/types.ts
| 2.953125
| 3
|
import { HTMLAttributes } from 'react'
interface GutterSize {
/** 需要提供最小尺寸,小的时候才不会乱。暂时这么解决 */
sm: number
md?: number
lg?: number
xl?: number
}
type Gutter = number | GutterSize
interface RowProps extends HTMLAttributes<HTMLDivElement> {
/* 栅栏间隔,可以写成像素值或支持响应式的对象写法,默认为10 */
gutter?: Gutter
}
type ColSize = number | { span?: number; offset?: number }
interface ColProps extends HTMLAttributes<HTMLDivElement> {
/* 栅栏占位格数,为 0 时相当于 display: none */
span?: number
/* 栅栏左偏移量 */
offset?: number
/* 768px */
sm?: ColSize
/* 992px */
md?: ColSize
/* 1200px */
lg?: ColSize
/* 1920px */
xl?: ColSize
}
export type { Gutter, RowProps, ColProps }
|
c3dd6e507d3f069d1e50fcd47ed93df54e47e0bb
|
TypeScript
|
kvjnf/kvjnf-portfolio
|
/src/styled.d.ts
| 2.546875
| 3
|
// import original module declarations
import 'styled-components';
import { MediaQueryCallBack, PartialRecord } from './components/utils/types';
type Colors = PartialRecord<'black'|'gray', string>;
type Media = Record<'sm'|'md'|'lg'|'xl', MediaQueryCallBack>
interface FontFamiliesDefault{
fontFamily: string;
fontSize: string;
}
interface FontFamilesAlt extends FontFamiliesDefault{
fontWeight: number;
letterSpacing: string;
fontStyle: string;
}
interface FontFamilies {
default: FontFamiliesDefault;
alt: FontFamilesAlt;
}
// and extend them!
declare module 'styled-components' {
export interface DefaultTheme {
colors: Colors;
fill: Colors;
borderColor: Colors;
fontFamilies: FontFamilies;
fontSizes: string[];
breakpoints: string[];
media: Media;
}
}
|
b99996ca7efbb26d86328cf401cf3d295f37b9d5
|
TypeScript
|
binygal/norbert
|
/src/common/input/devices/KeyboardDevice.ts
| 2.921875
| 3
|
import { Direction, IInputDevice } from '../InputTypes';
export default function KeyboardDevice(): IInputDevice {
let hasSpaceClicked = false;
let latestDirection: 'left' | 'right' = 'left';
const keydownCallback = (e: KeyboardEvent) => {
const { key } = e;
if (key === ' ') {
hasSpaceClicked = true;
}
if (key === 'ArrowLeft') {
latestDirection = 'left';
}
if (key === 'ArrowRight') {
latestDirection = 'right';
}
};
document.body.addEventListener('keydown', keydownCallback);
function takeStartInput(): boolean {
if (hasSpaceClicked) {
hasSpaceClicked = false;
return true;
}
return false;
}
function getDirection(): Direction {
return [latestDirection, 0];
}
return {
takeStartInput,
getDirection,
};
}
|
78ea0b5152dc5379063ce77fdae84e51a3cc8c0b
|
TypeScript
|
carmendrl/HelpMe
|
/client/e2e/profQuestionFunctions.e2e-spec.ts
| 2.53125
| 3
|
import { ProfQuestionFunctionsPage } from './profQuestionFunctions.po';
xdescribe('Professor Question Functions', () => {
let page: ProfQuestionFunctionsPage;
beforeEach(() => {
page = new ProfQuestionFunctionsPage();
});
//must log in and out in every file?
var child_process = require('child_process');
child_process.exec('rails runner ~/help-me-web/scripts/profQuestionFunctionsScript.rb',
function(err, stdout, stderr){
if(err){
console.log("child processes failed with error code: " + err.code);
}
});
it('Click on viewButton of first lab session and take to correct url', () => {
page.navigateTo();
page.getEmailTextbox().sendKeys('prof@hope.edu');
page.getPasswordTextbox().sendKeys('password');
page.getSubmitButton().click();
page.getViewButtonForSession(page.getTableRowForSession(0)).click();
page.getCurrentUrl().then((url:string) =>{
expect(url).toEqual('http://localhost:4200/lab_sessions/d82fabc9-0976-4f6f-8bb1-b8ec9f16a395');
});
});
//re-do navigate to page - like main refresh - also compare actual question content
//rather than just list length
it('should have right title',() =>{
page.navigateToLab1();
page.getPageTitle().then((title:string) =>{
expect(title).toEqual('Session View - HelpMe');
});
});
//These tests requies that there be enough questions in the applicable claimedQuestions
//otherwise array-index-out-of-bound errors are likely to occur
//pssible set up is: 4 in unclaimed, 3 in my questions(claimed), 0 in faqs, 3 in other questions
//after button is clicked, page is re-navigated to as a "manuel-refresh"
//in addition to list lengths being checked it is made sure that the actual question is
//where it is supposed to be.
it('should claim 1st question',() =>{
//need to make sure enough questions in the list.
page.navigateToLab1();
let a = page.getElementArrayLength(page.getQuestionElementArray(page.getMyQuestionComponent())).then((i:number) => {return i+1});
let b = page.getElementArrayLength(page.getQuestionElementArray(page.getUnclaimedQuestionComponent())).then((i:number) => {return i-1});
let q = page.getQuestionElement(page.getQuestionElementArray(page.getUnclaimedQuestionComponent()), 0);
let id= page.getQuestionId(q); //id to compare at end
page.getClaimButton(q).click();
page.navigateToLab1();
expect(page.getElementArrayLength(page.getQuestionElementArray(page.getMyQuestionComponent()))).toBe(a);
expect(page.getElementArrayLength(page.getQuestionElementArray(page.getUnclaimedQuestionComponent()))).toBe(b);
expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getMyQuestionComponent()))).toContain(id);
expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getUnclaimedQuestionComponent()))).not.toContain(id);
});
it('should unclaim 1st question',() =>{
page.navigateToLab1();
let a = page.getElementArrayLength(page.getQuestionElementArray(page.getMyQuestionComponent())).then((i:number) => {return i-1});
let b = page.getElementArrayLength(page.getQuestionElementArray(page.getUnclaimedQuestionComponent())).then((i:number) => {return i+1});
page.getCollapseButton(page.getMyQuestionComponent()).click();
let q = page.getQuestionElement(page.getQuestionElementArray(page.getMyQuestionComponent()), 0);
let id= page.getQuestionId(q); //id to compare at end
page.getUnclaimButton(q).click();
page.navigateToLab1();
expect(page.getElementArrayLength(page.getQuestionElementArray(page.getMyQuestionComponent()))).toBe(a);
expect(page.getElementArrayLength(page.getQuestionElementArray(page.getUnclaimedQuestionComponent()))).toBe(b);
expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getMyQuestionComponent()))).not.toContain(id);
expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getUnclaimedQuestionComponent()))).toContain(id);
});
//COMMENTED OUT BECAUSE DOESN"T WORK (YET?)
xit('should delete 1st question in unclaimed',() =>{
//need to make sure enough questions in the list.
page.navigateToLab1();
let b = page.getElementArrayLength(page.getQuestionElementArray(page.getUnclaimedQuestionComponent())).then((i:number) => {return i-1});
let q = page.getQuestionElement(page.getQuestionElementArray(page.getUnclaimedQuestionComponent()), 0);
let id= page.getQuestionId(q); //id to compare at end
page.getDeleteButton(q).click();
page.navigateToLab1();
expect(page.getElementArrayLength(page.getQuestionElementArray(page.getUnclaimedQuestionComponent()))).toBe(b);
expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getUnclaimedQuestionComponent()))).not.toContain(id);
});
it('should add 1st question in other to faq',() =>{
//need to make sure enough questions in the list.
page.navigateToLab1();
let a = page.getElementArrayLength(page.getQuestionElementArray(page.getOtherQuestionComponent())).then((i:number) => {return i-1});
let b = page.getElementArrayLength(page.getQuestionElementArray(page.getFaqComponent())).then((i:number) => {return i+1});
page.getCollapseButton(page.getOtherQuestionComponent()).click();
let q = page.getQuestionElement(page.getQuestionElementArray(page.getOtherQuestionComponent()), 0);
let id= page.getQuestionId(q); //id to compare at end
page.getAddFaqButton(q).click();
page.navigateToLab1();
expect(page.getElementArrayLength(page.getQuestionElementArray(page.getOtherQuestionComponent()))).toBe(a);
expect(page.getElementArrayLength(page.getQuestionElementArray(page.getFaqComponent()))).toBe(b);
expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getOtherQuestionComponent()))).not.toContain(id);
expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getFaqComponent()))).toContain(id);
});
it('should remove 1st question faq (and move back to other)',() =>{
page.navigateToLab1();
let a = page.getElementArrayLength(page.getQuestionElementArray(page.getOtherQuestionComponent())).then((i:number) => {return i+1});
let b = page.getElementArrayLength(page.getQuestionElementArray(page.getFaqComponent())).then((i:number) => {return i-1});
page.getCollapseButton(page.getFaqComponent()).click();
let q = page.getQuestionElement(page.getQuestionElementArray(page.getFaqComponent()), 0);
let id= page.getQuestionId(q); //id to compare at end
page.getRemoveFaqButton(q).click();
page.navigateToLab1();
expect(page.getElementArrayLength(page.getQuestionElementArray(page.getOtherQuestionComponent()))).toBe(a);
expect(page.getElementArrayLength(page.getQuestionElementArray(page.getFaqComponent()))).toBe(b);
expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getOtherQuestionComponent()))).toContain(id);
expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getFaqComponent()))).not.toContain(id);
});
//BELOW ARE ASSIGN TESTS BUT THEY DON"T HAVE THE MODAL/SELECT STUFF IMPLEMENTED YET
// it('should assign question from unclaimed to other professor',() =>{
// page.navigateToLab1();
// let a = page.getElementArrayLength(page.getQuestionElementArray(page.getUnclaimedQuestionComponent())).then((i:number) => {return i-1});
// let b = page.getElementArrayLength(page.getQuestionElementArray(page.getOtherQuestionComponent())).then((i:number) => {return i+1});
// let q = page.getQuestionElement(page.getQuestionElementArray(page.getFaqComponent()), 0);
// let id= page.getQuestionId(q); //id to compare at end
// page.getAssignButton(q).click();
// //have to do modal stuff
//
// page.navigateToLab1();
// expect(page.getElementArrayLength(page.getQuestionElementArray(page.getUnclaimedQuestionComponent()))).toBe(a);
// expect(page.getElementArrayLength(page.getQuestionElementArray(page.getOtherQuestionComponent()))).toBe(b);
// expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getUnclaimedQuestionComponent()))).not.toContain(id);
// expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getOtherQuestionComponent()))).toContain(id);
// //also compare assigned to field
// });
//
// it('should assign question from My(Claimed)Questions to other professor',() =>{
// page.navigateToLab1();
// let a = page.getElementArrayLength(page.getQuestionElementArray(page.getMyQuestionComponent())).then((i:number) => {return i-1});
// let b = page.getElementArrayLength(page.getQuestionElementArray(page.getOtherQuestionComponent())).then((i:number) => {return i+1});
// page.getCollapseButton(page.getMyQuestionComponent()).click();
// let q = page.getQuestionElement(page.getQuestionElementArray(page.getFaqComponent()), 0);
// let id= page.getQuestionId(q); //id to compare at end
// page.getAssignButton(q).click();
// //have to do modal stuff
//
// page.navigateToLab1();
// expect(page.getElementArrayLength(page.getQuestionElementArray(page.getMyQuestionComponent()))).toBe(a);
// expect(page.getElementArrayLength(page.getQuestionElementArray(page.getOtherQuestionComponent()))).toBe(b);
// expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getMyQuestionComponent()))).not.toContain(id);
// expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getOtherQuestionComponent()))).toContain(id);
// //also compare to assigned to field
// });
});
|
0403ed0160888ad8a5185041ed393c7b400ee8cf
|
TypeScript
|
karlhulme/mantella
|
/workspaces/mantella-engine/src/execution/executeOperation.ts
| 2.625
| 3
|
import { pause } from 'piggle'
import { OperationContext, OperationDefinition, OperationRecord } from 'mantella-interfaces'
import { validateOperationInput } from './validateOperationInput'
import { executeStep } from './executeStep'
import { determineOperationStatusFromError } from './determineOperationStatusFromError'
import { RESOLVE_IMMEDIATELY } from '../consts'
import { OperationSaveStrategy } from 'mantella-interfaces/types/opDefs/OperationSaveStrategy'
/**
* Defines the properties required to execute an operation.
*/
interface ExecuteOperationProps {
/**
* A function that indicates if processing can continue.
*/
canContinueProcessing: () => boolean
/**
* The retry interval to use for step retries if the step
* does not provide a strategy.
*/
defaultRetryIntervalsInMilliseconds: number[]
/**
* The operation definition that defines the operation to be run.
*/
operation: OperationDefinition<unknown, unknown, unknown>
/**
* A function that can be called when it is time to send a
* response to the client.
*/
sendResponse: () => void,
/**
* A function that can be called when it is time to save
* the current state of the operation.
*/
saveOperation: () => Promise<void>,
/**
* The operation record that will be mutated by the operation
* as it is executed.
*/
record: OperationRecord,
/**
* True if the operation should be saved at each stage.
*/
saveProgress: boolean
/**
* The name of the step that should be completed when the
* sendResponse function should be invoked.
*/
resolveStep: string|null
/**
* The services object that should be provided to the operation.
*/
services: unknown
}
/**
* Executes an operation.
* @param props A property bag.
*/
export async function executeOperation (props: ExecuteOperationProps): Promise<void> {
// Init the timers, resolved status and determine if saving is required.
const timerStart = process.hrtime()
let hasSentResponse = false
// Determine the save strategy, which may be overriden by the client
// supplying an operationg id.
const saveModel: OperationSaveStrategy = props.saveProgress
? 'always'
: props.operation.saveModel
// Put the record into the running state and discard any error from the previous execution.
props.record.status = 'running'
props.record.error = null
// If this operation is going to be saved after each step
// then also save the inputs before we begin.
if (saveModel === 'always') {
await props.saveOperation()
}
// Create the context that holds all the data associated with
// an operation while it executes.
const context: OperationContext<unknown, unknown, unknown> = {
input: props.record.input,
log: ({ message }) => props.record.logEntries.push({ message, dateTime: new Date().toISOString() }),
pause: milliseconds => pause(milliseconds),
requestId: props.record.id,
services: props.services,
step: async ({ func, stepName, isErrorTransient, retryIntervalsInMilliseconds }) => {
return await executeStep({
stepDataEntries: props.record.stepDataEntries,
resolveStepName: props.resolveStep,
stepName,
func,
isErrorTransient,
retryIntervalsInMilliseconds: retryIntervalsInMilliseconds || props.defaultRetryIntervalsInMilliseconds,
canContinueProcessing: props.canContinueProcessing,
sendResponse: () => { hasSentResponse = true; props.sendResponse(); },
saveOperation: async () => props.saveOperation(),
saveProgress: saveModel === 'always'
})
},
output: ({ value }) => {
props.record.output = value as Record<string, unknown>|null
if (!props.resolveStep && !hasSentResponse) {
hasSentResponse = true
props.sendResponse()
}
}
}
try {
// Validate the input.
validateOperationInput(props.record.input, props.operation.inputValidator)
// Check to see if we need to return immediately
if (props.resolveStep === RESOLVE_IMMEDIATELY) {
hasSentResponse = true
props.sendResponse()
}
// Run the operation to completion, which may include resolving the client request
// before the operation has completed running.
await props.operation.func(context)
props.record.status = 'completed'
} catch (err) {
const error = err as Error
props.record.status = determineOperationStatusFromError(error)
props.record.error = props.record.status === 'rejected'
? error.message
: `${error.message}\n${error.stack}`
}
// Determine the time spent processing the operation.
props.record.finished = new Date().toISOString()
const duration = process.hrtime(timerStart)
props.record.durationInMs += ((duration[0] * 1000) + Math.trunc(duration[1] / 1000000))
// If the client did not request the data be returned after a
// particular step then return a response now.
if (!hasSentResponse) {
props.sendResponse()
}
// Determine if we need to make a final save, which depends on both the
// saving strategy and also how the operation ended.
const isFinalSaveRequired = saveModel === 'always' ||
props.record.status === 'interrupted' ||
(saveModel === 'error' && props.record.status === 'failed') ||
(saveModel === 'rejection' && ['failed', 'rejected'].includes(props.record.status))
if (isFinalSaveRequired) {
await props.saveOperation()
}
}
|
f86d8d17f3c1e706e5fe79acc831faf5cbe84991
|
TypeScript
|
MaoParadise/andoProyect
|
/server/src/controllers/stateMediaControllers.ts
| 2.546875
| 3
|
import { Request, Response } from 'express';
import pool from '../database';
import { json } from 'body-parser';
class StateMediaController{
public async listStateMedia(req: Request ,res: Response){
const statemedia = await pool.query('SELECT * from statemedia');
res.json(statemedia);
}
public async getStateMedia(req: Request, res: Response): Promise<any> {
const { id } = req.params;
const statemedia = await pool.query('SELECT * FROM statemedia WHERE IDSTATEMEDIA = ?', [id]);
console.log(statemedia.length);
if (statemedia.length > 0) {
return res.json(statemedia[0]);
}
res.status(404).json({ text: "The State doesn't exits" });
}
public async createStateMedia(req: Request ,res: Response): Promise<void>{
await pool.query('INSERT INTO statemedia set ?', [req.body])
res.json({message: 'State Saved '});
}
public async updateStateMedia(req: Request ,res: Response): Promise<any>{
const { id } = req.params;
await pool.query('UPDATE statemedia set ? WHERE IDSTATEMEDIA = ?', [req.body, id]);
res.json({message: 'the State was updated'});
}
public async deleteStateMedia(req: Request ,res: Response): Promise<void>{
const { id } = req.params;
await pool.query('DELETE FROM statemedia WHERE IDSTATEMEDIA = ?', [id]);
res.json({message: 'The State was deleted'});
}
}
const stateMediaController = new StateMediaController();
export default stateMediaController;
|
0a41d1f9e81bc7cdc793f2bab3883be9f785b62b
|
TypeScript
|
Thei1186/AT-Forum
|
/AT-Forum-functions/functions/src/users/user.service.ts
| 2.671875
| 3
|
import {UserRepository} from "./user.repository";
import {User} from "../models/user";
export class UserService {
constructor(private userRepository: UserRepository) {
}
deleteUser(uid: string): Promise<void> {
if (!uid.length) {
const error = new TypeError('Id has to be defined')
return Promise.reject(error);
}
return this.userRepository.deleteUser(uid);
}
updateUserUpdatesAuthor(userBefore: User, userAfter: User): Promise<User> {
if (!userAfter.uid.length || !userBefore.uid.length) {
const error = new TypeError('Email has to be defined');
return Promise.reject(error);
}
if (!userBefore.email.length || !userAfter.email.length) {
const error = new TypeError('Email has to be defined');
return Promise.reject(error);
}
return this.userRepository.updateUserUpdatesAuthor(userBefore, userAfter);
}
}
|
a2ba7cb6be1ed35a45ba58dd4c595107c62db949
|
TypeScript
|
odnodn/dockview
|
/packages/splitview/src/gridview/gridview.ts
| 2.65625
| 3
|
import {
ISplitviewStyles,
LayoutPriority,
Orientation,
Sizing,
} from '../splitview/core/splitview';
import { Position } from '../dnd/droptarget';
import { tail } from '../array';
import { LeafNode } from './leafNode';
import { BranchNode } from './branchNode';
import { Node } from './types';
import { Emitter, Event } from '../events';
import { IDisposable, MutableDisposable } from '../lifecycle';
function flipNode<T extends Node>(
node: T,
size: number,
orthogonalSize: number
): T {
if (node instanceof BranchNode) {
const result = new BranchNode(
orthogonal(node.orientation),
node.proportionalLayout,
node.styles,
size,
orthogonalSize
);
let totalSize = 0;
for (let i = node.children.length - 1; i >= 0; i--) {
const child = node.children[i];
const childSize =
child instanceof BranchNode ? child.orthogonalSize : child.size;
let newSize =
node.size === 0
? 0
: Math.round((size * childSize) / node.size);
totalSize += newSize;
// The last view to add should adjust to rounding errors
if (i === 0) {
newSize += size - totalSize;
}
result.addChild(
flipNode(child, orthogonalSize, newSize),
newSize,
0,
true
);
}
return result as T;
} else {
return new LeafNode(
(node as LeafNode).view,
orthogonal(node.orientation),
orthogonalSize
) as T;
}
}
export function indexInParent(element: HTMLElement): number {
const parentElement = element.parentElement;
if (!parentElement) {
throw new Error('Invalid grid element');
}
let el = parentElement.firstElementChild;
let index = 0;
while (el !== element && el !== parentElement.lastElementChild && el) {
el = el.nextElementSibling;
index++;
}
return index;
}
/**
* Find the grid location of a specific DOM element by traversing the parent
* chain and finding each child index on the way.
*
* This will break as soon as DOM structures of the Splitview or Gridview change.
*/
export function getGridLocation(element: HTMLElement): number[] {
const parentElement = element.parentElement;
if (!parentElement) {
throw new Error('Invalid grid element');
}
if (/\bgrid-view\b/.test(parentElement.className)) {
return [];
}
const index = indexInParent(parentElement);
const ancestor = parentElement.parentElement!.parentElement!.parentElement!;
return [...getGridLocation(ancestor), index];
}
export function getRelativeLocation(
rootOrientation: Orientation,
location: number[],
direction: Position
): number[] {
const orientation = getLocationOrientation(rootOrientation, location);
const directionOrientation = getDirectionOrientation(direction);
if (orientation === directionOrientation) {
const [rest, _index] = tail(location);
let index = _index;
if (direction === Position.Right || direction === Position.Bottom) {
index += 1;
}
return [...rest, index];
} else {
const index =
direction === Position.Right || direction === Position.Bottom
? 1
: 0;
return [...location, index];
}
}
export function getDirectionOrientation(direction: Position): Orientation {
return direction === Position.Top || direction === Position.Bottom
? Orientation.VERTICAL
: Orientation.HORIZONTAL;
}
export function getLocationOrientation(
rootOrientation: Orientation,
location: number[]
): Orientation {
return location.length % 2 === 0
? orthogonal(rootOrientation)
: rootOrientation;
}
export interface IViewSize {
width?: number;
height?: number;
}
export interface IGridView {
readonly onDidChange: Event<IViewSize | undefined>;
readonly element: HTMLElement;
readonly minimumWidth: number;
readonly maximumWidth: number;
readonly minimumHeight: number;
readonly maximumHeight: number;
priority?: LayoutPriority;
layout(
width: number,
height: number
// top: number, left: number
): void;
toJSON(): object;
fromJSON?(json: object): void;
snap?: boolean;
setVisible?(visible: boolean): void;
}
export const orthogonal = (orientation: Orientation) =>
orientation === Orientation.HORIZONTAL
? Orientation.VERTICAL
: Orientation.HORIZONTAL;
export interface GridLeafNode<T extends IGridView> {
readonly view: T;
readonly cachedVisibleSize: number | undefined;
readonly box: { width: number; height: number };
}
export interface GridBranchNode<T extends IGridView> {
readonly children: GridNode<T>[];
readonly box: { width: number; height: number };
}
export type GridNode<T extends IGridView> = GridLeafNode<T> | GridBranchNode<T>;
export function isGridBranchNode<T extends IGridView>(
node: GridNode<T>
): node is GridBranchNode<T> {
return !!(node as any).children;
}
export interface SerializedGridObject<T> {
type: 'leaf' | 'branch';
data: T | SerializedGridObject<T>[];
size?: number;
visible?: boolean;
}
const serializeBranchNode = <T extends IGridView>(
node: GridNode<T>,
orientation: Orientation
): SerializedGridObject<any> => {
const size =
orientation === Orientation.VERTICAL ? node.box.width : node.box.height;
if (!isGridBranchNode(node)) {
if (typeof node.cachedVisibleSize === 'number') {
return {
type: 'leaf',
data: node.view.toJSON(),
size: node.cachedVisibleSize,
visible: false,
};
}
return { type: 'leaf', data: node.view.toJSON(), size };
}
return {
type: 'branch',
data: node.children.map((c) =>
serializeBranchNode(c, orthogonal(orientation))
),
size,
};
};
export interface ISerializedLeafNode {
type: 'leaf';
data: any;
size: number;
visible?: boolean;
}
export interface ISerializedBranchNode {
type: 'branch';
data: ISerializedNode[];
size: number;
}
export type ISerializedNode = ISerializedLeafNode | ISerializedBranchNode;
export interface INodeDescriptor {
node: Node;
visible?: boolean;
}
export interface IViewDeserializer {
fromJSON: (data: ISerializedLeafNode) => IGridView;
}
export class Gridview implements IDisposable {
private _root: BranchNode | undefined;
public readonly element: HTMLElement;
private disposable: MutableDisposable = new MutableDisposable();
private readonly _onDidChange = new Emitter<number | undefined>();
readonly onDidChange: Event<number | undefined> = this._onDidChange.event;
public serialize() {
return {
root: serializeBranchNode(this.getView(), this.orientation),
height: this.height,
width: this.width,
orientation: this.orientation,
};
}
public dispose() {
this._onDidChange.dispose();
this.root.dispose();
}
public clear() {
const orientation = this.root.orientation;
this.root = new BranchNode(
orientation,
this.proportionalLayout,
this.styles,
this.root.size,
this.root.orthogonalSize
);
}
public deserialize(json: any, deserializer: IViewDeserializer) {
const orientation = json.orientation;
const height = json.height;
this.orientation = orientation;
this._deserialize(
json.root as ISerializedBranchNode,
orientation,
deserializer,
height
);
}
private _deserialize(
root: ISerializedBranchNode,
orientation: Orientation,
deserializer: IViewDeserializer,
orthogonalSize: number
): void {
this.root = this._deserializeNode(
root,
orientation,
deserializer,
orthogonalSize
) as BranchNode;
}
private _deserializeNode(
node: ISerializedNode,
orientation: Orientation,
deserializer: IViewDeserializer,
orthogonalSize: number
): Node {
let result: Node;
if (node.type === 'branch') {
const serializedChildren = node.data as ISerializedNode[];
const children = serializedChildren.map((serializedChild) => {
return {
node: this._deserializeNode(
serializedChild,
orthogonal(orientation),
deserializer,
node.size
),
visible: (serializedChild as { visible: boolean }).visible,
} as INodeDescriptor;
});
result = new BranchNode(
orientation,
this.proportionalLayout,
this.styles,
node.size,
orthogonalSize,
children
);
} else {
result = new LeafNode(
deserializer.fromJSON(node),
orientation,
orthogonalSize,
node.size
);
}
return result;
}
public get orientation() {
return this.root.orientation;
}
public set orientation(orientation: Orientation) {
if (this.root.orientation === orientation) {
return;
}
const { size, orthogonalSize } = this.root;
this.root = flipNode(this.root, orthogonalSize, size);
this.root.layout(size, orthogonalSize);
}
private get root(): BranchNode {
return this._root!;
}
private set root(root: BranchNode) {
const oldRoot = this._root;
if (oldRoot) {
oldRoot.dispose();
this.element.removeChild(oldRoot.element);
}
this._root = root;
this.element.appendChild(this._root.element);
this.disposable.value = this._root.onDidChange((e) => {
this._onDidChange.fire(e);
});
}
public next(location: number[]) {
return this.progmaticSelect(location);
}
public previous(location: number[]) {
return this.progmaticSelect(location, true);
}
getView(): GridBranchNode<IGridView>;
getView(location?: number[]): GridNode<IGridView>;
getView(location?: number[]): GridNode<IGridView> {
const node = location ? this.getNode(location)[1] : this.root;
return this._getViews(node, this.orientation);
}
private _getViews(
node: Node,
orientation: Orientation,
cachedVisibleSize?: number
): GridNode<IGridView> {
const box = { height: node.height, width: node.width };
if (node instanceof LeafNode) {
return { box, view: node.view, cachedVisibleSize };
}
const children: GridNode<IGridView>[] = [];
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
const cachedVisibleSize = node.getChildCachedVisibleSize(i);
children.push(
this._getViews(
child,
orthogonal(orientation),
cachedVisibleSize
)
);
}
return { box, children };
}
private progmaticSelect(location: number[], reverse = false) {
const [path, node] = this.getNode(location);
if (!(node instanceof LeafNode)) {
throw new Error('invalid location');
}
const findLeaf = (node: Node, last: boolean): LeafNode => {
if (node instanceof LeafNode) {
return node;
}
if (node instanceof BranchNode) {
return findLeaf(
node.children[last ? node.children.length - 1 : 0],
last
);
}
throw new Error('invalid node');
};
for (let i = path.length - 1; i > -1; i--) {
const n = path[i];
const l = location[i] || 0;
const canProgressInCurrentLevel = reverse
? l - 1 > -1
: l + 1 < n.children.length;
if (canProgressInCurrentLevel) {
return findLeaf(n.children[reverse ? l - 1 : l + 1], reverse);
}
}
return findLeaf(this.root, reverse);
}
get width(): number {
return this.root.width;
}
get height(): number {
return this.root.height;
}
get minimumWidth(): number {
return this.root.minimumWidth;
}
get minimumHeight(): number {
return this.root.minimumHeight;
}
get maximumWidth(): number {
return this.root.maximumHeight;
}
get maximumHeight(): number {
return this.root.maximumHeight;
}
constructor(
readonly proportionalLayout: boolean,
readonly styles: ISplitviewStyles | undefined,
orientation: Orientation
) {
this.element = document.createElement('div');
this.element.className = 'grid-view';
this.root = new BranchNode(
orientation,
proportionalLayout,
styles,
0,
0
);
}
isViewVisible(location: number[]): boolean {
const [rest, index] = tail(location);
const [, parent] = this.getNode(rest);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid from location');
}
return parent.isChildVisible(index);
}
setViewVisible(location: number[], visible: boolean): void {
const [rest, index] = tail(location);
const [, parent] = this.getNode(rest);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid from location');
}
parent.setChildVisible(index, visible);
}
public moveView(parentLocation: number[], from: number, to: number): void {
const [, parent] = this.getNode(parentLocation);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid location');
}
parent.moveChild(from, to);
}
public addView(view: IGridView, size: number | Sizing, location: number[]) {
const [rest, index] = tail(location);
const [pathToParent, parent] = this.getNode(rest);
if (parent instanceof BranchNode) {
const node = new LeafNode(
view,
orthogonal(parent.orientation),
parent.orthogonalSize
);
parent.addChild(node, size, index);
} else {
const [grandParent, ..._] = [...pathToParent].reverse();
const [parentIndex, ...__] = [...rest].reverse();
let newSiblingSize: number | Sizing = 0;
const newSiblingCachedVisibleSize = grandParent.getChildCachedVisibleSize(
parentIndex
);
if (typeof newSiblingCachedVisibleSize === 'number') {
newSiblingSize = Sizing.Invisible(newSiblingCachedVisibleSize);
}
grandParent.removeChild(parentIndex);
const newParent = new BranchNode(
parent.orientation,
this.proportionalLayout,
this.styles,
parent.size,
parent.orthogonalSize
);
grandParent.addChild(newParent, parent.size, parentIndex);
const newSibling = new LeafNode(
parent.view,
grandParent.orientation,
parent.size
);
newParent.addChild(newSibling, newSiblingSize, 0);
if (typeof size !== 'number' && size.type === 'split') {
size = { type: 'split', index: 0 };
}
const node = new LeafNode(
view,
grandParent.orientation,
parent.size
);
newParent.addChild(node, size, index);
}
}
public remove(view: IGridView, sizing?: Sizing) {
const location = getGridLocation(view.element);
return this.removeView(location, sizing);
}
removeView(location: number[], sizing?: Sizing): IGridView {
const [rest, index] = tail(location);
const [pathToParent, parent] = this.getNode(rest);
if (!(parent instanceof BranchNode)) {
throw new Error('Invalid location');
}
const node = parent.children[index];
if (!(node instanceof LeafNode)) {
throw new Error('Invalid location');
}
parent.removeChild(index, sizing);
if (parent.children.length === 0) {
// throw new Error('Invalid grid state');
return node.view;
}
if (parent.children.length > 1) {
return node.view;
}
if (pathToParent.length === 0) {
// parent is root
const sibling = parent.children[0];
if (sibling instanceof LeafNode) {
return node.view;
}
// we must promote sibling to be the new root
parent.removeChild(0, sizing);
this.root = sibling;
return node.view;
}
const [grandParent, ..._] = [...pathToParent].reverse();
const [parentIndex, ...__] = [...rest].reverse();
const sibling = parent.children[0];
const isSiblingVisible = parent.isChildVisible(0);
parent.removeChild(0, sizing);
const sizes = grandParent.children.map((_, i) =>
grandParent.getChildSize(i)
);
grandParent.removeChild(parentIndex, sizing);
if (sibling instanceof BranchNode) {
sizes.splice(
parentIndex,
1,
...sibling.children.map((c) => c.size)
);
for (let i = 0; i < sibling.children.length; i++) {
const child = sibling.children[i];
grandParent.addChild(child, child.size, parentIndex + i);
}
} else {
const newSibling = new LeafNode(
sibling.view,
orthogonal(sibling.orientation),
sibling.size
);
const sizing = isSiblingVisible
? sibling.orthogonalSize
: Sizing.Invisible(sibling.orthogonalSize);
grandParent.addChild(newSibling, sizing, parentIndex);
}
for (let i = 0; i < sizes.length; i++) {
grandParent.resizeChild(i, sizes[i]);
}
return node.view;
}
public layout(width: number, height: number) {
const [size, orthogonalSize] =
this.root.orientation === Orientation.HORIZONTAL
? [height, width]
: [width, height];
this.root.layout(size, orthogonalSize);
}
private getNode(
location: number[],
node: Node = this.root,
path: BranchNode[] = []
): [BranchNode[], Node] {
if (location.length === 0) {
return [path, node];
}
if (!(node instanceof BranchNode)) {
throw new Error('Invalid location');
}
const [index, ...rest] = location;
if (index < 0 || index >= node.children.length) {
throw new Error('Invalid location');
}
const child = node.children[index];
path.push(node);
return this.getNode(rest, child, path);
}
}
|
585bea82277d7cd4d3e8da6b27d4c97b7efb7ab2
|
TypeScript
|
beyondOurself/typescript
|
/类的访问类型.ts
| 3.671875
| 4
|
/*
* @Author: canlong.shen
* @Date: 2021-04-12 15:26:23
* @LastEditors: your name
* @LastEditTime: 2021-04-21 22:21:11
* @Description: file content
*/
// 类的内部和外部都能使用
class Person {
public name: string;
public sayHello() {
console.log(this.name + ' say heloo')
console.log(this.hobby)
}
private age: number;
// 只能在内部或者子类里使用
protected hobby: string = "打游戏";
}
class Teach extends Person {
sayHobby() {
this.hobby
}
}
const person = new Person()
person.name = 'long'
person.sayHello()
// 只能内部使用
// console.log(person.age) Property 'age' is private an
console.log(person.hobby)
|
889ee48aa95ae04c2bfce4d552535dfacb2fa0b0
|
TypeScript
|
egova-safety/flagwind
|
/packages/core/src/commands/Decorators.ts
| 2.96875
| 3
|
namespace flagwind
{
/**
* 标注当前类型是一个可通过命令执行器执行的命令。
* @param {string} path
*/
export function command(path: string)
{
if(!path)
{
throw new InvalidOperationException("The command path is empty.");
}
return function(commandType: Function)
{
if(!Type.isAssignableFrom(CommandBase, commandType))
{
throw new InvalidOperationException(`The class '${Type.getQualifiedClassName(commandType)}' is not a command type.`);
}
// 生成命令实例
let command = <ICommand>Activator.createInstance(commandType);
// 注册至默认的执行器中
CommandExecutor.default.register(path, command);
};
}
}
|
cc92cbed5f63882ae1c45ddb17a5799c4a3360c2
|
TypeScript
|
Fija1/snake_var
|
/dev/level.ts
| 2.84375
| 3
|
/// <reference path="snake.ts" />
class Level {
private scoreDiv: HTMLElement;
private score: number = 0;
private snake: Snake;
private block: Block;
private redBlocks: Array<RedBlock>;
private timer: number;
private message: string;
public div: HTMLElement;
private gameObjects: Array<GameObject> = new Array<GameObject>();
constructor() {
this.div = document.createElement("level");
document.body.appendChild(this.div);
this.scoreDiv = document.createElement("score");
this.div.appendChild(this.scoreDiv);
this.block = new Block(this);
this.gameObjects.push(this.block);
this.snake = new Snake(this);
this.timer = setInterval(this.createRedBlock.bind(this), 1000);
this.redBlocks = new Array();
this.message = "Score: " + this.score;
}
private createRedBlock() {
this.redBlocks.push(new RedBlock(this));
}
public update() {
if (this.snake.checkBlock(this.block)) {
this.block.remove();
this.block = new Block(this);
this.score++;
this.message = "Score: " + this.score;
}
for (let i = 0; i < this.redBlocks.length; i++) {
if (this.snake.checkBlock(this.redBlocks[i])) {
clearInterval(this.timer);
this.snake.div.remove();
this.message = "Game over!";
}
}
this.snake.move();
this.snake.draw();
this.block.draw();
for (let i = 0; i < this.redBlocks.length; i++) {
console.log("In de for loop!");
this.redBlocks[i].draw();
}
this.scoreDiv.innerHTML = this.message;
}}
|
9a36875bb8090916a48d4f21a5c8765fc3196dff
|
TypeScript
|
kenkz447/react-restful
|
/dist/src/utilities/ResourceType.d.ts
| 2.53125
| 3
|
/**
* ResourceType
* Defines the general data structure for a set of Resources.
*/
import { Record } from './RecordTable';
import { Store } from './Store';
export interface SchemaField {
field: string;
type: 'PK' | 'FK' | 'MANY';
resourceType?: string;
}
interface ResourceTypeProps {
name: string;
schema?: SchemaField[];
store?: Store;
}
export declare class ResourceType<T extends Record = {}> {
static defaultProps: Partial<ResourceTypeProps>;
name: string;
schema: ResourceTypeProps['schema'];
primaryKey: string;
static findPKField(schema: ResourceTypeProps['schema']): SchemaField;
constructor(props: ResourceTypeProps | string);
getAllRecords(store: Store, predicate?: (record: T) => boolean): T[];
populate(store: Store, record: T): T;
getAllChildType(store: Store): ResourceType<{}>[];
getChildTypeSchemafield(childType: ResourceType): SchemaField;
getRecordKey(record: T): any;
}
export {};
|
a451cff0ac8282826c2d443613b5c33ca1a9c7ba
|
TypeScript
|
hungnhse1997/blouse-api
|
/src/services/favorited-doctor-service.ts
| 2.59375
| 3
|
import { Request, Response } from "express";
import { FavoritedDoctor } from "../models/favorited-doctor";
import { Constant } from "../utils/constant";
class FavoritedDoctorService{
static getFavoritedDoctorbyPatientId = async (req: Request, res: Response) => {
let favoritedDoctor = await FavoritedDoctor.find({where: {patientId: req.params.id}});
if(!favoritedDoctor) return res.status(400).send({ message: "Doctor Not Found." });
return res.status(200).send(favoritedDoctor);
}
static createFavoritedDoctor = async (req: Request, res: Response) => {
let favoritedDoctor = new FavoritedDoctor();
favoritedDoctor.patientId = req.body.patientId;
favoritedDoctor.doctorId = req.body.doctorId;
favoritedDoctor.isActive = Constant.ONE;
favoritedDoctor.createdAt = (new Date());
favoritedDoctor.modifiedAt = (new Date());
await FavoritedDoctor.save(favoritedDoctor);
return res.status(200).send({ message: "Create Favorited Doctor Successfully!" });
}
static deleteFavoritedDoctor = async (req: Request, res: Response) => {
const favoritedDoctor = await FavoritedDoctor.findOne(req.params.id);
if (!favoritedDoctor) return res.status(400).send({ message: "Favorited Doctor Not Found." });
await FavoritedDoctor.delete(favoritedDoctor.id);
return res.status(200).send({ message: "Delete Favorited Doctor Successfully !" });
}
}
export default FavoritedDoctorService;
|
ab95325eef44cba58734b5829d59144e3e7173eb
|
TypeScript
|
akhilome/nopw
|
/src/controllers/Auth.ts
| 2.5625
| 3
|
import jwt from 'jsonwebtoken';
import { Request, Response, NextFunction } from 'express';
import responses from '../utils/responses';
import UserService from '../services/User';
import { Profile } from 'passport';
import logger from '../logging';
const { JWT_PRIVATE_KEY = '' } = process.env;
class AuthController {
static generateLoginToken(email: string): string {
return jwt.sign({ email }, JWT_PRIVATE_KEY, {
expiresIn: '15m'
});
}
static verifyToken(token: string): false | { email: string } {
try {
const decoded: any = jwt.verify(token, JWT_PRIVATE_KEY);
return decoded;
} catch (error) {
return false;
}
}
static generateAuthToken(email: string): string {
return jwt.sign({ email }, JWT_PRIVATE_KEY, { expiresIn: '3d' });
}
static authenticate(req: Request, res: Response): Response {
const { token } = req.params;
const decoded = AuthController.verifyToken(token);
if (!decoded)
return res
.status(401)
.json(responses.unsucessful('invalid or expired token'));
const { email } = decoded;
const authToken = AuthController.generateAuthToken(email);
return res
.status(200)
.json(
responses.successful('authentication successful', { token: authToken })
);
}
static authorize(
req: Request,
res: Response,
next: NextFunction
): Response | void {
const { authorization: authToken } = req.headers;
const decoded = AuthController.verifyToken(authToken || '');
if (!decoded)
return res
.status(401)
.json(responses.unsucessful('no or invalid authorization token'));
req.body.email = decoded.email;
next();
}
static async socialCallback(
accessToken: string,
refreshToken: string,
profile: Profile,
cb: CallableFunction
) {
const {
emails: [{ value: email }],
displayName
} = profile;
const [firstName, lastName] =
displayName.split(' ').length === 1
? [displayName, ' ']
: displayName.split(' ');
const userExists = await UserService.checkIfUserExists(email);
if (!userExists)
await UserService.addNewUser({ firstName, lastName, email });
return cb(null, { email });
}
static socialAuth(req: Request, res: Response): Response {
const user: { email: string } = req.user;
const token = AuthController.generateAuthToken(user.email);
return res
.status(200)
.json(responses.successful('authentication successful', { token }));
}
}
export default AuthController;
|
2ffce1438d865c1e1dd4478c46c2a90982a56160
|
TypeScript
|
jrwalt4/arga
|
/src/core/Util/EventEmitter.ts
| 3.375
| 3
|
export class EventEmitter<TEventArgs> {
private _listeners: Array<(eventArgs: TEventArgs) => void>
subscribe(listener: (eventArgs: TEventArgs) => void): () => void {
if (typeof listener === "function") {
(this._listeners || (this._listeners = [])).push(listener);
let listenersArray = this._listeners;
return function unsubscribe() {
unsubscribeListener(listener, listenersArray)
}
} else {
throw new TypeError("listener must be of type: (EventArgs)=>void");
}
}
unsubscribe(listener) {
unsubscribeListener(listener, this._listeners);
}
publish(eventArgs: TEventArgs) {
for (let callback of (this._listeners || (this._listeners = []))) {
callback.call(void 0, eventArgs);
}
}
get count(): number {
return this._listeners.length;
}
}
function unsubscribeListener(listener:Function, listenersArray:Function[]) {
for (let index = 0; index < listenersArray.length; index++) {
if (listenersArray[index] === listener) {
listenersArray.splice(index, 1);
// since a listener can subscribe multiple times,
// keep iterating to remove all instances
// (i.e. don't 'break')
}
}
}
|
8b211cee91d5648e2ddbd53161775d755910e1a9
|
TypeScript
|
GotoJP/AtCoder
|
/ABC-042/D.ts
| 3.234375
| 3
|
import * as fs from 'fs';
const input = fs.readFileSync("/dev/stdin", "utf8").split(' ');
// D-いろはちゃんとマス目
// 不正解
const height = +input[0];
const width = +input[1];
// 下からA個以内左からB個以内のマスは進入禁止
const A = +input[2];
const B = +input[3];
let result = 0;
for (let i = B; i < width; i++) {
result += combi(height - A - 1 + i, i) * combi(A + width - i - 2, A - 1);
}
console.log(result % 1000000007);
function combi(num: number, num2: number): number {
let res = 1;
for (let count1 = 0; count1 < num2; count1++) {
res *= num - count1;
res /= num2 - count1;
}
return res;
}
|
0c5c249a47c7e1581d93b04243adf069cb644271
|
TypeScript
|
steveruizok/nextjs-content-starter
|
/lib/getSearchResults.ts
| 2.734375
| 3
|
import searchPosts from "./post-list.json"
import { PostLite } from "../types"
/**
* Returns frontmatter for posts with titles that match a search string.
* @param search
*/
export function getSearchResults(search: string): PostLite[] {
const postsData = searchPosts.filter(({ terms }) => terms.includes(search))
return postsData
}
|
a1dfcddae612cd92bc18bf1c5a23035175b36200
|
TypeScript
|
chouhanaditya/Demo-application-using-Aurelia-and-ASP.NET-Core
|
/ClientApp/app/services/toDoService.ts
| 2.984375
| 3
|
import toDo from "../models/todo";
export class ToDoService{
todoList: toDo[]= [
new toDo(1,'Email Jane.',false),
new toDo(2,'Checkin your code on Github',true),
new toDo(3,'Pickup your laundry.',false)];
getToDoList()
{
return this.todoList.slice();
}
addToDo(todo: toDo)
{
this.todoList.push(todo);
return this.todoList.slice();
}
removetoDo(id: number)
{
this.todoList = this.todoList.filter(x => x.id !== id);
return this.todoList.slice();
}
// getNextToDoID() {
// if (this.todoList.length === 0) {
// return 1;
// } else {
// var last_id= this.todoList.slice(-1).pop();
// console.log(last_id['id']);
// return 4;
// }
// }
}
|
2cddf090a5834fb5fbc04aafcff22c0622cda89f
|
TypeScript
|
AlphaJon/WhileInterpret
|
/old/tokenparser.ts
| 3.125
| 3
|
/*class TokenParser {
static parse(code: string) {
let tokens = this.tokenize(code.trim());
if (tokens.filter(value => value === "(").length
!== tokens.filter(value => value === ")").length){
throw new Error("Bracket mismatch");
}
if (tokens.filter(value => value === "{").length
!== tokens.filter(value => value === "}").length){
throw new Error("Curly bracket mismatch");
}
let blockRegex = "\{([^\{\}]*)\}";
let ifRegex = new RegExp("if\s+"+blockRegex);
let whileRegex = new RegExp("while\s+"+blockRegex);
}
static tokenize(code: string) {
let tokensRegex = /(V[0-9]+|cons|hd|tl|=\?|:=|;|\(|\)|\{|\}|if|then|else|while)/;
let instructions = code.split(tokensRegex).map(value => value.trim());
instructions = instructions.filter(value => value !== "");
return instructions;
}
static buildTree(tokens: string[]): InstructionBlock {
let root = new InstructionBlock(tokens);
let changed = true;
while (changed) {
changed = false;
let startIndex = tokens.indexOf("(");
if (startIndex !== -1){
changed = true;
let endIndex = tokens.indexOf(")", startIndex);
let next = tokens.indexOf("(", startIndex+1);
while (next !== -1 && next < endIndex){
startIndex = next;
next = tokens.indexOf("(", startIndex+1);
}
let group = tokens.slice(startIndex+1, endIndex-1);
let beforeGroup = tokens.slice(0, startIndex-1);
let afterGroup = tokens.slice(endIndex+1);
//tokens = beforeGroup.push(group).concat(afterGroup);
}
}
return root;
}
static findgroup(tokens: string[]) {}
}*/
|