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
|
|---|---|---|---|---|---|---|
ed1489a12f28f9d19ed2a90a3553a76b35129246
|
TypeScript
|
ithiris/Training
|
/typescript-promise/promisetest.ts
| 3.03125
| 3
|
/**
* Created by ithir on 01-03-2018.
*/
import PromiseAsync from '../typescript-promise/promiseasynchronus'
class PromiseTest {
constructor() {
}
database1() {
return new PromiseAsync(function (resolve, reject) {
let a:number = 5;
let b:number = 25;
setTimeout(function () {
if (a < b) {
resolve('database success');
} else {
reject('database failure');
}
}, 3000);
})
}
database2() {
return new PromiseAsync(function (resolve, reject) {
var a = 5;
var b = 10;
setTimeout(function () {
if ((a < b)) {
resolve('database 2 succuss');
} else {
reject('database 2 failure');
}
}, 2000);
})
}
}
let databaseone=new PromiseTest()
databaseone.database1()
.then(function (response) {
console.log(response)
})
.catchFunction(function (error) {
console.log(error)
})
let databasetwo =new PromiseTest()
databasetwo.database2()
.then(function (response) {
console.log(response)
})
.catchFunction(function (error) {
console.log(error)
})
|
2fc6793ba9121e062dc5338716f60b676a171c71
|
TypeScript
|
Backbase/autoconfig-app
|
/src/app/types/notification.ts
| 2.78125
| 3
|
export enum NotificationType {
ERROR,
INFO,
SUCCESS,
WARNING
}
export interface Notification {
id: number;
message: string;
type: NotificationType;
}
|
72c98ef1d31bc4921c461b3ded46f69ec32a1bdd
|
TypeScript
|
thehig/autofilebot
|
/src/wrap/console.ts
| 2.71875
| 3
|
import chalk from "chalk";
const preamble = () =>
new Promise((resolve) => {
console.log(
chalk.magenta(`=====Autofilebot=====`)
);
resolve(null);
});
/**
* Wrap a promise-generating function in some CLI-behavior
*/
export const ConsoleWrapper = (func: (...params: any[]) => Promise<any>) => (
...args: any[]
) =>
preamble()
.then(() => func(...args))
.then(
// Output any trailing responses
(msg) =>
msg &&
console.log(
chalk.redBright(`Trailing response: ${JSON.stringify(msg, null, 4)}`)
)
)
.catch((err) => console.error(chalk.red(err)))
.finally(() => {
console.log("Press any key to exit");
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on("data", process.exit.bind(process, 0));
});
export default ConsoleWrapper;
|
1bc973d8689d3f33481d9a167d4cdc9c0840f8b9
|
TypeScript
|
yedu-YK/node_express_mongo_crud_example
|
/src/controller/classController.ts
| 2.71875
| 3
|
//module for class controller
import { Request, Response } from "express";
//importing class model
// import Classes from "../model";
import Classes from "../model/classModel";
//async function to get all registered classes
export const getAllClasses = async (req: Request, res: Response) => {
console.log("get all classes");
//find all class
Classes.find({})
.then((classes: any) => {
res.status(200).send(classes);
})
.catch((err: any) => {
res
.status(400)
.send({ message: err.message || "an error occurred to database" });
});
};
//async function to get a registered classes
export const getAClasses = async (req: Request, res: Response) => {
Classes.findById(req.params.id)
.then((data: any) => {
if (!data) {
//validating data
res.status(400).send({ message: "cannot find user by this id" });
}
res.status(200).send(data);
})
.catch((err: any) => {
//error handling
res
.status(400)
.send({ message: err.message || "an error occurred to database" });
});
};
export const createClass = async (req: Request, res: Response) => {
console.log("create class called", req.body);
Classes.create(req.body)
.then(() => {
res.status(200).send({ message: "success" });
})
.catch((err: any) => {
res
.status(400)
.send({ message: err.message || "an error occurred to database" });
});
};
export const deleteClasses = async (req: Request, res: Response) => {
console.log("delete class called", req.body);
Classes.findByIdAndDelete(req.params.id)
.then(() => {
res.status(200).send({ message: "class details deleted" });
})
.catch((err: any) => {
res
.status(400)
.send({ message: err.message || "an error occurred to database" });
});
};
export const updateClasses = async (req: Request, res: Response) => {
if (!req.body) {
//validating data
return res.status(400).send({ message: "cannot be empty" });
}
//find classes by id and updateing
Classes.findByIdAndUpdate(req.params.id, req.body, { new: true })
.then((data: any) => {
if (!data) {
return res.status(400).send({ message: "id does not exist" });
}
res.status(200).send({ message: "updated" });
})
.catch((err: any) => {
res
.status(400)
.send({ message: err.message || "an error occurred to database" });
});
};
|
8138387ad89380c09b35b3995aa98fb75487f093
|
TypeScript
|
Koquay/hsupp02
|
/src/app/cart/cart.service.ts
| 2.59375
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { tap } from 'rxjs/operators';
import {of} from 'rxjs/observable/of';
import { Cart, CartSummary, Product } from '../shared/models/data-model';
import { ErrorService } from '../shared/error/error.service';
@Injectable({
providedIn: 'root'
})
export class CartService {
private cart: Cart;
public numberOfItems: number = 0;
private cartSummary: CartSummary;
private cartAddUrl = '/api/cart/add';
private cartDeleteUrl = '/api/cart/delete/';
constructor(
private httpClient: HttpClient,
private errorService:ErrorService
) {
this.cart = new Cart();
this.cartSummary = new CartSummary();
}
public addToCart(product: Product, quantity:number=1) {
return this.httpClient.patch<Cart>(this.cartAddUrl, { product: product, quantity:quantity }).pipe(
tap(cart => {
console.log('cart', cart);
if(cart.errorMessage) {
this.errorService.handleError(cart);
} else {
this.setCart(cart);
}
})
)
}
public deleteItem(itemId) {
return this.httpClient.delete<Cart>(`${this.cartDeleteUrl}${itemId}`).pipe(
tap(cart => {
console.log('cart after delete', cart)
this.setCart(cart);
})
)
}
public setCart(cart) {
this.cart = cart;
this.numberOfItems = cart.items.length;
}
public getCartSummary() {
this.cartSummary.cart = this.cart;
this.cartSummary.subtotal = this.getCartSubtotal();
this.cartSummary.discount = this.getDiscount();
this.cartSummary.numberOfItems = this.numberOfItems;
this.cartSummary.tax = this.getTax();
this.cartSummary.total = this.getCartTotal();
return of(this.cartSummary);
}
public resetCart() {
this.cartSummary = new CartSummary();
this.cart = new Cart();
this.numberOfItems = 0;
}
public getTax() {
return this.getCartSubtotal() * 0.05;
}
public getDiscount() {
return this.getCartSubtotal() * 0.10;
}
public getCartTotal() {
return this.getCartSubtotal() + this.getTax() - this.getDiscount();
}
public getCartSubtotal() {
let subtotal = 0;
for(let item of this.cart.items) {
subtotal += item.product.price * item.quantity;
}
return subtotal;
}
}
|
ada35284153c6da1dbca76e423907ec74541585c
|
TypeScript
|
xiongz945/chat-room-project
|
/src/controllers/earthquake.ts
| 2.515625
| 3
|
import { Request, Response, NextFunction } from 'express';
import {
EarthquakeReport,
IEarthquakeReportDocument,
} from '../models/EarthquakeReport';
import { EarthquakePrediction } from '../models/EarthquakePrediction';
export const postEarthquakeReport = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const payload = req.body;
payload['reporterName'] = req.user.username;
const earthquakeReport = new EarthquakeReport(payload);
await earthquakeReport.save();
return res.status(200).json({});
} catch (err) {
next(err);
}
};
export const getEarthquakeReport = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const reports: IEarthquakeReportDocument[] = await EarthquakeReport.getAllReports();
return res.status(200).json({ reports: reports });
} catch (err) {
next(err);
}
};
export const patchEarthquakeReport = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const payload = req.body;
const reportID = payload['report_id'];
const report = payload['report'];
const originalReport: IEarthquakeReportDocument = await EarthquakeReport.findOne(
{ _id: reportID }
).exec();
if (originalReport.reporterName != req.user.username) {
return res.status(401).json({ err: 'Unauthorized' });
}
await EarthquakeReport.updateOne({ _id: reportID }, report);
return res.status(200).json({});
} catch (err) {
next(err);
}
};
export const postEarthquakePrediction = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
if (req.user.role !== 'coordinator' && req.user.role !== 'administrator') {
return res.status(401).json({ err: 'Unauthorized' });
}
const payload = req.body;
payload['predictorName'] = req.user.username;
const earthquakePrediction = new EarthquakePrediction(payload);
await earthquakePrediction.save();
return res.status(200).json({});
} catch (err) {
next(err);
}
};
|
889fec903cbbe5849707993d87e9076c274ae841
|
TypeScript
|
IPVS-AS/MMP-Frontend
|
/src/app/timeout/timeout.component.ts
| 2.625
| 3
|
import {Subscription} from 'rxjs';
export class TimeoutComponent {
timeout = false;
TIMEOUT_TIME = 3000;
number;
waitForTimeOut(subscription: Subscription) {
this.number = setTimeout(() => {
subscription.unsubscribe();
this.timeout = true;
}, this.TIMEOUT_TIME);
}
cancelTimeout() {
if (this.number) {
this.timeout = false;
clearTimeout(this.number);
}
}
}
|
c75e3398d43f15e749ec0bae991c57a933f7b19f
|
TypeScript
|
ts-tooling/source-analyzer
|
/sample-source-1/sample-source.ts
| 2.578125
| 3
|
// root for sample source 1 - analysis starts from here
import { SomeClassA } from './some-class-a';
import { SomeClassB } from "./some-class-b";
import { TestFunction1, TestFunction2 } from "./some-exports-1";
export class SampleSource {
constructor(
a: SomeClassA,
b: SomeClassB
) {}
test() {
TestFunction1();
TestFunction2('', 1);
}
}
|
ae67183265d1d3f255d3bec19e1d4b93d5c70d8b
|
TypeScript
|
vuepress-theme-hope/vuepress-theme-hope
|
/packages/theme/src/shared/frontmatter/projectHome.ts
| 2.90625
| 3
|
import type { ThemeHopePageFrontmatter } from "./home.js";
export interface ThemeProjectHomeActionOptions {
/**
* Action name
*
* 操作名称
*/
text: string;
/**
* Action link
*
* 操作链接
*/
link: string;
/**
* Type of action
*
* 操作类型
*
* @default "default"
*/
type?: "primary" | "default";
}
export interface ThemeProjectHomeHighlightItem {
/**
* Item name, supports HTML string
*
* 项目名称,支持 HTML 字符串
*/
title: string;
/**
* Item description, supports HTML string
*
* 项目描述,支持 HTML 字符串
*/
details?: string;
/**
* Item icon
*
* @description image link or icon fontClass are supported
*
* 项目图标
*
* @description 支持图片链接或者图标字体类
*/
icon?: string;
/**
* Item link
*
* 项目链接
*/
link?: string;
}
export type ThemeProjectHomeFeatureItem = ThemeProjectHomeHighlightItem;
export interface ThemeProjectHomeHighlightOptions {
/**
* Highlight section header, supports HTML string
*
* 亮点标题,支持 HTML 字符串
*/
header: string;
/**
* Highlight section description, supports HTML string
*
* 亮点描述,支持 HTML 字符串
*/
description?: string;
/**
* Text color
*
* 文字颜色
*/
color?: string;
/**
* Highlight section image
*
* 亮点图像
*/
image?: string;
/**
* Highlight section image used in darkmode
*
* 夜间模式使用的亮点图片
*
* @default image
*/
imageDark?: string;
/**
* Highlight Background image
*
* 亮点背景图
*/
bgImage?: string;
/**
* Highlight Background image used in darkmode
*
* 夜间模式使用的亮点背景图
*
* @default bgImage
*/
bgImageDark?: string;
/**
* Highlight Background image style
*
* 亮点背景图样式
*/
bgImageStyle?: Record<string, string> | string;
/**
* Highlight section list type
*
* 亮点列表类型
*
* @default un-order
*/
type?: "order" | "un-order" | "no-order";
/**
* Highlights
*
* 亮点
*/
highlights?: ThemeProjectHomeHighlightItem[];
}
export interface ThemeProjectHomeFeatureOptions {
/**
* Feature header
*
* 功能标题
*/
header?: string;
/**
* Feature section description, supports HTML string
*
* 功能描述,支持 HTML 字符串
*/
description?: string;
/**
* Text color
*
* 文字颜色
*/
color?: string;
/**
* Feature section image
*
* 功能图像
*/
image?: string;
/**
* Feature section image used in darkmode
*
* 夜间模式使用的功能图片
*
* @default image
*/
imageDark?: string;
/**
* Feature Background image
*
* 功能背景图
*/
bgImage?: string;
/**
* Feature Background image used in darkmode
*
* 夜间模式使用的功能背景图
*
* @default bgImage
*/
bgImageDark?: string;
/**
* Feature Background image style
*
* 功能背景图样式
*/
bgImageStyle?: Record<string, string> | string;
/**
* Features
*
* 功能
*/
features: ThemeProjectHomeFeatureItem[];
}
export interface ThemeProjectHomePageFrontmatter
extends ThemeHopePageFrontmatter {
actions?: ThemeProjectHomeActionOptions[];
features?: ThemeProjectHomeFeatureItem[];
highlights?: (
| ThemeProjectHomeFeatureOptions
| ThemeProjectHomeHighlightOptions
)[];
}
|
97ce56c509ea6f1c595e1aa14edc8f6e9a959f90
|
TypeScript
|
weyoss/redis-smq
|
/tests/tests/consuming-messages/test00008.test.ts
| 2.609375
| 3
|
import { Message } from '../../../src/lib/message/message';
import { events } from '../../../src/common/events/events';
import { delay } from 'bluebird';
import { getConsumer } from '../../common/consumer';
import { getProducer } from '../../common/producer';
import {
createQueue,
defaultQueue,
} from '../../common/message-producing-consuming';
test('Async exceptions are caught when consuming a message', async () => {
const producer = getProducer();
await producer.runAsync();
await createQueue(defaultQueue, false);
let callCount = 0;
const consumer = getConsumer({
messageHandler: jest.fn((msg, cb) => {
callCount += 1;
if (callCount === 1) {
setTimeout(() => {
cb(new Error('Async error'));
}, 2000);
} else if (callCount === 2) cb();
else throw new Error('Unexpected call');
}),
});
let unacknowledged = 0;
consumer.on(events.MESSAGE_UNACKNOWLEDGED, () => {
unacknowledged += 1;
});
let acknowledged = 0;
consumer.on(events.MESSAGE_ACKNOWLEDGED, () => {
acknowledged += 1;
});
const msg = new Message();
msg.setBody({ hello: 'world' }).setQueue(defaultQueue);
await producer.produceAsync(msg);
consumer.run();
await delay(15000);
expect(unacknowledged).toBe(1);
expect(acknowledged).toBe(1);
});
|
f13cf3bbabd2a3b9a15828f3e2a5fcb595285d1d
|
TypeScript
|
jsmack/learn
|
/old/language/typescript/udemy/developer/src/array.ts
| 3.546875
| 4
|
export {};
let numbers: number[] = [1, 2, 3];
console.log(numbers)
// not recoomended
// <> generics 型を抽象化
let numbers2: Array<number> = [1, 2, 3];
let strings2: Array<string> = ['Tokyo', 'Osaka', 'Kyoto'];
let strings: string[] = ['Type', 'Java', 'Coffee'];
let twodimensionalarray: number[][] = [
[50, 100],
[150, 300],
]
console.log(twodimensionalarray[0][1]);
let array2: (string | number | boolean)[] = [ 1, false, 'Java'];
|
acb58eb0d18d2d904b97efe31f9061bdd3e5a446
|
TypeScript
|
andrii-bo/NodeMent
|
/HW_4_1/src/utils.ts
| 2.671875
| 3
|
export enum lstCRUD {
Create = "CREATE",
Read = "READ",
Update = "UPDATE",
Delete = "DELETE",
Clear = "CLEAR"
}
export interface iExecResult {
code?: number;
message?: string;
stack?: string;
request?: string;
result?: any;
}
export function retResult(
result?: any,
code: number = 200,
req?: string,
message?: string
): iExecResult {
let lResult: iExecResult = <iExecResult>{};
lResult.code = code;
lResult.message = message;
lResult.request = req;
lResult.result = result;
return lResult;
}
export function print_info(
title: string,
message?: any,
is_end: boolean = false
): void {
if (is_end) {
console.log(message);
console.log("----------" + title + "--/\\---");
} else {
console.log("----------" + title + "--\\/---");
console.log(message);
};
}
export function retError(
pCode: number,
pErr?: any,
pReq?: string
): iExecResult {
let lError: iExecResult = <iExecResult>{};
lError.code = pCode;
lError.message = pErr.message;
lError.stack = pErr.stack;
lError.request = pReq;
lError.result = pErr;
return lError;
}
export interface iGetParams {
filters?: any;
entity?: any;
crudOp?: lstCRUD;
}
export interface iKey {
name: string;
dbName: string;
value?: any;
}
export interface iKeys {
[index: number]: string;
}
|
9361609b410a5ed4cd337f3fd2de43ceb52f58e8
|
TypeScript
|
nxttx/ReactNative---Runconnect_App
|
/src/core/mapper/SegmentMapper.ts
| 3.265625
| 3
|
import SegmentResponseDTO from '../dto/SegmentResponseDTO';
import {Segment} from '../domain/Segment';
import {SegmentDTO} from '../dto/SegmentDTO';
export class SegmentMapper {
/**
* Maps a single Segment DTO to a domain.
* @param {SegmentResponseDTO} DTO
* @returns {Segment}
*/
static toDomain(DTO: SegmentResponseDTO): Segment {
return {
id: DTO.id,
start: DTO.startCoordinate,
end: DTO.endCoordinate,
poi: DTO.POI,
};
}
/**
* Maps multiple segment DTOs to an array of domains.
* @param {SegmentResponseDTO[]} DTOs
* @returns {Segment[]}
*/
static multipleToDomain(DTOs: SegmentResponseDTO[]): Segment[] {
return DTOs.map(DTO => this.toDomain(DTO));
}
/**
* Maps a single Segment domain to a DTO.
* @returns {Segment}
* @param segment
*/
static toDTO(segment: Segment): SegmentDTO {
return {
startCoordinate: segment.start,
endCoordinate: segment.end,
};
}
/**
* Maps segments to DTOs.
* @returns {Segment}
* @param segments
*/
static multipleToDTO(segments: Segment[]): SegmentDTO[] {
return segments.map(segment => this.toDTO(segment));
}
}
|
d8a017f09aad87f5624dcae29bf266bccf753c81
|
TypeScript
|
lovefishs/leetcode
|
/src/javascript/intersectionOfTwoLinkedLists/iterative.ts
| 3.734375
| 4
|
/*
解这道题之前,我们需要首先明确一个概念:
如果两个单链表有共同的节点,那么从第一个共同节点开始,后面的节点都会重叠,直到链表结束。
这个概念很重要, 千万不要与 数组 互为混淆!!!
解题思路:
1. 遍历数组得到两个链表的长度差及长短链表
2. 遍历长链表消除长度差, 然后长短链表节点做等式判断, 如果相等则相交, 否则不相交
*/
import SinglyLinkedListNode from '../struct/SinglyLinkedListNode'
const iterative = (headA: SinglyLinkedListNode, headB: SinglyLinkedListNode): null | SinglyLinkedListNode => {
if (headA === null || headB === null) {
return null
}
let headACurr = headA
let headBCurr = headB
let headLong = null
// let longLength = 0
let dLengthValue = 0
// 找出长链表并且得出两个链表的长度差
while (headACurr !== null && headBCurr !== null) {
// longLength++
headACurr = headACurr !== null ? headACurr.next : headACurr
headBCurr = headBCurr !== null ? headBCurr.next : headBCurr
if (headACurr === null || headBCurr === null) {
// 如果两个链表同时为 null, 则长度差为 0, 否则加 1
dLengthValue = headACurr === null && headBCurr === null ? 0 : dLengthValue + 1
// 只做一次长链表赋值
if (headLong === null) {
headLong = headACurr === null ? headB : headA
}
}
}
// console.log('dLengthValue', dLengthValue)
// console.log('longLength', longLength)
// 根据长链表得到短链表
let headShort = headLong === headA ? headB : headA
let ret = null
let moveLength = 0
while (headLong) {
if (moveLength >= dLengthValue) {
if (headLong === headShort) {
ret = headLong
break
}
headShort = headShort.next
}
moveLength++
headLong = headLong.next
}
return ret
}
export default iterative
|
9e0eb218ce5e5be3a8821e2e763b5aa729932f83
|
TypeScript
|
toyobayashi/vuemodel
|
/src/util.ts
| 2.921875
| 3
|
import type { Store } from './Store'
import type { IAction, IMutation, ISubscriberEvent } from './types'
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
export function forEach<T> (arr: T[], fn: (value: T, index: number, self: T[]) => void | 'break'): void {
for (let i = 0; i < arr.length; i++) {
const shouldBreak = fn(arr[i], i, arr)
if (shouldBreak === 'break') {
break
}
}
}
export const oid = /*#__PURE__*/ (function () {
let index = 0
const PROCESS_UNIQUE: [number, number, number, number, number] = [0, 0, 0, 0, 0]
function reset (): void {
index = ~~(Math.random() * 0xffffff)
for (let i = 0; i < 5; i++) PROCESS_UNIQUE[i] = Math.floor(Math.random() * 256)
}
function generate (time?: number): string {
if (typeof time !== 'number') {
time = ~~(Date.now() / 1000)
}
index = (index + 1) % 0xffffff
const inc = index
const buffer = []
buffer[3] = time & 0xff
buffer[2] = (time >> 8) & 0xff
buffer[1] = (time >> 16) & 0xff
buffer[0] = (time >> 24) & 0xff
buffer[4] = PROCESS_UNIQUE[0]
buffer[5] = PROCESS_UNIQUE[1]
buffer[6] = PROCESS_UNIQUE[2]
buffer[7] = PROCESS_UNIQUE[3]
buffer[8] = PROCESS_UNIQUE[4]
buffer[11] = inc & 0xff
buffer[10] = (inc >> 8) & 0xff
buffer[9] = (inc >> 16) & 0xff
let res = ''
for (let i = 0; i < buffer.length; i++) {
const hex = buffer[i].toString(16)
res += (hex.length === 1 ? ('0' + hex) : hex)
}
return res
}
reset()
return generate
})()
export function def (obj: any, name: string, value: any): void {
try {
Object.defineProperty(obj, name, {
configurable: true,
enumerable: false,
writable: true,
value: value
})
} catch (_) {
obj[name] = value
}
}
export class MutationEvent<P> implements ISubscriberEvent<IMutation<P>> {
public constructor (
public id: string,
public payload: P,
public type: string
) {}
}
export class ActionEvent<P> implements ISubscriberEvent<IAction<P, any>> {
public constructor (
public id: string,
public payload: P,
public status: 'before' | 'after' | 'error',
public type: string
) {}
}
export function deepCopy<T> (obj: T, cache: Array<{ original: T; copy: any }> = []): T {
// just return if obj is immutable value
if (obj === null || typeof obj !== 'object') {
return obj
}
// if obj is hit, it is in circular structure
const hit = cache.filter(c => c.original === obj)[0]
if (hit) {
return hit.copy
}
const copy: any = Array.isArray(obj) ? [] : {}
// put the copy into cache at first
// because we want to refer it in recursive deepCopy
cache.push({
original: obj,
copy
})
Object.keys(obj).forEach(key => {
copy[key] = deepCopy((obj as any)[key], cache)
})
return copy
}
export function addMutation<P> (mutations: Record<string, Array<IMutation<any>>>, name: string, handler: (payload: P) => void, self?: Store<any, any>): IMutation<P> {
let disposed = false
const mutation: IMutation<P> = function wrappedMutationHandler (payload) {
handler.call(self, payload)
}
mutation.type = name
mutation.isDisposed = function isDisposed () {
return disposed
}
mutation.dispose = function dispose () {
if (disposed) return
const array = mutations[name]
const i = array.indexOf(mutation)
if (i !== -1) {
array.splice(i, 1)
}
if (array.length === 0) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete mutations[name]
}
disposed = true
}
mutations[name] = mutations[name] || []
mutations[name].push(mutation)
return mutation
}
export function addAction<P, R> (actions: Record<string, Array<IAction<any, any>>>, name: string, handler: (payload: P) => R | Promise<R>, self?: Store<any, any>): IAction<P, R> {
let disposed = false
const action: IAction<P, R> = function wrappedActionHandler (payload) {
return handler.call(self, payload)
}
action.type = name
action.isDisposed = function isDisposed () {
return disposed
}
action.dispose = function dispose () {
if (disposed) return
const array = actions[name]
const i = array.indexOf(action)
if (i !== -1) {
array.splice(i, 1)
}
if (array.length === 0) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete actions[name]
}
disposed = true
}
actions[name] = actions[name] || []
actions[name].push(action)
return action
}
|
fb937cf5726a8fb9fc1b85feb163830392d81956
|
TypeScript
|
mamazu/p5-projects
|
/Crossword Puzzle/sketch/CrosswordPuzzleFactory.ts
| 3.515625
| 4
|
class CrosswordPuzzleFactory {
private readonly wordList: WordToGuess[];
constructor(wordList: string[], optimized?: boolean) {
this.wordList = [];
for (let wordString of wordList) {
let word = this.parseWord(wordString)
if (word !== undefined) {
this.wordList.push(word);
}
}
if(optimized === true){
this.optimize();
}
}
private parseWord(line: string): WordToGuess | undefined {
let regex = /\{([ad])(\d+)\|(\d+)\}([^|]+)\|(.*)/i;
let match = regex.exec(line)
if (match === null) {
console.error(`${line} does not match.`);
return;
}
let parsedDirection = Direction.ACROSS;
switch (match[1]) {
case 'a':
case 'A':
parsedDirection = Direction.ACROSS;
break;
case 'd':
case 'D':
parsedDirection = Direction.DOWN;
break;
}
let position: WordPosition = {
direction: parsedDirection,
x: Number(match[2]),
y: Number(match[3]),
};
return new WordToGuess(match[4], position, match[5]);
}
private optimize(): void {
// todo: optimize cross word puzzle
}
getCrossWordSize(): number[] {
let maxX = 0, maxY = 0;
this.wordList.forEach((word) => {
let position = word.getPosition();
let direction = position.direction;
let x = position.x + ((direction === Direction.ACROSS) ? word.getLength() : 0);
let y = position.y + ((direction === Direction.DOWN) ? word.getLength() : 0);
maxX = sketchP.max(x, maxX);
maxY = sketchP.max(y, maxY);
});
return [maxX, maxY];
}
make(): CrosswordPuzzle {
let size = this.getCrossWordSize();
let crossWordPuzzle = new CrosswordPuzzle(size[0], size[1]);
this.wordList.forEach((word) => {
crossWordPuzzle.addWord(word);
});
return crossWordPuzzle;
}
makeFilled(): CrosswordPuzzle {
let crossWordPuzzle = this.make();
this.wordList.forEach(crossWordPuzzle.addWord);
return crossWordPuzzle;
}
}
|
ee528ba196e6efbc872b81aa736795313b16caed
|
TypeScript
|
elbernante/cs572-store-app
|
/src/app/cart/cart.ts
| 3.0625
| 3
|
import { Product } from '../product';
export class LineItem {
constructor (
public product: Product,
public quantity: number = 0
) {}
}
export class Cart {
items: LineItem[] = [];
size: number = 0;
addItem(product: Product): LineItem {
if (!product) return null;
let lineItem : LineItem = this.items.find(i => i.product.id === product.id)
|| new LineItem(product);
if (lineItem.quantity === 0) {
this.items.push(lineItem);
}
lineItem.quantity += 1;
this.size += 1;
return lineItem;
}
}
|
35bbc8a0b1951689863be4ff19f7159c2dec7abe
|
TypeScript
|
Avinashkumar8694/Angular-resolvers-example
|
/server/src/utils/Logger.ts
| 2.734375
| 3
|
import { createLogger, format, transports } from 'winston';
import * as DailyRotateFile from 'winston-daily-rotate-file';
import config from '../config/config';
const { combine, timestamp, label, printf, colorize } = format;
class WinstonLogger {
constructor() {
}
getWinstonTransportConfig(transportType) {
const transportConfig = { transports: [], exceptionHandlers: [] };
if (transportType.file) {
transportConfig.transports.push(new DailyRotateFile({
filename: config.logger.logFile ? config.logger.logFile : 'logs/console.log',
datePattern: 'DD-MM-YYYY',
maxSize: '10m',
maxFiles: '30d'
}));
transportConfig.exceptionHandlers.push(new DailyRotateFile({
filename: config.logger.exceptionFile ? config.logger.exceptionFile : 'logs/exception.log',
datePattern: 'DD-MM-YYYY',
maxSize: '10m'
}));
}
if (transportType.console) {
transportConfig.transports.push(new transports.Console());
transportConfig.exceptionHandlers.push(new transports.Console());
}
return transportConfig;
}
loggerStream() {
const consoleConfig = { file: false, console: false };
if (config.logger && config.logger.transport) {
const transportType: any = config.logger.transport;
if ((Array.isArray(transportType) && (transportType.findIndex(item => item.toLowerCase() === 'console') > -1)) || (typeof transportType === 'string' && transportType.toLowerCase() === 'console')) {
consoleConfig.console = true;
}
if ((Array.isArray(transportType) && (transportType.findIndex(item => item.toLowerCase() === 'file') > -1)) || (typeof transportType === 'string' && transportType.toLowerCase() === 'file')) {
consoleConfig.file = true;
}
}
return this.getWinstonTransportConfig(consoleConfig);
}
logFormat = printf(info => {
return `[${info.label}] ${info.timestamp} ${info.level}: ${info.message}`;
});
initLogger() {
let logInstance = createLogger({
level: ((config.logger && config.logger.level) ? config.logger.level : 'info'),
levels: {
error: 0,
warn: 1,
info: 2,
verbose: 3,
debug: 4,
silly: 5
},
exitOnError: false,
format: combine(
colorize(),
label({ label: 'SSD' }),
timestamp({ format: 'DD-MM-YYYY HH:mm:ss' }),
this.logFormat
),
...this.loggerStream()
});
// Extend logger object to properly log 'Error' types
const origLog = logInstance.log
logInstance.log.prototype = function (level, msg) {
if (msg instanceof Error) {
var args = Array.prototype.slice.call(arguments)
args[1] = msg.stack
origLog.apply(logInstance, args)
} else {
origLog.apply(logInstance, arguments)
}
}
return logInstance;
}
}
export default new WinstonLogger().initLogger();
|
19224136c541392432c7d8ce5569139cbac22c12
|
TypeScript
|
Antoonds/Aloys
|
/src/app/store/reducers/fill-in.reducers.ts
| 2.5625
| 3
|
import * as FillInsActions from '../actions/fill-in.actions';
import {FillIn} from '../../_models/fill-in';
import {FillInModel} from '../../_models/fill-in.model';
import * as moment from 'moment';
export interface State{
fillIns: FillIn[];
}
const initialState: State = {
fillIns: []
};
export function fillInReducer(state= initialState, action: FillInsActions.FillInsActions
) {
switch (action.type) {
case FillInsActions.SET_FILLINS:
console.log(action.payload);
return{
...state,
fillIns: [...action.payload]
};
}
}
|
d9a99307a4a33459b6b2daa8ea59653ba55441ef
|
TypeScript
|
shi444363988/raduis-battle
|
/server/controller/GameController.ts
| 2.59375
| 3
|
import Global from "../global/Global";
import Clone from "../util/Clone";
import Uuid from "../util/Uuid";
import Vector from "../util/Vector";
import { Code, IUserInfo, IUserStatusFlags, IWindInfo, IBaseInfo, IWeaponInfo, ISkillInfo, IPositionInfo, IMoveReq, IMoveRsp, IRsp, IShootReq, ISkillStatusInfo, ISkillHitStatusInfo, SkillHitStatusStep, IShootInfo, IGameInfo } from "../typings/Common";
import Logger from "../decorator/Logger";
export default class GameController {
@Logger.log
initialize() {
this._initEvent();
}
private _maxPower:number = 10;
@Logger.log
private _initEvent() {
Global.instance.eventModule.on(Code.moveReq,this._onMoveReq,this);
Global.instance.eventModule.on(Code.shootReq,this._onShootReq,this);
}
@Logger.log
public createGame(userInfoList:Array<IUserInfo>) {
let gameInfo = this._createGameInfo(userInfoList);
Global.instance.dataModule.gameInfoList.insert(gameInfo);
return gameInfo;
}
@Logger.log
private _createUserInfoGameContext(userInfoList:Array<IUserInfo>) {
userInfoList.forEach(userInfo => {
userInfo.baseInfo = this._createBaseInfo();
userInfo.positionInfo = this._createPositionInfo();
userInfo.weaponInfo = this._createWeaponInfo();
userInfo.skillInfoList = [];
for(let i =0,l = 3;i < l;i++) {
userInfo.skillInfoList.push(this._createSkillInfo());
}
userInfo.skillHitStatusInfoList = [];
userInfo.userStatusFlags = {} as IUserStatusFlags;
})
return userInfoList;
}
@Logger.log
private _createGameInfo(userInfoList:Array<IUserInfo>) {
let gameInfo = {} as IGameInfo;
gameInfo.roomId = Uuid.instance.create();
gameInfo.windInfo = this._createWindInfo();
gameInfo.userInfoList = this._createUserInfoGameContext(userInfoList);
let fastestUserInfo = this._updatePower(gameInfo.userInfoList);
gameInfo.fastestUserInfo = fastestUserInfo;
gameInfo.round = 1;
return gameInfo;
}
@Logger.log
private _createWindInfo() {
let windInfo = {} as IWindInfo;
windInfo.windAngle = Math.floor((Math.random()*2-1) * 180);
windInfo.windPower = Math.floor(Math.random() * 7);
return windInfo;
}
@Logger.log
private _createBaseInfo():IBaseInfo {
let baseInfo = {} as IBaseInfo;
baseInfo.hp = 100;
baseInfo.atk = 5;
baseInfo.def = 2;
baseInfo.agl = 3;
baseInfo.radius = 50;
baseInfo.power = 0;
return baseInfo;
}
//技能信息
@Logger.log
private _createSkillInfo():ISkillInfo {
//todo;
let skillInfo = {} as ISkillInfo;
let skillInfoList = Global.instance.dataModule.skillInfoList.select(v => true);
let randomSkillInfo = skillInfoList[Math.floor(Math.random() * skillInfoList.length)];
Clone.instance.clone(skillInfo,randomSkillInfo);
return skillInfo;
}
//武器信息
@Logger.log
private _createWeaponInfo():IWeaponInfo {
//todo;
let weaponInfo = {} as IWeaponInfo;
let weaponInfoList = Global.instance.dataModule.weaponInfoList.select(v => true);
let randomWeaponInfo = weaponInfoList[Math.floor(Math.random() * weaponInfoList.length)];
Clone.instance.clone(weaponInfo,randomWeaponInfo);
return weaponInfo;
}
//位置信息
@Logger.log
private _createPositionInfo():IPositionInfo {
//todo;
let positionInfo = {} as IPositionInfo;
positionInfo.x = (Math.random()-0.5) * 1280;
positionInfo.y = (Math.random()-0.5) * 720;
return positionInfo;
}
@Logger.log
private _onMoveReq(req:IMoveReq) {
//不插入位置信息 仅仅保留在客户端
let moveRsp = {} as IMoveRsp;
moveRsp.positionInfo = req.positionInfo;
moveRsp.userId = req.userId;
let dataRsp = {} as IRsp;
dataRsp.code = Code.moveRsp;
dataRsp.rsp = moveRsp;
Global.instance.networkModule.sendToRoom(req.roomId,dataRsp);
}
@Logger.log
private _onShootReq(req:IShootReq) {
//获取房间信息
let gameInfoList = Global.instance.dataModule.gameInfoList.select(item => item.roomId === req.roomId);
if(gameInfoList && gameInfoList.length !== 0) {
let gameInfo = gameInfoList[0];
if(req.round !== gameInfo.round) {
return;
}
let userInfoList = gameInfo.userInfoList.filter(item => item.userId === req.userId);
//更新玩家位置信息
if(userInfoList && userInfoList.length !== 0) {
let userInfo = userInfoList[0];
userInfo.positionInfo = req.positionInfo;
//插入技能状态
let skillStatusInfo = {} as ISkillStatusInfo;
skillStatusInfo.duration = req.skillInfo.duration;
skillStatusInfo.shootPosition = this._getShootPosition(req.shootInfo,userInfo,gameInfo.windInfo);
skillStatusInfo.skillInfo = req.skillInfo;
skillStatusInfo.skillStatusId = Uuid.instance.create();
skillStatusInfo.userInfo = userInfo;
gameInfo.skillStatusInfoList.push(skillStatusInfo);
//更新该玩家体力
userInfo.baseInfo.power -= req.skillInfo.consume;
//更新玩家手牌
userInfo.skillInfoList.splice(req.skillIndex,1,this._createSkillInfo());
//迭代计算技能比例,插入
for(let skillStatusInfo of gameInfo.skillStatusInfoList) {
let shootRatioList = this._getShootRatioList(skillStatusInfo,gameInfo.userInfoList);
for(let i = 0,l = gameInfo.userInfoList.length; i < l; i++) {
if(shootRatioList[i] !== 0) {
let eachUserInfo = gameInfo.userInfoList[i];
if(eachUserInfo.skillHitStatusInfoList.filter(item => item.skillStatusInfo === skillStatusInfo).length === 0){
let skillHitStatusInfo = {} as ISkillHitStatusInfo;
skillHitStatusInfo.hitDuration = skillStatusInfo.skillInfo.hitDuration;
//skillHitStatusInfo.skillInfo = skillStatusInfo.skillInfo;
//skillHitStatusInfo.skillStatusId = skillStatusInfo.skillStatusId;
//skillHitStatusInfo.userInfo = skillStatusInfo.userInfo;
skillHitStatusInfo.skillStatusInfo = skillStatusInfo;
skillHitStatusInfo.ratio = shootRatioList[i];
skillHitStatusInfo.step = SkillHitStatusStep.start;
eachUserInfo.skillHitStatusInfoList.push(skillHitStatusInfo);
}
}
}
}
//计算技能效果
for(let eachUserInfo of gameInfo.userInfoList) {
for(let skillHitStatusInfo of eachUserInfo.skillHitStatusInfoList) {
Global.instance.skillController.updateSkillHitStatusInfoList(eachUserInfo,skillHitStatusInfo);
}
}
//计算全局技能状态
Global.instance.skillController.updateSkillStatusInfoList(gameInfo.skillStatusInfoList);
//计算所有玩家体力
let fastestUserInfo = this._updatePower(gameInfo.userInfoList);
//更新下一个出手的玩家
gameInfo.fastestUserInfo = fastestUserInfo;
//回合增加
gameInfo.round++;
}
}
}
@Logger.log
private _updatePower(userInfoList:Array<IUserInfo>) {
let fastestUserInfo:IUserInfo;
let minDuration:number = Number.POSITIVE_INFINITY;
userInfoList.forEach(item => {
let duration = (this._maxPower - item.baseInfo.power)/item.baseInfo.agl;
if(minDuration > duration){
fastestUserInfo = item;
minDuration = duration;
}
})
userInfoList.forEach(item => {
if(item === fastestUserInfo){
item.baseInfo.power = this._maxPower;
}else{
item.baseInfo.power += minDuration * item.baseInfo.agl
}
})
return fastestUserInfo;
}
@Logger.log
private _getShootRatioList(skillStatusInfo:ISkillStatusInfo,userInfoList:Array<IUserInfo>):number[] {
let ret:number[] = [];
for(let userInfo of userInfoList) {
let distance = Vector.instance.distance(userInfo.positionInfo,skillStatusInfo.shootPosition);
let radiusDistance = userInfo.baseInfo.radius + skillStatusInfo.userInfo.weaponInfo.exploreRadius;
if(distance > radiusDistance) {
ret.push(0);
}else{
ret.push(distance/radiusDistance);
}
}
return ret;
}
@Logger.log
private _getShootPosition(shootInfo:IShootInfo,userInfo:IUserInfo,windInfo:IWindInfo):IPositionInfo {
let positionInfo = userInfo.positionInfo;
let shootDirectionOffset = this._getShootDirectionOffset(shootInfo,userInfo.weaponInfo.shootRadius);
let windOffset = this._getWindOffset(windInfo);
positionInfo.x = shootDirectionOffset.x + windOffset.x;
positionInfo.y = shootDirectionOffset.y + windOffset.y;
return positionInfo;
}
@Logger.log
private _getShootDirectionOffset(shootInfo:IShootInfo,length:number):IPositionInfo {
let positionInfo = {} as IPositionInfo;
//客户端反向
let radian = Vector.instance.deg2rad(shootInfo.angle);
positionInfo.x = length * shootInfo.ratio * Math.cos(radian);
positionInfo.y = length * shootInfo.ratio * Math.sin(radian);
return positionInfo;
}
@Logger.log
private _getWindOffset(windInfo:IWindInfo):IPositionInfo {
let length = windInfo.windPower * 27;
let positionInfo = {} as IPositionInfo;
let radian = Vector.instance.deg2rad(windInfo.windAngle)
positionInfo.x = length * Math.cos(radian);
positionInfo.y = length * Math.sin(radian);
return positionInfo;
}
}
|
259f217b90472ac148bf07e92ac042ed217746cc
|
TypeScript
|
RavilAxmadyllin/social-network
|
/src/redux/profile-reducer.ts
| 2.640625
| 3
|
import {PhotosType, profileAPI, ProfileType} from '../api/api'
import {FormAction, stopSubmit} from 'redux-form'
import {Dispatch} from 'redux';
import {AppRootStateType} from './redux-store';
import {ThunkAction} from 'redux-thunk';
const ADD_POST = 'SOCIAL_NETWORK/PROFILE/ADD_POST'
const SET_PROFILE_USERS = 'SOCIAL_NETWORK/PROFILE/SET_PROFILE_USERS'
const GET_PROFILE_STATUS = 'SOCIAL_NETWORK/PROFILE/GET_PROFILE_STATUS'
const SET_PHOTOS = 'SOCIAL_NETWORK/PROFILE/SET_PHOTOS'
const TOGGLE_PROFILE_MODE = 'SOCIAL_NETWORK/PROFILE/TOGGLE_PROFILE_MODE'
const DELETE_POST = 'SOCIAL_NETWORK/PROFILE/DELETE_POST'
let initialState = {
profile: null as ProfileType | null,
profileEditMode: false,
status: '',
posts: [{id: 1, message: 'hello my darling', likesCounter: 12},] as Array<PostType>
}
//reducer
const profileReducer = (state: ProfileReducerType = initialState, action: ProfileActionsType) => {
switch (action.type) {
case ADD_POST: {
const newPost = {id: Math.random(), message: action.newPost, likesCounter: 0}
return {...state, posts: [newPost, ...state.posts]}
}
case DELETE_POST:
return {...state, posts: state.posts.filter(p => p.id !== action.id)}
case SET_PHOTOS:
return {...state, profile: {...state.profile, photos: action.url}}
case TOGGLE_PROFILE_MODE:
return {...state, profileEditMode: action.mode}
case SET_PROFILE_USERS:
return {...state, profile: action.data}
case GET_PROFILE_STATUS:
return {...state, status: action.status}
default:
return state
}
}
export default profileReducer
//action creator
export const addPost = (newPost: PostType) => ({type: ADD_POST, newPost} as const)
export const removePost = (id: number) => ({type: DELETE_POST, id} as const)
export const toggleProfileMode = (mode: boolean) => ({type: TOGGLE_PROFILE_MODE, mode} as const)
export const setUsersProfile = (data: ProfileType) => ({type: SET_PROFILE_USERS, data} as const)
export const getProfileStatus = (status: string) => ({type: GET_PROFILE_STATUS, status} as const)
const updatePhotos = (url: PhotosType) => ({type: SET_PHOTOS, url} as const)
//thunk
export const editProfile = (data: ProfileType): ProfileThunkType => async (dispatch, getState) => {
const result = await profileAPI.editProfile(data)
const userId = getState().auth.userId
if (result.resultCode === 0) {
userId !== null && dispatch(setProfile(userId))
dispatch(toggleProfileMode(false))
} else {
const someError = result.messages[0].length > 0 ? result.messages[0] : 'some error'
if (result.resultCode === 1) {
dispatch(stopSubmit('profileEdit', {_error: someError}))
}
}
}
export const setProfile = (userId: number) => async (dispatch: Dispatch) => {
const result = await profileAPI.getProfile(userId)
dispatch(setUsersProfile(result))
}
export const getStatus = (userId: number) => async (dispatch: Dispatch) => {
const result = await profileAPI.getStatus(userId)
dispatch(getProfileStatus(result))
}
export const updateStatus = (status: string) => async (dispatch: Dispatch) => {
const result = await profileAPI.updateStatus(status)
if (result.resultCode === 0) {
dispatch(getProfileStatus(status))
}
}
export const savePhotos = (file: File) => async (dispatch: Dispatch) => {
const result = await profileAPI.changePhotos(file)
dispatch(updatePhotos(result.data.photos))
}
//type
type ProfileReducerType = typeof initialState
type PostType = { id: number, message: string, likesCounter: number }
type ProfileThunkType = ThunkAction<void, AppRootStateType, unknown, ProfileActionsType | FormAction>
type ProfileActionsType = ReturnType<typeof addPost>
| ReturnType<typeof removePost>
| ReturnType<typeof toggleProfileMode>
| ReturnType<typeof setUsersProfile>
| ReturnType<typeof setUsersProfile>
| ReturnType<typeof getProfileStatus>
| ReturnType<typeof updatePhotos>
|
62a8a597d754f0896957cc700834df21b417a3e0
|
TypeScript
|
jamataran/programacion-servicios-procesos-ejemplos
|
/src/app/services/login-service.service.ts
| 2.703125
| 3
|
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from "rxjs";
import {LoginModel} from "../model/login.model";
import {Router} from "@angular/router";
import {HttpClient} from "@angular/common/http";
import {map} from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class LoginServiceService {
/**
* BehaviorSubject al igual que cualquier otro Subject es tanto un Observable como un Observador. Llevándolo a concreto, significa que te puedes suscribir al igual que con un Observable normal pero además expone los métodos next, error y complete , y los puedes llamar de forma imperativa en cualquier parte de tu código.
* Al llamar a cualquiera de estos métodos, todo suscriptor que esté suscrito al Subject va a ser notificado.
*
* Porque así impides que cualquier componente al que le hayas inyectado el servicio interactúe directamente con el Subject
* y envíe mensajes por otro medio que no sea la API pública que define tu servicio.
* @private
*/
private loginModelBehaviorSubject: BehaviorSubject<LoginModel | null>
public login: Observable<LoginModel | null>;
constructor(private router: Router, private http: HttpClient) {
this.loginModelBehaviorSubject = new BehaviorSubject<LoginModel | null>(JSON.parse(<string>localStorage?.getItem('login')));
this.login = this.loginModelBehaviorSubject.asObservable();
}
performLogin(inLogin: LoginModel): Observable<LoginModel> {
return this
.http
.post<LoginModel>('https://reqres.in/api/login', inLogin)
.pipe(map(uresponse => {
console.log('"*** LOGIN RESPONSE ***')
console.log(JSON.stringify(uresponse));
console.log('"**********************')
this.loginModelBehaviorSubject.next(uresponse);
localStorage.setItem('login', JSON.stringify(uresponse));
return uresponse;
}
));
}
performLogout(): void {
localStorage.removeItem('login');
this.loginModelBehaviorSubject.next(null);
this.router.navigate(['/login']);
}
loginValue(): LoginModel | null {
return this.loginModelBehaviorSubject?.value;
}
}
|
68c6fba438b85227d5c32533bebe403171221af8
|
TypeScript
|
JSideris/gearbox2d
|
/assembly/shapes/box.ts
| 3.15625
| 3
|
//type i16=number; type i32=number;type i64=number;type u16=number; type u32=number;type u64=number;type f32=number;
// var vec2 = require('../math/vec2')
// , Shape = require('./Shape')
// , shallowClone = require('../utils/Utils').shallowClone
// , Convex = require('./Convex');
import Convex from "./convex";
import { ConvexOptions } from "./convex";
import AABB from "../collision/aabb";
import Shape from "./shape";
import vec2 from "../math/vec2";
export class BoxOptions extends ConvexOptions{
width: f32 = 1;
height: f32 = 1;
}
export default class Box extends Convex{
/**
* Total width of the box
* @property width
* @type {Number}
*/
width: f32 = 1;
/**
* Total height of the box
* @property height
* @type {Number}
*/
height: f32 = 1;
/**
* Box shape class.
* @class Box
* @constructor
* @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
* @param {Number} [options.width=1] Total width of the box
* @param {Number} [options.height=1] Total height of the box
* @extends Convex
* @example
* var body = new Body({ mass: 1 });
* var boxShape = new Box({
* width: 2,
* height: 1
* });
* body.addShape(boxShape);
*/
constructor(options: BoxOptions|null){
// let width:f32 = 1;
// let height:f32 = 1;
// if(options){
// width = options.width;
// height = options.height;
// }
// let hw = width/2;
// let hh = height/2;
super(Shape.BOX, (
options ? [
vec2.fromValues(-options.width/2, -options.height/2),
vec2.fromValues( options.width/2, -options.height/2),
vec2.fromValues( options.width/2, options.height/2),
vec2.fromValues(-options.width/2, options.height/2)
] : [
vec2.fromValues(-0.5, -0.5),
vec2.fromValues( 0.5, -0.5),
vec2.fromValues( 0.5, 0.5),
vec2.fromValues(-0.5, 0.5)
]), options);
if(options){
this.height = options.height;
this.width = options.width;
}
}
/**
* Compute moment of inertia
* @method computeMomentOfInertia
* @return {Number}
*/
computeMomentOfInertia(): f32{
var w = this.width,
h = this.height;
return (h*h + w*w) / 12;
};
/**
* Update the bounding radius
* @method updateBoundingRadius
*/
updateBoundingRadius(): f32{
var w = this.width,
h = this.height;
this.boundingRadius = Mathf.sqrt(w*w + h*h) / 2;
return this.boundingRadius;
};
/**
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position
* @param {Number} angle
*/
computeAABB(out: AABB, position: Float32Array, angle: f32): void{
var c = Mathf.abs(Mathf.cos(angle)),
s = Mathf.abs(Mathf.sin(angle)),
w = this.width,
h = this.height;
var height = (w * s + h * c) * 0.5;
var width = (h * s + w * c) * 0.5;
var l = out.lowerBound;
var u = out.upperBound;
var px = position[0];
var py = position[1];
l[0] = px - width;
l[1] = py - height;
u[0] = px + width;
u[1] = py + height;
};
updateArea():f32{
this.area = this.width * this.height;
return this.area;
};
pointTest(localPoint: Float32Array): boolean{
return Mathf.abs(localPoint[0]) <= this.width * 0.5 && Mathf.abs(localPoint[1]) <= this.height * 0.5;
};
}
|
7e867316f9146fc577cae145a2aa44ce3e989fa4
|
TypeScript
|
coder-th/mock-platform
|
/packages/core/src/lifecycle.ts
| 2.859375
| 3
|
import chalk from "chalk";
import { MockApp } from "./types";
/**
* 路由注册之前想做的事情
* @param {*} app
* @returns
*/
export function beforeRouterMounted(app: MockApp) {
// 在路由创建之前,用户不能使用router属性
return createBaseHanlder(app, false);
}
/**
* 路由挂在后想完成的事情
* @param {*} app
* @returns
*/
export function routerMounted(app: MockApp) {
return createBaseHanlder(app);
}
export function routerBeforeUnmount(app: MockApp) {
return createBaseHanlder(app);
}
export function createBaseHanlder(app: MockApp, withRouter = true) {
// 拦截get操作,目的是避免用户在不恰当的生命周期取到路由,导致一系列报错
const appProxy = new Proxy(app, {
get(target, key) {
if (key === "router" && !withRouter) {
console.log(chalk.red("当前的生命周期不能使用路由"));
return undefined;
} else {
return target[key];
}
},
});
return (handler) => {
handler.call(app, appProxy);
};
}
export function createInvokeHooks() {
return {
beforeRouterMounted: (app: MockApp) => beforeRouterMounted(app),
routerMounted: (app: MockApp) => {
return routerMounted(app);
},
routerBeforeUnmount: (app: MockApp) => {
return routerBeforeUnmount(app);
},
};
}
|
0b8973596e351cb68666992b59cb3587b1d1f99a
|
TypeScript
|
ajcrites/rxjs-visualize
|
/src/app/visualizations/operators/observeOn.ts
| 2.515625
| 3
|
import { Component } from '@angular/core';
import { animationFrameScheduler, timer } from 'rxjs';
import { observeOn, take } from 'rxjs/operators';
@Component({
selector: 'rx-observe-on',
template: `
<h1>observeOn</h1>
<p>
This allows you to change the scheduler used for a source Observable for
another Observable. I don't understand schedulers well, and they're not
well-documented, so this example is pretty limited.
</p>
<pre prism-highlight="typescript">{{ code }}</pre>
<rxjs-visualize-marble [source]="input"></rxjs-visualize-marble>
<rxjs-visualize-marble [source]="output"></rxjs-visualize-marble>
`,
})
export class RxObserveOnComponent {
code = preval`module.exports = require('../codefile')(__filename)`;
input = timer(0, 1000).pipe(take(5));
output = this.input.pipe(observeOn(animationFrameScheduler, 100));
}
|
ff6057e4397c0585ebd4f02565a28387f00f6f68
|
TypeScript
|
AndrewLang/matrix-node-kit
|
/src/io/file.ts
| 3.109375
| 3
|
import * as EventStream from 'event-stream';
import * as fs from 'fs';
import * as path from 'path';
import { ConsoleLogger } from '../logging/index';
import { FileSizeCalculator } from './filesize';
export class File {
private static logger = new ConsoleLogger('File ');
/**
* Check whether given file is exist.
* @param filename full file name with path
*/
static Exists(filename: string): boolean {
let existed: boolean;
try {
existed = fs.existsSync(filename);
} catch (error) {
File.logger.Error(error);
existed = false;
}
return existed;
}
/**
* Write given content to file in sync mode
* @param filename filename to write
* @param content file content to write
*/
static Create(filename: string, content: string): void {
try {
fs.writeFileSync(filename, content);
} catch (error) {
File.logger.Error(error);
throw error;
}
}
/**
* Remove a file from file system
* @param filename the full name of file
*/
static Delete(filename: string): void {
try {
fs.unlinkSync(filename);
} catch (error) {
File.logger.Error(error);
}
}
/**
* Copy file
* @param source source file to read
* @param destination destination file to write
* @param overwrite whether overwrite give file
*/
static Copy(source: string, destination: string, overwrite: boolean): void {
try {
let goodToWrite = false;
let sourceStream = fs.createReadStream(source);
if (File.Exists(destination)) {
if (overwrite) {
fs.unlinkSync(destination);
goodToWrite = true;
}
} else {
goodToWrite = true;
}
if (goodToWrite) {
sourceStream.pipe(fs.createWriteStream(destination));
}
} catch (error) {
File.logger.Error(error);
}
}
static Move(source: string, destination: string, overwrite: boolean = true) {
try {
File.Copy(source, destination, overwrite);
File.Delete(source);
} catch (error) {
File.logger.Error(error);
}
}
/**
*
* @param filename
*/
static FindFolder(filename: string): string {
let folder = '';
if (filename && File.Exists(filename)) {
folder = filename.substr(0, filename.lastIndexOf('/'));
}
return folder;
}
/**
* Read file content in sync mode
* @param filename filename to read
* @param encoding encoding use to read file
*/
static ReadAllText(filename: string, encoding: string): string {
let content = '';
try {
content = fs.readFileSync(filename, encoding);
} catch (error) {
File.logger.Error(error);
content = '';
}
return content;
}
static ReadJson(filename: string, encoding: string): any {
let value = {};
try {
let content = fs.readFileSync(filename, encoding);
value = JSON.parse(content);
} catch (error) {
File.logger.Error(error);
}
return value;
}
/**
* Read file in async mode
* @param file
*/
static ReadFileAsync(file: string): Promise<any> {
let self = File;
return new Promise(function (resolve, reject) {
if (!self.Exists(file))
reject(new Error(`File doesn't exist.`));
fs.readFile(file, 'utf8', (error: any, data: any) => {
if (error)
reject(error);
resolve(data);
});
});
}
/**
* Read file line by line in async mode
* @param file
*/
static ReadFileLineByLine(file: string): Promise<string> {
let self = File;
return new Promise(function (resolve, reject) {
let lines: string[] = [];
let stream = fs.createReadStream(file)
.pipe(EventStream.split())
.pipe(EventStream.mapSync(
function (line: string) {
stream.pause();
lines.push(line);
stream.resume();
})
.on('error', function () {
reject('Read file error.');
})
.on('end', function () {
resolve(lines.join(''));
})
);
});
}
/**
* Read file content as base65 encoded string in async mode
* @param file file path
*/
static ReadFileAsBase64Async(file: string): Promise<string> {
let self = File;
let fullPath = File.NormalizePath(file.toString());
File.logger.Error('Full path: ' + fullPath);
return new Promise(function (resolve, reject) {
if (!self.Exists(fullPath))
reject(new Error(`File doesn't exist.' + fullPath`));
File.logger.Error('File to open ' + fullPath);
let data = fs.readFileSync(fullPath, 'base64');
let buffer = new Buffer(data, 'base64');
let base64Data = buffer.toString('base64');
resolve(base64Data);
});
}
/**
* Read file content as base65 encoded string in sync mode
* @param file file path
*/
static ReadFileAsBase64(file: string): string {
let self = File;
let fullPath = File.NormalizePath(file.toString());
if (!self.Exists(fullPath))
throw Error(`File doesn't exist.${fullPath}`);
let data = fs.readFileSync(fullPath, 'base64');
let buffer = new Buffer(data, 'base64');
let base64Data = buffer.toString('base64');
return base64Data;
}
/**
* Read file as node js stream
* @param file
*/
static ReadFileStream(file: string): any {
return fs.createReadStream(file);
}
/**
* Write file in async mode
* @param file
* @param data
*/
static WriteFileAsync(file: string, data: any): Promise<any> {
let self = File;
return new Promise(function (resolve, reject) {
fs.writeFile(file, data, (error: any) => {
if (error)
reject(error);
resolve(true);
});
});
}
/**
* Normalize given path
* @param path
*/
static NormalizePath(path: string): string {
return path.normalize(path);
}
/**
* Get file name with extension
* @param file
*/
static GetFilename(file: string): string {
try {
return path.basename(file);
} catch (error) {
File.logger.Error('Get file name error: ' + error);
return '';
}
}
/**
* Get file name without extension
* @param file
*/
static GetFilenameWithoutExtension(file: string): string {
let filename = File.GetFilename(file);
return path.parse(filename).name;
}
/**
* Get file size in number
* @param file
*/
static GetFileSize(file: string): number {
let stats = fs.statSync(file);
return stats['size'];
}
/**
* Get formated file size string
* @param file
*/
static GetFileSizeString(file: string): string {
try {
let size = File.GetFileSize(file);
let sizeString = FileSizeCalculator.Calculate(size);
return sizeString;
} catch (error) {
File.logger.Error('Get file name error: ' + error);
return '';
}
}
/**
* Convert give file size to readable file size string
* @param size
*/
static ConverToFileSizeString(size: number): string {
return FileSizeCalculator.Calculate(size);
}
}
|
9570e93b71202718159d8546e06e6bdd92cf83f2
|
TypeScript
|
markormesher/money-dashboard
|
/src/models/IUser.tests.ts
| 2.578125
| 3
|
import { expect } from "chai";
import { describe } from "mocha";
import { DEFAULT_PROFILE } from "./IProfile";
import { IUser, mapUserFromApi, mapUserForApi } from "./IUser";
describe(__filename, () => {
describe("mapUserFromApi()", () => {
it("should return undefined for null/undefined/empty-string inputs", () => {
expect(mapUserFromApi(null)).to.equal(undefined);
expect(mapUserFromApi(undefined)).to.equal(undefined);
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
expect(mapUserFromApi("")).to.equal(undefined);
});
it("should not mutate the input", () => {
const user: IUser = {
id: "id",
externalUsername: "external username",
displayName: "display name",
image: "image",
profiles: [DEFAULT_PROFILE],
activeProfile: DEFAULT_PROFILE,
deleted: false,
};
mapUserFromApi(user).should.not.equal(user);
});
});
describe("mapUserForApi()", () => {
it("should return undefined for null/undefined/empty-string inputs", () => {
expect(mapUserForApi(null)).to.equal(undefined);
expect(mapUserForApi(undefined)).to.equal(undefined);
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
expect(mapUserForApi("")).to.equal(undefined);
});
it("should not mutate the input", () => {
const user: IUser = {
id: "id",
externalUsername: "external username",
displayName: "display name",
image: "image",
profiles: [DEFAULT_PROFILE],
activeProfile: DEFAULT_PROFILE,
deleted: false,
};
mapUserForApi(user).should.not.equal(user);
});
});
});
|
9544e712d772db24ed60bb9ea5878a4046df105f
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/react-edit-text/index.d.ts
| 2.859375
| 3
|
// Type definitions for react-edit-text 5.0
// Project: https://github.com/bymi15/react-edit-text#readme
// Definitions by: Brian Min <https://github.com/bymi15>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as React from 'react';
export type inputTextType =
| 'date'
| 'datetime-local'
| 'email'
| 'month'
| 'number'
| 'password'
| 'search'
| 'tel'
| 'text'
| 'url'
| 'week';
export interface onSaveProps {
name: string;
value: string;
previousValue: string;
}
export interface SharedProps {
/**
* id attribute set for both input and display element
*/
id?: string;
/**
* name attribute set for input element
*/
name?: string;
/**
* class attribute set for display element
*/
className?: string;
/**
* class attribute set for input element
*/
inputClassName?: string;
/**
* value sets the input value and text of display element
*/
value?: string;
/**
* defaultValue sets the defaultValue for input element and initial text of display element
*/
defaultValue?: string;
/**
* placeholder is shown in the display element when value is empty
*/
placeholder?: string;
/**
* formatDisplayText is used to pass in a function which takes in a value and returns a formatted value
* which is used to format the text shown in the display element
* default: (val) => val
*/
formatDisplayText?: (value: string) => string;
/**
* onSave is called when the input blur event is triggered or enter key is pressed
* returns an object: {name, value, previousValue} which correspond to the input name, value, and previous value before changes were made
*/
onSave?: ({ name, value, previousValue }: onSaveProps) => void;
/**
* onChange is called when the input value changes and
* returns a string which corresponds to the new input value
*/
onChange?: (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
/**
* onEditMode is a callback function triggered when the display
* component is clicked and edit mode is toggled on
*/
onEditMode?: () => void;
/**
* onBlur is a callback function triggered when the focus is blurred
* and edit mode is toggled off
*/
onBlur?: () => void;
/**
* Sets the css styling for both input and div elements
*/
style?: React.CSSProperties;
/**
* Displays only the view element when set to true,
* default: false
*/
readonly?: boolean;
}
export interface EditTextProps extends SharedProps {
/**
* type attribute set for input element,
* default: 'text'
*/
type?: inputTextType;
/**
* Sets the element display to inline when set to true,
* default: false
*/
inline?: boolean;
/**
* Displays an edit button that can be pressed to enable edit mode,
* default: false
*/
showEditButton?: boolean;
/**
* Sets the content for the edit button. This can be any valid element,
* default: <EditIcon />
*/
editButtonContent?: React.ReactNode;
/**
* Sets the props passed to the edit button. This can be any valid DOM attribute,
* default: {}
*/
editButtonProps?: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>;
}
export interface EditTextareaProps extends SharedProps {
/**
* the number of visible rows,
* default: 3
*/
rows?: number;
}
export class EditText extends React.Component<EditTextProps> {}
export class EditTextarea extends React.Component<EditTextareaProps> {}
|
b1ccc63799b933eb41663649826139d2dbf7b852
|
TypeScript
|
12kb/jira.js
|
/src/version2/models/issueLink.ts
| 3.015625
| 3
|
import { IssueLinkType } from './issueLinkType';
import { LinkedIssue } from './linkedIssue';
/**
* Details of a link between issues. */
export interface IssueLink {
/** The ID of the issue link. */
id?: string;
/** The URL of the issue link. */
self?: string;
/** The type of link between the issues. */
type: IssueLinkType[];
/** The issue the link joins to. */
inwardIssue: LinkedIssue[];
/** The issue the link originates from. */
outwardIssue: LinkedIssue[];
}
|
3590041961745b1b6fa7fc54eb0c8fedde999ea1
|
TypeScript
|
juazsh/codingChallenge
|
/src/app/challenge/challenge.component.ts
| 3.125
| 3
|
import { Component, OnInit } from '@angular/core';
import { Employee } from '../Employee';
@Component({
selector: 'app-challenge',
templateUrl: './challenge.component.html',
styleUrls: ['./challenge.component.css']
})
export class ChallengeComponent implements OnInit {
buttonText: string;
buttonFlag: boolean;
employees: Employee[];
ngOnInit() {
this.buttonText = 'Hello';
this.buttonFlag = true;
// this can be a data service getting required data
const sam: Employee = { id: 1, name: 'Sam Smith', active: true};
const john: Employee = { id: 2, name: 'John Doe', active: true };
const berry = { id: 3, name: 'Berry Turner', active: false };
sam.reportingEmployees = [john, berry];
john.reportingEmployees = [berry];
this.employees = [sam, john, berry];
// end of data retrieval
// Call to retrieve string property
this.retrieveStringProperty(this.employees);
// Call to retrieve string arry from the optional employees array
this.retrieveStringPropertyFromOptionalArray(this.employees);
}
/**
* @param employees list of employees.
*/
retrieveStringProperty ( employees ) {
// getting the string property array
const employeeName = employees.map(emp => emp.name);
console.log(employeeName);
// end of string property retrieval
}
/**
*
* @param employees list of employees
*/
retrieveStringPropertyFromOptionalArray( employees ) {
// getting the string array from the optional employee list
const employeeNameFromOptionalProperty: string[] = [];
employees.forEach(emp => {
if (emp.reportingEmployees && emp.reportingEmployees.length > 0) {
emp.reportingEmployees.forEach(item => employeeNameFromOptionalProperty.push(item.name));
}
});
console.log(employeeNameFromOptionalProperty);
// end of string array retrieval from the optional employee list
}
/**
* toggle flag to change button text
*/
toggleText() {
this.buttonFlag = !this.buttonFlag;
this.buttonText = (this.buttonFlag) ? 'Hello' : 'World';
}
}
|
2c7a670c70a95517d9cdeecfd0300daf8885c6de
|
TypeScript
|
adrianndwiga/store
|
/index.ts
| 2.734375
| 3
|
import * as fs from 'fs';
export class Store {
constructor(private baseFolder: string) {
}
public read(file: string): string {
return fs.readFileSync(`${this.baseFolder}${file}`, 'utf8');
}
public write(file: string, data: string): void {
fs.writeFileSync(`${this.baseFolder}${file}`, data, 'utf8');
}
}
|
de77cfa2b3af92ffe02cd6436a676b9dd883c435
|
TypeScript
|
glitchwizard/handbook
|
/src/lib/getGitHistory.ts
| 2.578125
| 3
|
import path from 'path'
import { gitlogPromise as gitlog } from 'gitlog'
import { CONTENT_FOLDER } from './constants'
export default async function getGitHistory(
file: string
): Promise<(Record<'hash' | 'authorName' | 'committerDateRel' | 'status', string> & { files: string[] })[]> {
const filepath = path.join(CONTENT_FOLDER, file)
const log = gitlog({
repo: '.',
number: 100,
file: filepath,
fields: ['committerDateRel', 'authorName', 'hash'],
})
return log
}
export interface GitHistorySummary {
creator: string | undefined
createdTimeAgo: string | undefined
latestCommitId: string
lateCommitTimeAgo: string
contributorNames: string[]
}
export async function getGitHistoryStats(file: string): Promise<GitHistorySummary> {
const history = await getGitHistory(file)
const creationCommit = history.find(commit => commit.status.includes('A'))
const latestCommit = history[0]
const contributors = history
.map(commit => commit.authorName)
.filter((value, index, self) => self.indexOf(value) === index)
return {
creator: creationCommit?.authorName,
createdTimeAgo: creationCommit?.committerDateRel,
latestCommitId: latestCommit?.hash,
lateCommitTimeAgo: latestCommit?.committerDateRel,
contributorNames: contributors,
}
}
|
78290dcfdeba13f650851eaf8cf9d7675cc9576e
|
TypeScript
|
flotos/prisme-rpg
|
/src/routes.ts
| 2.53125
| 3
|
import test from "./intentHandlers/test";
import travel from "./intentHandlers/travel";
export default (request: IPrismeRequest) => {
const {
body: {
intent: { inputs = {}, name = "" } = {},
fulfillment = {},
query = "",
} = {},
} = request;
console.log("got request", name, fulfillment, query);
switch (name) {
case "test":
return test();
case "travel":
return travel();
case "default":
return null;
}
};
|
7a2d33a204ec1ccaf56f9ebe9d832cc0d8bfa6b0
|
TypeScript
|
bmbell/wolverine-websites
|
/maze/src/app/mazes/_shared/models/maze-cell.model.ts
| 2.671875
| 3
|
import { Direction } from "../enumerations/direction.enum";
export interface MazeCell {
/**
* The cell's id
*/
id: string;
/**
* The available passages from this cell
*/
passages: Direction[];
}
|
fb5e10bf6b0b8731628649173a5cb00e4d06164a
|
TypeScript
|
stschoelzel/dungeonsAndDragonsAndReceipts
|
/types/Monster.ts
| 2.703125
| 3
|
export interface Monster {
name: string;
source: string;
page: number;
srd?: boolean;
size: Size;
type: Type;
alignment: Alignment[];
ac: ArmorClass[];
hp: HP;
speed: Speed;
str: number;
dex: number;
con: number;
int: number;
wis: number;
cha: number;
save?: Save;
resist?: (string | { resist: string[]; note?: string; cond?: boolean })[];
skill: Skill;
passive: number;
languages: string[];
cr: string | { cr: string; coven: string };
trait: Entry[];
action: Entry[];
reaction: Entry[];
environment?: Environment[];
hasToken?: boolean;
traitTags?: string[];
senseTags?: string[];
languageTags?: string[];
spellcastingTags?: string[];
damageTags?: string[];
miscTags?: string[];
conditionInflict?: string[];
conditionInflictSpell?: string[];
conditionImune?: string[];
immune?: string[];
variant?: any;
spellcasting: any[];
legendaryGroup?: { name: string; source: string };
}
export type Size = "S" | "M" | "L" | "H" | "G" | "T";
// Add types
export type Alignment = string;
export type Environment = string;
export type Type = string;
export interface ArmorClass {
ac: number;
from: string[];
}
export interface HP {
average: number;
formula: string;
}
export interface Speed {
walk?: number;
burrow?: number;
climb?: number;
fly?: number | { number: number; condition: string };
swim?: number;
canHover?: boolean;
}
export interface Skill {
perception?: string;
stealth?: string;
insight?: string;
arcana?: string;
athletics?: string;
// add rest
}
export interface Entry {
name: string;
entries: string[];
}
export interface Save {
str: string;
dex: string;
con: string;
int: string;
wis: string;
}
|
76df97885e4e002777b92ee6b607110a86ab40f7
|
TypeScript
|
Telematica/TypeScript
|
/typescript-book/Future JavaScript Now/arrow-functions.ts
| 4.0625
| 4
|
//var inc = (x) => x + 1;
/* 1)
function Person(age) {
this.age = age;
this.growOld = function() {
this.age++;
}
}
*/
/* 1.1)
function Person(age) {
this.age = age;
this.growOld = function() { this.age++; };
this.growOld = this.growOld.bind(this);
}
*/
/*
// 2)
function Person(age) {
this.age = age;
this.growOld = () => {
this.age++;
}
}
*/
/*
// 3)
function Person(age) {
this.age = age;
var _this = this; // capture this
this.growOld = function() {
_this.age++;
}
}
*/
// 4) TypeScript
export class Person {
constructor(public age:number) {}
growOld = () => {
this.age++;
}
}
var person = new Person(1);
setTimeout(person.growOld, 1000);
console.log('TEST');
setTimeout(function() { console.log('LOOOL'); }, 1);
|
267cb9959ed9f7bbfe76fa97dbda3ac7f2f834b8
|
TypeScript
|
Ibrahim9595/schools
|
/src/groups-permissions/new-permission-group.ts
| 2.703125
| 3
|
export class NewPermissionGroup {
groupName: string;
description: string;
updating: boolean;
id: number;
constructor(updating: boolean, groupName="", description="", id?: number){
this.groupName = groupName;
this.description = description;
this.updating = updating;
this.id = id;
}
}
|
cd7c64d3a1affe3efe735e4a2531746383bc7d2d
|
TypeScript
|
robbie-cahill/hcard-hybrid-react-app
|
/tests/save-hcard.spec.ts
| 2.546875
| 3
|
import saveHCard from "../src/save-hcard";
import HCard from "../src/hcard";
/**
* Mocking multiple async functions that return Promises
*/
jest.mock('../src/hcard-repository', function() {
return {
default : {
addOne : async function() {
return Promise.resolve();
}
}
};
});
jest.mock('../src/recent-hcard-repository', function() {
return {
default : {
addOne : async function() {
return Promise.resolve()
},
deleteAll : async function() {
return Promise.resolve();
}
}
};
});
// Testing an async function that returns a Promise using the new async/await
describe('Save HCard should take the HCard data and save it', () => {
it('Should save the HCard', async () => {
let hCard = new HCard();
await saveHCard(hCard);
return Promise.resolve();
});
});
|
93ed16618482593d40b7e978402788e01efc1af7
|
TypeScript
|
determined-ai/determined
|
/webui/react/src/ee/SamlAuth.test.ts
| 2.65625
| 3
|
import * as utils from './SamlAuth';
describe('SamlAuth', () => {
describe('samlUrl', () => {
const BASE_PATHS = ['/abc/def-ghi', '/HelloWorld/What%20is%20up?'];
const QUERIES = [
{
default: 'columns=id&columns=user&sortDesc=false&tableLimit=20',
encoded: 'columns%3Did%26columns%3Duser%26sortDesc%3Dfalse%26tableLimit%3D20',
},
{
default: 'sortDesc=false&sortKey=SORT_BY_NAME&tags=mnist',
encoded: 'sortDesc%3Dfalse%26sortKey%3DSORT_BY_NAME%26tags%3Dmnist',
},
];
it('should return base path only if no queries are provided', () => {
for (const basePath of BASE_PATHS) {
expect(utils.samlUrl(basePath)).toBe(basePath);
}
});
it('should encode the query param', () => {
const basePath = BASE_PATHS.first();
for (const query of QUERIES) {
const expected = `${basePath}?relayState=${query.encoded}`;
expect(utils.samlUrl(basePath, query.default)).toBe(expected);
}
});
});
describe('handleRelayState', () => {
const QUERIES_WITHOUT_RELAY = new URLSearchParams({ someKey: 'noRelayState' });
const QUERIES_INPUT = new URLSearchParams({
relayState: 'columns=id&columns=user&sortDesc=false&tableLimit=20',
someKey: 'someValue',
});
const QUERIES_OUTPUT: { [key: string]: unknown } = {
columns: ['id', 'user'],
someKey: 'someValue',
sortDesc: 'false',
tableLimit: '20',
};
it('should return original queries object without relay state', () => {
const result = utils.handleRelayState(QUERIES_WITHOUT_RELAY);
for (const [key, val] of QUERIES_WITHOUT_RELAY.entries()) {
expect(result.get(key)).toEqual(val);
}
});
it('should decode and flatten relayState query param', () => {
const result = utils.handleRelayState(QUERIES_INPUT);
for (const key of result.keys()) {
const val = result.getAll(key);
expect(val.length === 1 ? val[0] : val).toStrictEqual(QUERIES_OUTPUT[key]);
}
});
});
});
|
a729daf9526460056ca255881919462a9a23e31d
|
TypeScript
|
praneybehl/toybot
|
/src/parser.ts
| 3.078125
| 3
|
import Table, { IPosition } from "./table";
import { Directions, DirectionsTypes } from "./toybot";
import { showError, simpleLog } from "./utils";
import { ConsoleMessage } from "./constants/console-message";
export interface PlaceOptions {
position: IPosition;
direction: DirectionsTypes;
}
export function isValidPlacement(
placeOptions: PlaceOptions,
table: Table
): boolean {
const {
position: { x, y },
direction,
} = placeOptions;
const isValidPosition: boolean = table.isInBounds({ x, y });
const isValidDirection = Object.keys(Directions).includes(direction);
!isValidPosition && showError(ConsoleMessage.INVALID_POSITION);
!isValidDirection && showError(ConsoleMessage.INVALID_DIRECTION);
return isValidPosition && isValidDirection;
}
export function parsePlaceOptions(options: string): PlaceOptions | undefined {
try {
const parsedPlacement = options.split(",");
const x: number = parseInt(parsedPlacement[0]);
const y: number = parseInt(parsedPlacement[1]);
const direction = parsedPlacement[2] as DirectionsTypes;
return {
position: { x, y },
direction,
};
} catch (err) {
showError(ConsoleMessage.INVALID_COMMAND);
simpleLog(ConsoleMessage.HELP);
}
}
|
1d6a535fb2486884f6cacba73a117289ebd08de2
|
TypeScript
|
fozeu-jm/the_mower
|
/models/Mower.ts
| 3.28125
| 3
|
import {Cardinal} from "./cardinalDirection";
import {Coordinate} from "./Coordinate";
import {Imow} from "../Interfaces/Imow";
import {Ipoint} from "../Interfaces/Ipoint";
import {IOrientation} from "../Interfaces/IOrientation";
export class Mower implements Imow {
private _coordinates : Ipoint;
private _orientation : IOrientation;
private _instructions : string[];
constructor(coordinate? : Ipoint , orientation? : IOrientation, instructions? : string[]) {
this._coordinates = coordinate ?? new Coordinate(0, 0);
this._orientation = orientation ?? new Cardinal("N");
this._instructions = instructions ?? [];
}
public get coordinates():Ipoint{
return this._coordinates;
}
public get orientation():IOrientation{
return this._orientation;
}
public set coordinates(coordinate:Ipoint){
this._coordinates = coordinate;
}
public set orientation(orientation:IOrientation){
this._orientation = orientation;
}
public get instructions(): string[]{
return this._instructions;
}
public set instructions(instructions: string[]){
this._instructions = instructions;
}
public mow = (limX:number, limY:number) => {
this._instructions.forEach((instruction) =>{
switch (instruction) {
case 'R':
this.rotateRight();
break;
case 'L':
this.rotateLeft();
break;
case 'F':
this.moveForward(limX, limY);
break;
}
});
}
private rotateRight(){
switch (this._orientation.direction.toUpperCase()) {
case 'N':
this._orientation.direction = 'E';
break;
case 'E' :
this._orientation.direction = 'S';
break;
case 'S' :
this._orientation.direction = 'W';
break;
case 'W' :
this._orientation.direction = 'N';
break;
}
}
private rotateLeft(){
switch (this._orientation.direction.toUpperCase()) {
case 'N':
this._orientation.direction = 'W';
break;
case 'E' :
this._orientation.direction = 'N';
break;
case 'S' :
this._orientation.direction = 'E';
break;
case 'W' :
this._orientation.direction = 'S';
break;
}
}
private moveForward(limX:number, limY:number){
switch (this._orientation.direction.toUpperCase()) {
case 'N':
this._coordinates.plusY(limY);
break;
case 'E' :
this._coordinates.plusX(limX);
break;
case 'S' :
this._coordinates.minusY();
break;
case 'W' :
this._coordinates.minusX();
break;
}
}
public toString = () :string => {
return this._coordinates.X.toString()+ " " + this._coordinates.Y.toString() + " " + this._orientation.direction;
}
}
|
95d7e71f927516149bb390ae35a38740fd51e04b
|
TypeScript
|
JoritVergalle/T4T
|
/src/app/models/session.model.ts
| 2.828125
| 3
|
import {Talk} from './talk.model';
export class Session {
private _talks: Talk[];
private _maxTime: number;
constructor(time: number) {
this._talks = new Array<Talk>();
this._maxTime = time;
}
get talks(): Talk[] {
return this._talks;
}
addTalk(talk: Talk) {
this._talks.push(talk);
}
get maxTime(): number {
return this._maxTime;
}
set maxTime(value: number) {
this._maxTime = value;
}
}
|
88ce1edea28a015ede1248bc0d0fa1fba42690c3
|
TypeScript
|
awjae/TypeScript
|
/exercise/src/18-function-types-with-promises.problem.ts
| 3.1875
| 3
|
import { expect, it } from "vitest";
import { Equal, Expect } from "./helpers/type-utils";
interface User {
id: string;
firstName: string;
lastName: string;
}
const createThenGetUser = async (
createUser: () => Promise<string>,
getUser: (id: string) => Promise<User>,
): Promise<User> => {
const userId: string = await createUser();
const user = await getUser(userId);
return user;
};
it("Should create the user, then get them", async () => {
const user = await createThenGetUser(
async () => "123",
async (id) => ({
id: "123",
firstName: "Matt",
lastName: "Pocock",
}),
);
expect(user).toEqual({
id: "123",
firstName: "Matt",
lastName: "Pocock",
});
});
|
ade4bbacf72dff060dd3e07320cb8bca8aea05b5
|
TypeScript
|
stozuka/marvel-api-challenge
|
/src/module/marvel/marvel.controller.spec.ts
| 2.640625
| 3
|
import {
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import { RedisService } from 'nestjs-redis';
import { MarvelController } from './marvel.controller';
import { MervelService } from './marvel.service';
describe('MarvelController', () => {
let marvelController: MarvelController;
let mervelService: MervelService;
beforeEach(() => {
mervelService = new MervelService({} as RedisService);
marvelController = new MarvelController(mervelService);
});
describe('getCharacterIds', () => {
it('should return success response', async () => {
const expected = [1, 2, 3];
jest
.spyOn(mervelService, 'fetchCharacterIds')
.mockResolvedValue(expected);
const result = await marvelController.getCharacterIds();
expect(result).toEqual(expected);
});
it('should throw an error when fetch data failed', async () => {
jest
.spyOn(mervelService, 'fetchCharacterIds')
.mockRejectedValue(new InternalServerErrorException());
try {
await marvelController.getCharacterIds();
fail('Should have thrown error');
} catch (error) {
expect(error).toBeInstanceOf(InternalServerErrorException);
}
});
});
describe('getCharacter', () => {
it('should return success response', async () => {
const expected = {
id: 1,
name: 'name',
description: 'description',
};
jest.spyOn(mervelService, 'fetchCharacter').mockResolvedValue(expected);
const result = await marvelController.getCharacter(1);
expect(result).toEqual(expected);
});
});
it('should throw an error when fetch data failed', async () => {
jest
.spyOn(mervelService, 'fetchCharacter')
.mockRejectedValue(new NotFoundException());
try {
await marvelController.getCharacter(1);
fail('Should have thrown error');
} catch (error) {
expect(error).toBeInstanceOf(NotFoundException);
}
});
});
|
fb1bc1cdf4a0ede093ce96c3505eccf20fbfaac2
|
TypeScript
|
jkhaui/anchor-web-app
|
/app/src/@anchor-protocol/webapp-charts/interactions/useCoordinateSpace.ts
| 2.78125
| 3
|
import { CSSProperties, useMemo } from 'react';
import { Gutter, SpaceRect } from '../types';
interface CoordinateSpaceParams {
width: number;
height: number;
margin?: Gutter;
gutter?: Gutter;
}
export interface CoordinateSpaceComponent {
margin?: Gutter;
gutter?: Gutter;
}
export function useCoordinateSpace({
width,
height,
margin = { top: 0, bottom: 0, left: 0, right: 0 },
gutter = { top: 0, bottom: 0, left: 0, right: 0 },
}: CoordinateSpaceParams): {
coordinateSpace: SpaceRect;
canvasStyle: CSSProperties;
} {
const coordinateSpace = useMemo(() => {
const w = width + margin.left + margin.right;
const h = height + margin.top + margin.bottom;
return {
x: gutter.left,
y: gutter.top,
width: w - gutter.left - gutter.right,
height: h - gutter.top - gutter.bottom,
top: gutter.top,
left: gutter.left,
right: w - gutter.right,
bottom: h - gutter.bottom,
};
}, [
gutter.bottom,
gutter.left,
gutter.right,
gutter.top,
height,
margin.bottom,
margin.left,
margin.right,
margin.top,
width,
]);
const canvasStyle = useMemo<CSSProperties>(() => {
return {
width: width + margin.left + margin.right,
height: height + margin.top + margin.bottom,
marginTop: -margin.top,
marginLeft: -margin.left,
};
}, [height, margin.bottom, margin.left, margin.right, margin.top, width]);
return { coordinateSpace, canvasStyle };
}
|
4b07c670ba3458eb9f16bc55a01c41a870183063
|
TypeScript
|
pinojs/pino
|
/test/transport/core.test.ts
| 2.609375
| 3
|
import * as os from 'os'
import { join } from 'path'
import { once } from 'events'
import fs from 'fs'
import { watchFileCreated } from '../helper'
import { test } from 'tap'
import pino from '../../'
import * as url from 'url'
import { default as strip } from 'strip-ansi'
import execa from 'execa'
import writer from 'flush-write-stream'
if (process.platform === 'win32') {
// TODO: Implement .ts files loading support for Windows
process.exit()
}
const readFile = fs.promises.readFile
const { pid } = process
const hostname = os.hostname()
test('pino.transport with file', async ({ same, teardown }) => {
const destination = join(
os.tmpdir(),
'_' + Math.random().toString(36).substr(2, 9)
)
const transport = pino.transport({
target: join(__dirname, '..', 'fixtures', 'ts', 'to-file-transport.ts'),
options: { destination }
})
teardown(transport.end.bind(transport))
const instance = pino(transport)
instance.info('hello')
await watchFileCreated(destination)
const result = JSON.parse(await readFile(destination, { encoding: 'utf8' }))
delete result.time
same(result, {
pid,
hostname,
level: 30,
msg: 'hello'
})
})
test('pino.transport with file (no options + error handling)', async ({ equal }) => {
const transport = pino.transport({
target: join(__dirname, '..', 'fixtures', 'ts', 'to-file-transport.ts')
})
const [err] = await once(transport, 'error')
equal(err.message, 'kaboom')
})
test('pino.transport with file URL', async ({ same, teardown }) => {
const destination = join(
os.tmpdir(),
'_' + Math.random().toString(36).substr(2, 9)
)
const transport = pino.transport({
target: url.pathToFileURL(join(__dirname, '..', 'fixtures', 'ts', 'to-file-transport.ts')).href,
options: { destination }
})
teardown(transport.end.bind(transport))
const instance = pino(transport)
instance.info('hello')
await watchFileCreated(destination)
const result = JSON.parse(await readFile(destination, { encoding: 'utf8' }))
delete result.time
same(result, {
pid,
hostname,
level: 30,
msg: 'hello'
})
})
test('pino.transport with two files', async ({ same, teardown }) => {
const dest1 = join(
os.tmpdir(),
'_' + Math.random().toString(36).substr(2, 9)
)
const dest2 = join(
os.tmpdir(),
'_' + Math.random().toString(36).substr(2, 9)
)
const transport = pino.transport({
targets: [{
level: 'info',
target: join(__dirname, '..', 'fixtures', 'ts', 'to-file-transport.ts'),
options: { destination: dest1 }
}, {
level: 'info',
target: join(__dirname, '..', 'fixtures', 'ts', 'to-file-transport.ts'),
options: { destination: dest2 }
}]
})
teardown(transport.end.bind(transport))
const instance = pino(transport)
instance.info('hello')
await Promise.all([watchFileCreated(dest1), watchFileCreated(dest2)])
const result1 = JSON.parse(await readFile(dest1, { encoding: 'utf8' }))
delete result1.time
same(result1, {
pid,
hostname,
level: 30,
msg: 'hello'
})
const result2 = JSON.parse(await readFile(dest2, { encoding: 'utf8' }))
delete result2.time
same(result2, {
pid,
hostname,
level: 30,
msg: 'hello'
})
})
test('no transport.end()', async ({ same, teardown }) => {
const destination = join(
os.tmpdir(),
'_' + Math.random().toString(36).substr(2, 9)
)
const transport = pino.transport({
target: join(__dirname, '..', 'fixtures', 'ts', 'to-file-transport.ts'),
options: { destination }
})
const instance = pino(transport)
instance.info('hello')
await watchFileCreated(destination)
const result = JSON.parse(await readFile(destination, { encoding: 'utf8' }))
delete result.time
same(result, {
pid,
hostname,
level: 30,
msg: 'hello'
})
})
test('autoEnd = false', async ({ equal, same, teardown }) => {
const destination = join(
os.tmpdir(),
'_' + Math.random().toString(36).substr(2, 9)
)
const count = process.listenerCount('exit')
const transport = pino.transport({
target: join(__dirname, '..', 'fixtures', 'ts', 'to-file-transport.ts'),
options: { destination },
worker: { autoEnd: false }
})
teardown(transport.end.bind(transport))
await once(transport, 'ready')
const instance = pino(transport)
instance.info('hello')
await watchFileCreated(destination)
equal(count, process.listenerCount('exit'))
const result = JSON.parse(await readFile(destination, { encoding: 'utf8' }))
delete result.time
same(result, {
pid,
hostname,
level: 30,
msg: 'hello'
})
})
test('stdout in worker', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], ['-r', 'ts-node/register', join(__dirname, '..', 'fixtures', 'ts', 'transport-main.ts')])
child.stdout?.pipe(writer((s, enc, cb) => {
actual += s
cb()
}))
await once(child, 'close')
not(strip(actual).match(/Hello/), null)
})
test('log and exit on ready', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], ['-r', 'ts-node/register', join(__dirname, '..', 'fixtures', 'ts', 'transport-exit-on-ready.ts')])
child.stdout?.pipe(writer((s, enc, cb) => {
actual += s
cb()
}))
await once(child, 'close')
not(strip(actual).match(/Hello/), null)
})
test('log and exit before ready', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], ['-r', 'ts-node/register', join(__dirname, '..', 'fixtures', 'ts', 'transport-exit-immediately.ts')])
child.stdout?.pipe(writer((s, enc, cb) => {
actual += s
cb()
}))
await once(child, 'close')
not(strip(actual).match(/Hello/), null)
})
test('log and exit before ready with async dest', async ({ not }) => {
const destination = join(
os.tmpdir(),
'_' + Math.random().toString(36).substr(2, 9)
)
const child = execa(process.argv[0], ['-r', 'ts-node/register', join(__dirname, '..', 'fixtures', 'ts', 'transport-exit-immediately-with-async-dest.ts'), destination])
await once(child, 'exit')
const actual = await readFile(destination, { encoding: 'utf8' })
not(strip(actual).match(/HELLO/), null)
not(strip(actual).match(/WORLD/), null)
})
test('string integer destination', async ({ not }) => {
let actual = ''
const child = execa(process.argv[0], ['-r', 'ts-node/register', join(__dirname, '..', 'fixtures', 'ts', 'transport-string-stdout.ts')])
child.stdout?.pipe(writer((s, enc, cb) => {
actual += s
cb()
}))
await once(child, 'close')
not(strip(actual).match(/Hello/), null)
})
|
0a5eadf2d43e8d53808bf338abaad406b4ff5d68
|
TypeScript
|
skoldborg/foundation-lib-spa-core
|
/dist/Components/LazyComponent.d.ts
| 2.625
| 3
|
import React from 'react';
import { SpinnerProps } from './Spinner';
export declare type LazyComponentProps<T = any> = {
/**
* The name of the component to load, this is the component path after
* app/Components/ e.g. a value of CheckoutPage will load the default export
* of app/Components/CheckoutPage as ReactElement;
*
* @type string
*/
component: string;
/**
* If this property is set on the LazyComponent it will not show a spinner while
* the referenced component is loading.
*
* @type boolean
*/
noSpinner?: boolean;
} & SpinnerProps & T;
export declare const LazyComponent: React.FunctionComponent<LazyComponentProps>;
export default LazyComponent;
|
2ec4edd33ebe0674a016346d23f569cdee1baaef
|
TypeScript
|
rkumar0099/CSCI3100_project
|
/server/routes/index.ts
| 2.828125
| 3
|
import express from 'express'
// super class of all routes
export abstract class Routes {
router: express.Router
name: string // name of the group of routes
constructor(router: express.Router, name: string) {
this.router = router
this.name = name
this.configureRoutes()
}
/**
* return name of this route
*
*/
getName(): string {
return this.name
}
abstract configureRoutes(): void
}
|
5f23ce113b93faf1d143a4a29d2c16c26b6d73ae
|
TypeScript
|
Ompluscator/ompluscript
|
/src/typescript/Model/Attribute/Attribute.ts
| 3.5625
| 4
|
/// <reference path="../../Core/Observer/Observable.ts" />
/// <reference path="../../Core/Interfaces/ICloneable.ts" />
/// <reference path="../Event/OnUpdateAttribute.ts" />
/// <reference path="../Event/OnInvalidAttribute.ts" />
/**
* Module that contains attributes' classes.
*
* @module Ompluscript.Model.Attribute
*/
module Ompluscript.Model.Attribute {
"use strict";
import Observable = Ompluscript.Core.Observer.Observable;
import OnUpdateAttribute = Ompluscript.Model.Event.OnUpdateAttribute;
import OnInvalidAttribute = Ompluscript.Model.Event.OnInvalidAttribute;
import ICloneable = Ompluscript.Core.Interfaces.ICloneable;
import IBase = Ompluscript.Core.Interfaces.IBase;
/**
* Class that contains functionality for single attribute.
*
* @class Attribute<T>
*/
export abstract class Attribute<T> extends Observable implements ICloneable {
/**
* @type {number} ERROR_WRONG_TYPE Error code for setting a wrong type of value.
*/
public static ERROR_WRONG_TYPE: number = 101;
/**
* @type {number} ERROR_IS_REQUIRED Error code for not entering required value.
*/
public static ERROR_IS_REQUIRED: number = 102;
/**
* @type {number} ERROR_BELOW_MINIMUM Error code for invalid minimum value.
*/
public static ERROR_BELOW_MINIMUM: number = 201;
/**
* @type {number} ERROR_OVER_MAXIMUM Error code for invalid maximum value.
*/
public static ERROR_OVER_MAXIMUM: number = 202;
/**
* @type {string} PARAMETER_REQUIRED Required parameter name.
*/
public static PARAMETER_REQUIRED: string = "required";
/**
* @type {string} PARAMETER_VALUE Value parameter name.
*/
public static PARAMETER_VALUE: string = "value";
/**
* @type {string} PARAMETER_MINIMUM Minimum parameter name.
*/
public static PARAMETER_MINIMUM: string = "minimum";
/**
* @type {string} PARAMETER_MAXIMUM Maximum parameter name.
*/
public static PARAMETER_MAXIMUM: string = "maximum";
/**
* @type {string} type Value's type
*/
protected type: string;
/**
* @type {string} name Value's name
*/
protected name: string;
/**
* @type {any} value Value that should be stored
*/
protected value: T;
/**
* @type {number} error Error code when value is invalid
*/
protected error: number;
/**
* @type {boolean} required Defines if value is required
*/
protected required: boolean;
/**
* Class constructor.
*
* Sets type of value, value itself and defines if it's required.
*
* @param {string} type Value's type
* @param {string} name Name of attribute
* @param {any} value Value that should be stored
* @param {boolean} required Defines if value is required
* @constructs
*/
constructor(type: string, name: string, value: T = undefined, required: boolean = false) {
super();
this.type = type;
this.name = name;
this.value = value;
this.required = required;
}
/**
* Method that sets value of attribute
*
* @param {any} value Attribute's value
*/
public setValue(value: T): void {
let oldValue: T = this.value;
this.value = value;
this.fireOnUpdateAttributeEvent(oldValue, this.value);
if (!this.validate()) {
this.fireOnInvalidAttributeEvent(this.value, this.error);
}
}
/**
* Method that returns value of attribute
*
* @returns {any} Attribute's value
*/
public getValue(): T {
return this.value;
}
/**
* Method that clears value from attribute
*/
public resetValue(): void {
this.setValue(undefined);
}
/**
* Method that explains if value is required or not
*
* @returns {boolean} defines if value is required
*/
public isRequired(): boolean {
return this.required;
}
/**
* Method that returns name of attribute
*
* @returns {string} Attribute's name
*/
public getName(): string {
return this.name;
}
/**
* Method that returns error code
*
* @returns {number|undefined} Error code
*/
public getError(): number {
return this.error;
}
/**
* Method that validates attribute's value.
*
* @returns {boolean} Validation result
*/
public validate(): boolean {
this.error = undefined;
if (typeof this.value !== this.type && this.value !== undefined) {
this.error = Attribute.ERROR_WRONG_TYPE;
return false;
} else if (this.required === true && typeof this.value !== this.type) {
this.error = Attribute.ERROR_IS_REQUIRED;
return false;
}
return true;
}
/**
* Method that returns all current attributes of object.
*
* @returns {Object} contains all attributes of the object
*/
public getStackTrace(): Object {
let trace: Object = {
name: this.name,
required: this.required,
type: this.type,
value: this.value,
};
return trace;
}
public fireEventIfInvalid(): void {
if (this.validate() === false) {
this.fireOnInvalidAttributeEvent(this.value, this.error);
}
}
/**
* Method that should be called when class object should be cloned.
*/
public abstract clone(): IBase;
/**
* Method that fires event when attribute is updated
*
* @param {any} oldValue Old value of attribute
* @param {any} newValue New value of attribute
*/
protected fireOnUpdateAttributeEvent(oldValue: T, newValue: T): void {
let event: OnUpdateAttribute = new OnUpdateAttribute(this, oldValue, newValue);
this.notifyObservers(event);
}
/**
* Method that fires event when attribute is invalid
*
* @param {any} value New value of attribute
* @param {number} validationCode Error validation code
*/
protected fireOnInvalidAttributeEvent(value: T, validationCode: number): void {
let event: OnInvalidAttribute = new OnInvalidAttribute(this, value, validationCode);
this.notifyObservers(event);
}
}
}
|
9ec46075717dc719af24985a1fd876e5ed824a52
|
TypeScript
|
bhagyashreeWalanj/TypescriptWithGit
|
/day1/function.ts
| 3.96875
| 4
|
// with typed parameters
function sum(num1: number, num2: number): number{
return num1+num2;
}
let value= sum(5,3);
console.log("result-------->"+value);
//-----------------------------------------------------
// return string
function sum1(num1, num2): string{
return num1+num2;
}
let value1= sum1('5',3);
console.log("result1-------->"+value1);
//-----------------------------------------------------
// 'any' type of parameters
function sum2(num1, num2){
return num1+num2;
}
let value2= sum2(5,3);
console.log("result2-------->"+value2);
|
68398a7417b4b94e9e60512c231aaac35a1e69c3
|
TypeScript
|
RobertoMalatesta/bitflow
|
/packages/core/src/lerpColor.ts
| 3
| 3
|
export function lerpColor(a: string, b: string, amount: number): string {
let ah = +a.replace("#", "0x"),
ar = ah >> 16,
ag = (ah >> 8) & 0xff,
ab = ah & 0xff,
bh = +b.replace("#", "0x"),
br = bh >> 16,
bg = (bh >> 8) & 0xff,
bb = bh & 0xff,
rr = ar + amount * (br - ar),
rg = ag + amount * (bg - ag),
rb = ab + amount * (bb - ab);
return (
"#" + (((1 << 24) + (rr << 16) + (rg << 8) + rb) | 0).toString(16).slice(1)
);
}
|
9264d23ec8c32f62446e1de99c12a06d8449a411
|
TypeScript
|
dfmurillo/symmetrical-octo-barnacle-api
|
/src/quizzes/quizzes.controller.ts
| 2.546875
| 3
|
import { Request, Response } from "express";
import QuizzesService from "./quizzes.service";
import { IAnsweredSchema } from "./quizzes.schema.answered";
import { ValidatedRequest } from "express-joi-validation";
class QuizzesController {
private static instance: QuizzesController;
static getInstance(): QuizzesController {
if (!QuizzesController.instance) {
QuizzesController.instance = new QuizzesController();
}
return QuizzesController.instance;
}
listQuizzes(request: Request, response: Response) {
try {
const quizzes = QuizzesService.getAllQuizzes();
response.statusCode = 200;
response.json({ quizzes });
} catch(error) {
response.statusCode = 404;
response.json({error: error.message});
}
}
getQuizById(request: Request, response: Response) {
try {
const quiz = QuizzesService.getQuizById(parseInt(request.params.quizId, 10));
response.statusCode = 200;
response.json({ quiz });
} catch(error) {
response.statusCode = 404;
response.json({ error: error.message });
}
}
validateQuiz(request: ValidatedRequest<IAnsweredSchema>, response: Response) {
try {
const { quizId, questions } = request.body;
const quizResult = QuizzesService.validateQuizAnswers(quizId, questions);
response.statusCode = 200;
response.json({ quizResult });
} catch (error) {
response.statusCode = 500;
response.json({ error: error.message });
}
}
}
export default QuizzesController.getInstance();
|
1ff95814558c7173b732a121af95be2bbbc62b28
|
TypeScript
|
cartant/rxjs-tslint-rules
|
/source/rules/rxjsNoIgnoredObservableRule.ts
| 2.515625
| 3
|
/**
* @license Use of this source code is governed by an MIT-style license that
* can be found in the LICENSE file at https://github.com/cartant/rxjs-tslint-rules
*/
import { tsquery } from "@phenomnomnominal/tsquery";
import * as Lint from "tslint";
import * as ts from "typescript";
import * as peer from "../support/peer";
import { couldBeType } from "../support/util";
export class Rule extends Lint.Rules.TypedRule {
public static metadata: Lint.IRuleMetadata = {
deprecationMessage: peer.v5 ? peer.v5NotSupportedMessage : undefined,
description: "Disallows the ignoring of observables returned by functions.",
options: null,
optionsDescription: "Not configurable.",
requiresTypeInfo: true,
ruleName: "rxjs-no-ignored-observable",
type: "functionality",
typescriptOnly: true,
};
public static FAILURE_STRING = "Ignoring a returned Observable is forbidden";
public applyWithProgram(
sourceFile: ts.SourceFile,
program: ts.Program
): Lint.RuleFailure[] {
const failures: Lint.RuleFailure[] = [];
const typeChecker = program.getTypeChecker();
const callExpressions = tsquery(
sourceFile,
`ExpressionStatement > CallExpression`
);
callExpressions.forEach((callExpression) => {
const type = typeChecker.getTypeAtLocation(callExpression);
if (couldBeType(type, "Observable")) {
failures.push(
new Lint.RuleFailure(
sourceFile,
callExpression.getStart(),
callExpression.getStart() + callExpression.getWidth(),
Rule.FAILURE_STRING,
this.ruleName
)
);
}
});
return failures;
}
}
|
4bcec952c17797087c02f49bfbd49cede7fd87cb
|
TypeScript
|
Krlozz/Deber-6-Middleware
|
/project/src/usuario.controller.ts
| 2.546875
| 3
|
import {Controller, Get, Req, Res} from "@nestjs/common";
@Controller('usuario')
export class UsuarioController {
@Get('logueo')
usuarioLogueoCookie(@Res() res,
@Req() req) {
const parametros = {
nombre: "Tu cookie",
valor: "Tu cache"
};
//console.log(req.cookies)
res.cookie(parametros.nombre, parametros.valor);
return res.send({mensaje: 'Tu cookie esta en cache'});
}
}
|
8453ff739fd87ba29eb66bffb381d28b045b8bdc
|
TypeScript
|
Andrewalr/node-lint-config
|
/test/base/good.ts
| 3.25
| 3
|
// tslint:disable:no-unused-expression
declare var require: any;
import 'tslint';
import 'tslint-config-airbnb';
require('tslint');
const variable = '';
const singleConcat = 'a' + 'b';
const array: number[] = [1];
if (true) {
/**/
}
class MyClass {
public static defaultName: string;
protected static defaultAge: string;
private static defaultSalary: number;
public static doSomethingStatic1() {
/**/
}
protected static doSomethingStatic2() {
/**/
}
private static doSomethingStatic3() {
/**/
}
public name: string;
protected age: string;
private salary: number;
private _hidden: number;
constructor() {
/**/
}
// No order for the functions visibility...
protected doSomething2() {
/**/
}
public doSomething1() {
/**/
}
private doSomething3() {
/**/
}
}
interface IMyInterface {
name: string;
}
|
25cd28f7599ebc9309501edc798a0f13023a13b1
|
TypeScript
|
YouSafe/tgi-pages
|
/src/assets/decompiler.ts
| 3.09375
| 3
|
export interface ParsedInstruction {
aMux: boolean;
mbr: boolean;
mar: boolean;
rdWr: boolean;
ms: boolean;
enS: boolean;
cond: number;
alu: number;
sh: number;
sBus: number;
bBus: number;
aBus: number;
adr: number;
}
export function parse(binaryCode: string): ParsedInstruction {
let getRange = (start: number, length: number): string => {
let string = "";
for (let i = 0; i < length; i++) {
string += binaryCode[i + start];
}
return string;
};
let convertBinaryToDecimal = (binary: string): number => {
let sum = 0;
for (let i = 0; i < binary.length; i++) {
sum += Math.pow(2, binary.length - 1 - i) * parseInt(binary[i]);
}
return sum;
};
let convertBitToBool = (bit: string): boolean => {
return "1" === bit;
};
let aMux = convertBitToBool(getRange(0, 1));
let cond = convertBinaryToDecimal(getRange(1, 2));
let alu = convertBinaryToDecimal(getRange(3, 2));
let sh = convertBinaryToDecimal(getRange(5, 2));
let mbr = convertBitToBool(getRange(7, 1));
let mar = convertBitToBool(getRange(8, 1));
let rdWr = convertBitToBool(getRange(9, 1));
let ms = convertBitToBool(getRange(10, 1));
let enS = convertBitToBool(getRange(11, 1));
let sBus = convertBinaryToDecimal(getRange(12, 4));
let bBus = convertBinaryToDecimal(getRange(16, 4));
let aBus = convertBinaryToDecimal(getRange(20, 4));
let adr = convertBinaryToDecimal(getRange(24, 8));
return {
aMux,
cond,
alu,
sh,
mbr,
mar,
rdWr,
ms,
enS,
sBus,
bBus,
aBus,
adr,
};
}
export function getRegistry(address: number): string {
switch (address) {
case 0:
return "0";
case 1:
return "1";
case 2:
return "-1";
case 3:
return "PC";
case 15:
return "AC";
default:
return "R" + (address - 4);
}
}
export function calc(a: string, b: string, inst: ParsedInstruction) {
let s = "";
switch (inst.alu) {
case 0:
s = a;
break;
case 1:
s = a + " + " + b;
break;
case 2:
s = a + " & " + b;
break;
case 3:
s = "~" + a;
break;
}
switch (inst.sh) {
case 1:
s = "lsh(" + s + ")";
break;
case 2:
s = "rsh(" + s + ")";
break;
}
return s;
}
export interface Check {
correct: boolean;
message: string;
}
export function checkInput(input: string, inst: ParsedInstruction): Check {
let check = { correct: true, message: "" };
if (input.length != 32) {
check.correct = false;
check.message += `instruction should be 32 bit long, currently it is ${input.length}; `;
}
for (let c of input) {
if (c != "0" && c != "1") {
check.correct = false;
check.message += 'instruction should only contain "0" and "1" as characters; ';
break;
}
}
if (inst.sh == 3) {
check.correct = false;
check.message += "shift cannot be 11; ";
}
return check;
}
export function interpret(binarycode: string): string {
let inst = parse(binarycode);
let checked = checkInput(binarycode, inst);
if (!checked.correct) {
return checked.message;
}
let decompiled = "";
let s = getRegistry(inst.sBus);
let a = inst.aMux ? "MBR" : getRegistry(inst.aBus);
let b = getRegistry(inst.bBus);
let rightSide = calc(a, b, inst);
if (inst.enS) {
decompiled += "" + getRegistry(inst.sBus) + " <- " + rightSide + "; ";
}
if (inst.mbr) {
decompiled += "MBR <- " + rightSide + "; ";
}
if (inst.mar) {
decompiled += "MAR <- " + b + "; ";
}
if (inst.ms) {
decompiled += inst.rdWr ? "rd; " : "wr; ";
}
if (!inst.enS && !inst.mbr && !inst.mar && !inst.ms) {
decompiled += rightSide + "; ";
}
switch (inst.cond) {
case 1:
decompiled += "if N goto " + inst.adr;
break;
case 2:
decompiled += "if Z goto " + inst.adr;
break;
case 3:
decompiled += "goto " + inst.adr;
}
return decompiled;
}
|
0033b1943bee56b51371fde9ee21c014b6b6b9c2
|
TypeScript
|
jingu76/iot
|
/poc_iot_client/public/app/shared/utils/string/string-utils.ts
| 2.640625
| 3
|
export class StringUtils {
static format(str: string, params: any[]) {
return params.reduce((result, param, i) => result.replace(new RegExp(`\\{${i}\\}`, 'gi'), param), str);
}
}
|
b5fc1ad47001489cd8acd16d5973bebf3d18563b
|
TypeScript
|
V4Fire/Core
|
/src/core/kv-storage/engines/string/spec.ts
| 3.03125
| 3
|
/*!
* V4Fire Core
* https://github.com/V4Fire/Core
*
* Released under the MIT license
* https://github.com/V4Fire/Core/blob/master/LICENSE
*/
import * as kv from 'core/kv-storage';
import StringEngine from 'core/kv-storage/engines/string';
import { defaultDataSeparators as separators } from 'core/kv-storage/engines/string/const';
describe('kv-storage/engines/string', () => {
let
storage: kv.SyncStorage,
engine: StringEngine;
beforeEach(() => {
engine = new StringEngine();
storage = kv.factory(engine);
});
it('the storage can be initialized with data', () => {
const
initialData = `foo${separators.record}true${separators.chunk}bar${separators.record}baz`;
const
engine = new StringEngine({data: initialData}),
storage = kv.factory(engine);
expect(engine.serializedData).toBe(initialData);
expect(storage.get('foo')).toBe(true);
expect(storage.get('bar')).toBe('baz');
});
it('removing a value should delete it from the string', () => {
storage.set('foo', true);
storage.set('bar', 1);
expect(engine.serializedData).toBe(`foo${separators.record}true${separators.chunk}bar${separators.record}1`);
storage.remove('bar');
expect(engine.serializedData).toBe(`foo${separators.record}true`);
expect(storage.get('bar')).toBe(undefined);
});
it('getting all keys stored in the storage', () => {
engine.set('a', '1');
engine.set('b', '2');
engine.set('c', '3');
expect(engine.keys()).toEqual(['a', 'b', 'c']);
});
it('adding a new value should save it to the string', () => {
storage.set('foo', 'some value');
expect(engine.serializedData).toBe(`foo${separators.record}"some value"`);
expect(storage.get('foo')).toBe('some value');
storage.set('bar', [1, 2, 3]);
expect(engine.serializedData).toBe(`foo${separators.record}"some value"${separators.chunk}bar${separators.record}[1,2,3]`);
expect(storage.get('bar')).toEqual([1, 2, 3]);
});
it('clearing the storage should clear the string', () => {
storage.set('foo', true);
storage.set('bar', 1);
storage.clear();
expect(engine.serializedData).toBe('');
});
it(
'clearing the storage with passing a function should only clear those values for which the filter returned true',
() => {
storage.set('foo', true);
storage.set('bar', 1);
storage.set('baz', 2);
storage.clear((el) => Object.isNumber(el));
expect(engine.serializedData).toBe(`foo${separators.record}true`);
storage.clear((el, key) => key === 'foo');
expect(engine.serializedData).toBe('');
}
);
it('using non-standard separators', () => {
const
engine = new StringEngine({separators: {record: '=', chunk: ';'}}),
storage = kv.factory(engine);
storage.set('foo', 1);
storage.set('bar', true);
expect(engine.serializedData).toBe('foo=1;bar=true');
});
});
|
193dfbb776694fa14576e3fd6bcff356c42ba2b4
|
TypeScript
|
Sambl4/123
|
/src/app/core/+store/list/list.reducer.ts
| 2.78125
| 3
|
import { ListActions, ListActionTypes } from './list.actions';
import { ListState, initialListState } from './list.state';
import { ListItem } from '../../../model/list-item.model';
export function listReducer(state = initialListState, action: ListActions): ListState {
console.log('reducer', action.type);
switch (action.type) {
case ListActionTypes.GET_LIST: {
return {
...state,
loading: true
};
}
case ListActionTypes.GET_LIST_SUCCESS: {
const data = action.payload['items'];
const totalPages = action.payload['totalPages'];
return {
...state,
data: data,
totalPages: totalPages,
loading: false,
loaded: true
};
}
case ListActionTypes.GET_LIST_ITEM: {
return {
...state
};
}
case ListActionTypes.CREATE_LIST_ITEM: {
return {
...state
};
}
case ListActionTypes.UPDATE_LIST_ITEM: {
return {
...state
};
}
case ListActionTypes.EDIT_LIST_ITEM: {
const id = (<ListItem>action.payload).id;
const data = state.data.map(item => {
if (item.id === id) {
return { ...action.payload, editMode: true };
}
return item;
});
return {
...state,
data
};
}
case ListActionTypes.CANCEL_EDIT_LIST_ITEM: {
const id = (<ListItem>action.payload).id;
const data = state.data.map(item => {
if (item.id === id) {
return { ...action.payload, editMode: false};
}
return item;
});
return {
...state,
data
};
}
case ListActionTypes.RESULT_FAILURE: {
const error = action.payload;
return {
...state,
loading: false,
loaded: false,
error
};
}
default: {
return state;
}
}
}
|
fd66d988c864ca8991a090e5d69ba3dfc94f8ea7
|
TypeScript
|
loop-revolution/display-api-js
|
/src/components/blocklist.ts
| 2.671875
| 3
|
export type BlockList = {
cid: "blocklist"
args: BlocklistArgs
}
export type BlocklistArgs = {
/** Initial list of ids. Breadcrumbs need to be queried from front-end */
initial_value?: number[]
/**
* The name of the arg to return, should replace instances of this (like input)
* but the value should be an array of block ids.
*/
name?: string
/** Should the user be able to add other blocks to the list? Default true */
able_to_add_items?: boolean
}
|
a86be51ca55a697f2b896fff73de6b9260b24652
|
TypeScript
|
dgzlg/ligang123
|
/src/modules/common/MapViewer/TileLayerWMTS.ts
| 2.734375
| 3
|
import {TileLayer, TileLayerOptions, Point, Util} from 'leaflet';
export enum ValuesType {
KVP = 'KVP',
REST = 'REST',
RESTFUL = 'RESTFUL',
}
interface Dimension{
key: string;
default: string;
values?: string[];
}
export interface WMTSOptions extends TileLayerOptions {
valuesType?: ValuesType;
uppercase?: boolean;
layer: string;
tileMatrixSet: string;
tileMatrixIds?: string[];
format: string;
style: string;
dimensions: Dimension[];
}
interface WMTSParams {
SERVICE: string,
REQUEST: string,
VERSION: string,
LAYER: string,
TILEMATRIXSET: string,
STYLE: string,
FORMAT: string,
}
export class TileLayerWMTS extends TileLayer {
// property from TileLayer
_globalTileRange: any;
// property from TileLayer
_url: string;
options: WMTSOptions;
params: WMTSParams;
constructor(url: string, options: WMTSOptions) {
super(url, options);
this.params = {
SERVICE: 'WMTS',
REQUEST: 'GetTile',
VERSION: '1.0.0',
LAYER: options.layer,
TILEMATRIXSET: options.tileMatrixSet,
STYLE: options.style,
FORMAT: options.format,
};
}
// override TileLayer's method 'getTileUrl'
getTileUrl(coords: Point) {
const {tileMatrixIds, dimensions} = this.options;
const data: any = {
...this.params,
TILECOL: coords.x,
TILEROW: coords.y,
};
if (this._map && this._map.options.crs.infinite) {
let revertedY = this._globalTileRange.max.y - coords.y;
if (this.options.tms) {
data.TileRow = revertedY;
}
}
// TileMatrix
if (tileMatrixIds) {
data.TILEMATRIX = tileMatrixIds[this._getZoomForUrl()];
} else {
data.TILEMATRIX = this._getZoomForUrl();
}
// Dimension
if (dimensions.length > 0)
{
for (let i = 0, l = dimensions.length; i < l; i++) {
const {key, default: dft, values} = dimensions[i];
if (values.length > 0)
{
data[key.toLocaleUpperCase()] = values[0];
continue;
}
data[key.toLocaleUpperCase()] = dft;
}
}
// KVP url
if (this.options.valuesType === ValuesType.KVP) {
return `${this._url}${Util.getParamString(data, this._url, this.options.uppercase)}`;
}
// default REST url
return Util.template(this._url, data);
}
}
export function tileLayerWMTS(url: string, options: WMTSOptions): TileLayerWMTS {
return new TileLayerWMTS(url, options);
}
|
b8a3db4dc2eac0aa437fa37c2d7ab1b0e1274277
|
TypeScript
|
Yaduo/MaterialUI_Typescript
|
/src/store/environment/actions.ts
| 2.859375
| 3
|
import { Dispatch } from 'react-redux';
export const ACTION = {
INIT_ENVIRONMENT: "INIT_ENVIRONMENT",
CHANGE_IS_MOBILE: "CHANGE_IS_MOBILE",
CHANGE_WIDTH_AND_HEIGHT: "CHANGE_WIDTH_AND_HEIGHT",
CHANGE_LANGUAGE: "CHANGE_LANGUAGE",
UPDATE_LANGUAGE: "UPDATE_LANGUAGE",
}
export const initEnvironment = (): any => ({
type: ACTION.INIT_ENVIRONMENT
})
export const checkIsMobile = (): any => {
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
return {
type: ACTION.CHANGE_IS_MOBILE,
payload: { isMobile }
}
}
export const changeWidthAndHeight = (): any => ({
type: ACTION.CHANGE_WIDTH_AND_HEIGHT,
payload: { height: window.innerHeight, width: window.innerWidth }
})
export const changeLanguage = (langCode?: string): any => {
let userLanguage: string;
if(langCode != null)
{
userLanguage = langCode
} else {
userLanguage = navigator.language != null ? navigator.language : 'en';
}
return {
type: ACTION.CHANGE_LANGUAGE,
payload: { userLanguage }
};
}
|
2d6e9eda8d1f804223710c971f7da2405012dd12
|
TypeScript
|
pmuellr/catbo
|
/docs/scripts/model/types.ts
| 3
| 3
|
export interface CreateBoardParams {
boards: number; // number of 4x6 boards to use; 1, 2, or 4 currently
}
export interface IBoard {
squares: ILocation[][];
}
export interface CreateLocationParams {
x: number;
y: number;
isPort: boolean;
islandNumber?: number | null | undefined;
}
export interface ILocation {
x: number;
y: number;
isPort: boolean;
isIsland: boolean;
hasShip: boolean;
islandNumber: number;
ship: IShip;
setShip(ship: IShip): void;
removeShip(): void;
clonedWithLocation (x: number, y: number): ILocation;
}
export interface IShip {
color: string;
location: ILocation;
treasure: Record<string, number>;
moveTo (location: ILocation): void;
}
|
21dfc546e7ffe4bcdd8b0d9bcfb23c194faefe5b
|
TypeScript
|
caderek/aoc2019
|
/src/day03/index.ts
| 2.84375
| 3
|
import { test, readInput } from "../utils"
import { pipe } from "@arrows/composition"
type Wire = { dir: "R" | "L" | "U" | "D"; dis: number }[]
type Wires = [Wire, Wire]
type XYSteps = [number, number, number]
type Paths = [XYSteps[], XYSteps[]]
type XYStepsAStepsB = [string, number, number]
type Intersections = XYStepsAStepsB[]
const prepareInput = (rawInput: string) =>
rawInput.split("\n").map((x) =>
x.split(",").map((item) => ({
dir: item.slice(0, 1),
dis: Number(item.slice(1)),
})),
)
const input = prepareInput(readInput())
const getPaths = (input: Wires) => {
return input.map((wire) => {
let steps = 0
let x = 0
let y = 0
let path = []
for (const { dir, dis } of wire) {
path = path.concat(
Array.from({ length: dis }, () => [
`${dir === "R" ? ++x : dir === "L" ? --x : x},${
dir === "U" ? ++y : dir === "D" ? --y : y
}`,
++steps,
]),
)
}
return path
})
}
const findIntersections = (paths: Paths) => {
const [a, b] = paths
const bCords = new Map(b.map((x) => [x[0], x[1]]))
const intersections = []
for (const x of a) {
const ySteps = bCords.get(x[0])
if (ySteps !== undefined) {
intersections.push([x[0], x[1], ySteps])
}
}
return intersections
}
const findNearestCross = (intersections: Intersections) => {
return Math.min(
...intersections.map((item) => {
const [x, y] = item[0].split(",").map(Number)
return Math.abs(x) + Math.abs(y)
}),
)
}
const goA = (intersections: Intersections) => {
return findNearestCross(intersections)
}
const goB = (intersections: Intersections) => {
return Math.min(...intersections.map((x) => x[1] + x[2]))
}
/* Tests */
pipe.now(
"R75,D30,R83,U83,L12,D49,R71,U7,L72\nU62,R66,U55,R34,D71,R55,D58,R83",
prepareInput,
getPaths,
findIntersections,
goA,
test(159),
)
pipe.now(
"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\nU98,R91,D20,R16,D67,R40,U7,R15,U6,R7",
prepareInput,
getPaths,
findIntersections,
goA,
test(135),
)
pipe.now(
"R75,D30,R83,U83,L12,D49,R71,U7,L72\nU62,R66,U55,R34,D71,R55,D58,R83",
prepareInput,
getPaths,
findIntersections,
goB,
test(610),
)
pipe.now(
"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\nU98,R91,D20,R16,D67,R40,U7,R15,U6,R7",
prepareInput,
getPaths,
findIntersections,
goB,
test(410),
)
/* Results */
console.time("Time")
const intersections = pipe.now(input, getPaths, findIntersections)
const resultA = goA(intersections)
const resultB = goB(intersections)
console.timeEnd("Time")
console.log("Solution to part 1:", resultA) // -> 258
console.log("Solution to part 2:", resultB) // -> 12304
|
c5997b63b5873fa8abeeae8ec4d854ac3e74cd2a
|
TypeScript
|
AssemblyScript/assemblyscript
|
/tests/parser/type-signature.ts.fixture.ts
| 2.78125
| 3
|
type foo = () => void;
type foo = (() => void) | null;
type foo = (() => void) | null;
type foo = Array<() => void>;
type foo = Array<() => void> | null;
type foo = Array<() => void> | null;
type foo = (a: i32) => i32;
type foo = (a?: i32) => i32;
type foo = (this: AClass, a: i32) => i32;
type foo = () => () => void;
type foo = () => (() => void) | null;
type foo = (this: AClass, a: i32) => ((this: BClass, b?: f32) => i32) | null;
|
bb9cf4dd3e1024405dbdf74690e9a5c411abdb7f
|
TypeScript
|
vmarc/knooppuntnet
|
/client/libs/planner/src/lib/domain/commands/planner-command-reset.spec.ts
| 2.671875
| 3
|
import { PlannerTestSetup } from '../context/planner-test-setup';
import { PlanFlag } from '../plan/plan-flag';
import { PlanUtil } from '../plan/plan-util';
import { PlannerCommandAddLeg } from './planner-command-add-leg';
import { PlannerCommandAddStartPoint } from './planner-command-add-start-point';
import { PlannerCommandReset } from './planner-command-reset';
describe('PlannerCommandReset', () => {
it('do and undo', () => {
const setup = new PlannerTestSetup();
const sourceFlag = PlanFlag.start('sourceFlag', [1, 1]);
const sinkFlag1 = PlanFlag.via('viaFlag', [2, 2]);
const sinkFlag2 = PlanFlag.end('endFlag', [3, 3]);
const leg12 = PlanUtil.singleRoutePlanLeg(
'12',
setup.node1,
setup.node2,
sinkFlag1,
null
);
const leg23 = PlanUtil.singleRoutePlanLeg(
'23',
setup.node2,
setup.node3,
sinkFlag2,
null
);
setup.context.execute(
new PlannerCommandAddStartPoint(setup.node1, sourceFlag)
);
setup.context.execute(new PlannerCommandAddLeg(leg12));
setup.context.execute(new PlannerCommandAddLeg(leg23));
setup.markerLayer.expectFlagCount(3);
setup.markerLayer.expectStartFlagExists('sourceFlag', [1, 1]);
setup.markerLayer.expectViaFlagExists('viaFlag', [2, 2]);
setup.markerLayer.expectEndFlagExists('endFlag', [3, 3]);
setup.routeLayer.expectRouteLegExists('12', leg12);
setup.routeLayer.expectRouteLegExists('23', leg23);
{
const legs = setup.context.plan.legs;
expect(legs.size).toEqual(2);
const leg1 = legs.get(0);
expect(leg1.featureId).toEqual('12');
expect(leg1.sinkFlag.featureId).toEqual('viaFlag');
expect(leg1.viaFlag).toEqual(null);
const leg2 = legs.get(1);
expect(leg2.featureId).toEqual('23');
expect(leg2.sinkFlag.featureId).toEqual('endFlag');
expect(leg2.viaFlag).toEqual(null);
}
const resetCommand = new PlannerCommandReset();
setup.context.execute(resetCommand);
expect(setup.context.plan.sourceNode).toEqual(null);
expect(setup.context.plan.sourceFlag).toEqual(null);
expect(setup.context.plan.legs.size).toEqual(0);
resetCommand.undo(setup.context);
setup.markerLayer.expectFlagCount(3);
setup.markerLayer.expectStartFlagExists('sourceFlag', [1, 1]);
setup.markerLayer.expectViaFlagExists('viaFlag', [2, 2]);
setup.markerLayer.expectEndFlagExists('endFlag', [3, 3]);
setup.routeLayer.expectRouteLegExists('12', leg12);
setup.routeLayer.expectRouteLegExists('23', leg23);
{
const legs = setup.context.plan.legs;
expect(legs.size).toEqual(2);
const leg1 = legs.get(0);
expect(leg1.featureId).toEqual('12');
expect(leg1.sinkFlag.featureId).toEqual('viaFlag');
expect(leg1.viaFlag).toEqual(null);
const leg2 = legs.get(1);
expect(leg2.featureId).toEqual('23');
expect(leg2.sinkFlag.featureId).toEqual('endFlag');
expect(leg2.viaFlag).toEqual(null);
}
});
});
|
673cea92fe5cbf79281adf14bd41098f3cd43c74
|
TypeScript
|
FormidableLabs/prism-react-renderer
|
/packages/demo/src/sample-code.ts
| 2.90625
| 3
|
export const sampleCode = {
["TypeScript with React"]: {
language: "tsx",
code: `
import React from 'react';
interface GroceryItemProps {
item: {
name: string;
price: number;
quantity: number;
}
}
const GroceryItem: React.FC<GroceryItemProps> = ({ item }) => {
return (
<div>
<h2>{item.name}</h2>
<p>Price: {item.price}</p>
<p>Quantity: {item.quantity}</p>
</div>
);
}
export default GroceryItem;
`,
},
["JavaScript"]: {
language: "javascript",
code: `
const GroceryItem = new Proxy({}, {
set(target, prop, value) {
if (prop === 'name' && typeof value !== 'string') {
throw new TypeError('Name must be a string');
}
if (prop === 'price' && typeof value !== 'number') {
throw new TypeError('Price must be a number');
}
if (prop === 'quantity' && typeof value !== 'number') {
throw new TypeError('Quantity must be a number');
}
target[prop] = value;
return true;
}
});
`,
},
["Objective-C"]: {
language: "objectivec",
code: `
@interface GroceryItem : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) float price;
@property (nonatomic, assign) NSInteger quantity;
- (instancetype) initWithName: (NSString *)name
price: (float)price
quantity: (NSInteger)quantity;
@end
@implementation GroceryItem
- (instancetype) initWithName: (NSString *)name
price: (float)price
quantity: (NSInteger)quantity {
self = [super init];
if (self) {
_name = name;
_price = price;
_quantity = quantity;
}
return self;
}
@end
`,
},
["HTML"]: {
language: "html",
code: `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Formidable</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
`,
},
["AppleScript"]: {
language: "applescript",
code: `
display alert "Do you wish to buy groceries?" buttons {"No", "Yes"}
set theAnswer to button returned of the result
if theAnswer is "Yes" then
beep 5
end if
`,
},
["Rust"]: {
language: "rust",
code: `
use serde::{Deserialize, Serialize};
use reqwest::Error as ReqwestError;
#[derive(Debug, Serialize, Deserialize)]
struct GroceryItem {
name: String,
price: f32,
quantity: i32,
}
impl GroceryItem {
async fn fetch_all() -> Result<Vec<GroceryItem>, ReqwestError> {
let response = reqwest::get("https://example.com/grocery_items")
.await?
.json::<Vec<GroceryItem>>()
.await?;
Ok(response)
}
async fn fetch_by_name(name: &str) -> Result<GroceryItem, ReqwestError> {
let response = reqwest::get(&format!("https://example.com/grocery_items/{}", name))
.await?
.json::<GroceryItem>()
.await?;
Ok(response)
}
async fn create(&self) -> Result<(), ReqwestError> {
let client = reqwest::Client::new();
let response = client.post("https://example.com/grocery_items")
.json(self)
.send()
.await?;
if !response.status().is_success() {
return Err(ReqwestError::from(response.status()));
}
Ok(())
}
async fn update(&self, name: &str) -> Result<(), ReqwestError> {
let client = reqwest::Client::new();
let response = client.put(&format!("https://example.com/grocery_items/{}", name))
.json(self)
.send()
.await?;
if !response.status().is_success() {
return Err(ReqwestError::from(response.status()));
}
Ok(())
}
async fn delete(name: &str) -> Result<(), ReqwestError> {
let client = reqwest::Client::new();
let response = client.delete(&format!("https://example.com/grocery_items/{}", name))
.send()
.await?;
if !response.status().is_success() {
return Err(ReqwestError::from(response.status()));
}
Ok(())
}
}
`,
},
}
|
f1b66de408b828480e81714ff33abed3a61554dc
|
TypeScript
|
mccaulleyg94/laughing-tribble
|
/src/Utils/Random.ts
| 3.390625
| 3
|
export function randomEnum<T>(anEnum: T): T[keyof T] {
const enumValues = Object.keys(anEnum).map(n => Number.parseInt(n)).filter(n => !Number.isNaN(n)) as unknown as T[keyof T][]
const randomIndex = Math.floor(Math.random() * enumValues.length)
const randomEnumValue = enumValues[randomIndex]
return randomEnumValue;
}
export function randomNumber(min: number, max: number) {
return Math.floor(Math.random() * (max - min) + min);
}
|
a1be0017ce6dbd81b8b74d126c81b90344de8bf6
|
TypeScript
|
NativeScript/nativescript-picker
|
/demo/app/examples/value-api/value-api-model.ts
| 2.703125
| 3
|
import { Observable } from 'tns-core-modules/data/observable';
import { ObservableArray } from "tns-core-modules/data/observable-array";
export class ValueApiModel extends Observable {
public pickerItems: ObservableArray<DataItem>;
constructor() {
super();
this.pickerItems = this.getItems(20);
}
private getItems(size: number) {
let array = new ObservableArray<DataItem>();
for (let i = 0; i < size; i++) {
array.push(new DataItem("Item " + i, i, "Description " + i));
}
return array;
}
}
class DataItem {
constructor(public name: string, public id: number, public description: string) { }
}
|
a3d6751c0a5b681210844defd88f1ccba23a57bb
|
TypeScript
|
GlitchEnzo/Cacophony
|
/ProgressBar.ts
| 3.140625
| 3
|
/**
* Represents a progress bar that displays the current time and total time of the current song.
* @class Represents a ProgressBar
*/
class ProgressBar
{
// Example:
//<div onmousedown="progressClicked(event)" id="progressWrapper" style="width: 320px; position: relative; border: 1px solid black;">
// <div id="progressBar" style="width: 0%; background-color: #33cc33; position: absolute; top: 0; left: 0; height: 100%;"></div>
// <div id="progressText" style="width: 320px; text-align: center; position: relative;">
// <b id="progressTime">0:00 / 0:00</b>
// </div>
//</div>
durationSeconds: number = 0;
durationString: string = "0:00";
currentTime: number = 0;
currentTimeString: string = "0:00";
width: number = null;
progressWrapper: HTMLDivElement = null;
progressBarElement: HTMLDivElement = null;
progressTimeElement: HTMLDivElement = null;
progressSlider: HTMLDivElement = null;
CreateChild(width, parentElement)
{
this.width = width;
this.progressWrapper = document.createElement("div");
var thisProgressBar = this;
//progressWrapper.addEventListener("onmousedown", function(e) { thisProgressBar.clicked(e); }, false);
this.progressWrapper.onmousedown = function (e) { thisProgressBar.Clicked(e); };
this.progressWrapper.style.width = width + "px";
//this.progressWrapper.style.width = "95%";
this.progressWrapper.style.border = "1px solid black";
this.progressWrapper.style.borderRadius = "15px";
this.progressWrapper.style.height = "20px";
this.progressWrapper.style.margin = "0px auto";
this.progressWrapper.style.backgroundColor = "#aaaaaa";
this.progressWrapper.style.overflow = "hidden";
this.progressBarElement = document.createElement("div");
this.progressBarElement.style.width = "0%";
//this.progressBarElement.style.backgroundColor = "#33cc33";
this.progressBarElement.style.backgroundColor = "#00bbff";
this.progressBarElement.style.borderRadius = "15px";
this.progressBarElement.style.height = "100%";
this.progressTimeElement = document.createElement("div");
this.progressTimeElement.innerText = "0:00 / 0:00";
this.progressTimeElement.style.width = width + "px";
this.progressTimeElement.style.textAlign = "center";
this.progressTimeElement.style.position = "relative";
this.progressTimeElement.style.top = "-18px";
this.progressTimeElement.style.fontWeight = "bolder";
this.progressSlider = document.createElement("div");
this.progressSlider.innerText = "slider";
this.progressSlider.style.height = "24px";
this.progressSlider.style.width = "24px";
this.progressSlider.style.backgroundColor = "#cccccc";
this.progressSlider.style.borderRadius = "15px";
this.progressSlider.style.position = "relative";
this.progressSlider.style.top = "-36px";
this.progressWrapper.appendChild(this.progressBarElement);
this.progressWrapper.appendChild(this.progressTimeElement);
//this.progressWrapper.appendChild(this.progressSlider);
parentElement.appendChild(this.progressWrapper);
//parentElement.appendChild(this.progressSlider);
}
SetWidth(width: number)
{
this.width = width;
this.progressWrapper.style.width = width + "px";
this.progressTimeElement.style.width = width + "px";
}
Clicked(e: MouseEvent)
{
//console.log(e);
var percentage = e.offsetX / this.width;
this.progressBarElement.style.width = percentage * 100 + "%";
//audioElement.currentTime = audioElement.durationSeconds * percentage;
}
SetDuration(durationSeconds: number)
{
this.durationSeconds = durationSeconds;
this.durationString = this.ConvertSecondsToTime(durationSeconds);
this.progressTimeElement.innerText = this.currentTimeString + " / " + this.durationString;
this.progressBarElement.style.width = this.currentTime / this.durationSeconds * 100 + "%";
}
SetCurrentTime(currentSeconds: number)
{
this.currentTime = currentSeconds;
this.currentTimeString = this.ConvertSecondsToTime(currentSeconds);
this.progressTimeElement.innerText = this.currentTimeString + " / " + this.durationString;
this.progressBarElement.style.width = this.currentTime / this.durationSeconds * 100 + "%";
}
/**
* Creates a string representation of a time duration from a given number of seconds.
* For example: 121 passed in will return "2:01"
* @param {int} seconds The number of seconds representing the time.
* @returns string} The stringified time, in the format "#:##".
*/
ConvertSecondsToTime(seconds: number)
{
var secondsPart: string = Math.floor(seconds % 60).toString();
if (Math.floor(seconds % 60) < 10)
secondsPart = "0" + secondsPart;
var minutesPart = Math.floor(seconds / 60);
//TODO: Display hours?
return minutesPart + ":" + secondsPart;
}
}
|
0029120168837348d70e5a37fcffb64d4dd819db
|
TypeScript
|
reactdenver/reactdenver.com
|
/app/utils/files.server.ts
| 3.0625
| 3
|
import nodePath from "path";
import { readFile, readdir } from "fs/promises";
/**
*
* @param relativeMdxFileOrDirectory the path to the content. For example:
* content/events/2001-01-01.mdx
* @returns A promise that resolves to an object of the full path and the file content
*/
async function downloadMdxFile(
relativeMdxFileOrDirectory: string
): Promise<{ entry: string; file: string }> {
const mdxFileOrDirectory = `content/${relativeMdxFileOrDirectory}`;
const content = await downloadFile(mdxFileOrDirectory);
let file = "";
let entry = mdxFileOrDirectory;
if (content) {
file = content;
}
return { entry, file };
}
/**
*
* @param filePath the full file path to the individual file
* @returns a promise that resolves to a string of the contents of the file
*/
async function downloadFile(filePath: string) {
const file = await readFile(filePath);
return Buffer.from(file).toString();
}
/**
*
* @param path the full path to list
* @returns a promise that resolves to a file ListItem of the files/directories in the given directory (not recursive)
*/
async function downloadDirList(path: string) {
const directory = await readdir(nodePath.join(path), { withFileTypes: true });
return directory;
}
export { downloadMdxFile, downloadDirList };
|
80113d28c64c681ec7a7284b13055ec158a24cf7
|
TypeScript
|
steps798/google_maps_example
|
/packages/design-systems/dist/types/components/atoms/skeleton/Skeleton.d.ts
| 2.71875
| 3
|
import React from 'react';
declare type DefaultProps = {
/** 'Indexer: use for other props */
[x: string]: any;
} & Partial<PropTypes>;
declare type PropTypes = {
/** total skeleton to render. default is 1 */
count: number;
/** animation duration. default is 1.2 */
duration: number;
/** skeleton width. default is null */
width: number;
/** skeleton height. default is null */
height: number;
/** set skeleton to be a circle or not. if you need a circle skeleton you must set the "width" & "height" first. default is false */
circle: boolean;
};
declare class Skeleton extends React.Component<DefaultProps, any> {
static defaultProps: DefaultProps;
renderSkeleton: (key: number, count: number, duration: number, width: number, height: number, circle: boolean) => JSX.Element;
render(): JSX.Element;
}
export { Skeleton };
|
7e9ae611fc9d2b0cebf6086698f773377ab06f44
|
TypeScript
|
virtual1680/qhy-ui
|
/src/api/action.ts
| 2.53125
| 3
|
import axios from '@/utils/request'
// //post
function postAction(url:string,data?:object) {
return axios({
url: url,
method:'post',
data: data
})
}
// //put
function putAction(url:string,data?:object) {
return axios({
url: url,
method:'put',
data: data
})
}
// //get
function getAction(url:string,data?:object) {
return axios({
url: url,
method: 'get',
params: data
})
}
// //delete
function deleteAction(url:string,data?:object) {
return axios({
url: url,
method: 'delete',
params: data
})
}
/**
* 文件上传 用于富文本上传图片
* @param url
* @param data
* @returns {*}
*/
function uploadAction(url:string,data:any){
return axios({
url: url,
data: data,
method:'post' ,
headers: {
'Content-Type': 'multipart/form-data', // 文件上传
},
})
}
export {
postAction,
putAction,
getAction,
deleteAction,
uploadAction
}
|
fcf691434266617a130410775f669c22b047e1b6
|
TypeScript
|
tokovenko/bet-analyzer
|
/ts/strategies/DogonStrategyWithLimit.ts
| 2.734375
| 3
|
import {Strategy} from './../Strategy';
class DogonStrategyWithLimit extends Strategy {
public title: 'Dogon Strategy with limits';
public betPercent: number = 10;
public betMaximum: number = 500;
public setBetPercent(percent: number) {
this.betPercent = percent;
}
public setBetMaximum(maximum: number) {
this.betMaximum = maximum;
}
public getBetSum() {
let betSum = this.bank * (this.betPercent / 100);
return betSum>this.betMaximum ? this.betMaximum : betSum;
}
}
export {DogonStrategyWithLimit};
|
acefcd8929f20d2b0036341b6dfc18b8f17cd4d5
|
TypeScript
|
jayfreestone/priority-plus
|
/src/events/eventHandler.ts
| 3.0625
| 3
|
import { Events } from './createEvent';
import eventTarget from './eventTarget';
export type EventCallback = (eventDetail: CustomEvent<{}>) => void;
interface CallbackRef {
eventType: Events;
wrappedCallback: EventCallback;
}
function createEventHandler() {
const state = { eventReady: false };
const eventChannel = eventTarget();
const eventListeners: Map<EventCallback, CallbackRef> = new Map();
/**
* Registers an an event listener for the instance.
* By default the callback will only be run after the first-load.
* However this can be overridden by setting 'afterReady' to 'false'.
*/
function on(eventType: Events, cb: EventCallback, afterReady = true) {
function wrappedCallback(event: CustomEvent<{}>) {
if (!afterReady || state.eventReady) cb(event);
}
// Store it so we can remove it later
eventListeners.set(cb, { eventType, wrappedCallback });
eventChannel.addEventListener(eventType, wrappedCallback as EventListener);
return this;
}
/**
* Removes an event listener.
*/
function off(eventType: Events, cb: EventCallback) {
const { wrappedCallback } = eventListeners.get(cb) as CallbackRef;
eventChannel.removeEventListener(eventType, wrappedCallback as EventListener);
return this;
}
/**
* Dispatch an event.
*/
function trigger(event: CustomEvent<{}>) {
eventChannel.dispatchEvent(event);
}
/**
* Set if we're ready to fire event callbacks.
*/
function setEventReady(ready = true) {
state.eventReady = ready;
}
return {
off,
on,
setEventReady,
trigger,
};
}
export default createEventHandler;
|
83c64e52d5c9f1bcce991dc23e4d7e636b307a9b
|
TypeScript
|
kelvinsjk/math-edu
|
/src/classes/exponential/expClass.ts
| 3.6875
| 4
|
import Fraction from '../fractionClass';
import Ln from './lnClass';
import Term from '../algebra/termClass';
import convertNumberToFraction from '../../internal/convertNumberToFraction';
/**
* ln class
*
* @exponent Fraction | Exp
*
* class representing exponentiation by Euler's number
*
* as a extension of the `Term` class
*/
export default class Exp extends Term {
/** exponent */
exponent: Fraction;
////
// constructor
////
/**
* Creates a new exp instance
*
* @exponent number | Fraction | Ln
*
*/
constructor(exponent: number | Fraction | Ln, coeff?: number | Fraction) {
coeff = coeff === undefined ? Fraction.ONE : convertNumberToFraction(coeff);
if (exponent instanceof Ln) {
if (exponent.coeff.isEqual(1)) {
super(exponent.argument.times(coeff));
this.exponent = Fraction.ZERO;
} else {
throw new Error('exp ERROR: change the coefficient of the logarithm to 1 to proceed');
}
} else {
exponent = convertNumberToFraction(exponent);
if (exponent.valueOf() === 0) {
super(coeff);
} else if (exponent.valueOf() === 1) {
super(coeff, `\\mathrm{e}`);
} else {
super(coeff, `\\mathrm{e}^{${exponent}}`);
}
this.exponent = exponent;
}
}
/**
* multiplication
*/
times(expY: Exp): Exp {
const exponent = this.exponent.plus(expY.exponent);
return new Exp(exponent, this.coeff.times(expY.coeff));
}
/**
* multiplication
*/
divide(expY: Exp): Exp {
const exponent = this.exponent.minus(expY.exponent);
return new Exp(exponent, this.coeff.divide(expY.coeff));
}
/**
* multiplication
*/
pow(n: number): Exp {
if (Number.isInteger(n)) {
const exponent = this.exponent.times(n);
let coeff: Fraction;
if (n === 0) {
coeff = Fraction.ONE;
} else if (n < 0) {
coeff = Fraction.ONE.divide(this.coeff.pow(Math.abs(n)));
} else {
coeff = this.coeff.pow(n);
}
return new Exp(exponent, coeff);
} else {
throw new Error('exp ERROR: pow of non-integers not supported at this point');
}
}
/**
* @returns - k e^x
*/
negative(): Exp {
return new Exp(this.coeff.negative(), this.exponent);
}
/**
* @returns the value of the logarithm in the javascript number type
*/
valueOf(): number {
return this.coeff.valueOf() * Math.exp(this.exponent.valueOf());
}
clone(): Exp {
return new Exp(this.coeff, this.exponent);
}
}
|
d77f9b773b06ef5e5888472b24e6fd24e1364e5e
|
TypeScript
|
sergeevtoll/conformition-email
|
/src/user/repositories/user.repository.ts
| 2.578125
| 3
|
import { confirmEmailLink } from '../../utils/confirmEmailLink';
import { User } from '../entities/user.entitiy';
import { UserDto } from '../dto/user.dto';
import { Injectable } from "@nestjs/common";
import { EntityManager, EntityRepository, FindOneOptions, getManager } from 'typeorm';
import { sendEmail } from '../../utils/sendEmail';
import { redis } from '../../redis';
@Injectable()
@EntityRepository(User)
export class UserRepositiry {
manager: EntityManager
constructor() {
this.manager = getManager();
}
// @Cron('100 * * * * *')
async handleCron(userData: UserDto) {
setTimeout(async () => {
const opt: FindOneOptions<User> = {
where: {
email: userData.email,
}
}
const user = await this.manager.findOne(User, opt)
if (!user.confirm) {
await this.manager.delete(User, user)
}
}, 1000 * 60 * 15)
}
async createUser(userData: UserDto): Promise<string> {
const newUser = new User()
newUser.email = userData.email
newUser.password = userData.password
newUser.confirm = false
const user = await this.manager.save(newUser)
await sendEmail(user.email, await confirmEmailLink(user.id))
this.handleCron(user)
return 'всё заеьумба, письмо должны отправить'
}
async confirmUser(id: string): Promise<string> {
const userId = await redis.get(id)
if (!userId) {
return 'истек строк ссылки или ссылка не вернеая'
}
const opt: FindOneOptions<User> = {
where: {
id: userId
}
}
const user = await this.manager.findOne(User, opt)
user.confirm = true
await this.manager.update(User, { id: userId }, { confirm: true })
return `сслыка подтверждена, вот прув: ${JSON.stringify(user)}`
}
async checkUser(email: UserDto): Promise<string> {
const opt: FindOneOptions<User> = {
where: {
email: email.email,
}
}
const user = await this.manager.findOne(User, opt)
if (user && user.confirm) {
return 'Пользователь зареган'
}
return 'Пользователь не зареган'
}
};
|
7dbc9b5818260e5a3374aefb5206b958b3544e9a
|
TypeScript
|
Brandux/SPA-Angular
|
/fundamentos_typescript/4-poo/poo.ts
| 3.5625
| 4
|
class Coche{
private color : string ;
private modelo : string;
private velocidad : number;
// con el signo de ? quiere decir que puede llegar dicha variable y en ocaciones no.
constructor(colorDefault ?:string){
this.color= colorDefault;
}
public getColor(){
return this.color;
}
public setColor(color:string){
this.color = color;
}
public getVelocidad(){
return this.velocidad;
}
public setVelocidad(velocidad){
this.velocidad = velocidad;
}
}
var coche = new Coche('blanco');
var coche_dos = new Coche();
var coche_tres = new Coche('rojo');
console.log ('Este primer carro es de color: ', coche.getColor() );
// console.log ('Este segundo carro es de color: ', coche_dos.getColor());
console.log ('Este tercer carro es de color: ', coche_tres.getColor());
|
f549592ea323b192440542d443dbbc5d9eecf0d4
|
TypeScript
|
rafgraph/current-input
|
/src/index.ts
| 2.609375
| 3
|
import * as detectIt from 'detect-it';
import { eventFrom } from 'event-from';
function setupCurrentInput() {
const body = document.querySelector('body');
type CurrentInput = 'mouse' | 'touch';
// set initial state based on primaryInput
let currentInput: CurrentInput = detectIt.primaryInput;
body?.classList.add(`current-input-${currentInput}`);
const eventHandler = (e: any) => {
const eventFromValue = eventFrom(e);
if (
eventFromValue !== currentInput &&
(eventFromValue === 'mouse' || eventFromValue === 'touch')
) {
body?.classList.remove(`current-input-${currentInput}`);
body?.classList.add(`current-input-${eventFromValue}`);
currentInput = eventFromValue;
}
};
const eventListenerOptions = detectIt.supportsPassiveEvents
? { passive: true, capture: true }
: true;
// set event listeners
[
'touchstart',
'touchmove',
'touchend',
'touchcancel',
'pointerenter',
'pointerover',
'pointermove',
'pointerout',
'pointerleave',
'pointerdown',
'pointerup',
'pointercancel',
'mouseenter',
'mouseover',
'mousemove',
'mouseout',
'mouseleave',
'mousedown',
'mouseup',
].map((eventType) => {
document.addEventListener(eventType, eventHandler, eventListenerOptions);
});
// remove event listener set by launcher (if no event listener was set this does nothing)
document.removeEventListener('DOMContentLoaded', setupCurrentInput);
}
(() => {
const body = document.querySelector('body');
if (body) setupCurrentInput();
else document.addEventListener('DOMContentLoaded', setupCurrentInput);
})();
|
791891a3adeab1c26c18833f787597899755a7bf
|
TypeScript
|
jhbertra/data-grace
|
/test/maybe.spec.ts
| 3.09375
| 3
|
import * as fc from "fast-check";
import { Maybe } from "../src";
import { constant, simplify } from "../src/prelude";
/*------------------------------
UNIT TESTS
------------------------------*/
describe("fromArray", () => {
it("returns nothing when input is empty", () => {
expect(simplify(Maybe.fromArray([]))).toEqual(simplify(Maybe.Nothing()));
});
it("returns the first element when the input is not empty", () => {
fc.assert(
fc.property(
fc.array(fc.integer()).filter((x) => x.length > 0),
(xs: number[]) => {
expect(simplify(Maybe.fromArray(xs))).toEqual(simplify(Maybe.Just(xs[0])));
},
),
);
});
});
describe("build", () => {
interface Foo {
bar: number;
baz: boolean;
qux: string;
}
it("equals construct + wrap when all components have value", () => {
fc.assert(
fc.property(
fc.record({
bar: fc.float(),
baz: fc.boolean(),
qux: fc.string(),
}),
(r) => {
expect(
simplify(
Maybe.record<Foo>({
bar: Maybe.Just(r.bar),
baz: Maybe.Just(r.baz),
qux: Maybe.Just(r.qux),
}),
),
).toEqual(simplify(Maybe.Just(r)));
},
),
);
});
it("equals Nothing when any components have no value", () => {
fc.assert(
fc.property(
fc.float(),
fc.boolean(),
fc.string(),
fc.array(fc.integer(0, 2), 1, 3),
(bar: number, baz: boolean, qux: string, empties: number[]) => {
function getComponent<T>(i: number, value: T): Maybe<T> {
return empties.find((x) => x === i) !== undefined ? Maybe.Nothing() : Maybe.Just(value);
}
expect(
simplify(
Maybe.record<Foo>({
bar: getComponent(0, bar),
baz: getComponent(1, baz),
qux: getComponent(2, qux),
}),
),
).toEqual(simplify(Maybe.Nothing()));
},
),
);
});
});
describe("catMaybes", () => {
it("returns every Maybe with a value", () => {
fc.assert(
fc.property(
fc.array(fc.oneof(fc.constant(Maybe.Nothing<number>()), fc.integer().map(Maybe.Just))),
(xs: Array<Maybe<number>>) => {
expect(Maybe.catMaybes(xs)).toEqual(
xs.filter((x) => x.isJust).map((x) => (x as any).data.value),
);
},
),
);
});
});
describe("mapMaybe", () => {
it("is equal to map for only pure results", () => {
fc.assert(
fc.property(fc.array(fc.string()), (strs: string[]) => {
expect(Maybe.mapMaybe((str) => Maybe.Just(str.length), strs)).toEqual(
strs.map((str) => str.length),
);
}),
);
});
it("is equal to filter + map for discarding results", () => {
fc.assert(
fc.property(
fc
.array(fc.string(), 1, 10)
.chain((strs) =>
fc
.array(fc.integer(0, strs.length - 1), 1, strs.length)
.map(
(empties) =>
[strs.map((s, i) => [s, i]), empties] as [Array<[string, number]>, number[]],
),
),
([strs, empties]) => {
const predicate = ([, i]: [string, number]) => empties.find((x) => x === i) === undefined;
expect(
Maybe.mapMaybe(
(str) => (predicate(str) ? Maybe.Just(str.length) : Maybe.Nothing()),
strs,
),
).toEqual(strs.filter(predicate).map((str) => str.length));
},
),
);
});
});
describe("sequence", () => {
it("is equal to wrap for only pure results", () => {
fc.assert(
fc.property(fc.array(fc.string()), (strs: string[]) => {
expect(simplify(Maybe.sequence(strs.map(Maybe.Just)))).toEqual(simplify(Maybe.Just(strs)));
}),
);
});
it("is equal to Nothing for any empty results", () => {
fc.assert(
fc.property(
fc
.array(fc.string(), 1, 10)
.chain((strs) =>
fc
.array(fc.integer(0, strs.length - 1), 1, strs.length)
.map(
(empties) =>
[strs.map((s, i) => [s, i]), empties] as [Array<[string, number]>, number[]],
),
),
([strs, empties]) => {
const predicate = ([, i]: [string, number]) => empties.find((x) => x === i) === undefined;
expect(
simplify(
Maybe.sequence(
strs.map((str) => (predicate(str) ? Maybe.Just(str[0]) : Maybe.Nothing())),
),
),
).toEqual(simplify(Maybe.Nothing()));
},
),
);
});
});
describe("fromJS", () => {
it("produces Nothing for null", () => {
expect(simplify(Maybe.fromJS(null))).toEqual(simplify(Maybe.Nothing()));
});
it("produces Nothing for undefined", () => {
expect(simplify(Maybe.fromJS(undefined))).toEqual(simplify(Maybe.Nothing()));
});
it("produces a value for values", () => {
fc.assert(
fc.property(fc.integer(), (n: number) =>
expect(simplify(Maybe.fromJS(n))).toEqual(simplify(Maybe.Just(n))),
),
);
});
});
describe("Maybe", () => {
it("obeys the left identity monad law", () => {
const k = (s: string) =>
Maybe.Just(s)
.filter((x) => x.length < 4)
.map((x) => x.length);
fc.assert(
fc.property(fc.string(), (s) => {
expect(simplify(Maybe.Just(s).chain(k))).toEqual(simplify(k(s)));
}),
);
});
it("obeys the right identity monad law", () => {
fc.assert(
fc.property(
fc.oneof(fc.constant(Maybe.Nothing<string>()), fc.string().map(Maybe.Just)),
(m) => {
expect(simplify(m.chain(Maybe.Just))).toEqual(simplify(m));
},
),
);
});
it("obeys the right monad associativity law", () => {
const k = (s: string) =>
Maybe.Just(s)
.filter((x) => x.length < 4)
.map((x) => x.length);
const h = (n: number) =>
Maybe.Just(n)
.filter((x) => x % 2 === 0)
.map((x) => x.toString());
fc.assert(
fc.property(
fc.oneof(fc.constant(Maybe.Nothing<string>()), fc.string().map(Maybe.Just)),
(m) => {
expect(simplify(m.chain((x) => k(x).chain(h)))).toEqual(simplify(m.chain(k).chain(h)));
},
),
);
});
describe("defaultWith", () => {
it("Returns payload when present", () => {
fc.assert(
fc.property(fc.string(), (s) => {
expect(Maybe.Just(s).defaultWith("foo")).toEqual(s);
}),
);
});
it("Returns default when empty", () => {
expect(Maybe.Nothing().defaultWith("foo")).toEqual("foo");
});
});
describe("filter", () => {
it("Passes the value into predicate", () => {
fc.assert(
fc.property(fc.string(), (s) => {
// @ts-ignore
Maybe.Just(s).filter((x) => expect(x).toEqual(s));
}),
);
});
it("Erases the value when the predicate returns false", () => {
fc.assert(
fc.property(fc.string(), (s) => {
expect(simplify(Maybe.Just(s).filter(constant(false)))).toEqual(
simplify(Maybe.Nothing()),
);
}),
);
});
it("Leaves the value when the predicate returns true", () => {
fc.assert(
fc.property(fc.string(), (s) => {
expect(simplify(Maybe.Just(s).filter(constant(true)))).toEqual(simplify(Maybe.Just(s)));
}),
);
});
it("Does not affect empty values", () => {
fc.assert(
fc.property(fc.boolean(), (b) => {
expect(simplify(Maybe.Nothing().filter(constant(b)))).toEqual(simplify(Maybe.Nothing()));
}),
);
});
});
describe("chain", () => {
it("Passes the payload to the callback", () => {
fc.assert(
fc.property(fc.string(), (s) => {
Maybe.Just(s).chain((x) => Maybe.Just(expect(x).toEqual(s)));
}),
);
});
it("Returns the value returned by the callback", () => {
const k = (s: string) => Maybe.Just(s).filter((x) => x.length < 5);
fc.assert(
fc.property(fc.string(), (s) => {
expect(simplify(Maybe.Just(s).chain(k))).toEqual(simplify(k(s)));
}),
);
});
it("Skips the callback on empty", () => {
const k = (s: string) => Maybe.Just(s).filter((x) => x.length < 5);
expect(simplify(Maybe.Nothing<string>().chain(k))).toEqual(simplify(Maybe.Nothing()));
});
});
describe("isJust", () => {
it("Returns true for Just(s)", () => {
fc.assert(
fc.property(fc.string(), (s) => {
expect(simplify(Maybe.Just(s).isJust)).toEqual(true);
}),
);
});
it("Returns false for Nothing()", () => {
expect(simplify(Maybe.Nothing().isJust)).toEqual(false);
});
});
describe("isNothing", () => {
it("Returns false for Just(s)", () => {
fc.assert(
fc.property(fc.string(), (s) => {
expect(simplify(Maybe.Just(s).isNothing)).toEqual(false);
}),
);
});
it("Returns true for Nothing()", () => {
expect(simplify(Maybe.Nothing().isNothing)).toEqual(true);
});
});
describe("map", () => {
it("Passes the payload to the callback", () => {
fc.assert(
fc.property(fc.string(), (s) => {
Maybe.Just(s).map((x) => expect(x).toEqual(s));
}),
);
});
it("Wraps the value returned by the callback", () => {
const k = (s: string) => s.length;
fc.assert(
fc.property(fc.string(), (s) => {
expect(simplify(Maybe.Just(s).map(k))).toEqual(simplify(Maybe.Just(k(s))));
}),
);
});
it("Skips the callback on empty", () => {
const k = (s: string) => s.length;
expect(simplify(Maybe.Nothing<string>().map(k))).toEqual(simplify(Maybe.Nothing()));
});
});
describe("matchCase", () => {
it("Passes the payload to the correct callback", () => {
Maybe.Just("foo").matchCase({
Just: (x) => expect(x).toEqual("foo"),
Nothing: () => fail("Not expected to be called"),
});
Maybe.Nothing().matchCase({
Just: () => fail("Not expected to be called"),
Nothing: () => undefined,
});
});
it("returns the correct value when a value is provided", () => {
fc.assert(
fc.property(fc.string(), (s) => {
expect(
Maybe.Just(s).matchCase({
Just: (x) => x.length,
Nothing: () => s.length - 1,
}),
).toEqual(s.length);
}),
);
});
it("returns the correct value when no value is provided", () => {
expect(Maybe.Nothing().matchCase({ Just: () => 1, Nothing: () => 0 })).toEqual(0);
});
});
describe("or", () => {
it("Picks the first if non empty", () => {
expect(simplify(Maybe.Just("foo").or(Maybe.Just("bar")))).toEqual(
simplify(Maybe.Just("foo")),
);
});
it("Picks the second if first empty", () => {
expect(simplify(Maybe.Nothing().or(Maybe.Just("bar")))).toEqual(simplify(Maybe.Just("bar")));
});
it("Picks nothing if both empty", () => {
expect(simplify(Maybe.Nothing().or(Maybe.Nothing()))).toEqual(simplify(Maybe.Nothing()));
});
});
describe("replace", () => {
it("Returns something if both are non-empty", () => {
expect(simplify(Maybe.Just("foo").replace(Maybe.Just("bar")))).toEqual(
simplify(Maybe.Just("bar")),
);
});
it("Returns nothing if the second is empty", () => {
expect(simplify(Maybe.Just("foo").replace(Maybe.Nothing()))).toEqual(
simplify(Maybe.Nothing()),
);
});
it("Returns nothing if the first is empty", () => {
expect(simplify(Maybe.Nothing().replace(Maybe.Just("bar")))).toEqual(
simplify(Maybe.Nothing()),
);
});
it("Returns nothing if both are empty", () => {
expect(simplify(Maybe.Nothing().replace(Maybe.Nothing()))).toEqual(simplify(Maybe.Nothing()));
});
});
describe("replacePure", () => {
it("Replaces value if non-empty", () => {
expect(simplify(Maybe.Just("foo").replacePure(2))).toEqual(simplify(Maybe.Just(2)));
});
it("Returns nothing if empty", () => {
expect(simplify(Maybe.Nothing().replacePure(2))).toEqual(simplify(Maybe.Nothing()));
});
});
describe("toArray", () => {
it("Returns singleton array if non-empty", () => {
expect(Maybe.Just("foo").toArray()).toEqual(["foo"]);
});
it("Returns empty array if empty", () => {
expect(Maybe.Nothing().toArray()).toEqual([]);
});
});
describe("toString", () => {
it("Renders Nothing as Nothing", () => {
expect(Maybe.Nothing().toString()).toEqual("Nothing");
});
it("Renders Just(s) as Just (s)", () => {
expect(Maybe.Just("foo").toString()).toEqual("Just (foo)");
});
});
describe("voidOut", () => {
it("Returns Nothing for Nothing", () => {
expect(simplify(Maybe.Nothing().voidOut())).toEqual(simplify(Maybe.Nothing()));
});
it("Renders Just(s) as Just (s)", () => {
expect(Maybe.Just("foo").voidOut().toJSON()).toBeUndefined();
});
});
describe("unCons", () => {
it("Returns Nothing for empty", () => {
expect(simplify(Maybe.unCons([]))).toEqual(simplify(Maybe.Nothing()));
});
it("Returns a tuple for non empty", () => {
fc.assert(
fc.property(
fc.array(fc.anything()).filter((arr) => !arr.isEmpty()),
(arr) => {
expect(simplify(Maybe.unCons(arr))).toEqual(
simplify(Maybe.Just([arr[0], arr.slice(1)])),
);
},
),
);
});
});
describe("valueEquals", () => {
it("Returns false if either are Nothing", () => {
expect(Maybe.Just(1).valueEquals(Maybe.Nothing())).toEqual(false);
expect(Maybe.Nothing().valueEquals(Maybe.Just(1))).toEqual(false);
expect(Maybe.Nothing().valueEquals(Maybe.Nothing())).toEqual(false);
});
it("Returns true if equal", () => {
expect(Maybe.Just(1).valueEquals(Maybe.Just(1))).toEqual(true);
});
it("Returns false if not equal", () => {
expect(Maybe.Just(1).valueEquals(Maybe.Just(0))).toEqual(false);
});
it("Returns equality check result if predicate specified", () => {
expect(Maybe.Just(1).valueEquals(Maybe.Just(0), () => true)).toEqual(true);
expect(Maybe.Just(1).valueEquals(Maybe.Just(1), () => false)).toEqual(false);
});
});
describe("valueEqualsPure", () => {
it("Returns false if Nothing", () => {
expect(Maybe.Nothing().valueEqualsPure(1)).toEqual(false);
});
it("Returns true if equal", () => {
expect(Maybe.Just(1).valueEqualsPure(1)).toEqual(true);
});
it("Returns false if not equal", () => {
expect(Maybe.Just(1).valueEqualsPure(0)).toEqual(false);
});
it("Returns equality check result if predicate specified", () => {
expect(Maybe.Just(1).valueEqualsPure(0, () => true)).toEqual(true);
expect(Maybe.Just(1).valueEqualsPure(1, () => false)).toEqual(false);
});
});
describe("fromData", () => {
it("Returns Nothing when no match", () => {
fc.assert(
fc.property(
fc
.record({
match: fc.string(),
data: fc.record({
tag: fc.string(),
value: fc.anything(),
}),
})
.filter(({ match, data }) => match !== data.tag),
({ match, data }) => {
expect(simplify(Maybe.fromData(data, match))).toEqual(simplify(Maybe.Nothing()));
},
),
);
});
it("Returns Just when the tag matches", () => {
fc.assert(
fc.property(
fc.record({
tag: fc.string(),
value: fc.anything(),
}),
(data) => {
expect(simplify(Maybe.fromData(data, data.tag))).toEqual(
simplify(Maybe.Just(data.value)),
);
},
),
);
});
});
});
|
301e0cf0459aaf2c2ca44346b5c7420375f06560
|
TypeScript
|
cgbinho/chocoanimato-frontend-public
|
/src/validations/fieldMasks.ts
| 3.1875
| 3
|
export const lowerCaseMask = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.value) {
event.target.value = event.target.value.toLowerCase();
}
};
// Formatação de dd/mm/aaaa
export const fullDateMask = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.value) {
event.target.value = event.target.value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '$1/$2')
.replace(/(\d{2})(\d)/, '$1/$2')
.replace(/(\d{4})\d+?$/, '$1');
}
};
// Formatação de mm/yyyy
export const monthYearMask = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.value) {
event.target.value = event.target.value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '$1/$2')
.replace(/(\d{4})\d+?$/, '$1');
}
};
//formata cpf
export const cpfMask = (event: React.ChangeEvent<HTMLInputElement>) => {
const { value } = event.target;
event.target.value = value
.replace(/\D/g, '') // substitui qualquer caracter que nao seja numero por nada
.replace(/(\d{3})(\d)/, '$1.$2') // captura 2 grupos de numero o primeiro de 3 e o segundo de 1, apos capturar o primeiro grupo ele adiciona um ponto antes do segundo grupo de numero
.replace(/(\d{3})(\d)/, '$1.$2') // captura 2 grupos de numero o primeiro de 3 e o segundo de 1, apos capturar o primeiro grupo ele adiciona um ponto antes do segundo grupo de numero
.replace(/(\d{3})(\d{1,2})/, '$1-$2')
.replace(/(-\d{2})\d+?$/, '$1'); // captura 2 numeros seguidos de um traço e não deixa ser digitado mais nada
};
/* /^[a-z\d]{5,12}$/i, */
export const telMask = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.value) {
event.target.value = event.target.value
.replace(/\D/g, '') // substitui qualquer caracter que nao seja numero por nada
.replace(/^(\d{2})(\d)/g, '($1) $2') //Coloca parênteses em volta dos dois primeiros dígitos
.replace(/(\d)(\d{4})$/, '$1-$2'); //Coloca hífen entre o quarto e o quinto dígitos
}
};
export const cepMask = (event: React.ChangeEvent<HTMLInputElement>) => {
const { value } = event.target;
event.target.value = value
.replace(/\D/g, '') // substitui qualquer caracter que nao seja numero por nada
.replace(/(\d)(\d{3})$/, '$1-$2'); // Coloca hifen entre o quarto e o quinto dígitos;
};
// export const cepMask = (event: React.ChangeEvent<HTMLInputElement>) => {
// const { value } = event.target;
// event.target.value = value
// .replace(/\D/g, '') // substitui qualquer caracter que nao seja numero por nada
// .replace(/(\d)(\d{3})$/, '$1 $2'); // Coloca espaço entre o quarto e o quinto dígitos;
// };
// máscara para numero de cartão de crédito
export const creditCardMask = (event: React.ChangeEvent<HTMLInputElement>) => {
const { value } = event.target;
event.target.value = value
.replace(/\D/g, '')
.replace(/^(\d{4})(\d)/g, '$1 $2')
.replace(/^(\d{4})\s(\d{4})(\d)/g, '$1 $2 $3')
.replace(/^(\d{4})\s(\d{4})\s(\d{4})(\d)/g, '$1 $2 $3 $4');
};
export const cvvMask = (event: React.ChangeEvent<HTMLInputElement>) => {
const { value } = event.target;
event.target.value = value.replace(/\D/g, '').replace(/(\d{4})\d+?$/, '$1'); // até 4 dígitos
};
|
71f56faa965c19bdf072be05383431d4a2750d97
|
TypeScript
|
UPCSocialNetwork/backend
|
/src/models/Cursada.ts
| 2.640625
| 3
|
import {
Model, Schema, model
} from 'mongoose';
import TimeStampPlugin, {
ITimeStampedDocument
} from './plugins/timestamp-plugin';
export interface ICursada extends ITimeStampedDocument {
/** FK ID de l'estudiant */
estudiantID: string;
/** FK ID de l'assigntura */
assignaturaID: string;
/** Situació actual de l'assignatura */
situacioActual: string;
/** Comptador de num de vegades cursada */
numVegades: number;
}
interface ICursadaModel extends Model<ICursada> { }
const schema = new Schema<ICursada>({
estudiantID: { type: String, required: true },
assignaturaID: { type: String, required: true },
situacioActual: { type: String, required: true },
numVegades: { type: Number, required: true }
});
// Add timestamp plugin for createdAt and updatedAt in miliseconds from epoch
schema.plugin(TimeStampPlugin);
schema.index({ estudiantID: 1, assignaturaID: 1 }, { unique: true });
const Cursada: ICursadaModel = model<ICursada, ICursadaModel>('Cursada', schema);
export default Cursada;
|
0b156197d8ffb2e4ce10fa79d719d33e65c76580
|
TypeScript
|
GeorgeCiocan/CF-CR6-GeorgeCiocan
|
/js/index.ts
| 2.984375
| 3
|
let places: Array<{}> = [];
let restaurants: Array<{}> = [];
let events: Array<{}> = [];
class Locations {
name: string
zipCode: string
address: string
image: string
constructor(name: string, zipCode: string, address: string, image: string) {
this.name = name
this.zipCode = zipCode;
this.address = address;
this.image = image
}
display() {
return (`
<div class="col mb-4">
<div class="card h-100">
<img src="${this.image}" class="card-img-top d-none d-md-block" alt="${this.name}">
<div class="card-body">
<h5 class="card-title">${this.name}</h5>
<p class="card-text">${this.address}, ${this.zipCode}</p>
</div>
</div>
</div>
`)
}
}
class Places extends Locations {
constructor(name: string, zipCode: string, address: string, image: string) {
super(name, zipCode, address, image)
super.display()
places.push(this)
}
}
class Restaurants extends Locations {
website: string
phone: any
type: string
constructor(name: string, zipCode: string, address: string, image: string, website: string, phone: any, type: string) {
super(name, zipCode, address, image);
this.website = website
this.phone = phone
this.type = type
restaurants.push(this)
}
display() {
return (`
<div class="col mb-4">
<div class="card h-100">
<img src="${this.image}" class="card-img-top d-none d-md-block" alt="${this.name}">
<div class="card-body">
<h5 class="card-title">${this.name} - <small>${this.type}</small></h5>
<p class="card-text">${this.address}, ${this.zipCode}</p>
<p class="card-text">${this.website}</p>
<p class="card-text">${this.phone}</p>
</div>
</div>
</div>
`)
}
}
class Events extends Locations {
eventDate: string
eventTime: string
price: number
website: string
constructor(name: string, zipCode: string, address: string, image: string, website: string, date: string, time: string, price: number) {
super(name, zipCode, address, image);
this.website = website
this.eventDate = date
this.eventTime = time
this.price = price
events.push(this)
}
display() {
return (`
<div class="col mb-4">
<div class="card h-100">
<img src="${this.image}" class="card-img-top d-none d-md-block" alt="${this.name}">
<div class="card-body">
<h5 class="card-title">${this.name}</h5>
<p class="card-text">${this.website}</p>
<p class="card-text">$${this.address}, ${this.zipCode}</p>
<p class="card-text">${this.eventDate}, ${this.eventTime}</p>
<p class="card-text">Price: ${this.price} EUR</p>
</div>
</div>
</div>
`)
}
}
//creates new objects
new Places("St. Charles Church", "1010 Vienna", "Karlsplatz 1", "./img/st-charles-church.jpg")
new Places("Zoo Vienna", "1130 Wien", "Maxingstraße 13b", "./img/vienna-zoo.jpg")
new Places("St. Charles Church", "1010 Vienna", "Karlsplatz 1", "./img/st-charles-church.jpg")
new Places("Zoo Vienna", "1130 Wien", "Maxingstraße 13b", "./img/vienna-zoo.jpg")
new Restaurants("Lemon Leaf", "1050 Vienna", "Kettenbrückengasse 19", "./img/lemon-leaf.png", "www.lemonleaf.at", "+43(1)5812308", "Thai restaurant")
new Restaurants("Sixta", "1050 Wien", "Schönbrunner Straße 21", "./img/sixta.png", "http://www.sixta-restaurant.at/", ["+43 1 58 528 56 l", "+43 1 58 528 56"], "thai food")
new Restaurants("Lemon Leaf", "1050 Vienna", "Kettenbrückengasse 19", "./img/lemon-leaf.png", "www.lemonleaf.at", "+43(1)5812308", "Thai restaurant")
new Restaurants("Sixta", "1050 Wien", "Schönbrunner Straße 21", "./img/sixta.png", "http://www.sixta-restaurant.at/", ["+43 1 58 528 56 l", "+43 1 58 528 56"], "thai food")
new Events("Kris Kristofferson", "1150 Wien", "Wiener Stadthalle, Halle F, Roland Rainer Platz 1", "./img/kriskristofferson.jpg", "http://kriskristofferson.com/", "Fr., 15.11.2021.", "20:00", 58.50)
new Events("Lenny Kravitz", "1150 Wien", "Wiener Stadthalle, Halle F, Roland Rainer Platz 1", "./img/lennykravitz.jpg", "www.lennykravitz.com/", "Sat, 09.12.2029", "19:30", 47.80)
new Events("Kris Kristofferson", "1150 Wien", "Wiener Stadthalle, Halle F, Roland Rainer Platz 1", "./img/kriskristofferson.jpg", "http://kriskristofferson.com/", "Fr., 15.11.2021.", "20:00", 58.50)
new Events("Lenny Kravitz", "1150 Wien", "Wiener Stadthalle, Halle F, Roland Rainer Platz 1", "./img/lennykravitz.jpg", "www.lennykravitz.com/", "Sat, 09.12.2029", "19:30", 47.80)
//append content to DOM
function displayPlaces (content: Array<any>) {
content.forEach( element => {
$("#places").append(
element.display())
})
}
function displayRestaurants (content: Array<any>) {
content.forEach( element => {
$("#restaurants").append(
element.display())
})
}
function displayEvents (content: Array<any>) {
content.forEach( element => {
$("#events").append(
element.display())
})
}
displayPlaces(places)
displayRestaurants(restaurants)
displayEvents(events)
|
9f9ab63ba4f7bb3a8a2b73965a188e118af57442
|
TypeScript
|
loctong/mapper
|
/packages/core/src/lib/member-map-functions/convert-using.ts
| 2.578125
| 3
|
import type {
Converter,
ConvertUsingFunction,
Dictionary,
Selector,
SelectorReturn,
} from '@automapper/types';
import { TransformationType } from '@automapper/types';
export function convertUsing<
TSource extends Dictionary<TSource> = unknown,
TDestination extends Dictionary<TDestination> = unknown,
TSelectorReturn = SelectorReturn<TDestination>,
TConvertSource = TSource
>(
converter: Converter<TConvertSource, TSelectorReturn>,
value?: Selector<TSource, TConvertSource>
): ReturnType<ConvertUsingFunction<TSource, TDestination, TSelectorReturn>> {
return [
TransformationType.ConvertUsing,
null,
(source) => {
const valueToConvert: TConvertSource = value
? value(source)
: ((source as unknown) as TConvertSource);
return converter.convert(valueToConvert);
},
];
}
|
c52dccfdd8e7aadee5f89252b9914c57a48168cc
|
TypeScript
|
Selbinyyaz/typeScriptPractice
|
/day02/function.ts
| 3.15625
| 3
|
// Parameter type annotation
function greet(name: string) {
console.log("Hello, " + name.toUpperCase() + "!!");
}
|
19f939205fabcfa17e6272ef39ede1c363c83dbb
|
TypeScript
|
AkroutiHamza/BookStoreApp
|
/frontend/src/app/models/Book.ts
| 2.75
| 3
|
import {BookInOrder} from "./BookInOrder";
export class Book {
BookId: number;
author: string;
title: string;
price: number;
BookIcon: string;
releaseDate: string;
stock: number;
bookStatus: number; // 0: onsale 1: offsale
/* createTime: string;
updateTime: string;
*/
constructor(BookInOrder?: BookInOrder) {
if (BookInOrder) {
this.BookId = BookInOrder.BookId;
this.author = BookInOrder.author;
this.title = BookInOrder.title;
this.price = BookInOrder.price;
this.BookIcon=BookInOrder.BookIcon;
this.releaseDate = BookInOrder.releaseDate;
this.stock = BookInOrder.stock;
this.bookStatus = 0;
} else {
this.BookId = 100;
this.author = '';
this.title = '';
this.price = 0;
this.BookIcon='';
this.releaseDate = '10/12/2020';
this.stock = 100;
this.bookStatus = 0;
}
}
}
|
cc0942dc53c13e95a3b5474f372192ab5f364f47
|
TypeScript
|
ltzenteno/my-car-value
|
/src/reports/service/reports.service.ts
| 2.6875
| 3
|
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../users/entity/users.entity';
import { CreateReportDto } from '../dto/create-report.dto';
import { GetEstimateDto } from '../dto/get-estimate-dto';
import { Report } from '../entity/report.entity';
@Injectable()
export class ReportsService {
constructor(@InjectRepository(Report) private reportRepository: Repository<Report>) {}
/**
* Creates and saves a report
* @param {CreateReportDto} dto
* @returns {Promise<Report>}
*/
async create(dto: CreateReportDto, user: User): Promise<Report> {
const entity = this.reportRepository.create(dto);
entity.user = user;
return this.reportRepository.save(entity);
}
async changeApproval(id: string, approved: boolean): Promise<Report> {
// here we are fetching the related user
// check: https://github.com/typeorm/typeorm/blob/master/docs/find-options.md#basic-options
const entity = await this.reportRepository.findOne(id, { relations: ['user'] });
if (!id || !entity) {
throw new NotFoundException('Report not found');
}
entity.approved = approved;
return this.reportRepository.save(entity);
}
/**
* Find reports for the same make and model, within +/- 5 degrees, within 3 years and order by closest mileage
* then return the top 3 closest reports
* @param {GetEstimateDto} dto
* @returns {Promise<Report[]>}
*/
createEstimate({ make, model, lng, lat, year, mileage }: GetEstimateDto): Promise<Report> {
return this.reportRepository.createQueryBuilder()
.select('AVG(price)', 'price')
.where('make like :make', { make: `%${make}%` })
.andWhere('model = :model', { model })
.andWhere('lng - :lng BETWEEN -5 AND 5', { lng })
.andWhere('lat - :lat BETWEEN -5 AND 5', { lat })
.andWhere('year - :year BETWEEN -3 AND 3', { year })
.andWhere('approved IS TRUE')
.orderBy('ABS(mileage - :mileage)', 'DESC')
.setParameters({ mileage })
.limit(3)
.getRawOne<Report>();
}
}
|
9c84338fd5c382220944f160e995ccf3cfc4acb2
|
TypeScript
|
Alarid/Spotify-Browser
|
/src/requests/albums/albums.request.ts
| 2.890625
| 3
|
import api from '../api'
import { SearchAlbumsResponse } from './albums.request.types'
/**
* Perform an album search with Spotify's API
*
* @param {string} search - the query
* @param {number} offset - for pagination
*/
export const searchAlbums = async (
search: string,
offset = 0
): Promise<SearchAlbumsResponse | null> => {
try {
const encodedSearh = encodeURIComponent(search)
const response = await api.get(`search?q=${encodedSearh}&type=album&offset=${offset}`)
return response.data
} catch (error) {
console.error('SEARCH ALBUMS / ', error)
return null
}
}
|
3af9ebf918b67cf01cc1e7814cd066d177979c7d
|
TypeScript
|
kabeleced77/foxfm2
|
/src/Common/Toolkit/SplitString.ts
| 3.40625
| 3
|
import { NumberFromString } from './NumberFromString';
import { Value } from './Value';
export interface ISplitString<T1, T2> {
firstValue(): T1;
secondValue(): T2;
}
export class SplitStringToNumbers implements ISplitString<Number, Number> {
private readonly string: String;
private readonly splitBy: String;
private readonly decimalPoint: String;
constructor(
string: String,
splitBy: String,
decimalPoint: String
) {
this.string = string;
this.splitBy = splitBy;
this.decimalPoint = decimalPoint;
}
public firstValue(): Number {
const splittedString = this.split();
return new NumberFromString(
new Value<String>(splittedString.length >= 1 ? splittedString[0].trim() : ""),
this.decimalPoint).value();
}
public secondValue(): Number {
const splittedString = this.split();
return new NumberFromString(
new Value<String>(splittedString.length >= 2 ? splittedString[1].trim() : ""),
this.decimalPoint).value();
}
private split(): string[] {
return this.string.split(this.splitBy.valueOf());
}
}
|
97f9f358aefc1ed60f7f337986ee541cf16b3110
|
TypeScript
|
dessoya/gravity-modules-ts
|
/Hash/Navigator/3.0/Navigator.ts
| 2.8125
| 3
|
// alias: Navigator
interface MyWindow extends Window {
onhashchange(): void
}
declare var window: MyWindow
/*
fire: -> onHashChange
catch: <- onSectionMatch
*/
export class Navigator extends Manager {
private _currentSection: HashSection = null
getDefaultSection(): HashSection {
return null
}
start() {
let self = this
window.onhashchange = function() {
var hash = window.location.hash
if (hash.length > 0 && hash[0] === '#') hash = hash.substr(1)
if (self._currentSection) {
self._currentSection.deactivate()
self._currentSection = null
}
self.fireEvent('onHashChange', hash)
if (!self._currentSection) {
self._currentSection = self.getDefaultSection()
}
if (self._currentSection) {
self._currentSection.activate()
}
}
window.onhashchange()
}
onSectionMatch(section: HashSection) {
this._currentSection = section
}
}
|
a6ee81f88d80f4e154bb69c369572210d45f7be8
|
TypeScript
|
omariosouto/mvp-devsoutinho
|
/packages/ui/src/components/foundation/Text.ts
| 2.546875
| 3
|
import styled, { css } from 'styled-components';
interface TextProps {
textAlign?: 'center' | 'right' | 'left' | 'justify';
}
const Text = styled.span<TextProps>`
${({ textAlign }) =>
textAlign &&
css`
text-align: ${textAlign};
`}
`;
export default Text;
|
36258283c6d4e3d57ca2a24be71f58230792f9cf
|
TypeScript
|
jitsi/jitsi-meet
|
/react/features/app/reducer.native.ts
| 2.65625
| 3
|
import ReducerRegistry from '../base/redux/ReducerRegistry';
import { _ROOT_NAVIGATION_READY } from '../mobile/navigation/actionTypes';
/**
* Listen for actions which changes the state of the app feature.
*
* @param {Object} state - The Redux state of the feature features/app.
* @param {Object} action - Action object.
* @param {string} action.type - Type of action.
* @returns {Object}
*/
ReducerRegistry.register('features/app', (state: Object = {}, action) => {
switch (action.type) {
case _ROOT_NAVIGATION_READY:
return {
...state,
ready: action.ready
};
default:
return state;
}
});
|
8160736bdfaa3ec07a3e4280327416d7d363575d
|
TypeScript
|
NurimOnsemiro/algorithm_solution
|
/fence_cut/nodejs/index.ts
| 3.171875
| 3
|
/**
* https://www.algospot.com/judge/problem/read/FENCE
* 결과: 208ms
*/
import * as readline from 'readline';
import * as process from 'process';
let rl: readline.Interface = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let input: string[] = [];
class stack_base {
data: number[];
private top: number;
constructor()
{
this.data = [];
this.data.length = 20001;
this.top = 0;
this.data[this.top] = 0;
}
push(value: number)
{
if(this.top === this.data.length - 1){
return;
}
this.top++;
this.data[this.top] = value;
}
front(): number
{
if(this.top === 0){
throw new Error("stack is empty");
}
return this.data[this.top];
}
pop()
{
if(this.top === 0){
throw new Error("stack is empty");
}
this.top--;
}
empty(): boolean
{
if(this.top === 0) return true;
else return false;
}
}
class game_manager{
fenceArr: number[];
numFences: number;
maxSquareSize: number;
constructor()
{
this.numFences = 0;
this.maxSquareSize = 0;
this.fenceArr = [];
}
clear_data()
{
this.fenceArr = [];
this.fenceArr.length = 20001;
this.numFences = 0;
this.maxSquareSize = 0;
}
input_data(fenceStrArr: string[])
{
for(let i=0;i<fenceStrArr.length;i++){
this.fenceArr[i] = Number(fenceStrArr[i]);
}
this.fenceArr[fenceStrArr.length] = 0;
this.numFences = fenceStrArr.length;
}
find_answer()
{
let stk: stack_base = new stack_base();
this.fenceArr[this.numFences] = 0;
for(let i=0;i<=this.numFences;i++){
while(!stk.empty() && this.fenceArr[stk.front()] >= this.fenceArr[i] ){
let pos: number = stk.front()
stk.pop();
let width: number = stk.empty() ? i : (i - stk.front() - 1);
let squareSize: number = width * this.fenceArr[pos];
if(squareSize > this.maxSquareSize){
this.maxSquareSize = squareSize;
}
}
stk.push(i);
}
}
output_data()
{
console.log(this.maxSquareSize);
}
}
function main(): void
{
let numTests: number = 0;
let idx: number = 0;
numTests = Number(input[idx++]);
let gm: game_manager = new game_manager();
while(numTests){
let numFences: number = Number(input[idx++]);
let fecneDataStr: string = input[idx++];
let fenceArr: string[] = fecneDataStr.split(' ');
gm.clear_data();
gm.input_data(fenceArr);
gm.find_answer();
gm.output_data();
numTests--;
}
}
rl.on('line', (line)=>{
input.push(line.trim());
});
rl.on('close', ()=>{
main();
});
|
a708cf3ce7219aa5c761d6565e2d08ab0cf8e22a
|
TypeScript
|
sergefontain/reactHW6-tsThunk
|
/src/store/actions.ts
| 2.625
| 3
|
import { createAction } from "typesafe-actions"
export const setJoke = createAction("SET_JOKE", (data) => data)()
export const setUser = createAction("SET_USER", (data) => data)()
export const loginSuccess = createAction("LOGIN_SUCCESS", (data) => data)()
export const fetchJoke = (chainDispatch: any) => () => {
setTimeout(() => {
fetch("https://icanhazdadjoke.com", {
headers: {
accept: "application/json",
},
})
.then((r) => r.json())
.then((data) => chainDispatch(setJoke(data)))
}, 3000)
}
export const fetchUser = (chainDispatch: any) => () => {
setTimeout(() => {
fetch("https://randomuser.me/api/", {
headers: {
url: "https://randomuser.me/api/",
accept: "application/json",
},
})
.then((r) => r.json())
.then((data) => chainDispatch(setUser(data)))
}, 3000)
}
export const checkLoginPass = (login: string, password: string) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
login === "admin" && password === "123" ? resolve("ok") : reject("wrong")
}, 3000)
})
}
|
5c3b0511dc9e9f1e3b1afb8de2fbc4ce63f5a4c9
|
TypeScript
|
SardineFish/zogra-renderer
|
/zogra-renderer/src/plugins/assets-importer/assets-importer.ts
| 2.640625
| 3
|
import { Asset } from "../../core/asset";
import { GlobalContext } from "../../core/global";
import { AssetImporterPlugin, AssetsPack } from "./types";
export * from "./types";
interface Importers
{
[key: string]: AssetImporterPlugin<any, Asset | AssetsPack>
}
// const importers = {
// img: TextureImporter,
// };
export class AssetsImporter<T extends Importers>
{
private importers: T;
constructor(importers: T)
{
this.importers = importers;
}
async url(url: string, ctx = GlobalContext())
{
const buffer = await fetch(url).then(r => r.arrayBuffer());
return await this.buffer(buffer, ctx);
}
async blob(blob: Blob, ctx = GlobalContext())
{
const buffer = await blob.arrayBuffer();
return await this.buffer(buffer, ctx);
}
async buffer(buffer: ArrayBuffer, ctx = GlobalContext()): Promise<BufferImporter<T>>
{
const bufImporters: BufferImporter<T> = {} as any;
for (const key in this.importers)
{
bufImporters[key] = (options?) => this.importers[key].import(buffer, options, ctx) as any;
}
return bufImporters;
}
}
type BufferImporter<T extends Importers> = {
[key in keyof T]: (options?: Parameters<T[key]["import"]>["1"]) => ReturnType<T[key]["import"]>;
};
// type BufferImporter = { [key in keyof typeof importers]: (options: AssetImportOptions) => Promise<AssetsPack> };
// function createBufferImporter(buffer: ArrayBuffer, ctx = GlobalContext()): BufferImporter
// {
// const wrapper = {} as any;
// for (const importer in importers)
// {
// wrapper[importer] = (options?: AssetImportOptions) => importers[importer as keyof typeof importers].import(buffer, options, ctx);
// }
// return wrapper;
// }
// export const AssetsImporter = {
// importers: importers,
// async url(url: string, ctx = GlobalContext())
// {
// const buffer = await fetch(url).then(r => r.arrayBuffer());
// return createBufferImporter(buffer, ctx);
// },
// async buffer(buffer: ArrayBuffer, ctx = GlobalContext())
// {
// return createBufferImporter(buffer, ctx);
// }
// };
|
a2704592e0694697fcefbfe016a210dad5cbd313
|
TypeScript
|
valdisz/ngrx-lib
|
/reducers/utils.ts
| 3.25
| 3
|
export interface Comparer<T> {
(a: T, b: T): number;
}
export interface EqualityComparer<T> {
(a: T, b: T): boolean;
}
export interface IdSelector<T> {
(value: T): string;
}
export function equalityComparer<T>(a: T, b: T): boolean {
return a === b;
}
export function selectByName(field: string): IdSelector<any> {
return (value: any) => value[field];
}
export function uplift<T>(value: string | T, uplifter: (field: string) => T): T {
return value && typeof value === 'string'
? uplifter(value)
: <T>value;
}
|
f46216ec660da6f513d0f32fc5b8fa4cc4afb926
|
TypeScript
|
micahscopes/davinci-eight
|
/src/davinci-eight/geometries/simplicesToDrawPrimitive.ts
| 2.9375
| 3
|
import copyToArray = require('../collections/copyToArray')
import dataFromVectorN = require('../geometries/dataFromVectorN')
import DrawMode = require('../core/DrawMode')
import simplicesToGeometryMeta = require('../geometries/simplicesToGeometryMeta');
import computeUniqueVertices = require('../geometries/computeUniqueVertices');
import DrawPrimitive = require('../geometries/DrawPrimitive');
import DrawAttribute = require('../geometries/DrawAttribute');
import expectArg = require('../checks/expectArg');
import GeometryMeta = require('../geometries/GeometryMeta');
import Simplex = require('../geometries/Simplex');
import VectorN = require('../math/VectorN');
import Vertex = require('../geometries/Vertex');
function numberList(size: number, value: number): number[] {
let data: number[] = [];
for (var i = 0; i < size; i++) { data.push(value); }
return data;
}
function attribName(name: string, attribMap?: { [name: string]: { name?: string } }): string {
expectArg('name', name).toBeString();
expectArg('attribMap', attribMap).toBeObject();
let meta = attribMap[name];
if (meta) {
let alias = meta.name;
return alias ? alias : name;
}
else {
throw new Error("Unable to compute name; missing attribute specification for " + name);
}
}
function attribSize(key: string, attribMap?: { [key: string]: { size: number } }): number {
expectArg('key', key).toBeString();
expectArg('attribMap', attribMap).toBeObject();
let meta = attribMap[key];
if (meta) {
let size = meta.size;
// TODO: Override the message...
expectArg('size', size).toBeNumber();
return meta.size;
}
else {
throw new Error("Unable to compute size; missing attribute specification for " + key);
}
}
function concat(a: number[], b: number[]): number[] {
return a.concat(b);
}
function simplicesToDrawPrimitive(simplices: Simplex[], geometryMeta?: GeometryMeta): DrawPrimitive {
expectArg('simplices', simplices).toBeObject()
var actuals: GeometryMeta = simplicesToGeometryMeta(simplices);
if (geometryMeta) {
expectArg('geometryMeta', geometryMeta).toBeObject();
}
else {
geometryMeta = actuals;
}
let attribMap = geometryMeta.attributes;
// Cache the keys and keys.length of the specified attributes and declare a loop index.
let keys = Object.keys(attribMap);
let keysLen = keys.length;
var k: number;
// Side effect is to set the index property, but it will be be the same as the array index.
let vertices: Vertex[] = computeUniqueVertices(simplices);
let vsLength = vertices.length;
var i: number;
// Each simplex produces as many indices as vertices.
// This is why we need the Vertex to have an temporary index property.
let indices: number[] = simplices.map(Simplex.indices).reduce(concat, []);
// Create intermediate data structures for output and to cache dimensions and name.
// For performance an array will be used whose index is the key index.
let outputs: { data: number[]; dimensions: number; name: string }[] = [];
for (k = 0; k < keysLen; k++) {
let key = keys[k];
let dims = attribSize(key, attribMap);
let data = numberList(vsLength * dims, void 0);
outputs.push({ data: data, dimensions: dims, name: attribName(key, attribMap) });
}
// Accumulate attribute data in intermediate data structures.
for (i = 0; i < vsLength; i++) {
let vertex = vertices[i]
let vertexAttribs = vertex.attributes;
if (vertex.index !== i) {
expectArg('vertex.index', i).toSatisfy(false, "vertex.index must equal loop index, i");
}
for (k = 0; k < keysLen; k++) {
let output = outputs[k]
let size = output.dimensions
let value: VectorN<number> = vertexAttribs[keys[k]]
if (!value) {
value = new VectorN<number>(numberList(size, 0), false, size)
}
// TODO: Merge functions to avoid creating temporary array.
let data: number[] = dataFromVectorN(value)
copyToArray(data, output.data, i * output.dimensions)
}
}
// Copy accumulated attribute arrays to output data structure.
var attributes: { [name: string]: DrawAttribute } = {};
for (k = 0; k < keysLen; k++) {
let output = outputs[k]
let data = output.data
attributes[output.name] = new DrawAttribute(data, output.dimensions)
}
switch (geometryMeta.k) {
case Simplex.TRIANGLE: {
return new DrawPrimitive(DrawMode.TRIANGLES, indices, attributes)
}
case Simplex.LINE: {
return new DrawPrimitive(DrawMode.LINES, indices, attributes)
}
case Simplex.POINT: {
return new DrawPrimitive(DrawMode.POINTS, indices, attributes)
}
case Simplex.EMPTY: {
// It should be possible to no-op render an EMPTY simplex.
return new DrawPrimitive(DrawMode.POINTS, indices, attributes)
}
default: {
throw new Error("k => " + geometryMeta.k)
}
}
}
export = simplicesToDrawPrimitive
|
e9f95b518c7a26727ff7131d4194f41d90185da6
|
TypeScript
|
Maverick95/challenges
|
/sameNecklace.test.ts
| 3.109375
| 3
|
import same_necklace from './sameNecklace';
describe('Verify functions returns true/false for appropriate values', () => {
test.each([
["nicole", "coneli"],
["abc", "cba"],
["xxyyy", "xxxyy"],
["xyxxz", "xxyxz"],
["x", "xx"],
["x", ""],
["xxx", "yyy"],
])('Strings are NOT cycles of each other - %s %s', (s1, s2) => {
expect(same_necklace(s1, s2)).toEqual(false);
});
test.each([
["nicole", "icolen"],
["nicole", "lenico"],
["aabaaaaabaab", "aabaabaabaaa"],
["", ""],
["x", "x"],
])('Strings are cycles - %s %s', (s1, s2) => {
expect(same_necklace(s1, s2)).toEqual(true);
});
});
|
34bdb415aedde13ce1f3f6057e03dc286f6549e3
|
TypeScript
|
patriciopenamunoz/deno_hipica
|
/src/hipica/models/track.model.ts
| 2.5625
| 3
|
export class TrackModel {
id: string | number;
tipo_pista: string;
cancha: string;
humedad: string;
dureza: string;
rodillo: string;
corte_pasto: string;
rastra: string;
acondicionador: string;
profundidad_de_rastra: string;
constructor(id?: string | number, tipo_pista?: string, cancha?: string, humedad?: string, dureza?: string, rodillo?: string,
corte_pasto?: string, rastra?: string, acondicionador?: string, profundidad_de_rastra?: string) {
this.id = id || -1;
this.tipo_pista = tipo_pista || '';
this.cancha = cancha || '';
this.humedad = humedad || '';
this.dureza = dureza || '';
this.rodillo = rodillo || '';
this.corte_pasto = corte_pasto || '';
this.rastra = rastra || '';
this.acondicionador = acondicionador || '';
this.profundidad_de_rastra = profundidad_de_rastra || '';
}
}
|
781384012caa34f5546ad636e276e34bd8ede74d
|
TypeScript
|
node-projects/hyperion-node
|
/tests/hyperion.test.ts
| 2.796875
| 3
|
import '../src/helper/stringExtensions';
import { HyperionSerializer, HyperionType } from '../src/HyperionDeserializer';
class Temp {
SubArray: [] = [];
}
test('testHyperion', () => {
const st = [254, 1, 0, 254, 0, 0, 3, 0, 0, 0, 8, 1, 0, 0, 0, 4, 2, 8, 3, 0, 0, 0];
let buffer = Buffer.from(st);
let h = new HyperionSerializer();
h.addCustomSerializer<Temp>(1, Temp, [['SubArray', 254]]);
h.addCustomSerializer<Array<object>>(0, Array);
let a = h.deserialize(buffer);
console.log(a);
h.serialize(a);
});
test('testHyperion2', () => {
//var msg = new Test1() { A = 98711111, B = new DateTime(2010, 5, 9), C = Guid.Parse("{A5AC6BA1-4F67-44A6-8B33-BD1F6A5A0DE0}"), D = "Hallo", E = 9.87, F = 88, G = null, H = 88, I = "Test2" };
const st = [254, 0, 0, 71, 54, 226, 5, 0, 0, 0, 0, 0, 0, 197, 179, 33, 189, 204, 8, 0, 161, 107, 172, 165, 103, 79, 166, 68, 139, 51, 189, 31, 106, 90, 13, 224, 6, 72, 97, 108, 108, 111, 61, 10, 215, 163, 112, 189, 35, 64, 88, 0, 0, 0, 0, 2, 88, 0, 0, 0, 0, 0, 0, 0, 6, 84, 101, 115, 116, 50];
let buffer = Buffer.from(st);
let h = new HyperionSerializer();
h.addCustomSerializer(0, Object, [
['A', HyperionType.Int64],
['B', HyperionType.DateTime],
['C', HyperionType.Guid],
['D', HyperionType.String],
['E', HyperionType.Double],
['F', HyperionType.Int32],
['G', HyperionType.Int64, true],
['H', HyperionType.Int64, true],
['I', HyperionType.String]]);
let a = h.deserialize(buffer);
console.log(a);
});
|