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 |
|---|---|---|---|---|---|---|
b0a19bc06bfeeba51eba5ed0e7e3669179d7278f | TypeScript | nullptru/puppeteer-crawl | /src/index.ts | 2.578125 | 3 | import puppeteer from 'puppeteer';
import { cookie, elementsConfig, startPage } from './config';
import { log, error } from './log';
import { createDir, download } from './utils';
class Crawl {
browser: puppeteer.Browser | undefined;
crawlCount = 0;
async init() {
this.browser = await puppeteer.launch(
{ headless: false, devtools: true }
);
log('init', 'init succeed');
}
async run(startPage: string, index: number = 0) {
this.crawlCount = index;
if (!this.browser) return;
const page = await this.browser.newPage();
await page.setCookie(...cookie as any);
await page.setExtraHTTPHeaders({
'x-tt-env': 'sprint/1.8',
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Mobile Safari/537.36'
})
await page.goto(startPage, {
waitUntil: 'networkidle0',
});
await this.handleSinglePage(page);
let res = true;
while(res) {
res = await this.navigateToNext(page);
if (res) {
await this.handleSinglePage(page, this.crawlCount);
}
}
log('run', 'run finished');
await this.clean();
}
private async navigateToNext(page: puppeteer.Page) {
let nextDom;
try {
try {
log('info', `finding next link`);
nextDom = await page.$(elementsConfig.next)
} catch(e) {
if (!nextDom) {
log('info', 'finding first next link');
// first page
nextDom = await page.$(elementsConfig.firstNext);
}
}
if (!nextDom) {
nextDom = await page.$(elementsConfig.firstNext);
if (!nextDom)
throw new Error()
}
await nextDom.click();
await page.waitForSelector(elementsConfig.next);
this.crawlCount++;
return true;
} catch (e) {
error('next dom does not exsit');
return false;
}
}
private async handleSinglePage(page: puppeteer.Page, index = 1) {
const title = (await (await page.$(elementsConfig.title))?.evaluate(node => node.textContent))
.replace(/[|\\/":*?]/g,'').split('-')[0].trim();
const dirPath = `${process.cwd()}\\data\\${index}`;
createDir(dirPath);
// store as png
log('info', `saving data ${title} in ${process.cwd()}\\data/${title}.png`)
await page.screenshot({ path: `${process.cwd()}\\data/${title}.png`, fullPage: true });
log('info', 'saving article imgs')
const imgSrcs = await page.evaluate((config) => {
// return Array.from(document.images, e => e.src);
const content = document.querySelector<HTMLElement>(config.content);
if (content) {
return Array.from(content.querySelectorAll('img'), e => e.src);
}
error(`content is not exsit, check article ${title}`);
return [];
}, elementsConfig);
imgSrcs.filter(src => src.startsWith('https')).forEach((src, idx) => {
download(src, `${dirPath}\\${src.split('/').slice(-1)[0]}`)
})
await page.waitForTimeout(1000);
}
private async clean() {
if (!this.browser) return;
await this.browser.close();
log('close', 'close succeed');
}
}
const crawl = new Crawl();
(async () => {
try {
await crawl.init();
await crawl.run(startPage, 0);
} catch(e) {
error(e);
}
})();
|
9dcddfe132a79e6e543145958ca5b2ad8cd20f50 | TypeScript | chenzhaozheng/express-ts-api | /src/util/util.ts | 3.015625 | 3 | /*
* @Author: chenzhaozheng
* @Date: 2019-12-02 10:17:13
* @LastEditors : chenzhaozheng
* @LastEditTime : 2020-02-05 17:55:31
* @Description: file content
*/
/**
* 加上前缀0
* @param num
* @returns
*/
export const addPreZero = (num: any) => {
if (num < 10){
return '0' + num;
}
return num.toString();
};
/**
* 获取范围内的时间【天】
* @param start_time
* @param end_time
* @returns
*/
export const getEveryDayArr = (start_time: any, end_time: any) => {
let temp_start_time = start_time;
let i = 1;
let data = [start_time];
if (end_time > start_time) {
while (i < 1000){
let next_time = new Date(temp_start_time).setDate(new Date(temp_start_time).getDate() + 1);
let t = new Date(next_time);
temp_start_time = t.getFullYear() + '-' + addPreZero(t.getMonth() + 1) + '-' + addPreZero(t.getDate());
console.log(temp_start_time);
if (new Date(temp_start_time).getTime() > new Date(end_time).getTime()) {
break;
}
data[i] = temp_start_time;
i++;
}
return data;
}
return [];
};
/**
* @param item
* @param size
* @returns {*}
*/
export function chunk(item: any, size: any) {
if (item.length <= 0 || size <= 0){
return item;
}
let chunks = [];
for (let i=0;i<item.length;i=i+size){
chunks.push(item.slice(i, i+size));
}
return chunks;
}
/**
* @param item
* @param num
* @returns {*}
*/
export function split(item: any, num: any) {
if (item.length <= 0){
return item;
}
let groupSize = Math.ceil(item.length / num) ;
return chunk(item, groupSize);
}
/**
* 随机文件名称
* @returns
*/
export function randFileName() {
const t = new Date();
return String(t.getFullYear()) + String(t.getMonth() + 1) + String(t.getSeconds()) + parseInt((Math.random() * 10000000).toString(), 10);
}
export default { addPreZero, split, getEveryDayArr, randFileName };
|
f152b582ac9da204a78436062f86f1509147190a | TypeScript | EddieAbbondanzio/MechanicLog.net | /src/user-system/services/auth/user-credentials.ts | 2.9375 | 3 |
/**
* Login credentials for a user.
*/
export interface UserCredentials {
/**
* The email of the user.
*/
email: string;
/**
* The password of the user.
*/
password: string;
}
|
c867b1797c2e0b14e2d4e9634fc30e97fd525d00 | TypeScript | ZorroLeVrai/Web.PathFinder | /src/controllerMediator.ts | 2.5625 | 3 | import { GridSize } from "./commonTypes";
import GameController from "./Game/gameController";
import SettingsController from "./Settings/settingsContoller";
export default class ControllerMediator
{
constructor(private gameController: GameController, private settingsController: SettingsController)
{
}
public updateGameDisplay = (gridSize: GridSize) =>
{
this.gameController.initGrid(gridSize);
}
public showSettingsForm = () =>
this.settingsController.showSettings();
public disableSettingsControls = (disable: boolean) =>
this.gameController.disableSettingsControls(disable);
} |
147ef566c0c310be9f983c028da0ca9cc731d20a | TypeScript | Mistrall/TypeScript.NET | /System/Collections/IList.ts | 3.046875 | 3 | /*
* @author electricessence / https://github.com/electricessence/
* Licensing: MIT https://github.com/electricessence/TypeScript.NET/blob/master/LICENSE
*/
module System.Collections {
export interface IList<T> extends ICollection<T>
{
/* From ICollection<T>:
count: number;
isReadOnly: boolean;
add(item: T): void;
clear(): number;
contains(item: T): boolean;
copyTo(array: T[], index?: number): void;
remove(item: T): number;
*/
get(index: number): T;
set(index: number, value: T):boolean;
indexOf(item: T): number;
insert(index: number, value: T):void;
removeAt(index: number): void;
}
} |
da76ea877194626f2318af66fa12f908d769f02b | TypeScript | Canxr/Hummer | /tenon/packages/tenon-utils/src/style/transformer/adapter.ts | 3.25 | 3 | /**
* 属性适配,特定场景下增加属性值
* @param style 待转换的Style值
* @param view 组件
*/
import {makeMap} from '../../utils'
const borderRadius = "border-radius,border-top-left-radius,border-top-right-radius,border-bottom-left-radius,border-bottom-right-radius"
const isBorderRadius = makeMap(borderRadius)
export function transformAdapter(style:Record<string, string>){
let tempStyle:Record<string, string> = {
...style
}
tempStyle = hackForBorderRadius(tempStyle);
tempStyle = hackForDefaultFlex(tempStyle);
tempStyle = hackForWhiteSpace(tempStyle);
return tempStyle
}
// HACK: 针对WhiteSpace属性,做属性转换,使用textLineClamp来禁止分行
function hackForWhiteSpace(style:Record<string, string>){
if(style['white-space'] === 'nowrap'){
style['textLineClamp'] = "1";
}
return style
}
// HACK: diplay:flex 中增加flex-direction:row的默认值
function hackForDefaultFlex(style:Record<string, string>){
if(style['display'] === 'flex' && !style['flex-direction']){
style['flex-direction'] = 'row';
}
return style
}
// HACK: iOS中不支持radius 100%,只支持固定宽度
function hackForBorderRadius(style:Record<string, string>){
if(hasSpecialAttr(style, isBorderRadius)){
transformBorderRadius(style);
}
return style
}
/**
* 判断对象中是否包含样式中任一属性
*/
function hasSpecialAttr(obj: Object, func:Function){
return Object.keys(obj).some(key => {
return func(key)
})
}
/**
* 转换Border Radius
* HACK: 处理radius: 100%;iOS不支持的case
* @param style
*/
function transformBorderRadius(style: Record<string, string>){
if(!style.width){
return
}
let [, width, unit] = style.width.split(/([\d\.]+)/);
if(unit === '%'){
return
}
Object.keys(style).forEach(key => {
if(isBorderRadius(key)){
style[key] = getBorderRadius(style[key], {width, unit})
}
})
}
/**
* 计算百分比对应的宽度
*/
function getBorderRadius(value:string, {width,unit}:any){
let [, bPercent, bUnit] = value.split(/([\d\.]+)/);
if(bUnit === '%'){
return (width * parseFloat(bPercent) / 100).toFixed(2) + unit
}
return value
} |
890694288b443e1dc1fcfc986408a30f1f4de550 | TypeScript | goldenhiar/react-native-mmkv | /example/src/Benchmarks.ts | 2.703125 | 3 | import AsyncStorage from '@react-native-async-storage/async-storage';
import { MMKV } from 'react-native-mmkv';
declare global {
var performance: {
now: () => number;
};
}
const storage = new MMKV({ id: 'benchmark' });
export const benchmarkAgainstAsyncStorage = async () => {
console.log('Starting benchmark...');
await AsyncStorage.setItem('test', 'Some test string.');
console.log('wrote test value to AsyncStorage');
storage.set('test', 'Some test string.');
console.log('wrote test value to MMKV');
const iters = 1000;
let value: string | null | undefined = null;
const benchmarkAsyncStorage = async (): Promise<void> => {
const start = global.performance.now();
for (let i = 0; i < iters; i++) {
value = await AsyncStorage.getItem('test');
}
const end = global.performance.now();
console.log(`AsyncStorage: ${end - start}ms for ${iters}x get()`);
};
const benchmarkMMKV = async (): Promise<void> => {
const start = global.performance.now();
for (let i = 0; i < iters; i++) {
value = storage.getString('test');
}
const end = global.performance.now();
console.log(`MMKV: ${end - start}ms for ${iters}x get()`);
};
await benchmarkAsyncStorage();
await benchmarkMMKV();
console.log(`Benchmarks finished. final value: ${value}`);
};
|
6b8e204efa84f66230291f86848e707e034b8287 | TypeScript | faramond/source-master | /patel-ui/src/app/app.ts | 2.5625 | 3 | import {Observable, OperatorFunction, throwError} from 'rxjs';
import {catchError, tap} from 'rxjs/operators';
import {HttpErrorResponse} from '@angular/common/http';
import {FormGroup} from '@angular/forms';
import {environment} from '../environments/environment';
export function scrub(formGroup: FormGroup): any {
const value = formGroup.value;
Object.keys(value).forEach(key => {
if (value.hasOwnProperty(key) && typeof value[key] === 'string' && value[key].trim() === '') {
delete value[key];
}
});
return value;
}
export function transform<T>(context: { clazz: any, method: string }, ...errors: { status: number, message: string, contains?: string }[]): OperatorFunction<T, T> {
return (source$: Observable<T>): Observable<T> => source$.pipe(
tap(next => log(context.clazz).out(context.method, next)),
catchError((httpError: HttpErrorResponse) => {
for (const error of errors) {
if (httpError.status === error.status) {
if (error.contains == null) {
return throwError(error.message);
}
if (httpError.error.messages instanceof Array && httpError.error.messages.includes(error.contains)) {
return throwError(error.message);
}
}
}
return throwError('failed');
})
);
}
export function log(clazz: any) {
return {
construct: () => {
if (!environment.debug) {
return;
}
console.group('construct');
console.count(clazz.constructor.name);
console.groupEnd();
},
info: (...objects: any[]) => {
if (!environment.debug) {
return;
}
console.group(`info ${clazz.constructor.name}`);
objects.forEach(f => console.log(f));
console.groupEnd();
},
warn: (...objects: any[]) => {
console.group(`warn ${clazz.constructor.name}`);
objects.forEach(f => console.warn(f));
console.groupEnd();
},
error: (...objects: any[]) => {
console.group(`error ${clazz.constructor.name}`);
objects.forEach(f => console.error(f));
console.groupEnd();
},
in: (method: string, ...objects: any[]): { clazz: any, method: string } => {
if (environment.debug) {
console.group(`in ${clazz.constructor.name} ${method}`);
objects.forEach(f => console.log(f));
console.groupEnd();
}
return {clazz: clazz, method: method};
},
out: (context: string, ...objects: any[]) => {
if (!environment.debug) {
return;
}
console.group(`out ${clazz.constructor.name} ${context}`);
objects.forEach(f => console.log(f));
console.groupEnd();
}
};
}
|
92a15f41e765bb4495d73086519d679ab3850253 | TypeScript | long2805l2/game_dashboard | /app/frontend/src/app/obj/Admin.ts | 2.625 | 3 | export class Admin
{
readonly domain: string;
public permissions?: any;
constructor (domain: string, permissions?:any)
{
this.domain = domain;
this.permissions = permissions ? permissions : {
// "admin_password": true
// , "admin_permissions": true
// , "admin_list": true
// , "admin_add": true
// , "admin_remove": true
// , "admin_permission": true
// , "player_getUserData": true
};
}
public check (permission:string):boolean
{
let check = this.permissions ? (permission in this.permissions ? this.permissions[permission] : false) : false;
return check;
}
} |
e1be5e869b1aa1ef53824a5a070d736403ef58ca | TypeScript | JohnnyRacket/elysian | /src/ViewObjects/DebugViewObject.ts | 2.625 | 3 | import { Dimensionable } from './../Shared/Dimensionable';
import { DoubleBufferedViewObject } from './DoubleBufferedViewObject';
import { DrawingStrategy } from './../DrawingStrategies/DrawingStrategy';
import { ClickableViewObject } from '../ViewObjects/ClickableViewObject';
import { AttachableViewObject } from './AttachableViewObject';
import { IObservable } from '../Observables/IObservable';
export class DebugViewObject extends ClickableViewObject{
hover() {
throw new Error("Method not implemented.");
}
protected _color: string;
get color(): string{
return this._color;
}
set color(color: string){
this._color = color;
this.render();
}
protected _clickAction: Function = () => {/*do nothing*/}
get clickAction(): Function{
return this._clickAction;
}
set clickAction(func: Function){
this._clickAction = func;
}
public constructor(x: number, y: number, width: number, height: number, angle: number, subject: IObservable, strategy: DrawingStrategy){
super(x,y,width,height,angle,strategy, null);
this.subject = subject;
this.color = "#FF1493";
}
protected render() {
this.context.beginPath();
this.context.fillStyle = this.color;
this.context.rect(0,0,this.width,this.height);
this.context.fill();
}
} |
156e76b47dd1b419240d71839d80b85e16b7d278 | TypeScript | tinyx3k/animeab | /client/src/controller/apis/controller.ts | 2.6875 | 3 |
const baseUrl = "api";
export class ApiController {
static GET_ANIME(
animeKey = "",
stus = 0,
banner = false,
sort = "date",
take = 0,
trend = 0): string {
let url = `${baseUrl}/animes`;
if(animeKey !== "") url += `/${animeKey}`;
else url += `?des=${sort}`;
if(stus > 0) {
url += `&completed=${stus}&take=12`;
}
if(trend > 0) {
url += `&trend=${trend}`
}
if(take > 0) {
url += `&take=${take}`;
}
if(banner) {
url += `&banner=true`
}
return url;
}
static GET_ANIME_FILTER(keyword = ""): string {
let filterApi = ApiController.GET_ANIME();
if(keyword !== ""){
filterApi += `&q=${keyword}`;
}
return filterApi;
}
static GET_EPISODE(animeKey: string, episode = ""): string {
let episodeApis = `${baseUrl}/animes/episodes?id=${animeKey}`;
if(episode !== "")
{
episodeApis += `&episode=${episode}`
}
return episodeApis;
}
static GET_ANIMECATE_OF_ANIMECOLLECT(categoryKey = "", collectionId = ""): string {
let cateOfCollectApi = `${baseUrl}/animes?des=views&des=date&`;
if(categoryKey !== ""){
cateOfCollectApi += `cate=${categoryKey}`;
}
if(collectionId !== ""){
cateOfCollectApi += `collect=${collectionId}`;
}
return cateOfCollectApi;
}
static GET_ANIME_RANK(sort: string):string {
let url = `${baseUrl}/animes?des=${sort}&take=10&completed=3`;
return url;
}
static GET_ANIME_NEW(take = 0):string {
let url = `${baseUrl}/animes?stus=2&des=date&des=views`;
if(take > 0) {
url += `&take=${take}`;
}
return url;
}
static GET_ANIME_OFFER(categoryKey: string, animeKey: string): string {
let url = `api/animes?offer=true&cate=${categoryKey}&id=${animeKey}&random=true&take=17`;
return url;
}
static GET_ANIME_RELATE(categoryKey: string, animeKey: string, sort: string): string {
var url = `/api/animes?cate=${categoryKey}&id=${animeKey}&des=${sort}&take=10&completed=3`;
return url;
}
static UPDATE_VIEW(animeKey: string, animeDetailKey = ""): string {
let viewApi = `${baseUrl}/animes/${animeKey}${animeDetailKey !== "" ? `/${animeDetailKey}/` : '/'}views`;
return viewApi;
}
static GET_CATES(): string {
return `${baseUrl}/categories`
}
static GET_COLLECTES(): string {
return `${baseUrl}/collections`
}
static GET_COMMENTS(animeKey: string, sort = 'lastest'): string {
return `${baseUrl}/comments?id=${animeKey}&sort=${sort}`;
}
static SEND_COMMENT(animeKey: string, link_notify: string = "", receiver: string = ""): string {
let commentApi = `/api/comments?id=${animeKey}`;
if(link_notify !== "" && receiver !== "")
commentApi += `&receiver=${receiver}&link_notify=${link_notify}`;
return commentApi;
}
static REPLY_COMMENT(animeKey: string, user_reply: string): string {
let replyCommentApi = ApiController.GET_COMMENTS(animeKey);
replyCommentApi += `&user_reply=${user_reply}&sort="lastest"`;
return replyCommentApi;
}
static NOTIFY(user_uid: string, notify = "", isCount = false): string {
let notifyApi = `${baseUrl}/notification?user=${user_uid}`;
if(notify !== "")
notifyApi += `¬ify=${notify}`;
if(isCount) {
notifyApi += `&count=true`;
}
return notifyApi;
}
static SERIES(key: string): string {
let url = `${baseUrl}/series/${key}`;
return url;
}
static LIKE_COMMENT(id: string, idComment: string): string {
return `${baseUrl}/likes?id=${id}&idComment=${idComment}`;
}
} |
f1b4bf8a77deb452cfb1bdf7061bde6ba89e73ed | TypeScript | takaaki12353491/scheduler | /client/app/src/modules/storage.ts | 2.828125 | 3 | export const set = (key: string, item: any) => {
localStorage.setItem(key, JSON.stringify(item))
}
export const get = <T>(key: string) => {
let data = localStorage.getItem(key)
if (!data) return null
let obj = JSON.parse(data) as T
return obj
}
export const remove = (key: string) => {
localStorage.removeItem(key)
}
|
e66cebf5853b89ffb180a882174393e4a7750ab6 | TypeScript | reghu-nair/timetrack | /server/src/resolvers/project.ts | 2.640625 | 3 | import { Resolver, Query, Ctx, Arg, Mutation } from "type-graphql";
import { Project } from "../entities/Project";
import { MyContext } from "../types";
@Resolver()
export class ProjectResolver {
@Query(() => [Project])
projects(@Ctx() { em }: MyContext): Promise<Project[]> {
return em.find(Project, {});
}
@Query(() => Project, { nullable: true })
project(@Arg("id") id: number, @Ctx() { em }: MyContext): Promise<Project | null> {
return em.findOne(Project, { id });
}
@Mutation(() => Project)
async createProject(
@Arg("name") name: string,
@Ctx() { em }: MyContext
): Promise<Project> {
const project = em.create(Project, { name });
await em.persistAndFlush(project);
return project;
}
@Mutation(() => Project, { nullable: true })
async updateProject(
@Arg("id") id: number,
@Arg("name", () => String, { nullable: true }) name: string,
@Ctx() { em }: MyContext
): Promise<Project | null> {
const project = await em.findOne(Project, { id });
if (!project) {
return null;
}
if (typeof name !== "undefined") {
project.name = name;
await em.persistAndFlush(project);
}
return project;
}
@Mutation(() => Boolean)
async deleteProject(
@Arg("id") id: number,
@Ctx() { em }: MyContext
): Promise<boolean> {
await em.nativeDelete(Project, { id });
return true;
}
}
|
473ddb8b23305a29b6d71be6fc0cdf6e67537a71 | TypeScript | jeffwu85182/usm | /packages/usm-redux/src/core/reducers.ts | 2.546875 | 3 | import { ActionTypes, Reducer, State, moduleStatuses } from 'usm';
export function getModuleStatusReducer<T>(types: ActionTypes, initialValue: T): Reducer {
return (state = initialValue || moduleStatuses.initial, { type }): State<any> => {
switch (type) {
case types.init:
return moduleStatuses.pending;
case types.reset:
return moduleStatuses.resetting;
case types.initSuccess:
return moduleStatuses.ready;
default:
return state;
}
};
}
|
dd887c7be926ff73a3ec80e7840ec26f119374aa | TypeScript | hejie3920/hejie-all | /个人部分博客文档总结和脚本/index.ts | 3.34375 | 3 | const enum Hejie {
up = 1,
down,
left,
right,
}
enum Type {
a = "A",
b = "B",
}
const enum Direction {
Up = 1,
Down,
Left,
Right,
}
type test = `${Hejie}-Haha`;
type PickFuncProp<T> = {
[P in keyof T]: T[P] extends Function ? P : never;
}[keyof T];
interface tt {
fn: function;
name: string;
age: number;
}
type jin = PickFuncProp<tt>;
|
8f6c2f7ef2ce7a65ec894add9f4a39fd1cdb3d29 | TypeScript | mage/mage-module-maintenance | /src/index.ts | 2.984375 | 3 | import * as fs from 'fs'
import * as http from 'http'
import * as path from 'path'
import * as mage from 'mage'
/**
* Details regarding the current maintenance
*
* @export
* @interface IMaintenanceDetails
*/
export interface IMaintenanceDetails {
start: number
end: number
message: string
}
/**
* Command
*
* @export
* @interface ICommand
*/
export interface ICommand {
name: string
params: { [name: string]: any }
}
/**
* Command batch
*
* @export
* @interface ICommandBatch
*/
export interface ICommandBatch {
req: http.IncomingMessage
commands: ICommand[]
}
/**
* Load all user commands
*
* @export
* @param {*} exports
*/
export function loadUserCommands() {
const userCommands: any = {}
mage.listModules().forEach((moduleName: string) => {
const modulePath = mage.getModulePath(moduleName)
const moduleUserCommandsPath = path.join(modulePath, 'usercommands')
let moduleUserCommandFiles
try {
moduleUserCommandFiles = fs.readdirSync(moduleUserCommandsPath)
} catch (error) {
if (error.code === 'ENOENT') {
return
}
throw error
}
moduleUserCommandFiles.forEach(function (file) {
const userCommandPath = path.join(moduleUserCommandsPath, file)
const pathInfo = path.parse(userCommandPath)
const userCommandName = pathInfo.name
// Skip all files but TypeScript source files
if (pathInfo.ext !== '.ts' && pathInfo.ext !== '.js') {
return
}
userCommands[`${moduleName}.${userCommandName}`] = require(userCommandPath)
})
})
return userCommands
}
// User commands key-value map
const USER_COMMANDS = loadUserCommands()
// Session key
const MAINTENANCE_SESSION_KEY = 'MAINTENANCE_HAS_ACCESS'
/**
* Execute the command hook
*
* This will essentially substitute any user commands
* which is not allowed to execute with a user command
* returning the status of the maintenance instead.
*
* @param {mage.core.IState} state
* @param {*} _data
* @param {ICommandBatch} batch
* @param {IHookCallback} callback
* @memberof AbstractMaintenanceModule
*/
function executeHook(state: mage.core.IState, _data: any, batch: ICommandBatch, callback: () => void) {
batch.commands = batch.commands.map((command) => {
// Whitelist all commands on the maintenance module
if (command.name.substring(0, 12) === 'maintenance.') {
return command
}
// Whitelist commands based on the user's session
if (state.session && state.session.getData(MAINTENANCE_SESSION_KEY)) {
return command
}
// Whitelist commands marked with @OnMaintenance(AllowAccess) decorator
if (USER_COMMANDS[command.name] && USER_COMMANDS[command.name]._OnMaintenance) {
return command
}
// Redirect all other commands to the status error
return { name: 'maintenance.status', params: {}}
})
callback()
}
/**
* OnMaintenance decorator
*
* This will mark the user command as valid or explicitly invalid
*
* @export
* @param {boolean} isAllowed
* @returns
*/
export function OnMaintenance(isAllowed: boolean) {
return function (target: any, key: string = 'execute') {
if (key !== 'execute') {
throw new Error('OnMaintenance must be placed over a user command\'s execute method')
}
target._OnMaintenance = isAllowed
}
}
/**
* Explicitly allow a user command to execute
* during maintenance
*/
export const AllowAccess = true
/**
* Explicitly disallow a user command to execute
* during maintenance
*/
export const DenyAccess = false
/**
* Mark a user as allowed to call user commands
* even during maintenances
*
* @export
* @param {mage.core.IState} state
*/
export function AllowUser(state: mage.core.IState) {
// Todo: create session if does not exist (log in anonymous???)
if (!state.session) {
throw new Error('Session does not exist for user')
}
state.session.setData(MAINTENANCE_SESSION_KEY, true)
}
/**
* Mark a user as not allowed to call user commands
* even during maintenances
*
* By default, this will also throw a maintenance error;
* you may use the shouldThrow parameter to disable this behavior.
*
* @export
* @param {mage.core.IState} state
*/
export function DenyUser(state: mage.core.IState, shouldThrow: boolean = true) {
if (state.session) {
state.session.delData(MAINTENANCE_SESSION_KEY)
}
// todo: review what error we are returning!
if (shouldThrow) {
throw new Error('oh noes maintenance')
}
}
/**
* msgServer reference, and constants for messages
* being broadcasted across the system
*/
const msgServer = mage.core.msgServer
const MAINTENANCE_UPDATE_EVENT = 'maintenance'
const MAINTENANCE_EVENT_START = 'start'
const MAINTENANCE_EVENT_END = 'end'
/**
* Abstract class used to create maintenance modules
*
* @export
* @abstract
* @class AbstractMaintenanceModule
*/
export abstract class AbstractMaintenanceModule {
/**
* You may also access the following helpers directly from
* this module, but we recommend accessing them from the created
* module instead, so to keep your code clear.
*
* @memberof AbstractMaintenanceModule
*/
public OnMaintenance = OnMaintenance
public AllowAccess = AllowAccess
public AllowUser = AllowUser
public DenyUser = DenyUser
/**
* Details object; set during maintenance, null otherwise
*
* @type {IMaintenanceDetails}@memberof AbstractMaintenanceModule
*/
public details?: IMaintenanceDetails
/**
* Whitelisted user commands
*
* By default, all user commands are filtered
* during maintenance; we will push in here
*
* @abstract
* @param {mage.core.IState} state
* @returns {Promise<IMaintenanceDetails>}
* @memberof AbstractMaintenanceModule
*/
/**
* The load method needs to be defined in the inheriting class;
* its role is to read the current maintenance status from
* persistent storage when needed (generally upon starting
* the MAGE server).
*
* @abstract
* @param {mage.core.IState} state
* @returns {IMaintenanceDetails}
* @memberof AbstractMaintenanceModule
*/
public abstract async load(): Promise<IMaintenanceDetails>
/**
* The store method needs to be defined in the inheriting class;
* its role is to store a maintenance message whenever needed, so
* that it may be read from persistent storage whenever needed.
*
* @abstract
* @param {mage.core.IState} state
* @param {IMaintenanceDetails} message
* @returns {string}
* @memberof AbstractMaintenanceModule
*/
public abstract async store(message: IMaintenanceDetails): Promise<void>
/**
* Setup method called when MAGE is initialized
*
* @param {mage.core.IState} state
* @param {Function} callback
* @memberof AbstractMaintenanceModule
*/
public async setup(_state: mage.core.IState, callback: (error?: Error) => void) {
const core: any = mage.core
const cmd: any = core.cmd
// Setup hook
cmd.registerMessageHook('maintenance', executeHook)
// Load current status
this.details = await this.load()
// Cluster communication - reload when we receive a notification
msgServer.getMmrpNode().on(`delivery.${MAINTENANCE_UPDATE_EVENT}`, async ({ messages }) => {
switch (messages[0]) {
case MAINTENANCE_EVENT_START:
this.details = await this.load()
break
case MAINTENANCE_EVENT_END:
this.details = undefined
break
}
})
callback()
}
/**
* Start a maintenance event
*
* @param {IMaintenanceDetails} details
* @memberof AbstractMaintenanceModule
*/
public async start(details: IMaintenanceDetails) {
await this.store(details)
this.notify(MAINTENANCE_EVENT_START)
}
/**
* End the current maintenance
*
* @memberof AbstractMaintenanceModule
*/
public end() {
this.details = undefined
this.notify(MAINTENANCE_EVENT_END)
}
/**
* Returns whether the server is currently under maintenance
*
* @returns
* @memberof AbstractMaintenanceModule
*/
public status() {
return this.details
}
/**
* Broadcast to all nodes the beginning or end of a maintenance
*
* @param message
*/
private notify(message: 'start' | 'end') {
// Notify all servers
const Envelope = msgServer.mmrp.Envelope
const maintenanceUpdate = new Envelope(MAINTENANCE_UPDATE_EVENT, [message])
msgServer.getMmrpNode().broadcast(maintenanceUpdate)
// Notify all users
const state = new mage.core.State()
state.broadcast(`maintenance.${message}`, this.details)
}
}
|
cf5e50603229e2257f2d77fce24d82f33b8edfba | TypeScript | kryz81/typescript-fast-refresh | /src/concepts/discriminated_union/discriminated_union.ts | 4.5625 | 5 | interface Circle {
radius: number;
}
interface Square {
sideLength: number;
}
// shape can be a circle or a square
type Shape = Circle | Square;
// will throw error, because only Circle has radius, but the function expects Shape, which can also be Square
// function getArea(shape: Shape) {
// return Math.PI * shape.radius ** 2;
// }
// Types from type union can have common property, so called "discriminant"
interface MyCirlce {
kind: "mycircle";
radius: number;
}
interface MySquare {
kind: "mysquare";
sideLength: number;
}
type MyShape = MyCirlce | MySquare;
function getArea(shape: MyShape) {
if (shape.kind === "mycircle") {
// TS knows it's a MyCircle here
return Math.PI * shape.radius ** 2;
}
// TS knows it's a MySquare here
if (shape.kind === "mysquare") {
return shape.sideLength ** 2;
}
// additional check
// if a new type will be added to MyShape this will throw an error:
// for example: type MyShape = MyCirlce | MySquare | { kind: "a" };
const check: never = shape;
return check;
}
|
515bf8225c512b6bb888a96daa9c1c2adec3ebd9 | TypeScript | NationalBankBelgium/stark | /packages/stark-rbac/src/modules/authorization/entities/state-permissions.entity.intf.ts | 3.109375 | 3 | import { Ng2StateDeclaration } from "@uirouter/angular";
import { StarkStateRedirection, StarkStateRedirectionFn } from "./state-redirection.intf";
/**
* Describes the content of the `permissions` object to be set inside the `data` property of a Router state configuration
*/
export interface StarkRBACStatePermissions {
/**
* Array of roles that the user must have in order to have permission to navigate to this route
*/
only?: string[];
/**
* Array of roles that the user must not have in order to have permission to navigate to this route
*/
except?: string[];
/**
* The redirection to be performed by the Router in case the user does not have permission to navigate to this route
*/
redirectTo?: StarkStateRedirection | StarkStateRedirectionFn;
}
/* tslint:disable:jsdoc-format */
/**
* Describes a Router state configuration with `data.permissions` defined in order to protect such state(s) with RBAC authorization
* via the {@link StarkRBACAuthorizationService}.
*
* **IMPORTANT:** Although the [Ng2StateDeclaration](https://ui-router.github.io/ng2/docs/latest/interfaces/state.ng2statedeclaration.html) can
* be used to define Router state configurations, it is recommended to use this interface instead because it clearly indicates the intention
* to protect the given state(s) and also enables the IDE to provide code completion and code hinting.
*
```typescript
export const APP_STATES: StarkRBACStateDeclaration[] = [
{
name: "someState",
url: "/someUrl",
component: SomeComponent,
data: {
...
permissions: {
only: ["roleA", "roleB"], // or define 'except' option instead
redirectTo: {
stateName: "anotherState",
params: {...}
}
}
}
},
...
];
```
*/
/* tslint:enable:jsdoc-format */
export interface StarkRBACStateDeclaration extends Ng2StateDeclaration {
/**
* An inherited property to store state data
*
* Child states' `data` object will prototypally inherit from their parent state.
*
* This is the right spot to store RBAC authorization info (`permissions`)
*
* **Note: because prototypal inheritance is used, changes to parent `data` objects reflect in the child `data` objects.
* Care should be taken if you are using `hasOwnProperty` on the `data` object.
* Properties from parent objects will return false for `hasOwnProperty`.**
*/
data: {
permissions: StarkRBACStatePermissions;
[prop: string]: any;
};
}
|
2513fead460cf4bb062a4a1277c72540bfa7c663 | TypeScript | zcong1993/node-delay-queue | /src/logger.ts | 3.34375 | 3 | function toPadStr(num: number, len: number) {
const str = String(num);
const diff = len - str.length;
if (diff <= 0) return str;
return '0'.repeat(diff) + str;
}
function getNowStr() {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const day = now.getDate();
const hour = now.getHours();
const minute = now.getMinutes();
const second = now.getSeconds();
return `${toPadStr(year, 4)}-${toPadStr(month, 2)}-${toPadStr(day, 2)} ${toPadStr(hour, 2)}:${toPadStr(minute, 2)}:${toPadStr(second, 2)}`;
}
class Logger {
private _log(level: 'debug' | 'info' | 'warn' | 'error', message?: any, ...args: any[]) {
if (message && typeof message === 'string') {
console.log(`${getNowStr()} [${level}] ${message}`, ...args);
} else {
console.log(`${getNowStr()} [${level}]`, message, ...args);
}
}
public debug(message?: any, ...args: any[]) {
this._log('debug', message, ...args);
}
public info(message?: any, ...args: any[]) {
this._log('info', message, ...args);
}
public warn(message?: any, ...args: any[]) {
this._log('warn', message, ...args);
}
public error(message?: any, ...args: any[]) {
this._log('error', message, ...args);
}
}
const logger = new Logger();
export default logger;
|
153ccc79380d31debb8b10ae15e1963ff3ad3235 | TypeScript | ornahasson/CoronaInvestigation | /client/src/redux/Airlines/airlineReducer.ts | 2.84375 | 3 | import * as Actions from './airlineActionTypes';
const initialState: Map<number, string> = new Map();
const airlineReducer = (state = initialState, action: Actions.airlinesAction) : Map<number, string> => {
switch (action.type) {
case Actions.SET_AIRLINES: {
return action.payload.airlines
}
default: return state;
}
}
export default airlineReducer;
|
20dd5f0972a435c45f7bb5ea9bbc32afe9929791 | TypeScript | unrealdrake/LParty | /Clients/Web/LP.Clients.Web.Endpoint/Features/Registration/RegistrationPage/RegistrationPage.ts | 2.578125 | 3 | interface IRegistrationPageViewModel {
firstName: string;
lastName: string;
login: string;
password: string;
passwordConfirm: string;
}
function registrationPageViewModel(): IVue {
var registrationPageViewModel = new Vue({
el: '#registration',
data: {
firstName: "",
lastName: "",
login: "",
password: "",
passwordConfirm: ""
},
computed: {
},
methods: {
login: () => {
}
}
});
return registrationPageViewModel;
} |
99f2dae3ecb85a0025be705d79fc7a0a806b54b2 | TypeScript | jokester/toosimple | /lib-ts/util.ts | 3.65625 | 4 | /**
* Methods that convert (err, result)=>void callback to promise
*
* NOTE not working well with overloaded functions
* NOTE not working well with parameter names
*/
export namespace Promisify {
interface CallbackFun1<A1, R> {
(arg1: A1, callback: (err: Error, result: R) => void): void;
}
interface CallbackFun2<A1, A2, R> {
(arg1: A1, arg2: A2, callback: (err: Error, result: R) => void): void;
}
export function toPromise1<A1, R>(fun: CallbackFun1<A1, R>) {
return (arg1: A1) => new Promise<R>((resolve, reject) => {
fun(arg1, (err, result) => {
if (err)
reject(err);
else
resolve(result);
});
});
}
/**
* partial specialization of toPromise1 where R is void
*/
export function toPromise1v<A1>(fun: CallbackFun1<A1, void>) {
return toPromise1(fun);
}
export function toPromise2<A1, A2, R>(fun: CallbackFun2<A1, A2, R>) {
return (arg1: A1, arg2: A2) => new Promise<R>((resolve, reject) => {
fun(arg1, arg2, (err, result) => {
if (err)
reject(err);
else
resolve(result);
});
});
}
/**
* partial specialization of toPromise2 where R is void
*/
export function toPromise2v<A1, A2>(fun: CallbackFun2<A1, A2, void>) {
return toPromise2<A1, A2, void>(fun);
}
}
/**
* Deferred: a wrapper for Promise that exposes fulfill / reject
*/
export class Deferred<T> {
private readonly _promise: Promise<T>;
private readonly _fulfill: (v: T) => void;
private readonly _reject: (e: any) => void;
readonly resolved = false;
constructor(private readonly strict = false) {
const self = this as any;
this._promise = new Promise((fulfill, reject) => {
self._fulfill = (v: T) => {
fulfill(v);
self.resolved = true;
};
self._reject = (e: any) => {
reject(e);
self.resolved = true;
};
});
}
toPromise() {
return this._promise;
}
follow(pv: PromiseLike<T>) {
pv.then(this._fulfill, this._reject);
}
/**
* NOTE v must be a value
* @param v the value
*/
fulfill(v: T) {
if (this.strict && this.resolved) {
throw new Error("already resolved");
} else {
this._fulfill(v);
}
}
reject(e: any) {
if (this.strict && this.resolved) {
throw new Error("already resolved");
} else {
this._reject(e);
}
}
} |
21686e6a3618ee5e0366d5adbb0eb8d890a15fab | TypeScript | Samour/story-guess | /fe-app-manager/src/services/LogInService.ts | 2.546875 | 3 | import { Store } from 'redux';
import { CreateSessionRequest, CreateSessionResponse } from '@story-guess/ts-shared/dtos/session';
import { IState } from '../state';
import { IApiService } from './api/ApiService';
import { ISessionStorageService } from './api/SessionStorageService';
import { userAuthenticatedEvent } from '../events/UserAuthenticatedEvent';
import { logInFormSetUsernameEvent } from '../events/LogInFormSetUsernameEvent';
import { logInFormSetPasswordEvent } from '../events/LogInFormSetPasswordEvent';
import { logInErrorEvent } from '../events/LogInErrorEvent';
export interface ILogInService {
initialise(): void;
logIn(): Promise<void>;
logOut(): Promise<void>;
}
export class LogInService implements ILogInService {
constructor(private readonly store: Store<IState>, private readonly sessionStorageService: ISessionStorageService,
private readonly apiService: IApiService) { }
initialise(): void {
if (this.sessionStorageService.getCurrentSession()) {
this.store.dispatch(userAuthenticatedEvent(true));
}
}
async logIn(): Promise<void> {
this.store.dispatch(logInErrorEvent(false));
const url: URL = await this.apiService.buildUrl('/session');
const { username, password } = this.store.getState().logInForm;
const request: CreateSessionRequest = {
loginId: username,
password,
};
try {
const { sessionId, sessionSecret, token }: CreateSessionResponse = await this.apiService.invoke(url.toString(), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
}, { noAuthentication: true });
this.sessionStorageService.storeSession({ sessionId, sessionSecret }, token);
} catch (e) {
this.store.dispatch(logInErrorEvent(true));
return;
}
this.store.dispatch(userAuthenticatedEvent(true));
this.store.dispatch(logInFormSetUsernameEvent(''));
this.store.dispatch(logInFormSetPasswordEvent(''));
}
async logOut(): Promise<void> {
const url: URL = await this.apiService.buildUrl('/session/logout');
await this.apiService.invoke(url.toString(), { method: 'POST' });
this.sessionStorageService.clearSession();
this.store.dispatch(userAuthenticatedEvent(false));
}
}
|
20eed812f949bd1d31151866167431eeb322b4a7 | TypeScript | rohitbakoliya/bugKira | /server/controllers/user.controller.ts | 2.59375 | 3 | import { Request, Response } from 'express';
import httpStatus from 'http-status-codes';
import { IUser, User } from '../models/User';
import { validateBio, validateName, validateUsername } from '../validators/User.validators';
/**
* @desc all users
* @route GET /api/user/:username
* @access private
*/
export const getAllUsers = async (req: Request, res: Response) => {
const MAX_ITEMS = 10;
const page = req.query.page ? parseInt(req.query.page as string) - 1 : 0;
try {
const users = await User.find({}).select('-password -email').sort('date_joined');
if (!users) return res.status(httpStatus.NOT_FOUND).json({ error: 'No users found!' });
return res.status(httpStatus.OK).json({
totalDocs: users.length,
totalPages: Math.ceil(users.length / MAX_ITEMS),
data: users.slice(MAX_ITEMS * page, MAX_ITEMS * page + MAX_ITEMS),
});
} catch (err) {
console.log(err);
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
error: 'Something went wrong while getting users',
});
}
};
/**
* @desc user info
* @route GET /api/user/:username
* @access private
*/
export const getUserFromUsername = async (req: Request, res: Response) => {
const { error, value: username } = validateUsername(req.params.username);
if (error) {
return res.status(httpStatus.UNPROCESSABLE_ENTITY).json({ error: error.details[0].message });
}
try {
const user = await User.findOne({
username: { $regex: `^${username}$`, $options: 'i' },
}).select('-password');
if (!user)
return res
.status(httpStatus.NOT_FOUND)
.json({ error: `User not found with username ${username}` });
return res.status(httpStatus.OK).json({ data: user });
} catch (err) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ error: `something went wrong` });
}
};
/**
* @desc current user
* @route GET /api/user/me
* @access private
*/
export const getCurrentUser = async (req: Request, res: Response) => {
try {
const { id } = req.user as IUser;
const user = await User.findById(id).select('-password');
if (!user) return res.status(httpStatus.NOT_FOUND).json({ error: 'User not found' });
return res.status(httpStatus.OK).json({ data: user });
} catch (err) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ error: `something went wrong` });
}
};
/**
* @desc update bio
* @route PATCH /api/user/me/bio
* @access private
*/
export const updateBio = async (req: Request, res: Response) => {
const { error, value: bio } = validateBio(req.body.bio);
if (error) {
return res.status(httpStatus.UNPROCESSABLE_ENTITY).json({ error: error.details[0].message });
}
try {
const { id } = req.user as IUser;
const user = await User.findByIdAndUpdate(
id,
{ bio },
{ new: true, useFindAndModify: false }
).select('-password');
if (!user) return res.status(httpStatus.NOT_FOUND).json({ error: 'User not found' });
return res.status(httpStatus.OK).json({ data: user.bio });
} catch (err) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ error: `something went wrong` });
}
};
/**
* @desc update name
* @route PATCH /api/user/me/name
* @access private
*/
export const updateName = async (req: Request, res: Response) => {
const { error, value: name } = validateName(req.body.name);
if (error) {
return res.status(httpStatus.UNPROCESSABLE_ENTITY).json({ error: error.details[0].message });
}
try {
const { id } = req.user as IUser;
const user = await User.findByIdAndUpdate(
id,
{ name },
{ new: true, useFindAndModify: false }
).select('-password');
if (!user) return res.status(httpStatus.NOT_FOUND).json({ error: 'User not found' });
return res.status(httpStatus.OK).json({ data: user.name });
} catch (err) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ error: `something went wrong` });
}
};
|
ec2b564f1f04cceed8a010f81dde4e6c9293c508 | TypeScript | admpresales/uft-one-flight-te-reflection-regression | /uft-one-flight-te-reflection-regression/Action2/Script.mts | 2.875 | 3 | ' View Order
' Viewing the order is not easy. You can't just enter the order number and view it.
' Instead you have to scroll through the orders and use an algorithm - FindOrder - to find it.
OrderNum = 0
ONum = 0
PgDown = 0
RowIndex = 0
Function FindOrder(OrderNum) ' Create the page down and row index for the given order number
ONum = int(OrderNum)
If ONum >= 28 Then ' Created order numbers start at 25 which will appear on the 2nd page, row 6
PgDown = int((ONum - 12) / 8)
RowIndex = ((ONum - 28) mod 8) + 1
msgbox ("ONum = " & ONum & " RowIndex = " & RowIndex & " PgDown = " & PgDown)
Else
PgDown = 1
RowIndex = (ONum mod 7) + 2 ' The first two pages are not purely numeric so we fudge it if it's on those pages
End If
End Function
FindOrder(Parameter("CreatedOrderNum"))
' Choose 4 to View an Existing Reservation
TeWindow("TeWindow").TeScreen("Flight Reservation System").TeField("Select").Set "4"
TeWindow("TeWindow").TeScreen("Flight Reservation System").TeField("Select").SetCursorPos 1
TeWindow("TeWindow").TeScreen("Flight Reservation System").SendKey TE_ENTER
TeWindow("TeWindow").TeScreen("Flight Reservation System").Sync
' Start by entering PF4 to search for the order
TeWindow("TeWindow").TeScreen("FR68 Flights").TeField("0000(protected)").SetCursorPos
TeWindow("TeWindow").TeScreen("FR68 Flights").SendKey TE_PF4
TeWindow("TeWindow").TeScreen("FR68 Flights").Sync
TeWindow("TeWindow").TeScreen("FR77 Sele").TeField("1").SetCursorPos
For i = 1 To PgDown ' Get to the correct page
TeWindow("TeWindow").TeScreen("FR77 Sele").SendKey TE_PF7
TeWindow("TeWindow").TeScreen("FR77 Sele").Sync
Next
' Set x on line that we want to view
riStr = CStr(RowIndex)
TeWindow("TeWindow").TeScreen("FR77 Sele").TeField(riStr).Set "x" @@ hightlight id_;_884_;_script infofile_;_ZIP::ssf2.xml_;_
TeWindow("TeWindow").TeScreen("FR77 Sele").TeField(riStr).SetCursorPos 1 @@ hightlight id_;_884_;_script infofile_;_ZIP::ssf3.xml_;_
' Now view the reservation selected
TeWindow("TeWindow").TeScreen("FR77 Sele").SendKey TE_ENTER @@ hightlight id_;_11645_;_script infofile_;_ZIP::ssf4.xml_;_
TeWindow("TeWindow").TeScreen("FR77 Sele").Sync
' Write viewed order num to Output tab
Print "== Viewed Order Number: " & Parameter("CreatedOrderNum")
Wait 2
' Go back to the main menu
TeWindow("TeWindow").TeScreen("FR68 Flights").SendKey TE_PF3
|
c6eaac92f0c795322d64993cb6e3ae399d8fa004 | TypeScript | davd33/BlablaMovie | /backend/src/users/users.service.ts | 2.5625 | 3 | import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { BlablaUser } from './entities/user.entity';
import { InsertResult, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { LoggedInUser } from './entities/logged-in-users.entity';
import { v4 as uuidv4 } from 'uuid';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(BlablaUser) private userRepo: Repository<BlablaUser>,
@InjectRepository(LoggedInUser) private loggedUserRepo: Repository<LoggedInUser>
) { }
create(createUserDto: QueryDeepPartialEntity<CreateUserDto>): Promise<InsertResult> {
return this.userRepo.insert(createUserDto);
}
findAll(): Promise<BlablaUser[]> {
return this.userRepo.find();
}
findOne(name: string): Promise<BlablaUser> {
return this.userRepo.findOne({
select: ["name", "id"],
where: { name }
});
}
async exists(name: string): Promise<boolean> {
return (await this.userRepo.count({ where: { name } })) === 1;
}
async logout(userName: string, token: string): Promise<any> {
return await this.loggedUserRepo.delete({ token, userName });
}
/**
* If a user exists it, log it in.
*/
async login(userName: string, password: string): Promise<any> {
const loggedInUser = new LoggedInUser();
loggedInUser.token = uuidv4();
loggedInUser.user = await this.userRepo.findOneOrFail({
where: { name: userName, password }
});
const res = await this.loggedUserRepo.insert(loggedInUser);
return {
...res,
token: loggedInUser.token
};
}
/**
* Verify that the user name and the provided token are registered.
*/
async authorized(userName: string, token: string): Promise<boolean> {
return (await this.loggedUserRepo.count({ where: { userName, token } })) === 1;
}
}
|
c6123f5e31ab5ed122dbdd6a01aa2713789e81fc | TypeScript | ananay/iaux | /packages/ia-js-client/src/controllers/item/item.ts | 3.046875 | 3 | import { MetadataService, Metadata } from '../../services/metadata'
import { DetailsService, DetailsResponse } from '../../services/details'
/**
* early prototype of audio file class (will change)
*/
export class AudioFile {
name:string
length:number
track:string
artist:string
sources:Array<{
file:string
type:string // eg mp3
height:string|number
width:string|number
}>
waveformUrl:string
youtubeId:string
spotifyId:string
constructor (file?:any) {
if (file) this.setFromFile(file)
}
setFromFile (file:any) {
// console.log(file)
this.name = file.title
this.track = file.track
this.length = file.length
this.artist = file.artist || ''
let externalIdentifiers:Array<string> = []
switch (typeof file['external-identifier']) {
case 'string':
externalIdentifiers.push(file['external-identifier'])
break
case 'object':
externalIdentifiers.push(...file['external-identifier'])
break
}
externalIdentifiers.forEach((id) => {
if (id.indexOf('urn:youtube') === 0) {
this.youtubeId = id.replace('urn:youtube:', '')
} else if (id.indexOf('urn:spotify') === 0) {
this.spotifyId = id.replace('urn:spotify:track:', '')
}
})
}
}
// Maybe this would abstract a bunch of services
// Using async in most functions, means it might have different strategies
// for fetching data.
export class Item {
readonly identifier:string
private metadataCache:Metadata
private detailsDataCache:DetailsResponse|null
constructor (identifier:string, metadata?:Metadata) {
this.identifier = identifier
this.metadataCache = metadata
this.detailsDataCache = null
}
public async getMetadata ():Promise<Metadata> {
return new Promise<Metadata>(async (resolve, reject) => {
if (this.metadataCache) {
resolve(this.metadataCache)
} else {
let metadataService = new MetadataService()
this.metadataCache = await metadataService.get({identifier: this.identifier})
resolve(this.metadataCache)
}
})
}
public async getMetadataField (field:string, safe:boolean):Promise<Array<any>|null> {
return new Promise<Array<any>|null>(async (resolve, reject) => {
let md = await this.getMetadata()
let value = md.data.metadata[field] || null
if (!value && safe) {
value = [null]
}
resolve(md.data[field] || value)
})
}
public async getDetailsData ():Promise<DetailsResponse> {
return new Promise<DetailsResponse>(async (resolve, reject) => {
if (this.detailsDataCache) {
resolve(this.detailsDataCache)
} else {
let detailsService = new DetailsService()
this.detailsDataCache = await detailsService.get({identifier: this.identifier})
resolve(this.detailsDataCache)
}
})
}
public async getAudioTracks ():Promise<Array<AudioFile>> {
return new Promise<Array<AudioFile>>(async (resolve, reject) => {
let metadata = await this.getMetadata()
let detailsResponse = await this.getDetailsData()
// TODO
let audioFiles = []
if (detailsResponse.jwInitData) {
console.log(detailsResponse.jwInitData)
// parse the audio files
detailsResponse.jwInitData.forEach(jwRow => {
let file = metadata.data.files.reduce((carry, file) => {
if (carry)
return carry
if (file.name == jwRow.orig) {
return file
}
}, null)
let audioFile = new AudioFile(file)
audioFile.name = jwRow.title.replace(/^(\d+\. )/, '')
audioFile.waveformUrl = jwRow.image
audioFile.length = jwRow.duration
console.log('setting sources')
audioFile.sources = jwRow.sources
// TODO get youtubeId and spotifyId from metadata files
// youtubeId:string
// spotifyId:string
audioFiles.push(audioFile)
})
}
resolve(audioFiles)
})
}
} |
6fd80c1d67ad51083a626c4a029e0cccf9e4526b | TypeScript | xiexingen/blog | /docs/note/_demos/core/function/index.ts | 3.390625 | 3 | Function.prototype["myCall"] = function (ctx, ...args) {
// 未传ctx上下文,或者传的是null和undefined等场景
if (!ctx) {
ctx = typeof window !== "undefined" ? window : global;
}
ctx = Object(ctx);
// 生成一个唯一的key
const fnName = Symbol();
// 这里的this就是要调用的函数
ctx[fnName] = this;
// 将args展开,并调用fnname 此时fnName函数内部的this也就是ctx了
const result = ctx[fnName](...args);
// 用完后将fnName从上下文ctx删除
delete ctx[fnName];
// 返回结果
return result;
};
// 注: 与call的区别就是args为数组(不需要展开)
Function.prototype["myApply"] = function (ctx, args = []) {
// 未传ctx上下文,或者传的是null和undefined等场景
if (!ctx) {
ctx = typeof window !== "undefined" ? window : global;
}
ctx = Object(ctx);
// 生成一个唯一的key
const fnName = Symbol();
// 这里的this就是要调用的函数
ctx[fnName] = this;
// 将args展开,并调用fnname 此时fnName函数内部的this也就是ctx了
const result = ctx[fnName](...args);
// 用完后将fnName从上下文ctx删除
delete ctx[fnName];
// 返回结果
return result;
};
Function.prototype["myBind"] = function (ctx, ...args) {
const fn = this;
return function (...innerArgs) {
return fn.myCall(ctx, [...args, ...innerArgs]);
};
};
|
c8f4e222dfdaffc0a5a9f4bc72fae0765dc83c24 | TypeScript | Loki1237/starsbook | /frontend/src/store/AutBar/actions.ts | 2.6875 | 3 | import { AppThunkAction } from '../thunk';
import { Dispatch } from 'redux';
import { toast as notify } from 'react-toastify';
import { history } from '../../middleware';
import { appUserLogIn } from '../../store/App/actions';
import {
AuthAction,
SignUpUserData,
AUTH_LOG_IN_LOADING,
AUTH_SIGN_UP_LOADING,
AUTH_ERROR,
AUTH_RESET_STATE
} from './types';
export const authLogInLoading = (value: boolean): AuthAction => ({
type: AUTH_LOG_IN_LOADING,
logInLoading: value
});
export const authSignUpLoading = (value: boolean): AuthAction => ({
type: AUTH_SIGN_UP_LOADING,
signUpLoading: value
});
export const authError = (value: string): AuthAction => ({
type: AUTH_ERROR,
error: value
});
export const authResetState = (): AuthAction => ({
type: AUTH_RESET_STATE
});
export const logIn = (email: string, password: string): AppThunkAction => {
return async (dispatch: Dispatch) => {
dispatch(authLogInLoading(true));
try {
const response = await fetch('/api/auth/login', {
method: "POST",
headers: {
"Content-Type": "application/json;charser=utf-8"
},
body: JSON.stringify({ email, password })
});
dispatch(authLogInLoading(false));
if (response.status === 200) {
const user = await response.json();
dispatch(appUserLogIn(user.id));
history.push(`/usr/${user.id}`);
} else {
notify.error("Неверно введён email или пароль");
throw Error(`${response.status} - ${response.statusText}`);
}
} catch(e) {
dispatch(authError(e.message));
}
}
}
export const signUp = (data: SignUpUserData): AppThunkAction => {
return async (dispatch: Dispatch) => {
dispatch(authSignUpLoading(true));
try {
const response = await fetch('/api/auth/sign-up', {
method: "POST",
headers: {
"Content-Type": "application/json;charser=utf-8"
},
body: JSON.stringify(data)
});
dispatch(authSignUpLoading(false));
if (response.status === 200) {
notify.success(`Пользователь ${data.firstName} ${data.lastName} успешно зарегестрирован`);
history.push('/auth/sign-in');
} else {
const result = await response.json();
notify.error(result.error);
throw Error(`${response.status} - ${response.statusText}`);
}
} catch(e) {
dispatch(authError(e.message));
}
}
}
|
a873b6e69aff2cc34e64b001bbfbfd6e0755cb0e | TypeScript | usfsoar/purchasing-manager | /src/global.d.ts | 3.421875 | 3 | /**
* All the simple triggers that will run automatically without installation.
* These triggers must have the names provided or they won't be found.
* @see https://developers.google.com/apps-script/guides/triggers
*/
type SimpleTriggers = {
/**
* Runs when a user opens a spreadsheet, document, presentation, or form that
* the user has permission to edit.
* @param e The event object that corresponds to the event.
* Note: If you know for certain that your app will not be used in one of
* Docs, Slides, Sheets, or Forms, you could delete the corresponding type(s)
* to narrow down the type of `e`.
* @template T Provide a more specific type hint for `e` if you know the
* script will only every run in a certain Google Apps file type.
*/
onOpen?: <
T extends
| GoogleAppsScript.Events.DocsOnOpen
| GoogleAppsScript.Events.SlidesOnOpen
| GoogleAppsScript.Events.SheetsOnOpen
| GoogleAppsScript.Events.FormsOnOpen
>(
e: T
) => void;
/**
* Runs when a user changes a value in a spreadsheet.
* Note: Only works in Sheets.
* @param e The event object that corresponds to the event.
*/
onEdit?: (e: GoogleAppsScript.Events.SheetsOnEdit) => void;
/**
* Runs when a user installs an add-on.
* Note: Only works in add-ons.
* @see https://developers.google.com/gsuite/add-ons/overview
* @param e The event object that corresponds to the event.
*/
onInstall?: (e: GoogleAppsScript.Events.AddonOnInstall) => void;
/**
* Runs when a program sends an HTTP POST request to a web app.
* Note: Only works in web apps.
* @see https://developers.google.com/apps-script/guides/web
* @param e The event object that corresponds to the event.
*/
doPost?: (e: GoogleAppsScript.Events.DoPost) => void;
/**
* Runs when a user visits a web app or a program sends an HTTP GET request to a
* web app.
* Note: Only works in web apps.
* @see https://developers.google.com/apps-script/guides/web
* @param e The event object that corresponds to the event.
*/
doGet?: (e: GoogleAppsScript.Events.DoGet) => void;
};
/**
* Installable triggers, which require manual or programmatic registration with
* the app service.
* @see https://developers.google.com/apps-script/guides/triggers/installable
*/
type InstallableTriggers = {
/**
* Any trigger function that will be attached to an installable trigger. You
* must manually register these functions.
* @param e The event object (exact type depends on the trigger).
* @see https://developers.google.com/apps-script/guides/triggers/events
* @template T The type of the event object. Use this to narrow the type of
* `e` to the relevant event.
*/
[key: string]: <
T extends
| GoogleAppsScript.Events.AppsScriptEvent
| GoogleAppsScript.Events.AppsScriptHttpRequestEvent
>(
e: T
) => void;
};
/** Add functions to this object to expose them to Google Apps triggers. */
declare const global: SimpleTriggers & InstallableTriggers;
|
4e584a05a2326f233e7ab130979d35794f575c69 | TypeScript | samsystems/vts | /src/utilities/isNull.ts | 3.78125 | 4 | /**
* Returns val is null or val is undefined or val is NaN
*
* @func
* @sig a -> b)
* @param value
* @return {Function} A Function :: value -> boolean.
* @example
*
* const f =v.isNull(false); => false
*/
export const isNull = (value?: any) => value !== 0 && value !== '' && value !== false && !Boolean(value);
|
c5816da777535502c2b52a7b88d6bf374bb68d48 | TypeScript | jaba0x/yaml-import | /src/get-schema/create-tree.ts | 2.515625 | 3 | import path from 'path';
import yaml from 'js-yaml';
import namify from 'namify';
import getFiles from './get-files';
import read from '~/read';
import { IOptions } from '~/types';
export default function createTree(
file: string,
directory: string,
options: IOptions,
schemas: yaml.Schema[],
recursive?: boolean
): any {
const obj: any = {};
getFiles([file], directory, options, recursive).forEach((item) => {
const content = read(
path.join(item.cwd, item.directory, item.name),
options,
schemas
);
// Get keys
let keys = path.join(item.directory, item.name).split(path.sep);
keys[keys.length - 1] = path.basename(
keys[keys.length - 1],
path.extname(keys[keys.length - 1])
);
keys = keys.map((key) => namify(key));
// Content to obj keys
let objKey = obj;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (!Object.hasOwnProperty.call(objKey, key)) {
objKey[key] = i === keys.length - 1 ? content : {};
}
objKey = objKey[key];
}
});
return obj;
}
|
cd55caf9f2f078701113694d7ef5f9026cffa0e4 | TypeScript | ultrabis/ultrabis | /workspaces/wow-common/src/enums/PlayableRace.ts | 2.515625 | 3 | /**
* Playable races. Taken from Blizzard API.
*/
enum PlayableRace {
Human = 1,
Orc = 2,
Dwarf = 3,
NightElf = 4,
Undead = 5,
Tauren = 6,
Gnome = 7,
Troll = 8
}
export default PlayableRace
|
c77c5a0b4aab99b1984bcb56d1615c7a197c452d | TypeScript | tspayne87/t-box | /modules/server/tests/schemas/index.ts | 2.546875 | 3 | import { Schema, Document } from 'mongoose';
export interface IUser extends Document {
username: string;
password: string;
}
export interface IRole extends Document {
name: string;
description: string;
}
export const User = new Schema<IUser>({
username: String,
password: String
});
export const Role = new Schema<IRole>({
name: String,
description: String
}); |
b85881caa77877eb8a22ca9fff565f8452d251c7 | TypeScript | ChristopherA8/ICOC-Teens | /commands/info/staffroles.ts | 2.609375 | 3 | module.exports = {
name:"staffroles",
execute(msg) {
const { roleMembersCount } = require('../../helper_functions/roleMembersCount.ts');
let staffRoles = [
{ name:"Bug Hunter", count:roleMembersCount("775448648229453865") },
{ name:"Gulag Gamer", count:roleMembersCount("759909786472415273") },
{ name:"Seek Discomfort", count:roleMembersCount("774117150859329586") },
{ name:"Ichiraku Chef", count:roleMembersCount("783864152606638130") },
{ name:"All Nations", count:roleMembersCount("805919361978073139") },
{ name:"Da Boiz ;)", count:roleMembersCount("776221452868648980") },
{ name:"The True Baby ;-;", count:roleMembersCount("776222027723178004") },
{ name:"Frogge Crew", count:roleMembersCount("776275846406340631") }
]
const Discord = require('discord.js');
const embed = new Discord.MessageEmbed()
.setTitle(`**Staff Roles**`);
for (let i = 0; i < staffRoles.length; i++) {
embed.addField(staffRoles[i].name, staffRoles[i].count, true);
}
msg.channel.send(embed);
},
}; |
6db0dc722b985c71fd5f06bffd13f46af8a165ef | TypeScript | opensource-emr/hospital-management-emr | /Code/Websites/DanpheEMR/wwwroot/DanpheApp/src/app/payroll-module/Shared/Payroll-Leave-Category.model.ts | 2.53125 | 3 | import
{NgForm,
FormGroup,
FormControl,
Validators,
FormBuilder,
ReactiveFormsModule
} from '@angular/forms'
export class LeaveCategories{
public LeaveCategoryId:number = 0;
public LeaveCategoryName:string = "";
public Description:string = "";
public CreatedBy: number = 0;
public CreatedOn : string = "";
public ApprovedBy: number = 0;
public IsActive :boolean = false;
public CategoryCode: string ="";
public LeaveCategoryValidator: FormGroup = null;
constructor() {
var _formBuilder = new FormBuilder();
this.LeaveCategoryValidator = _formBuilder.group({
'LeaveCategoryName': ['', Validators.compose([Validators.required, Validators.maxLength(50)])],
'CategoryCode': ['', Validators.compose([Validators.required, Validators.maxLength(30)])],
'Description': ['', Validators.compose([Validators.required, Validators.maxLength(200)])],
});
}
public IsDirty(fieldName): boolean {
if (fieldName == undefined)
return this.LeaveCategoryValidator.dirty;
else
return this.LeaveCategoryValidator.controls[fieldName].dirty;
}
public IsValid():boolean{if(this.LeaveCategoryValidator.valid){return true;}else{return false;}} public IsValidCheck(fieldName, validator): boolean {
if (fieldName == undefined) {
return this.LeaveCategoryValidator.valid;
}
else
return !(this.LeaveCategoryValidator.hasError(validator, fieldName));
}
} |
8158b168713063e68693bef385696cc17cc4d470 | TypeScript | gomberg5264/tfg | /crawler/src/util.ts | 3.234375 | 3 | import { IncomingMessage as httpIncomingMessage } from 'http'
/**
* Generate a numeric hash of a string
* @param str
*/
export function stringHash (str: string): number {
let hash = 5381
let i = str.length
while (i) {
hash = (hash * 33) ^ str.charCodeAt(--i)
}
/* Convert signed int to an unsigned by doing an unsigned bitshift. */
return hash >>> 0
}
/**
* Convert timestamp with ms precision to date in sql format
* @param timestamp
*/
export function timestampToSql (timestamp: number) {
return new Date(timestamp).toISOString().slice(0, 19).replace('T', ' ')
}
/**
* Groups the elements of an array according to the result of "iteratee"
* @param arr
* @param iteratee
*/
export function groupBy<T> (arr: T[], iteratee: (value: T, index: number, arr: T[]) => string) {
let result: { [key: string]: T[] } = {}
arr.forEach((value, index) => {
let key = iteratee(value, index, arr)
if (result.hasOwnProperty(key)) {
result[key].push(value)
} else result[key] = [value]
})
return result
}
/**
* EventLoopDelayAlert is a tool that notifies when a function takes a long time and blocks the event loop.
*/
type hrTime = [number, number]
export class EventLoopDelayAlert {
private stoping = false
constructor (
private interval: number = 300,
private maxDelay: number = 100,
private onDelayAlert: (delay: number) => void) {
}
start () {
if (this.stoping) {
this.stoping = false
return
}
let before = process.hrtime()
let This = this
setTimeout(() => {
const delay = This.getHrDiffTime(before) - This.interval
if (delay > This.maxDelay) {
This.onDelayAlert(delay)
}
This.start()
}, this.interval)
}
stop () {
this.stoping = true
}
private getHrDiffTime (time: hrTime) {
let ts = process.hrtime(time)
// convert seconds & nanoseconds to miliseconds
return ts[0] * 1000 + ts[1] / 1000000
}
}
export function capitalize (str: string) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
}
/**
* @param value String value that you want to convert
* @param decimal String Separator character like ',' or '.', if it is not provided, it is autodetected.
*/
export function parsePrice (value: string | string[], decimal?: string): Number | Number[] {
// Recursively unformat arrays:
if (Array.isArray(value)) {
return value.map(val => parsePrice(val)) as Number[]
}
// Fails silently (need decent errors):
let result = value || 0
// Return the value as-is if it's already a number:
if (typeof result === 'number') {
return result
}
// Detect decimal point separator char
function detectDecimalPointSeparatorChar (val: string): string {
const lastDot = val.lastIndexOf('.')
const lastComma = val.lastIndexOf(',')
if (lastDot === lastComma) {
return ''
}
let numDots = lastDot >= 0 ? (val.match(/\./g) || []).length : 0
let numCommas = lastComma >= 0 ? (val.match(/,/g) || []).length : 0
if (numDots > 2) numDots = 2
if (numCommas > 2) numCommas = 2
const last = lastDot > lastComma ? '.' : ','
/*
0 0 '' | 0 1 ',' | 0 2 '.'
1 0 '.' | 1 1 last | 1 2 last == '.' ? '.' : ''
2 0 ',' | 2 1 last == ',' ? ',' : '' | 2 2 ''
*/
const decimalLookup: { [key: number]: { [key: number]: { [key: string]: string } } } = {
0: { 1: { ',': ',' }, 2: { ',': '.' } },
1: { 0: { '.': '.' }, 1: { '.': '.', ',': ',' }, 2: { '.': '.', ',': '' } },
2: { 0: { '.': ',' }, 1: { '.': '', ',': ',' }, 2: { '.': '', ',': '' } }
}
return decimalLookup[numDots][numCommas][last]
}
if (decimal === undefined) {
decimal = detectDecimalPointSeparatorChar(result)
}
// Build regex to strip out everything except digits, decimal point and minus sign:
let regex = new RegExp('[^0-9\-' + decimal + ']', 'g')
result = result
.replace(/\((?=\d+)(.*)\)/, '-$1') // replace bracketed values with negatives
.replace(regex, '') // strip out any cruft
// make sure decimal point is standard
if (decimal !== '' && decimal !== '.') {
result = result.replace(decimal, '.')
}
result = parseFloat(result)
// This will fail silently which may cause trouble, let's wait and see:
return !isNaN(result) ? result : 0
}
// https://github.com/node-modules/charset/blob/master/index.js
// SEE: https://github.com/bitinn/node-fetch/blob/60cf26c2f3baf566c15632b723664b47f5b1f2db/src/body.js#L230
const CHARTSET_RE = /(?:charset|encoding)\s{0,10}=\s{0,10}['"]? {0,10}([\w\-]{1,100})/i
/**
* Guest data charset from req.headers, xml, html content-type meta tag
* headers:
* 'content-type': 'text/html;charset=gbk'
* meta tag:
* <meta http-equiv="Content-Type" content="text/html; charset=xxxx"/>
* xml file:
* <?xml version="1.0" encoding="UTF-8"?>
*
* @param {Object} obj `Content-Type` String, or `res.headers`, or `res` Object
* @param {Buffer} [data] content buffer
* @param {Number} [peekSize] max content peek size, default is 512
* @return {String} charset, lower case, e.g.: utf8, gbk, gb2312, ....
* If can\'t guest, return null
* @api public
*/
export function charset (obj: String | httpIncomingMessage | Object, data?: Buffer, peekSize?: number) {
let matchs = null
let end = 0
if (data) {
peekSize = peekSize || 512
end = data.length > peekSize ? peekSize : data.length
}
// charset('text/html;charset=gbk')
let contentType = obj
if (contentType && typeof contentType !== 'string') {
let headers: any = obj.hasOwnProperty('headers') ? (obj as httpIncomingMessage).headers : obj
contentType = headers['content-type'] || headers['Content-Type']
}
if (contentType) {
// guest from obj first
matchs = CHARTSET_RE.exec(contentType as string)
}
if (!matchs && end > 0) {
// guest from content body (html/xml) header
contentType = (data as Buffer).slice(0, end).toString()
matchs = CHARTSET_RE.exec(contentType as string)
}
let cs = null
if (matchs) {
cs = matchs[1].toLowerCase()
if (cs === 'utf-8') {
cs = 'utf8'
}
}
return cs
}
|
458544adfe3c0bd64b7db5f31c54a1516e17abd1 | TypeScript | Dennis2512/Musclery-Backend | /examples/orders.ts | 2.71875 | 3 | import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
import { Bestellung } from './models/bestellung.model';
import { BestellungService } from './service/bestellung.service';
const cors = require('cors')({ origin: true });
export function handler(
request: functions.https.Request,
response: functions.Response
): void {
cors(request, response, async () => {
try {
// als erstes wird der requestsender verifiziert
const user: admin.auth.DecodedIdToken = await verify(request);
// es wird nach requestmethod unterschieden
switch (request.method) {
case 'GET':
await getOrders(user, response);
break;
case 'POST':
await createOrder(user, request, response);
break;
default:
// unbekannte requestmethod
response.status(502).send('Unexpected method.');
}
} catch (err) {
response.status(501).send(err);
}
});
}
// hier wird der token aus den headers geholt, der den requestsender verifiziert
export function token(request: functions.https.Request): string {
if (request.headers.authorization?.startsWith('Bearer ')) {
return request.headers.authorization.split('Bearer ')[1];
} else {
return '';
}
}
export function verify(
request: functions.https.Request
): Promise<admin.auth.DecodedIdToken> {
return admin.auth().verifyIdToken(token(request));
}
export async function getOrders(
user: admin.auth.DecodedIdToken,
response: functions.Response
): Promise<void> {
try {
// alle bestellungen des requestsenders holen und schicken
const orders = await admin
.firestore()
.doc('user/' + user.uid)
.collection('bestellungen')
.orderBy('zeitpunkt', 'asc')
.get();
// die rohen daten auf konsistenz prüfen, indem sie hier einmal zu instanzen der klasse bestellung gemacht werden
const bestellungen: Bestellung[] = toBestellung(orders);
response.send({ bestellungen: bestellungen });
} catch (err) {
response.status(504).send(err);
}
}
export function toBestellung(
orders: FirebaseFirestore.QuerySnapshot<FirebaseFirestore.DocumentData>
): Bestellung[] {
const bs: BestellungService = new BestellungService();
const bestellungen: Bestellung[] = [];
if (orders !== null) {
orders.forEach((doc) => {
const data = doc.data();
if (bs.isCompatible(data)) {
bestellungen.push(bs.toBestellung(data));
}
});
}
return bestellungen;
}
export async function createOrder(
user: admin.auth.DecodedIdToken,
request: functions.https.Request,
response: functions.Response
): Promise<void> {
try {
// eine neue bestellung soll aufgegeben werden
if (request.body) {
const bestellung = request.body.bestellung;
// die bestellung wird unverändert in der datenbank gespeichert
const res = await admin
.firestore()
.collection('user/' + user.uid + '/bestellungen')
.add(bestellung);
response.send({ created: res.id });
} else {
response.status(503).send('Bestellung nicht gefunden.');
}
} catch (err) {
response.status(505).send(err);
}
}
|
983d74ee46d22747494032042186a7baf02f432c | TypeScript | jakub-gawlas/nest-todo-api | /src/modules/tasks/tasks.controller.ts | 2.59375 | 3 | import { Response } from '@types/express';
import {
Controller,
Get,
Post,
Res,
Param,
Body,
HttpStatus,
} from '@nestjs/common';
import { TasksService } from './tasks.service';
@Controller('tasks')
export class TasksController {
constructor(
private tasksService: TasksService,
){}
@Get()
async getAllTasks(
@Res() res: Response,
){
const tasks = await this.tasksService.getAll();
res.status(HttpStatus.OK).json(tasks);
}
@Get('/:id')
async getTaskById(
@Res() res: Response,
@Param('id') id: string,
){
const task = await this.tasksService.getById(id);
res.status(HttpStatus.OK).json(task);
}
@Post()
async createTask(
@Res() res: Response,
@Body('description') description: string,
){
const task = await this.tasksService.create(description);
res.status(HttpStatus.CREATED).json(task);
}
}
|
ad0ff41fc8d9e4f86fc9833d4caada76a79eaf29 | TypeScript | hoflish/beagle-web-core | /src/beagle-view/render/styling.ts | 2.578125 | 3 | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import StringUtils from 'utils/string'
import { BeagleUIElement } from 'beagle-tree/types'
type CSS = Record<string, any>
interface BeagleStyle {
size?: Record<string, any>,
position?: Record<string, any> | string,
flex?: Record<string, any> | string,
cornerRadius?: CornerRadiusDataFormat,
margin?: Record<string, any> | string,
padding?: Record<string, any> | string,
positionType?: string,
display?: string,
backgroundColor?: string,
borderWidth?: number,
borderColor?: string,
}
interface CornerRadiusDataFormat {
radius?: number,
topLeft?: number,
topRight?: number,
bottomLeft?: number,
bottomRight?: number,
[key: string]: any,
}
interface HeightDataFormat {
value: number,
type: string,
}
interface EdgeDataFormat {
value: number | string,
type: string,
}
const BEAGLE_STYLE_KEYS = [
'size',
'position',
'flex',
'cornerRadius',
'margin',
'padding',
'positionType',
'display',
'backgroundColor',
'borderWidth',
'borderColor',
]
const UNITY_TYPE: Record<string, string> = {
'REAL': 'px',
'PERCENT': '%',
'AUTO': 'auto',
}
const SINGLE_ATTRIBUTES: Record<string, string> = {
'positionType': 'position',
'backgroundColor': 'backgroundColor',
'display': 'display',
'borderColor': 'borderColor',
}
const EDGE_SPECIAL_VALUES: Record<string, string[]> = {
'all': ['right', 'left', 'top', 'bottom'],
'horizontal': ['right', 'left'],
'vertical': ['top', 'bottom'],
}
const FLEX_PROPERTIES_TO_RENAME: Record<string, string> = {
'grow': 'flexGrow',
'shrink': 'flexShrink',
'basis': 'flexBasis',
}
const SPECIAL_VALUES: Record<string, string> = {
'NO_WRAP': 'nowrap',
}
const EDGE_ORDER: Record<string, boolean> = {
'all': false,
'vertical': false,
'horizontal': false,
'top': false,
'right': false,
'left': false,
'bottom': false,
}
const POSITION_ORDER: Record<string, boolean> = {
'all': false,
'top': false,
'right': false,
'left': false,
'bottom': false,
'vertical': false,
'horizontal': false,
}
function handleAutoAsValue(value: string, parsedUnitType: string) {
return parsedUnitType === UNITY_TYPE.AUTO ? UNITY_TYPE.AUTO : `${value}${parsedUnitType}`
}
function toLowerCase(value: any) {
return typeof value === 'string' ? value.toLowerCase() : value
}
function replace(text: any, value: string, targetValue: string) {
return typeof text === 'string' ? text.replace(value, targetValue) : text
}
function parseValuesWithUnit(unitType: string, value: number) {
const parsedUnitType = UNITY_TYPE[unitType]
if (value === undefined || value === null)
return ''
return handleAutoAsValue(value.toString(), parsedUnitType)
}
function handleAspectRatio(
valueAspectRatio: number | null,
heightData: HeightDataFormat,
): CSS {
if (valueAspectRatio && heightData && heightData.value) {
const value = heightData.value * valueAspectRatio
const valueWithType = parseValuesWithUnit(heightData.type, value)
return { width: valueWithType }
}
return {}
}
function formatSizeProperty(size: BeagleStyle['size']) {
const css: CSS = {}
if (!size || typeof size !== 'object') return css
const keys = Object.keys(size)
let heightData = {} as HeightDataFormat
let valueAspectRatio = null
keys.forEach((key) => {
if (typeof size[key] === 'string') return
if (key !== 'aspectRatio') {
css[key] = parseValuesWithUnit(size[key].type, size[key].value)
if (key === 'height') {
heightData = size[key]
}
} else {
valueAspectRatio = size[key]
}
})
return { ...css, ...handleAspectRatio(valueAspectRatio, heightData) }
}
function handleSpecialPosition(key: string, value: string) {
const parsedNames = EDGE_SPECIAL_VALUES[key]
return parsedNames.reduce((css, name) => ({ ...css, [name]: value }), {})
}
function orderKeys(keys: string[], orderRule: Record<string, boolean>) {
const objectWithOrderRule = { ...orderRule }
keys.forEach((key) => objectWithOrderRule[key] = true)
return Object.keys(objectWithOrderRule).filter((key) => objectWithOrderRule[key])
}
function formatPositionProperty(position: BeagleStyle['position']) {
let css: CSS = {}
if (!position) return css
if (typeof position !== 'object') return { position }
let keys = Object.keys(position)
keys = orderKeys(keys, POSITION_ORDER)
keys.forEach((key) => {
if (typeof position[key] !== 'object') return
const valueWithType = parseValuesWithUnit(position[key].type, position[key].value)
if (Object.keys(EDGE_SPECIAL_VALUES).includes(key)) {
css = { ...css, ...handleSpecialPosition(key, valueWithType) }
} else {
css[key] = valueWithType
}
})
return css
}
function formatFlexAttributes(flex: BeagleStyle['flex']) {
const css: CSS = {}
if (!flex) return css
if (typeof flex !== 'object') return { flex }
const keys = Object.keys(flex)
keys.forEach((key) => {
const attributeName = FLEX_PROPERTIES_TO_RENAME[key] || key
let parsedValue
if (flex[key] && typeof flex[key] === 'object') {
parsedValue = parseValuesWithUnit(flex[key].type, flex[key].value)
}
else {
const hasSpecialValues = SPECIAL_VALUES[flex[key]]
parsedValue = hasSpecialValues ? hasSpecialValues : replace(flex[key], '_', '-')
parsedValue = toLowerCase(parsedValue)
}
css[attributeName] = parsedValue
})
return css
}
function formatCornerRadiusAttributes(cornerRadius: BeagleStyle['cornerRadius']): CSS {
if (!cornerRadius) return {}
const cornerRadiusProps: string[] = ['radius', 'topRight', 'topLeft', 'bottomLeft', 'bottomRight']
let cornerRadiusFormatted: CornerRadiusDataFormat = {}
cornerRadiusProps.forEach((prop, index) => {
cornerRadiusFormatted = {
...cornerRadiusFormatted,
...(Number.isFinite(cornerRadius[prop])
? {
[index === 0 ? 'borderRadius' : `border${prop.charAt(0).toUpperCase() + prop.slice(1)}Radius`]: `${cornerRadius[prop] * 2}px`,
}
: {}),
}
})
return cornerRadiusFormatted
}
function handleSpecialEdge(
key: string,
value: string,
prefixName: string,
): CSS {
if (key === 'all') return { [prefixName]: value }
const parsedNames = EDGE_SPECIAL_VALUES[key]
return parsedNames.reduce((css, name) => {
const cssName = `${prefixName}${StringUtils.capitalizeFirstLetter(name)}`
return { ...css, [cssName]: value }
}, {})
}
function formatBorderStyle(style: BeagleStyle) {
if (style.borderColor || style.borderWidth && !style.hasOwnProperty('borderStyle'))
return { borderStyle: 'solid' }
}
function formatBorderWidthAttributes(style: BeagleStyle['borderWidth']) {
if (style)
return { borderWidth: `${style}px` }
}
function formatEdgeAttributes(style: BeagleStyle, edgeType: 'margin' | 'padding') {
let css: CSS = {}
const edge = style[edgeType]
if (!edge) return css
if (typeof edge !== 'object') return { [edgeType]: edge }
let keys = Object.keys(edge)
keys = orderKeys(keys, EDGE_ORDER)
keys.forEach((key) => {
if (!edge[key] || typeof edge[key] !== 'object') return
const valueWithType = parseValuesWithUnit(edge[key].type, edge[key].value)
if (Object.keys(EDGE_SPECIAL_VALUES).includes(key)) {
css = { ...css, ...handleSpecialEdge(key, valueWithType, edgeType) }
} else {
const edgePosition = `${edgeType}${StringUtils.capitalizeFirstLetter(key)}`
css[edgePosition] = valueWithType
}
})
return css
}
function formatSingleAttributes(beagleStyle: BeagleStyle) {
const keys = Object.keys(beagleStyle) as (keyof BeagleStyle)[]
const singleAttributes = Object.keys(SINGLE_ATTRIBUTES)
return keys.reduce((result, prop) => {
if (!singleAttributes.includes(prop)) return result
const propName = SINGLE_ATTRIBUTES[prop]
return { ...result, [propName]: toLowerCase(beagleStyle[prop]) }
}, {})
}
function formatNonBeagleProperties(beagleStyle: BeagleStyle) {
const keys = Object.keys(beagleStyle) as (keyof BeagleStyle)[]
return keys.reduce((result, key) => (
BEAGLE_STYLE_KEYS.includes(key) ? result : { ...result, [key]: beagleStyle[key] }
), {})
}
function convertToCSS(style: BeagleStyle) {
if (style.hasOwnProperty('position') && !style.hasOwnProperty('positionType')) {
style.positionType = 'relative'
}
let css = formatSizeProperty(style.size)
css = { ...css, ...formatBorderWidthAttributes(style.borderWidth) }
css = { ...css, ...formatBorderStyle(style) }
css = { ...css, ...formatPositionProperty(style.position) }
css = { ...css, ...formatFlexAttributes(style.flex) }
css = { ...css, ...formatCornerRadiusAttributes(style.cornerRadius) }
css = { ...css, ...formatEdgeAttributes(style, 'margin') }
css = { ...css, ...formatEdgeAttributes(style, 'padding') }
css = { ...css, ...formatSingleAttributes(style) }
css = { ...css, ...formatNonBeagleProperties(style) }
return css
}
function convertStyleIdToClass(styleId: string) {
return styleId.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\./g, '-').toLowerCase()
}
function convert(component: BeagleUIElement) {
if (component.style && typeof component.style === 'object') {
component.style = convertToCSS(component.style)
}
if (component.styleId) {
component.styleId = convertStyleIdToClass(component.styleId)
}
}
export default {
convert,
}
|
027ebf1c43a071ad1eb1864bfcc98d1ffd616bd1 | TypeScript | dsehnal/CIFTools.js | /src/Binary/Parser.ts | 2.75 | 3 | /*
* Copyright (c) 2016 - now David Sehnal, licensed under MIT License, See LICENSE file for more info.
*/
namespace CIFTools.Binary {
"use strict";
function checkVersions(min: number[], current: number[]) {
for (let i = 0; i < 2; i++) {
if (min[i] > current[i]) return false;
}
return true;
}
export function parse(data: ArrayBuffer): ParserResult<CIFTools.File> {
const minVersion = [0, 3];
try {
let array = new Uint8Array(data);
let unpacked = MessagePack.decode(array);
if (!checkVersions(minVersion, unpacked.version.match(/(\d)\.(\d)\.\d/).slice(1))) {
return ParserResult.error<CIFTools.File>(`Unsupported format version. Current ${unpacked.version}, required ${minVersion.join('.')}.`);
}
let file = new File(unpacked);
return ParserResult.success(file);
} catch (e) {
return ParserResult.error<CIFTools.File>('' + e);
}
}
} |
fc5880c3a1ae8deb3bd77198f8735505811d985a | TypeScript | linode/manager | /packages/manager/src/features/Firewalls/FirewallDetail/Rules/shared.ts | 3.0625 | 3 | import { APIError } from '@linode/api-v4/lib/types';
import { prop, sortBy } from 'ramda';
export type Category = 'inbound' | 'outbound';
export interface FirewallRuleError {
category: string;
formField: string;
idx: number;
ip?: {
idx: number;
type: string;
};
reason: string;
}
// This is not the most efficient or elegant data structure ever,
// but it makes it easier to test and work with presets without having to .find()
// in multiple places.
export const PORT_PRESETS = {
'22': { label: 'SSH (22)', value: '22' },
'53': { label: 'DNS (53)', value: '53' },
'80': { label: 'HTTP (80)', value: '80' },
'443': { label: 'HTTPS (443)', value: '443' },
'3306': { label: 'MySQL (3306)', value: '3306' },
ALL: { label: 'Allow All', value: '1-65535' },
CUSTOM: { label: 'Custom', value: 'CUSTOM' },
};
export const PORT_PRESETS_ITEMS = sortBy(
prop('label'),
Object.values(PORT_PRESETS)
);
/**
* The API returns very good Firewall error messages that look like this:
*
* {
* "reason": "Must contain only valid IPv4 addresses or networks",
* "field": "rules.inbound[0].addresses.ipv4[0]"
* }
*
* This function parses the "field" into a data structure usable by downstream components.
*/
export const parseFirewallRuleError = (
error: APIError
): FirewallRuleError | null => {
const { field, reason } = error;
if (!field) {
return null;
}
const category = field.match(/inbound|outbound/)?.[0];
const idx = field.match(/\d+/)?.[0];
const formField = field.match(/ports|protocol|addresses/)?.[0];
const ipType = field.match(/ipv4|ipv6/)?.[0];
const ipIdx = field.match(/(ipv4|ipv6)\[(\d+)\]/)?.[2];
if (!category || !idx || !formField) {
return null;
}
const result: FirewallRuleError = {
category,
formField,
idx: +idx,
reason,
};
if (ipType && ipIdx) {
result.ip = {
idx: +ipIdx,
type: ipType,
};
}
return result;
};
/**
* Sorts ports string returned by the API into something more intuitive for users.
* Examples:
* "80, 22" --> "22, 80"
* "443, 22, 80-81" --> "22, 80-81, 443"
*/
export const sortPortString = (portString: string) => {
try {
const ports = portString.split(',');
return ports
.sort(sortString)
.map((port) => port.trim())
.join(', ');
} catch {
// API responses should always work with this logic,
// but in case we get bad input, return the unsorted/unaltered string.
return portString;
}
};
// Custom sort helper for working with port strings
export const sortString = (_a: string, _b: string) => {
const a = Number(stripHyphen(_a));
const b = Number(stripHyphen(_b));
if (a > b) {
return 1;
}
if (a < b) {
return -1;
}
return 0;
};
// If a port range is included (80-1000) return the first element of the range
const stripHyphen = (str: string) => {
return str.match(/-/) ? str.split('-')[0] : str;
};
|
b35d047fb83994dd8166a9e4c53f20f1dca83578 | TypeScript | an-Onion/leetcode | /src/848.shifting-letters.ts | 3.109375 | 3 | /*
* @lc app=leetcode id=848 lang=typescript
*
* [848] Shifting Letters
*/
// @lc code=start
export function shiftingLetters( s: string, shifts: number[] ): string {
let sum = 0;
for( let i = shifts.length-1; i >= 0; i-- ) {
sum = ( sum + shifts[i] ) % 26;
shifts[i] = sum;
}
const ret: string[] = [];
const basic = 'a'.charCodeAt( 0 );
for( let i = 0; i < s.length; ++i ){
const delta = s[i].charCodeAt( 0 ) - basic;
const code = ( delta+shifts[i] ) % 26 + basic;
ret.push( String.fromCharCode( code ) );
}
return ret.join( '' );
}
// @lc code=end
|
8fbb16d5ed2fcc3a610ae0b015e2fd116f327f57 | TypeScript | benjamin0809/xggl | /src/pipes/date/date.ts | 3.28125 | 3 | import { Pipe, PipeTransform } from '@angular/core';
/**
* Generated class for the DatePipe pipe.
*
* See https://angular.io/api/core/Pipe for more info on Angular Pipes.
*/
@Pipe({
name: 'datePipe',
})
export class DatePipe implements PipeTransform {
/**
* Takes a value and makes it lowercase.
*/
transform(value: number, ...args) {
const nowdate = new Date();
let now = nowdate.getTime();
let date = new Date(value);
let month = date.getMonth();
let day = date.getDay();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
console.log(now)
if(value > 0){
let devalue = now - value ;
if(devalue > 0 && devalue < 30 * 1000){
return "刚刚";
}else if(devalue >= 30 * 1000 && devalue < 3 * 60 * 1000){
return "3分钟前"
}else if(devalue >= 3 * 60 * 1000 && devalue < 60 * 60 * 1000){
return hour + ":" + minute + ":" + second;
}else if(devalue >= 3 * 60 * 1000 && devalue < 24 * 60 * 60 * 1000){
return "昨天"
}else if(devalue >= 24 * 60 * 60 * 1000 && devalue < 365 * 24 * 60 * 60 * 1000){
return (month + 1) +"月" + day + "日";
}else {
return "很久以前"
}
}
}
}
|
35acc16b034898c7bbc9cc29f729197e8e326591 | TypeScript | kknshastri/kk-learning-sample01 | /src/app-old-BKP/common/left-sidebar/left-sidebar.component.ts | 2.53125 | 3 | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Store, select } from '@ngrx/store';
@Component({
selector: 'app-left-sidebar',
templateUrl: './left-sidebar.component.html',
styleUrls: ['./left-sidebar.component.scss']
})
export class LeftSidebarComponent implements OnInit, OnDestroy {
name: Observable<string>;
counter: Observable<number>;
secondsInNumber = 0;
seconds: number | string = '00';
minutes: number | string = '00';
hours: number | string = '00';
remainingTime: string = this.hours + ':' + this.minutes + ':' + this.seconds + ' Hours';
clockInterval: any;
constructor(private store: Store<any>) {
this.name = store.pipe(select((s) => s.appState.testName));
this.counter = store.pipe(select('appState', 'testCounter'));
this.secondsInNumber = 3670;
}
ngOnInit() {
this.clockInterval = setInterval(() => this.startClock(), 1000);
this.store.select<any>((state: any) => state)
.subscribe((cs: any) => console.log(cs.appState.testName));
}
ngOnDestroy() {
clearInterval(this.clockInterval);
}
startClock() {
let HH: number | string = 0;
let MM: number | string = 0;
let SS: number | string = 0;
if (this.secondsInNumber >= (60 * 60)) {
HH = Math.floor(this.secondsInNumber / (60 * 60));
MM = Math.floor((this.secondsInNumber % (60 * 60)) / 60);
SS = this.secondsInNumber % 60;
// console.log('HH:MM:SS ===>> ' + HH + ':' + MM + ':' + SS);
} else if (this.secondsInNumber > 60) {
HH = 0;
MM = Math.floor(this.secondsInNumber / 60);
SS = this.secondsInNumber % 60;
// console.log('MM ===>> ' + MM);
} else if (this.secondsInNumber > 0) {
HH = 0;
MM = 0;
SS = this.secondsInNumber;
// console.log('SS ===>> ' + SS);
} else {
HH = 0;
MM = 0;
SS = 0;
// this.remainingTime = '00:00:00 Hours';
console.log('Time Over...');
clearInterval(this.clockInterval);
// alert('Time Over...');
}
HH = (HH < 10) ? ('0' + HH) : HH;
MM = (MM < 10) ? ('0' + MM) : MM;
SS = (SS < 10) ? ('0' + SS) : SS;
this.remainingTime = HH + ':' + MM + ':' + SS + ' Hours';
console.log('Running Clock...');
this.secondsInNumber -= 37;
console.log(this.secondsInNumber);
}
}
|
0bef21e8e5606bedb0cc010c165b19e339ab8b4e | TypeScript | ronyland/visualization | /src/componentsLibrary/Copy/directive.ts | 2.796875 | 3 | import { DirectiveBinding } from 'vue'
import CopyFun from './Copy'
interface CusDom extends HTMLElement {
$value: string
handler: () => void
}
const Copy = {
// 绑定元素的父组件挂载时调用
mounted(el: CusDom, { value }: DirectiveBinding) {
el.$value = value
el.handler = () => {
CopyFun(el.$value)
}
// 绑定点击事件,就是所谓的一键 copy 啦
el.addEventListener('click', el.handler)
},
update(el: CusDom, { value }: DirectiveBinding) {
el.$value = value
},
beforeUnmount(el: CusDom) {
el.removeEventListener('click', el.handler)
},
}
export default Copy
|
ab8b91f50be0677933d4fee6979959c9a35a6871 | TypeScript | lionnnnn/z-ftp | /src/ftp/index.ts | 2.71875 | 3 | /**
* @file ftp 二次封装功能
*/
import { ERROR_CODE, SUCCESS_CODE } from '../const/code';
import FtpNode from 'ftp';
import retry from 'retry';
import Uploader, { IUploader } from '../class/uploader';
import { FtpConnectOptions, OprStatus } from '../type/common';
import { logger } from '../util/log';
export default class Ftp extends Uploader implements IUploader {
private client: FtpNode;
constructor(opt: FtpConnectOptions) {
super(opt);
this.client = new FtpNode();
this.retryOperation = retry.operation({
retries: this.options.retries,
factor: this.options.factor,
minTimeout: this.options.minTimeout
});
this.client.on('ready', () => {
logger.info('ftp 连接成功');
this.emit('ftp:connected');
});
this.client.on('close', () => {
logger.info('ftp 服务关闭');
this.emit('ftp:close');
});
this.client.on('end', () => {
logger.info('ftp 服务结束');
this.emit('ftp:end');
});
this.client.on('error', (err) => {
this.emit('ftp:error', err);
});
}
init(opt) {
// username用来打印日志,连接还是需要user字段
opt.user = opt.username;
super.init(opt);
}
private retryConnect() {
logger.info('正在连接服务器 ------>');
this.client.connect(this.options);
return new Promise((resolve, reject) => {
this.once('connected', () => {
resolve({
code: SUCCESS_CODE
});
});
this.once('error', (err) => {
reject(err);
});
});
}
public connect(): Promise<OprStatus> {
this.retryOperation.attempt((curAttempt) => {
// 如果报错,就进行重新连接
this.retryConnect().then(() => {
return this.options;
}).catch((err) => {
if (this.retryOperation.retry(err)) {
logger.warn(`连接出错,正在尝试再次连接。尝试第${curAttempt}次重新连接`);
return;
}
logger.error(`无法与服务器建立连接!`);
logger.trace(`连接配置:${JSON.stringify(this.options)}`);
});
});
return new Promise((resolve) => {
this.on('connected', () => {
resolve({
code: SUCCESS_CODE,
data: this.options
});
});
});
}
public async delete(file: string): Promise<OprStatus> {
return new Promise((resolve, reject) => {
this.client.delete(file, err => {
if (err) {
logger.error(err);
reject({
code: ERROR_CODE,
error: err
});
}
logger.info(`${file} 文件删除成功`);
this.emit('ftp:delete', file);
resolve({
code: SUCCESS_CODE,
data: file
});
});
})
}
// overwrite
public async put(currentFile: string, remoteFile: string): Promise<OprStatus> {
return new Promise((resolve, reject) => {
this.emit('ftp:uploading', currentFile);
logger.info(`正在上传:${currentFile}`);
this.client.put(currentFile, remoteFile, (err) => {
if (err) {
logger.error(`上传失败:${err}`);
this.emit('ftp:uploadFailure', this.options, err);
reject({
code: ERROR_CODE,
error: err,
msg: `${currentFile} 文件上传失败`
});
}
logger.info(`上传成功:${remoteFile}`);
this.emit('ftp:uploadSuccess', remoteFile);
resolve({
code: SUCCESS_CODE,
data: currentFile
});
})
})
}
/**
* 创建服务器上的文件目录
* @param {String} remote 目录
* @memberof Ftp
*/
public mkdir(remote: string): Promise<OprStatus> {
return new Promise((resolve, reject) => {
this.client.mkdir(remote, (err) => {
if (err?.code === 550) {
logger.warn(`${remote} 目录已存在`);
return resolve({
code: SUCCESS_CODE
});
} else if (err) {
logger.error(err);
reject({
code: ERROR_CODE,
msg: '${remote} 目录创建失败',
error: err
});
}
logger.info(`${remote} 目录创建成功`);
this.emit('ftp:mkdirSuccess');
resolve({
code: SUCCESS_CODE,
data: remote
});
});
});
}
/**
* 查看文件夹文件
* @param r 查看服务器上的指定的文件夹
*/
public async list(r?: string): Promise<OprStatus> {
let root = r ?? this.options.root;
return new Promise((resolve, reject) => {
this.client.list(root, (err, list) => {
if (err) {
logger.error(err);
reject({
code: ERROR_CODE,
error: err
});
}
logger.info(`查看 ${root} 目录`);
this.emit('ftp:viewSuccess', root);
resolve({
code: SUCCESS_CODE,
data: list
});
});
});
}
public async close() {
this.client.end();
}
/**
* 退出登录
*/
public async logout() {
this.client.end();
this.destroy();
}
public onBeforeDestroy() {
this.emit('ftp:beforedestroy');
}
public onDestroyed() {
if (this.client) {
this.client = null;
}
this.emit('ftp:destroy');
}
}
|
eb52fd27195e024f913604a6d61f9055a635502b | TypeScript | dskoogh/game-of-life | /src/app/services/grid-creator.service.ts | 2.5625 | 3 | import { CellHandler } from './cell-handler.service';
import { Cell } from './../model/cell';
import { Grid } from './../model/grid';
import { Injectable } from '@angular/core';
import { flatten } from '@angular/compiler';
@Injectable({
providedIn: 'root'
})
export class GridCreatorService {
constructor(private cellHandler: CellHandler) { }
createGrid(grid: Grid): Array<Cell> {
document.getElementById("mainGrid")
.style
.gridTemplateColumns = this.setWidth(grid.width);
const cells = this.createCells(grid);
this.createHtmlElements(cells, grid);
return cells;
}
private createCells(grid: Grid): Array<Cell> {
const cellsToCreate = grid.height * grid.width;
const cells: Array<Cell> = [];
for (let i = 0; i < cellsToCreate; i++) {
const row: number = Math.floor(i / grid.width);
const cell: Cell = {
id: i,
alive: false,
column: i - (row * grid.width),
row,
survives: undefined
};
cells.push(cell);
}
return cells;
}
private createHtmlElements(cells: Array<Cell>, grid: Grid): void {
const container = document.getElementById("mainGrid");
cells.forEach(cell => {
const div = document.createElement("div");
div.setAttribute("class", "grid-item");
div.setAttribute("id", this.cellHandler.getId(cell));
div.style.height = Math.round(100 / grid.height) + "vh";
container.appendChild(div);
});
}
private setWidth(width: number): string {
let columns = "";
for (let i = 0; i < width; i++) {
columns += "auto ";
}
return columns.trim();
}
}
|
532df5bdfb270d41f8a0b358f26dde531f59e8e0 | TypeScript | ratpeddler/cribbigage | /src/game/rules.ts | 3.125 | 3 | export interface GameRules {
name: string;
players: number;
dealSize: number;
keepSize: number;
dealerExtra: number;
cribExtra: number;
cutSize: number;
pointsToWin: number
}
function createGame(name: string, players: number, dealSize: number, keepSize: number, dealerExtra = 0, cribExtra = 0, cutSize = 1, pointsToWin = 120): GameRules {
// Sanity check the rules
// Crib should be same size as regular hand
const totalDealt = players * dealSize + dealerExtra + cribExtra;
const keptInHand = players * keepSize;
const cribSize = totalDealt - keptInHand;
if (cribSize != keepSize) {
throw `${name}: Crib size should really be the same size as a normal hand! Crib was ${cribSize} hands were ${keepSize}`;
}
return {
name,
players,
dealSize,
keepSize,
dealerExtra,
cribExtra,
cutSize,
pointsToWin
}
}
export const CribBIGage_2Hand = createGame("2 hand CribBIGage", 2, 7, 5, 0, 1);
export const CribBIGage_3Hand = createGame("3 hand CribBIGage", 3, 6, 5, 1, 1);
export const cribbage_2Hand = createGame("2 Player regular cribbage", 2, 6, 4);
export const cribbage_3Hand = createGame("3 Player regular cribbage", 3, 5, 4, 1);
export const GameModes: GameRules[] = [
CribBIGage_2Hand,
CribBIGage_3Hand,
cribbage_2Hand,
cribbage_3Hand,
createGame("60 pt", 2, 7, 5, 0, 1, 1, 40),
]; |
09145d15310a34621bcc3df77248eeda50f2945e | TypeScript | dferrer333/personalFinance | /backend/server/src/main.ts | 2.703125 | 3 | import CSVModel from './model/CSVModel';
import Logger from './utils/Logger';
import Server from './Server';
require('dotenv').config();
async function initializeServer() {
const port: number = getHostPort();
const logger = new Logger();
const model = new CSVModel();
const server = new Server(logger, model, port);
const [certificatePath, keyPath] = getHTTPSPaths();
await server.start(certificatePath, keyPath);
}
function getHostPort(): number {
if (process.env.HOST_PORT === undefined) {
throw getEnvNotSetError('you must set the host port in the' +
' root ".env" file.');
}
const hostPort = parseInt(process.env.HOST_PORT);
if (hostPort !== 3000 && hostPort !== 8000) {
const valueError = new Error('host port must be 3000 or 8000');
valueError.name = 'ValueError';
throw valueError;
}
return hostPort;
}
function getHTTPSPaths() {
if (process.env.HTTPS_PATH === undefined) {
throw getEnvNotSetError('you must set the path to the "https" folder');
}
const httpsPath = process.env.HTTPS_PATH;
return [`${httpsPath}/certificate.pem`, `${httpsPath}/key.pem`];
}
function getEnvNotSetError(message: string) {
const envNotSetError = new Error(message);
envNotSetError.name = 'EnvNotSetError';
return envNotSetError;
}
initializeServer();
|
d4a1c844eb438f5883a01f5cc7e2b5e865de93ac | TypeScript | Apple-Music-Clone/back | /src/lib/orm/query_builder/query_builder.ts | 2.671875 | 3 | import {
QueryExpressionMap,
TableRef,
WhereClause,
WhereClauseCondition,
} from "./query-expression-map";
import { Connection } from "../../../connection/connection.interface";
import { QueryRunner } from "../query_runner/query_runner.interface";
export abstract class QueryBuilder<T = any> {
public expressionMap: QueryExpressionMap;
public parentQueryBuilder: QueryBuilder;
constructor(public connection: Connection, public runner: QueryRunner) {
this.expressionMap = new QueryExpressionMap(this.connection);
}
public select(fields: string[]) {
const qb =
new (require("./select/select_query_builder").SelectQueryBuilder)(
this.connection,
this.runner
);
qb.expressionMap.queryType = "select";
qb.expressionMap.selects = fields.map((field) => ({ selection: field }));
return qb;
}
public insert() {
const qb =
new (require("./insert/insert_query_builder").InsertQueryBuilder)(
this.connection,
this.runner
);
qb.expressionMap.queryType = "insert";
return qb;
}
public update() {
const qb =
new (require("./update/update_query_builder").UpdateQueryBuilder)(
this.connection,
this.runner
);
qb.expressionMap.queryType = "update";
return qb;
}
public delete() {
const qb =
new (require("./delete/delete_query_builder").DeleteQueryBuilder)(
this.connection,
this.runner
);
qb.expressionMap.queryType = "delete";
return qb;
}
protected parameterIndex = 0;
protected createWhereClausesExpression(clauses: WhereClause[]): string {
return clauses
.map((clause, index) => {
const expression = this.createWhereConditionExpression(
clause.condition
);
switch (clause.type) {
case "and":
return (index > 0 ? "AND " : "") + expression;
case "or":
return (index > 0 ? "OR " : "") + expression;
}
return expression;
})
.join(" ")
.trim();
}
protected createWhereConditionExpression(
condition: WhereClauseCondition
): string {
if (typeof condition === "string") {
return condition;
}
if (Array.isArray(condition) && condition.length > 0) {
if (condition.length === 1) {
return this.createWhereClausesExpression(condition);
}
return "(" + this.createWhereClausesExpression(condition) + ")";
}
return this.createWhereClausesExpression([condition as WhereClause]);
}
protected createWhereExpression(): string {
if (this.expressionMap.wheres.length === 0) {
return "";
}
const expressions = this.createWhereClausesExpression(
this.expressionMap.wheres
);
return `WHERE ${expressions} `;
}
public useTransaction(useTransaction = true) {
this.expressionMap.useTransaction = useTransaction;
return this;
}
public hasParameter(paramName: string): boolean {
return (
this.parentQueryBuilder?.hasParameter(paramName) ||
paramName in this.expressionMap.parameters
);
}
public createParameter(value: any) {
let parameterName: string;
do {
parameterName = `orm_${this.parameterIndex++}`;
} while (this.hasParameter(parameterName));
this.setParameter(parameterName, value);
return `:${parameterName}`;
}
public setParameter(key: string, value: any) {
if (this.parentQueryBuilder) {
this.parentQueryBuilder.setParameter(key, value);
}
this.expressionMap.parameters[key] = value;
return this;
}
public setParameters(params: Record<string, any>) {
for (const [key, value] of Object.entries(params)) {
this.setParameter(key, value);
}
return this;
}
public getParameters(): Record<string, any> {
return this.expressionMap.parameters;
}
public getQueryAndParameters(): [string, any[]] {
const query = this.getQuery();
const parameters = this.getParameters();
return this.connection.escapeQueryWithParameters(query, parameters);
}
abstract getQuery(): string;
public async execute() {
const query = this.getQuery();
const params = this.getParameters();
if (this.expressionMap.useTransaction) {
return this.runner.transaction((runner) => runner.query(query, params));
}
return this.runner.query(query, params);
}
}
|
0b5f8a2fc258e103b65b1b4e9bc5108f61f9e609 | TypeScript | WebForFunThailand/css-challenge | /src/data/questions.ts | 2.875 | 3 | interface Question {
id: string;
difficulty: 'e' | 'm' | 'h';
image: string;
defaultHtml: string;
defaultCss: string;
usedPixels: number;
}
const questions: Question[] = [
{
id: `debug-easy1`,
difficulty: `e`,
image: `q0.png`,
defaultHtml: `<div class='debug-question'></div>`,
defaultCss: `.debug-question {\n /* Enter Your CSS Here */\n}`,
usedPixels: 50000,
},
{
id: `debug-easy2`,
difficulty: `e`,
image: `q1.png`,
defaultHtml: `<div class='debug-question2'></div>`,
defaultCss: `.debug-question {\n /* Enter Your CSS Here */\n}`,
usedPixels: 50000,
},
{
id: `debug-medium1`,
difficulty: `m`,
image: `q0.png`,
defaultHtml: `<div class='debug-question'></div>`,
defaultCss: `.debug-question {\n /* Enter Your CSS Here */\n}`,
usedPixels: 50000,
},
{
id: `debug-medium2`,
difficulty: `m`,
image: `q1.png`,
defaultHtml: `<div class='debug-question2'></div>`,
defaultCss: `.debug-question {\n /* Enter Your CSS Here */\n}`,
usedPixels: 50000,
},
{
id: `debug-hard1`,
difficulty: `h`,
image: `q0.png`,
defaultHtml: `<div class='debug-question'></div>`,
defaultCss: `.debug-question {\n /* Enter Your CSS Here */\n}`,
usedPixels: 50000,
},
{
id: `debug-hard2`,
difficulty: `h`,
image: `q1.png`,
defaultHtml: `<div class='debug-question2'></div>`,
defaultCss: `.debug-question {\n /* Enter Your CSS Here */\n}`,
usedPixels: 50000,
},
];
export default questions;
|
fc6a16bbeb5341a60d2784549a76ed18466098ea | TypeScript | gw2efficiency/recipe-calculation | /tests/helpers/recipeItems.spec.ts | 2.75 | 3 | import { recipeItems } from '../../src'
import { RecipeTreeWithCraftFlags } from '../../src/types'
describe('helpers > recipeItems', () => {
it('gets all unique item ids of a recipe tree', () => {
const recipeTree: RecipeTreeWithCraftFlags = {
id: 1,
craft: true,
totalQuantity: 6,
usedQuantity: 6,
quantity: 6,
type: 'Recipe',
output: 1,
min_rating: null,
disciplines: [],
buyPriceEach: 1,
buyPrice: 1,
decisionPrice: 1,
craftResultPrice: 1,
components: [
{
id: 2,
craft: true,
totalQuantity: 6,
usedQuantity: 6,
quantity: 6,
type: 'Recipe',
output: 1,
min_rating: null,
disciplines: [],
buyPriceEach: 1,
buyPrice: 1,
decisionPrice: 1,
craftResultPrice: 1,
components: [
{
id: 3,
craft: false,
totalQuantity: 1,
usedQuantity: 1,
quantity: 1,
type: 'Item',
output: 1,
min_rating: null,
disciplines: [],
buyPriceEach: 1,
buyPrice: 1,
decisionPrice: 1,
craftResultPrice: 1,
},
{
id: 4,
craft: false,
totalQuantity: 1,
usedQuantity: 1,
quantity: 1,
type: 'Item',
output: 1,
min_rating: null,
disciplines: [],
buyPriceEach: 1,
buyPrice: 1,
decisionPrice: 1,
craftResultPrice: 1,
},
{
id: 12,
craft: false,
totalQuantity: 1,
usedQuantity: 1,
quantity: 1,
type: 'Currency',
output: 1,
min_rating: null,
disciplines: [],
buyPriceEach: false,
buyPrice: false,
decisionPrice: false,
craftResultPrice: false,
},
],
},
{
id: 5,
craft: false,
totalQuantity: 1,
usedQuantity: 1,
quantity: 1,
type: 'Item',
output: 1,
min_rating: null,
disciplines: [],
buyPriceEach: 1,
buyPrice: 1,
decisionPrice: 1,
craftResultPrice: 1,
},
{
id: 6,
craft: true,
totalQuantity: 6,
usedQuantity: 6,
quantity: 6,
type: 'Recipe',
output: 1,
min_rating: null,
disciplines: [],
buyPriceEach: 1,
buyPrice: 1,
decisionPrice: 1,
craftResultPrice: 1,
components: [
{
id: 3,
craft: false,
totalQuantity: 1,
usedQuantity: 1,
quantity: 1,
type: 'Item',
output: 1,
min_rating: null,
disciplines: [],
buyPriceEach: 1,
buyPrice: 1,
decisionPrice: 1,
craftResultPrice: 1,
},
],
},
],
}
expect(recipeItems(recipeTree)).toEqual([1, 2, 3, 4, 5, 6])
})
})
|
3b837cd4945f80ebe7f1ccca6519fe2cf0810843 | TypeScript | cuzfrog/palm-game | /ui/src/store/graphic/animation-console-start.ts | 2.921875 | 3 | import { I, O } from "./graphic-types";
import { List } from "immutable";
import { AnimType } from "./anim";
type Anim = import("./anim").Anim;
class ConsoleStartAnimation implements Anim {
private readonly step: number;
constructor(step?: number) {
this.step = step === undefined ? 1 : step;
}
public isCompleted(): boolean {
return this.step >= 3;
}
public advance(): Anim {
let next: Anim;
if (this.isCompleted()) {
next = this;
} else {
next = new ConsoleStartAnimation(this.step + 1);
}
return next;
}
public currentFrame(frameBuffer: Uint8Array): Frame {
switch (this.step) {
case 1:
frameBuffer.fill(O);
break;
case 2:
frameBuffer.fill(I);
break;
case 3:
frameBuffer.fill(O);
break;
}
return List(frameBuffer);
}
get frameInterval(): number {
switch (this.step) {
case 1:
return 200;
case 2:
return 1000;
case 3:
return 200;
default:
throw new Error("Asssertion error: no such step");
}
}
get type(): AnimType {
return AnimType.CONSOLE_START;
}
}
export const InitialConsoleStartAnimation: Anim = new ConsoleStartAnimation();
|
50ee05a7ef15455a9769e11150402f82f49f882e | TypeScript | sintetico82/cube-greenhouse | /src/farmer.ts | 2.640625 | 3 | var sensor = require('node-dht-sensor');
import { Led, Board, Pin, LCD, Sensor } from "johnny-five";
import util from "util";
import cron, { CronJob } from "cron";
import EventEmitter from "events";
import moment from 'moment';
import * as fs from 'fs';
class FarmerData {
public static readonly FILE_NAME = "cube-greenhouse-data.json";
public lightStartTime: string | undefined;
public lightEndTime: string | undefined;
constructor() { }
}
export class Farmer extends EventEmitter {
private data: FarmerData = new FarmerData();
private board: Board;
private readonly TEMP_HUMIDITY_PIN: number = 4; // GPIO4
private readonly LIGHT_PIN: number = 22;//GPIO6
private readonly LIGHT_HOUR_START: number = 20;
private readonly LIGHT_HOUR_END: number = 25;
private readonly FAN_PIN: number = 24; // GPIO19
private readonly WATER_PIN: number = 2; // GPIO27
private light = new Led(this.LIGHT_PIN); //GPIO6
private pinFan = new Pin(this.FAN_PIN); // GPIO19
private lcd = new LCD({ controller: "PCF8574" });
private waterSensor = new Pin({ pin: this.WATER_PIN, type: "digital" });
private isWaterIn: boolean = false;
private isLightOn: boolean = false;
private isFanOn: boolean = false;
private jobCheckTheLight: CronJob;
constructor(board: Board) {
super();
let t = this;
this.board = board;
let light = this.light;
let pinFan = this.pinFan;
let lcd = this.lcd;
this.board.on("exit", function () {
light.off();
pinFan.low();
lcd.off();
// @ts-ignore
lcd.noBacklight();
});
this.jobCheckTheLight = this.checkTheLightJob();
this.jobCheckTheLight.start();
this.lcd.on();
// @ts-ignore
this.lcd.backlight();
this.lcd.useChar("duck");
this.lcd.useChar("box2");
this.lcd.print("Cube Greenhouse ");
this.loadState(() => {
this.displayDataInfo()
});
}
checkTheLightJob(): CronJob {
let t = this;
return new cron.CronJob({
cronTime: '*/30 * * * * *',
runOnInit: true,
onTick: function () {
if (t.data.lightStartTime && t.data.lightEndTime) {
let start = moment(t.data.lightStartTime,"HH:mm");
let end = moment(t.data.lightEndTime,"HH:mm");
moment().isBetween(start, end) ? t.lightOn() : t.lightOff();
t.emit("light", t.isLightOn);
}
}
});
}
checkWater(callback?: Function) {
let t = this;
this.waterSensor.read(function (err, data) {
if (!err) {
t.isWaterIn = data > 0;
t.emit("water", t.isWaterIn);
if (callback)
callback(t.isWaterIn);
t.lcd.cursor(0, 15);
t.isWaterIn ? t.lcd.print(":duck:") : t.lcd.print(" ");
} else {
console.error(err);
}
})
}
checkTemperature(callback?: Function) {
let t = this;
let lcd = this.lcd;
// Read from GPIO4
sensor.read(22, this.TEMP_HUMIDITY_PIN, function (err: any, temperature: number, humidity: number) {
if (!err) {
t.emit("temperature", { temperature: temperature.toFixed(2), humidity: temperature.toFixed(2) });
if (callback)
callback({ temperature: temperature.toFixed(2), humidity: temperature.toFixed(2) })
lcd.cursor(1, 0);
lcd.print(util.format("T:%s:box2: H:%s %", temperature.toFixed(1), humidity.toFixed(1)));
}
});
}
lightOn(callback?: Function) {
this.light.on();
this.isLightOn = true;
this.emit("light", this.isLightOn);
}
lightOff(callback?: Function) {
this.light.off();
this.isLightOn = false;
this.emit("light", this.isLightOn);
}
getLightStatus(callback: Function) {
callback(this.isLightOn);
}
fanOn(callback?: Function) {
this.pinFan.high();
this.isFanOn = true;
this.emit("fan", this.isFanOn);
}
fanOff(callback?: Function) {
this.pinFan.low();
this.isFanOn = false;
this.emit("fan", this.isFanOn);
}
setLightTime(start: string, end: string) {
this.data.lightStartTime = moment(start, "HH:mm").isValid() ? start : undefined;
this.data.lightEndTime = moment(end, "HH:mm").isValid() ? end : undefined;
this.saveState();
this.displayDataInfo();
}
displayDataInfo() {
if (this.data.lightStartTime && this.data.lightEndTime ) {
this.lcd.clear();
this.lcd.cursor(0, 0);
this.lcd.print(util.format("L:%s-%s ", this.data.lightStartTime, this.data.lightEndTime));
}
}
saveState() {
var json = JSON.stringify(this.data);
fs.writeFile('cube-greenhouse-data.json', json, 'utf8', (err) => {
if (err) {
console.error(err)
}
});
}
loadState(callback?: Function) {
let t = this;
fs.exists(FarmerData.FILE_NAME, function (r: boolean) {
if (r) {
fs.readFile(FarmerData.FILE_NAME, 'utf8', function readFileCallback(err, data) {
if (err) {
console.error(err);
} else {
t.data = JSON.parse(data);
if (callback)
callback();
}
});
}
});
}
getStartTime() {
if (this.data.lightStartTime)
return this.data.lightStartTime;
else
return null;
}
getEndTime() {
if (this.data.lightEndTime)
return this.data.lightEndTime;
else
return null;
}
} |
d690eac99530fae9df0375deec431856bea2b6d1 | TypeScript | doYoungAn/chart | /lib/piechart.ts | 2.734375 | 3 | import * as d3 from 'd3';
interface IPiechartData {
[key: string]: number;
}
export interface IPiechartConfig {
element: HTMLElement;
data: IPiechartData
margin?: number;
strokeColor?: string;
strokeWidth?: number;
textColor?: string;
textSize?: number | string;
baseOpacity?: number;
strongOpacity?: number;
animationDuration?: number;
scaleSize?: number;
}
const Piechart = (config: IPiechartConfig) => {
const {
element,
data,
margin = 40,
strokeColor = '#000000',
strokeWidth = 2,
textColor = '#000000',
textSize = 20,
baseOpacity = 0.6,
strongOpacity = 1,
animationDuration = 300,
scaleSize = 1.05
} = config;
const width: number = element.clientWidth;
const height: number = element.clientHeight;
const radius: number = Math.min(width, height) / 2 - margin;
const svg = d3.select(element)
.append('svg')
.attr('width', width)
.attr('height', height)
const parentGEl = svg
.append('g')
.attr('transform', `translate(${width / 2}, ${height / 2})`)
const color = d3.scaleOrdinal()
.domain(data as any)
.range(d3.schemeSet3)
const pie: d3.Pie<any, any> = d3
.pie()
.value((d: any) => d.value)
const dataReady: d3.PieArcDatum<{key: string, value: number}>[] = pie(d3.entries(data));
const arcGenerator: d3.Arc<any, d3.DefaultArcObject> = d3
.arc()
.innerRadius(0)
.outerRadius(radius);
// 파이 부분들
const partEls = parentGEl
.selectAll('whatever')
.data(dataReady)
.enter()
.append('path')
.attr('d', arcGenerator as any)
.attr('fill', (d: d3.PieArcDatum<{key: string, value: number}>) => {
return color(d.data.key) as string;
})
.attr('stroke', strokeColor)
.style('stroke-width', strokeWidth)
.style('opacity', baseOpacity);
// 파이 이벤트
partEls
.on('mouseover', (d) => {
const targetEl = partEls.filter((obj) => obj.data.key === d.data.key);
partEls.style('opacity', baseOpacity);
targetEl
.transition()
.duration(animationDuration)
.attr('transform', `scale(${scaleSize})`)
.style('opacity', strongOpacity);
})
.on('mouseleave', (d) => {
partEls
.transition()
.duration(animationDuration)
.attr('transform', `scale(${1})`)
.style('opacity', baseOpacity);
});
// 파이에 나오는 텍스트
const textEls = parentGEl
.selectAll('whatever')
.data(dataReady)
.enter()
.append('text')
.text((d: d3.PieArcDatum<{key: string, value: number}>) => {
return d.data.key;
})
.attr('transform', (d: d3.PieArcDatum<{key: string, value: number}>) => {
return `translate(${arcGenerator.centroid(d as any)})`
})
.attr('fill', textColor)
.style('text-anchor', 'middle')
.style('font-size', textSize)
// 텍스트 이벤트
textEls
.on('mouseover', (d) => {
const targetEl = partEls.filter((obj) => obj.data.key === d.data.key);
partEls.style('opacity', baseOpacity);
targetEl
.transition()
.duration(animationDuration)
.attr('transform', `scale(${scaleSize})`)
.style('opacity', strongOpacity);
})
.on('mouseleave', (d) => {
partEls
.transition()
.duration(animationDuration)
.attr('transform', `scale(${1})`)
.style('opacity', baseOpacity);
});
};
export default Piechart;
|
cf9c184630a5e0c9cd75ec4e52d9e3514a38eeb5 | TypeScript | stardazed/sd-streams | /packages/streams-compression/src/decompression-stream.ts | 2.84375 | 3 | /*
streams-compression/decompression-stream - transform stream expanding compressed data
Part of Stardazed
(c) 2019-Present by @zenmumbler
https://github.com/stardazed/sd-streams
*/
import { Inflater } from "@stardazed/zlib";
const decContext = Symbol("decContext");
const decTransform = Symbol("decTransform");
class DecompressionTransformer implements Transformer<BufferSource, Uint8Array> {
private inflater_: Inflater;
constructor(inflater: Inflater) {
this.inflater_ = inflater;
}
transform(chunk: BufferSource, controller: TransformStreamDefaultController<Uint8Array>) {
if (!(chunk instanceof ArrayBuffer || ArrayBuffer.isView(chunk))) {
throw new TypeError("Input data must be a BufferSource");
}
const buffers = this.inflater_.append(chunk);
for (const buf of buffers) {
controller.enqueue(buf);
}
}
flush(_controller: TransformStreamDefaultController<Uint8Array>) {
const result = this.inflater_.finish();
if (! result.success) {
if (! result.complete) {
throw new Error("Unexpected EOF during decompression");
}
if (result.checksum === "mismatch") {
throw new Error("Data integrity check failed");
}
if (result.fileSize === "mismatch") {
throw new Error("Data size check failed");
}
throw new Error("Decompression error");
}
}
}
export class DecompressionStream {
private [decContext]: Inflater;
private [decTransform]: TransformStream<BufferSource, Uint8Array>;
constructor(format: string) {
if (format !== "deflate" && format !== "gzip") {
throw new TypeError("format must be one of `deflate`, `gzip`");
}
this[decContext] = new Inflater();
this[decTransform] = new TransformStream(new DecompressionTransformer(this[decContext]));
}
get readable() {
return this[decTransform].readable;
}
get writable() {
return this[decTransform].writable;
}
}
|
eb7545f33bed668ce568b252804806f774d34fef | TypeScript | DefinitelyTyped/DefinitelyTyped | /types/array-rearrange/index.d.ts | 3.421875 | 3 | // Type definitions for array-rearrange 2.2
// Project: https://github.com/dfcreative/array-rearrange#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = reorder;
/**
* Reorder elements within array by index. Mutates original array in-place.
*
* @param array The array to shuffle.
* @param index The indexes according to which to shuffle elements in `array`. Should contain unique indexes.
* @param [stride=1] Indicate groups of elements to shuffle.
*
* @example
* import reorder = require('array-rearrange')
*
* const arr = reorder([9,8,7,6], [3,2,1,0]) // [6,7,8,9]
* const arr2 = reorder([3,3, 2,2, 1,1], [2,1,0]) // [1,1, 2,2, 3,3]
*/
declare function reorder<TArr extends MutableArrayLike<unknown>>(
array: TArr,
index: MutableArrayLike<number>,
stride?: number,
): TArr;
interface MutableArrayLike<T> {
length: number;
[n: number]: T;
}
|
eb1f74f998bf0bd8a0040e0940d89bb930656cbe | TypeScript | ianwremmel/clark | /src/lib/version.spec.ts | 2.96875 | 3 | import {assert} from 'chai';
import {select} from './version';
describe('version', () => {
describe('select()', () => {
it('selects the greater of two compatible semver ranges', () => {
[
['^1.0.0', '^1.1.0', '^1.1.0'],
['^1.1.0', '^1.0.0', '^1.1.0'],
['~1.3.0', '^1.1.0', '^1.3.0'],
['~1.0.0', '~1.0.1', '~1.0.1'],
['^1.0.0', '1.1.0', '^1.1.0'],
].forEach(([left, right, correct]) => {
assert.equal(
select(left, right),
correct,
`the greater of [${left}, ${right}] is ${correct}`,
);
});
});
it('selects the only version specified if the other is null', () => {
[['^1.1.0', null, '^1.1.0'], [null, '^1.1.0', '^1.1.0']].forEach(
([left, right, correct]) => {
assert.equal(select(left, right), correct);
},
);
});
it('selects the more permissive of two compatible semver ranges', () => {
[
['~1.1.0', '^1.0.0', '^1.1.0'],
['^1.0.0', '~1.1.0', '^1.1.0'],
['^1.0.0', '~1.3.0', '^1.3.0'],
['^1.4.0', '~1.4.0', '^1.4.0'],
['^1.4.10', '~1.4.20', '^1.4.20'],
].forEach(([left, right, correct]) => {
assert.equal(
select(left, right),
correct,
`the more permissive of [${left}, ${right}] is ${correct}`,
);
});
});
it('throws if semver ranges are not compatible', () => {
[
['1.0.0', '2.0.0'],
['~1.0.0', '^1.1.0'],
['^0.1.0', '^0.0.1'],
['~0.1.0', '~0.2.0'],
['^1.3.0', '~1.1.0'],
].forEach(([left, right]) => {
assert.throws(
() => select(left, right),
`"${left}" and "${right}" are not compatible`,
);
});
assert.throws(
() => select(null, null),
'Cannot select a version from "null" and "null"',
);
});
});
});
|
1b2330e69bd2ab898879834d2b623f0988d1d999 | TypeScript | Innolize/twitter-front | /src/common/IAxios.ts | 2.609375 | 3 | import axios from 'axios'
import { store } from '../redux/store'
import { User } from '../types/User'
export const axiosI = axios.create({
baseURL: process.env.REACT_APP_BACKEND_URL,
withCredentials: true
})
axiosI.interceptors.request.use(function (config) {
const token = store.getState().authReducer.token
const currentToken = config.headers.Authorization
if (token && (`Bearer ${token}` !== currentToken)) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
interface RefreshReponse {
user: User,
message?: string,
access_token: string
}
axiosI.interceptors.response.use((response) => {
return response
}, async function (err) {
const originalRequest = err.config;
if (err.response.status === 401 && !originalRequest._retry) {
console.log("estoy refresheando token")
originalRequest._retry = true;
const refreshResponse: RefreshReponse = (await axiosI.post('/auth/refresh')).data
store.dispatch({ type: "REFRESH_TOKEN", payload: refreshResponse.access_token })
originalRequest.headers.Authorization = `Bearer ${refreshResponse.access_token}`
return axiosI(originalRequest)
} else {
return Promise.reject(err)
}
}) |
30eb8f3d13fdeb5a22226cd7583d69491bf669db | TypeScript | pixore/pixore | /src/utils/__tests__/Color.spec.ts | 2.78125 | 3 | import {
toHsl,
toHsv,
create,
createHsv,
createHsl,
fromHsl,
fromHsv,
fromHex,
} from '../Color';
test('toHsl', () => {
expect(toHsl(create(21, 105, 172))).toEqual(createHsl(207, 78, 38));
expect(toHsl(create(255, 0, 0))).toEqual(createHsl(0, 100, 50));
});
test('toHsv', () => {
expect(toHsv(create(21, 105, 172))).toEqual(createHsv(207, 88, 67));
expect(toHsl(create(255, 0, 0))).toEqual(createHsl(0, 100, 50));
});
test('fromHsl', () => {
const expected = create(21, 104, 172);
const hsl = createHsl(207, 78, 38);
expect(fromHsl(hsl)).toEqual(expected);
});
test('fromHsv', () => {
const expected = create(224, 142, 121);
const hsv = createHsv(12, 46, 88);
expect(fromHsv(hsv)).toEqual(expected);
});
test('fromHex', () => {
expect(fromHex('#909EDD')).toEqual(create(144, 158, 221));
expect(fromHex('#FFE091')).toEqual(create(255, 224, 145));
});
|
5324e2dd1ff39c27204f87a114d55d4cd30bff44 | TypeScript | abellaismail7/gas-station-electron | /src/local/users.ts | 2.515625 | 3 | import { UserI } from "@/types/User"
import Knex, { QueryBuilder } from "knex";
const electron = window.require("electron");
const db: Knex = electron.remote.getGlobal("$db");
const userdb: QueryBuilder = db("users");
export default class UserRepository {
async insert(user: UserI) {
const res = await userdb.insert(user)
if (!res) {
throw new Error(res)
}
user.id = await this.getLastId(db)
return res
}
update(user: UserI) {
return userdb.where('id', user.id).update(user)
}
del(user: UserI) {
if (!user.id)
return {
success: false,
msg: "can't delete IDless user"
}
return userdb.where("id", user.id,).del()
}
getAt(offset: number, limit: number) {
return userdb
.offset(offset * limit)
.orderBy('created_at', 'desc')
.limit(limit)
}
all() { userdb.select("*") }
async getLastId(_db: Knex) {
const idRes = await _db.raw("SELECT last_insert_rowid() as id")
return idRes[0]["id"]
}
};
|
449ffc0476be6ca7977554683269a2954738d460 | TypeScript | Mirroar/hivemind | /src/role/exploit/builder.ts | 2.625 | 3 | /* global FIND_DROPPED_RESOURCES RESOURCE_ENERGY FIND_SOURCES_ACTIVE
FIND_STRUCTURES FIND_MY_CONSTRUCTION_SITES */
import utilities from 'utilities';
import Role from 'role/role';
import BuilderRole from 'role/builder';
export default class ExploitBuilderRole extends Role {
builderRole: BuilderRole;
constructor() {
super();
this.builderRole = new BuilderRole();
}
/**
* Makes a creep behave like an exploit builder.
*
* @param {Creep} creep
* The creep to run logic for.
*/
run(creep) {
if (creep.memory.building && creep.store[RESOURCE_ENERGY] === 0) {
this.setExploitBuilderState(creep, false);
}
else if (!creep.memory.building && creep.store[RESOURCE_ENERGY] === creep.store.getCapacity()) {
this.setExploitBuilderState(creep, true);
}
const exploit = Game.exploits[creep.memory.exploitName];
if (exploit) {
// Follow cached path when requested.
if (creep.hasCachedPath()) {
creep.followCachedPath();
if (creep.hasArrived()) {
creep.clearCachedPath();
}
else {
return;
}
}
else if (creep.pos.roomName !== exploit.roomName && exploit.memory.pathToRoom) {
creep.setCachedPath(exploit.memory.pathToRoom, false, 3);
return;
}
}
if (creep.memory.building) {
this.performExploitBuild(creep);
return;
}
this.performGetExploitEnergy(creep);
}
/**
* Puts this creep into or out of build mode.
*
* @param {Creep} creep
* The creep to run logic for.
* @param {boolean} building
* Whether to start building or not.
*/
setExploitBuilderState(creep, building) {
creep.memory.building = building;
delete creep.memory.buildTarget;
delete creep.memory.resourceTarget;
}
/**
* Makes the creep use energy to finish construction sites in the current room.
*
* @param {Creep} creep
* The creep to run logic for.
*/
performExploitBuild(creep) {
// Repair structures around the room when necessary.
if (!creep.memory.repairTarget && Game.time % 10 === 0) {
const structure = creep.pos.findClosestByRange(FIND_STRUCTURES, {
filter: structure => structure.hits && structure.hits < structure.hitsMax * 0.5,
});
if (structure) {
creep.memory.repairTarget = structure.id;
delete creep.memory.buildTarget;
}
}
if (creep.memory.repairTarget) {
const target = Game.getObjectById<AnyOwnedStructure>(creep.memory.repairTarget);
if (target) {
if (target.hits >= target.hitsMax) {
delete creep.memory.repairTarget;
}
else if (creep.pos.getRangeTo(target) > 3) {
creep.moveToRange(target, 3);
if (Game.cpu.bucket > 5000) {
this.builderRole.repairNearby(creep);
}
}
else {
creep.repair(target);
}
return;
}
delete creep.memory.repairTarget;
}
// Build stuff in the room.
if (!creep.memory.buildTarget) {
const targets = creep.room.find(FIND_MY_CONSTRUCTION_SITES);
if (targets.length <= 0) {
return;
}
creep.memory.buildTarget = utilities.getClosest(creep, targets);
}
const best = creep.memory.buildTarget;
if (!best) {
return;
}
const target = Game.getObjectById(best);
if (!target) {
creep.memory.buildTarget = null;
return;
}
if (creep.pos.getRangeTo(target) > 3) {
creep.moveToRange(target, 3);
if (Game.cpu.bucket > 5000) {
this.builderRole.repairNearby(creep);
}
}
else {
creep.build(target);
}
}
/**
* Gathers energy while on an exploit operation.
*
* @param {Creep} creep
* The creep to run logic for.
*/
performGetExploitEnergy(creep) {
// Find nearby energy on the ground.
if (!creep.memory.energyTarget) {
const energy = creep.pos.findInRange(FIND_DROPPED_RESOURCES, 3, {
filter: energy => energy.amount > creep.store.getCapacity() * 0.1 && energy.resourceType === RESOURCE_ENERGY,
});
if (energy.length > 0) {
// Cache target energy to avoid ping-pong between it and target source.
creep.memory.energyTarget = energy[0].id;
}
else {
const tombs = creep.pos.findInRange(FIND_TOMBSTONES, 3, {
filter: tomb => tomb.store.getUsedCapacity(RESOURCE_ENERGY) > creep.store.getCapacity() * 0.1,
});
if (tombs.length > 0) {
// Cache target tombs to avoid ping-pong between it and target source.
creep.memory.energyTarget = tombs[0].id;
}
}
}
if (creep.memory.energyTarget) {
const energy = Game.getObjectById<Resource | Tombstone>(creep.memory.energyTarget);
if (energy && ('amount' in energy ? energy.amount : energy.store.getUsedCapacity(RESOURCE_ENERGY)) > 0) {
creep.whenInRange(1, energy, () => {
if (energy instanceof Tombstone) {
if (creep.withdraw(energy, RESOURCE_ENERGY) === OK) delete creep.memory.energyTarget;
}
else if (creep.pickup(energy) === OK) delete creep.memory.energyTarget;
});
return;
}
delete creep.memory.energyTarget;
}
// Harvest from safe sources.
const source = creep.pos.findClosestByRange(FIND_SOURCES_ACTIVE, {
filter: source => !source.isDangerous(),
});
if (!source) return;
const container = source.getNearbyContainer();
if (container && container.store[RESOURCE_ENERGY] > creep.store.getCapacity() * 0.5) {
creep.whenInRange(1, container, () => {
creep.withdraw(container, RESOURCE_ENERGY);
});
return;
}
creep.whenInRange(1, source, () => {
creep.harvest(source);
});
}
}
|
9ce95cfb816476b5167564af22270b401fe3b164 | TypeScript | njmyers/javascript-monorepo | /packages/smalldash/src/async/__tests__/pipe-async.test.ts | 3.390625 | 3 | // @ts-nocheck
import pipeAsync from '../pipe-async';
const defer = value =>
new Promise(resolve => {
setTimeout(() => resolve(value), 0);
});
const return1 = 1;
const return2 = 2;
const return3 = 3;
const fn1 = jest.fn().mockImplementation(() => defer(return1));
const fn2 = jest.fn().mockImplementation(() => defer(return2));
const fn3 = jest.fn().mockImplementation(() => defer(return3));
const arg = 0;
describe('async/pipeAsync', () => {
describe('no functions', () => {
test('it is a function', () => {
expect(typeof pipeAsync).toBe('function');
});
test('it does not throw an error', () => {
expect(() => pipeAsync()).not.toThrow();
});
const zeroFunctions = pipeAsync();
test('it returns a function', () => {
expect(typeof zeroFunctions).toBe('function');
});
test('it does not throw an error when curried', () => {
expect(zeroFunctions).not.toThrow();
});
let result;
beforeEach(async () => {
result = await zeroFunctions(arg);
});
test('it returns the argument passed in', () => {
expect(result).toBe(arg);
});
});
describe('one function', () => {
const oneFunction = pipeAsync(fn1);
let result;
beforeEach(async () => {
result = await oneFunction(arg);
});
test('it calls the first function with the argument', () => {
expect(fn1).toHaveBeenCalledWith(arg);
});
test('it returns the result of the first function', () => {
expect(result).toBe(return1);
});
});
describe('two function', () => {
const twoFunctions = pipeAsync(fn1, fn2);
let result;
beforeEach(async () => {
result = await twoFunctions(arg);
});
test('it calls the first function with the argument', () => {
expect(fn1).toHaveBeenCalledWith(arg);
});
test('it calls the second function with the return of the first', () => {
expect(fn2).toHaveBeenCalledWith(return1);
});
test('it returns the result of the second function', () => {
expect(result).toBe(return2);
});
});
describe('three function', () => {
const threeFunctions = pipeAsync(fn1, fn2, fn3);
let result;
beforeEach(async () => {
result = await threeFunctions(arg);
});
test('it calls the first function with the argument', () => {
expect(fn1).toHaveBeenCalledWith(arg);
});
test('it calls the second function with the return of the first', () => {
expect(fn2).toHaveBeenCalledWith(return1);
});
test('it calls the third function with the return of the second', () => {
expect(fn3).toHaveBeenCalledWith(return2);
});
test('it returns the result of the second function', () => {
expect(result).toBe(return3);
});
});
});
|
9595cc2679e3db2bd60001e58f4f228db6be81cf | TypeScript | vis-au/visflow | /client/src/common/color-scale.ts | 2.921875 | 3 | import { scaleLinear, scaleOrdinal } from 'd3-scale';
import { schemeCategory10 } from 'd3-scale-chromatic';
import _ from 'lodash';
enum ScaleType {
LINEAR = 'linear',
ORDINAL = 'ordinal',
}
export interface ColorScaleInfo {
id: string;
label: string;
type: ScaleType;
contrastColor: string;
domain: number[];
range: string[];
}
export const redGreen: ColorScaleInfo = {
id: 'red-green',
label: 'Red-Green',
type: ScaleType.LINEAR,
contrastColor: 'white',
domain: [.0, .5, 1.0],
range: ['red', '#333', 'green'],
};
export const CWYR: ColorScaleInfo = {
id: 'cwyr',
label: 'CWYR',
type: ScaleType.LINEAR,
contrastColor: 'black',
domain: [.0, .25, .5, .75, 1.0],
range: ['cyan', '#d5e9f0', 'white', 'yellow', 'red'],
};
export const monochrome: ColorScaleInfo = {
id: 'monochrome',
label: 'Monochrome',
type: ScaleType.LINEAR,
contrastColor: 'white',
domain: [.0, 1.0],
range: ['black', 'white'],
};
export const redYellow: ColorScaleInfo = {
id: 'red-yellow',
label: 'Red-Yellow',
type: ScaleType.LINEAR,
contrastColor: 'black',
domain: [.0, .5, 1.0],
range: ['red', '#333', 'yellow'],
};
export const yellowBlue: ColorScaleInfo = {
id: 'yellow-blue',
label: 'Yellow-Blue',
type: ScaleType.LINEAR,
contrastColor: 'black',
domain: [0.0, 0.5, 1.0],
range: ['yellow', '#333', 'blue'],
};
export const categorical: ColorScaleInfo = {
id: 'categorical',
label: 'Categorical',
type: ScaleType.ORDINAL,
contrastColor: 'white',
domain: _.range(10),
range: schemeCategory10 as string[],
};
export const allColorScaleInfo: ColorScaleInfo[] = [
redGreen,
CWYR,
monochrome,
redYellow,
yellowBlue,
categorical,
];
const findColorScale = (id: string): ColorScaleInfo => {
const scale = allColorScaleInfo.find(info => info.id === id);
if (!scale) {
console.error(`color scale ${id} not found`);
}
return scale as ColorScaleInfo;
};
type ColorScaleCallable = (value: number | string) => string;
// Returns ScaleLinear<string, string> | ScaleOrdinal<number, string> but as an alternative signature.
export const getColorScale = (id: string): ColorScaleCallable => {
const scale = findColorScale(id);
if (scale.type === ScaleType.LINEAR) {
return scaleLinear<string, string>()
.domain(scale.domain)
.range(scale.range) as ColorScaleCallable;
} else { // ScaleType.ORDINAL
return scaleOrdinal<number, string>()
.domain(scale.domain)
.range(scale.range) as ColorScaleCallable;
}
};
export const getColorScaleGradient = (id: string): string => {
const scale = findColorScale(id);
let gradient = 'linear-gradient(to right,';
if (scale.type === ScaleType.LINEAR) {
gradient += scale.range.join(',');
} else { // ScaleType.ORDINAL
gradient += scale.range.map((val: string, index: number) => {
return val + ' ' + (index * 100 / scale.range.length) + '%,' +
val + ' ' + ((index + 1) * 100 / scale.range.length) + '%';
}).join(',');
}
gradient += ')';
return gradient;
};
|
5f436d0eea409293187c40289b28fe5398f4a64b | TypeScript | alex404A/type-challenges | /questions/10-medium-tuple-to-union/test-cases.ts | 2.828125 | 3 | import { Equal, Expect } from "../../utils";
type TupleToUnion<T extends any[]> = T[number];
type TupleToUnion2<T extends any[]> = T extends Array<infer ITEMS>
? ITEMS
: never;
type cases = [
Expect<Equal<TupleToUnion<[123, "456", true]>, 123 | "456" | true>>,
Expect<Equal<TupleToUnion2<[123]>, 123>>
];
|
4a6a957625e275842773e64c39fff7f8936af616 | TypeScript | DefinitelyTyped/DefinitelyTyped | /types/yuka/test/examples/misc/savegame/index.ts | 2.546875 | 3 | import * as YUKA from "yuka";
import { CustomEntity } from './CustomEntity';
import { CustomVehicle } from './CustomVehicle';
const entityManager = new YUKA.EntityManager();
const time = new YUKA.Time();
const targetMesh = {matrix: new YUKA.Matrix4()};
const vehicleMesh = {matrix: new YUKA.Matrix4()};
// register custom types so the entity manager is able to instantiate
// custom objects from JSON
entityManager.registerType('CustomEntity', CustomEntity);
entityManager.registerType('CustomVehicle', CustomVehicle);
if (hasSavegame()) {
// load an existing savegame
onLoad();
} else {
const target = new CustomEntity();
target.setRenderComponent(targetMesh, sync);
target.generatePosition();
const vehicle = new CustomVehicle();
vehicle.target = target;
vehicle.setRenderComponent(vehicleMesh, sync);
const seekBehavior = new YUKA.SeekBehavior(target.position);
vehicle.steering.add(seekBehavior);
entityManager.add(target);
entityManager.add(vehicle);
}
time.update();
const delta = time.getDelta();
entityManager.update(delta);
function sync(entity: YUKA.GameEntity, renderComponent: {matrix: YUKA.Matrix4}) {
renderComponent.matrix.copy(entity.worldMatrix);
}
function onSave() {
const json = entityManager.toJSON();
const jsonString = JSON.stringify(json);
localStorage.setItem('yuka_savegame', jsonString);
}
function onLoad() {
const jsonString = localStorage.getItem('yuka_savegame');
if (jsonString !== null) {
try {
const json = JSON.parse(jsonString);
entityManager.fromJSON(json);
// restore render components (depends on 3D engine)
const target = entityManager.getEntityByName('target');
if (target instanceof YUKA.GameEntity) {
target.setRenderComponent(targetMesh, sync);
}
const vehicle = entityManager.getEntityByName('vehicle');
if (vehicle instanceof YUKA.GameEntity) {
vehicle.setRenderComponent(vehicleMesh, sync);
}
} catch (e) {
console.error(e);
onClear();
alert('Invalid Savegame found. Savegame was deleted.');
window.location.reload();
}
}
}
function onClear() {
localStorage.removeItem('yuka_savegame');
}
function hasSavegame() {
return localStorage.getItem('yuka_savegame') !== null;
}
|
6cff76314cf33cca77a840593a254b8d38861f63 | TypeScript | Gipphe/twitter-stream | /packages/backend/tests/Heartbeat.spec.ts | 2.671875 | 3 | import timers, { NodeClock } from '@sinonjs/fake-timers';
import { AbortController } from 'abort-controller';
import test from 'ava';
import { Heartbeat } from '../src/Heartbeat';
test('does not start by default', (t) => {
const clock = timers.createClock();
t.deepEqual(clock.countTimers(), 0);
// eslint-disable-next-line no-new
new Heartbeat(new AbortController(), clock as NodeClock);
t.deepEqual(clock.countTimers(), 0);
});
test.cb('calls the provided abort controller after 23 seconds', (t) => {
const clock = timers.createClock();
const ab = new AbortController();
const hb = new Heartbeat(ab, clock as NodeClock);
ab.signal.addEventListener('abort', () => {
t.deepEqual(clock.now, 23000);
t.end();
});
hb.start();
clock.next();
});
test.cb('resets the timer when `keepAlive` is called', (t) => {
const clock = timers.createClock();
const ab = new AbortController();
const hb = new Heartbeat(ab, clock as NodeClock);
ab.signal.addEventListener('abort', () => {
t.deepEqual(clock.now, 28000);
t.end();
});
hb.start();
clock.tick(5000);
hb.keepAlive();
clock.next();
});
test.cb('never calls the abort controller if `end` is called before timeout', (t) => {
const clock = timers.createClock();
const ab = new AbortController();
const hb = new Heartbeat(ab, clock as NodeClock);
ab.signal.addEventListener('abort', () => {
t.fail('Abort was called');
t.end();
});
hb.start();
clock.tick(5000);
hb.end();
clock.tick(23000);
t.deepEqual(clock.now, 28000);
t.end();
});
test.cb('calling end first does nothing', (t) => {
const clock = timers.createClock();
const ab = new AbortController();
const hb = new Heartbeat(ab, clock as NodeClock);
ab.signal.addEventListener('abort', () => {
t.fail('Abort was called');
t.end();
});
hb.end();
clock.tick(24000);
t.deepEqual(clock.now, 24000);
t.end();
});
|
d13a59683bfd4c5059cf7f85ec27a4c414cf2853 | TypeScript | delta62/json-schema-validator | /test/validators/type.test.ts | 3.359375 | 3 | import { SchemaType } from '../../lib/schema'
import validateType from '../../lib/validators/type'
const CASES: Record<string, any[]> = {
null: [ null ],
boolean: [ true, false ],
integer: [ 0, -0, -10, 10 ],
number: [ -12.34, 12.34 ],
string: [ '', 'foo', '42', '\x00' ],
object: [ { }, { foo: [ ] }, { foo: 'bar' } ],
array: [ [ ], [ 1, 2, 3 ] ],
never: [ Infinity, undefined ]
}
let allTypes: SchemaType[] = [ 'string', 'null', 'array', 'object', 'boolean', 'number', 'integer' ]
allTypes.forEach(type => {
describe(`${type} tests`, () => {
successCases(type, CASES[type])
failureCases(type, Object.entries(CASES)
.filter(([ k ]) => k !== type)
.reduce((acc, [ k, cases ]) => {
if ([ 'integer', 'number' ].includes(k) && [ 'integer', 'number'].includes(type)) {
return acc
}
return acc.concat(cases)
}, [ ] as any[])
)
})
})
function successCases(type: SchemaType, cases: any[]) {
generateCases(type, cases, true)
}
function failureCases(type: SchemaType, cases: any[]) {
generateCases(type, cases, false)
}
function generateCases(type: SchemaType, cases: any[], expectedResult: boolean) {
cases.forEach(input => {
let message = expectedResult
? `validates ${input}`
: `fails to validate ${input}`
test(message, () => {
expect(validateType(type, input as never)).toBe(expectedResult)
})
})
}
|
8689e53f21bca0c33c5e689a451af5efe42d4f67 | TypeScript | ToreRisinger/SpaceAge | /src/shared/data/shipmodule/ShipModuleInfo.ts | 2.53125 | 3 | import { ISprite } from "../ISprite";
import { IModuleTypeProperties } from "./IModuleTypeProperties";
import { EModuleItemType } from "../item/EModuleItemType";
import { EStatType } from "../stats/EStatType";
import { EStatModifier } from "../stats/EStatModifier";
import { EItemType } from "../item/EItemType";
import { SPRITES } from "../../util/SPRITES";
import { ERefinedMineralItemType } from "../item/ERefinedMineralItemType";
export module ShipModuleInfo {
export interface IShipModuleMineralInfo {
mineral: ERefinedMineralItemType,
base: number,
increase: number
}
export interface IShipModuleInfo {
sprite: ISprite,
stats: IModuleTypeProperties,
minerals: Array<IShipModuleMineralInfo>,
requireStat: EStatType
}
const moduleTypeToProperyMap : { [key: number]: IShipModuleInfo } = {
/* MAIN MODULES */
[EModuleItemType.MAIN_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.armor,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier : EStatModifier.increase_additive
},
{
stat: EStatType.thrust,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier : EStatModifier.increase_additive
},
{
stat: EStatType.radar_range,
baseMax : 2000,
baseMin : 1000,
increase: 1000,
modifier : EStatModifier.increase_additive
},
{
stat: EStatType.weapon_damage,
baseMax : 10,
baseMin : 5,
increase: 5,
modifier : EStatModifier.increase_additive
},
{
stat: EStatType.mining_laser_yield,
baseMax : 2,
baseMin : 1,
increase: 1,
modifier : EStatModifier.increase_additive
},
{
stat: EStatType.weapon_range,
baseMax : 1000,
baseMin : 500,
increase: 500,
modifier : EStatModifier.increase_additive
},
{
stat: EStatType.mining_laser_range,
baseMax: 1000,
baseMin: 500,
increase: 500,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.cargo_hold_size,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.power,
baseMax: 10,
baseMin: 5,
increase: 5,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
}
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.main_module_quality
},
/* MODULES */
[EModuleItemType.RADAR_SIGNATURE_REDUCTION_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.radar_signature_reduction,
baseMax: 2,
baseMin: 1,
increase: 1,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
}
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.radar_range_module_quality
},
[EModuleItemType.CARGO_HOLD_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.cargo_hold_size,
baseMax: 100,
baseMin: 50,
increase: 50,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
}
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.cargo_hold_module_quality
},
[EModuleItemType.THRUST_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.thrust,
baseMax: 21000,
baseMin: 20000,
increase: 10000,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
}
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.thrust_module_quality
},
[EModuleItemType.POWER_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.power,
baseMax: 2,
baseMin: 1,
increase: 1,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
}
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.power_module_quality
},
[EModuleItemType.RADAR_RANGE_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.radar_range,
baseMax: 2000,
baseMin: 1000,
increase: 1000,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier : EStatModifier.increase_additive
}
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.radar_range_module_quality
},
[EModuleItemType.WEAPON_RANGE_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.weapon_range,
baseMax: 2000,
baseMin: 1000,
increase: 1000,
modifier: EStatModifier.increase_additive
},
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.weapon_range_module_quality
},
[EModuleItemType.MINING_RANGE_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mining_laser_range,
baseMax: 2000,
baseMin: 1000,
increase: 1000,
modifier: EStatModifier.increase_additive
},
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.mining_laser_module_quality
},
[EModuleItemType.SHIELD_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.shield_generation,
baseMax: 2,
baseMin: 1,
increase: 1,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.shield,
baseMax: 200,
baseMin: 100,
increase: 100,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
}
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.shield_module_quality
},
[EModuleItemType.SHIELD_GENERATION_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.shield_generation,
baseMax: 10,
baseMin: 5,
increase: 5,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
}
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.shield_generation_module_quality
},
[EModuleItemType.ARMOR_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.armor,
baseMax: 200,
baseMin: 100,
increase: 100,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
}
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.armor_module_quality
},
[EModuleItemType.SUPPORT_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
}
],
possibleExtraStats: []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.support_module_quality
},
[EModuleItemType.TARGET_DODGE_REDUCTION_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.target_dodge_reduction,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
}
],
possibleExtraStats: []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.target_dodge_reduction_module_quality
},
/* WEAPON MODULES */
[EModuleItemType.MINING_LASER_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mining_laser_yield,
baseMax: 2,
baseMin: 1,
increase: 1,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mining_laser_range,
baseMax: 200,
baseMin: 100,
increase: 100,
modifier: EStatModifier.increase_additive
},
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.mining_laser_module_quality
},
[EModuleItemType.TURRET_MODULE] : {
sprite : SPRITES.SHIP_MODULE.sprite,
stats : {
base: [
{
stat: EStatType.hull,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.mass,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
{
stat: EStatType.weapon_damage,
baseMax: 20,
baseMin: 10,
increase: 10,
modifier: EStatModifier.increase_additive
},
],
possibleExtraStats : []
},
minerals: [
{
mineral: ERefinedMineralItemType.REFINED_IRON,
base: 10,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_GOLD,
base: 5,
increase: 1
},
{
mineral: ERefinedMineralItemType.REFINED_SILVER,
base: 5,
increase: 1
},
],
requireStat: EStatType.turret_module_quality
}
}
export function getModuleInfo(moduleType : EItemType) : IShipModuleInfo {
return moduleTypeToProperyMap[moduleType];
}
} |
72f104052561abf4b32099e4cbb3de17c894d91e | TypeScript | kyoujuro/typescript_practice | /20201122/add_function.ts | 3.46875 | 3 | function add(a: number, b: number): number{
return a + b
}
console.log(add(1, 2))
console.log(add.apply(1, null))
console.log(add.apply([1, 2], null))
console.log(add.apply(null, [1, 2]))
console.log(add.call(1, 2, null))
console.log(add.call(null, 1, 2))
console.log(add.call([10, 2], null))
console.log(add.bind(1, 2, null)())
console.log(add.bind(null, 1, 2)()) |
bb8f767ae1b1411702f5a5cb7b3028253bc2e78d | TypeScript | esterw/client | /src/app/shared/shared-pipes/filter-pipe.pipe.ts | 2.625 | 3 | import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: 'TextFilterPipe',
pure: false
})
export class TextFilterPipe implements PipeTransform {
filteredItems:any[];
transform(items: any[], args: any[]): any {
//console.log("*******args*************/////////"+args.toString)
if(args.toString().length === 0)
return items;
this.filteredItems=items.filter(item => item.AffiliateDate == args );
//console.log("----------------------filtered"+items)
return this.filteredItems;
}
}
//&& item.AffiliateDate.getFullYear() == args[1].getFullYear() |
4cf1dedbd51f37066a24733130089f094a7c9c46 | TypeScript | svenliebig/jarvil | /src/electron/plugins/JarvilSystemPlugin.ts | 2.578125 | 3 | import { ipcMain } from "electron"
import Events from "../Events"
import { ResultItem } from "../Processor"
import Logger from "../utils/Logger"
import JarvilPluginInterface from "./JarvilPluginInterface"
import { resolve } from "path"
export enum JarvilSystemPluginAction {
Settings = "jarvil/settings",
Close = "jarvil/close",
Exit = "jarvil/exit",
ReloadPlugins = "jarvil/reloadTheme"
}
export default class JarvilSystemPlugin implements JarvilPluginInterface {
public name: string = "jarvil-system-plugin"
public version: string = "1.0.0"
public trigger: string = "jarvil"
public action(actionId: string, ...args: Array<string>): void {
Logger.info(`${this.name} - action triggered`, ...args)
let action: string = null
if (args.length >= 1) {
action = args[0]
}
switch (actionId) {
case JarvilSystemPluginAction.Settings:
ipcMain.emit(Events.OpenSettings)
break
case JarvilSystemPluginAction.ReloadPlugins:
ipcMain.emit(Events.ReloadPlugins)
break
case JarvilSystemPluginAction.Close:
case JarvilSystemPluginAction.Exit:
process.exit()
default:
break
}
}
/**
*
*
* @static
* @param {...Array<string>} args
* @returns
* @memberof JarvilSystemPlugin
*/
public getResultItems(...args: Array<string>): Array<ResultItem> {
try {
let action: string = null
if (args.length >= 1) {
action = args[0]
}
switch (action) {
case JarvilSystemPluginAction.Settings:
return [JarvilSystemPlugin.settingsResultItem]
case JarvilSystemPluginAction.ReloadPlugins:
return [JarvilSystemPlugin.reloadPluginsResultItem]
case JarvilSystemPluginAction.Close:
case JarvilSystemPluginAction.Exit:
return [JarvilSystemPlugin.closeResultItem]
default:
return [
JarvilSystemPlugin.settingsResultItem,
JarvilSystemPlugin.closeResultItem,
JarvilSystemPlugin.reloadPluginsResultItem
]
}
} catch {
return []
}
}
private static get reloadPluginsResultItem(): ResultItem {
return {
...this.createResultItem(),
description: "Reload Plugins",
actionId: JarvilSystemPluginAction.ReloadPlugins,
image: resolve(__dirname, "jarvil-replay.svg")
}
}
private static get settingsResultItem(): ResultItem {
return {
...this.createResultItem(),
description: "Open Settings",
actionId: JarvilSystemPluginAction.Settings,
image: resolve(__dirname, "jarvil-logo.svg"),
preview: "<div style='background: black;'>Hey was geht</div>",
}
}
private static get closeResultItem(): ResultItem {
return {
...this.createResultItem(),
description: "Close Jarvil",
actionId: JarvilSystemPluginAction.Close,
image: resolve(__dirname, "jarvil-close.svg")
}
}
private static createResultItem(): Pick<ResultItem, "title" | "name"> {
return {
title: "Jarvil",
name: "jarvil-system-plugin"
}
}
} |
2e07a7c6eb485541de9a9bb25465525efbfcf9e0 | TypeScript | ksdemo/agile-mobile | /src/radio/PropsType.ts | 2.578125 | 3 | export interface RadioGroupPropsType {
className?: string;
style?: object;
value?: string | number;
activeColor?: string;
direction?: 'horizontal' | 'vertical';
disabled?: boolean;
children: any[];
onChange?: (e: object) => void;
}
export interface RadioListPropsType {
className?: string;
style?: object;
value?: string | number;
selectedValue?: string | number;
activeColor?: string;
disabled?: boolean;
checked?: boolean;
onChange?: () => void;
describe?: React.ReactNode;
}
export interface RadioPropsType {
className?: string;
style?: object;
value?: string | number;
selectedValue?: string | number;
checked?: boolean; // 仅List模式有效与value不冲突
activeColor?: string;
disabled?: boolean;
transparent?: boolean;
mode?: 'list';
shape?: 'round' | 'square';
onChange?: (e: any) => void;
} |
390f4fe9508a5dc6c9a41f84edbd93e48332b501 | TypeScript | Seikho/briskly-router | /test/request-match.ts | 2.59375 | 3 | import Types = require('../src/index.d.ts');
import Match = BR.Match;
import request = require('../src/parsers/request');
import route = require('../src/parsers/route');
import match = require('../src/match/request-part');
import chai = require('chai');
var expect = chai.expect;
describe('request/part comparison tests', () => {
describe('part tests', () => {
it('will match route part with request part', () => {
var req = request('/a-route');
var rt = route('/a-route');
testMatch(req[0], rt[0], Match.Literal);
});
it('will not match route part with misspelt request part', () => {
var req = request('/b-route');
var rt = route('/a-route');
testMatch(req[0], rt[0], Match.None);
});
})
describe('string parameter tests', () => {
it('will match route string parameter with request part', () => {
var req = request('/a-string');
var rt = route('/{param: string}');
testMatch(req[0], rt[0], Match.Type);
});
it('will not match route string parameter with request number part', () => {
var req = request('/12345');
var rt = route('/{param: string}');
testMatch(req[0], rt[0], Match.None);
});
it('will not match route string parameter with request array part', () => {
var req = request('/[]');
var rt = route('/{param: string}');
testMatch(req[0], rt[0], Match.None);
});
it('will not match route string parameter with request object part', () => {
var req = request('/{}');
var rt = route('/{param: string}');
testMatch(req[0], rt[0], Match.None);
});
it('will match route any parameter with request part', () => {
var req = request('/a-string');
var rt = route('/{param: any}');
testMatch(req[0], rt[0], Match.Any);
});
});
describe('number parameter tests', () => {
it('will match route number parameter with request number', () => {
var req = request('/12345.789');
var rt = route('/{param: number}');
testMatch(req[0], rt[0], Match.Type);
});
it('will not match route number parameter with request string', () => {
var req = request('/a-string');
var rt = route('/{param: number}');
testMatch(req[0], rt[0], Match.None);
});
it('will not match route number parameter with request array', () => {
var req = request('/["a-string"]');
var rt = route('/{param: number}');
testMatch(req[0], rt[0], Match.None);
});
it('will not match route number parameter with request object', () => {
var req = request('/{}');
var rt = route('/{param: number}');
testMatch(req[0], rt[0], Match.None);
});
it('will match route any parameter with request number', () => {
var req = request('/1e7');
var rt = route('/{param: any}');
testMatch(req[0], rt[0], Match.Any);
});
});
describe('array parameter tests', () => {
it('will match route array parameter with request array', () => {
var req = request('/[1,"a",{"b": "foo"}]');
var rt = route('/{param: array}');
testMatch(req[0], rt[0], Match.Type);
});
it('will not match route array parameter with request string', () => {
var req = request('/a-string-route');
var rt = route('/{param: array}');
testMatch(req[0], rt[0], Match.None);
});
it('will not match route array parameter with request number', () => {
var req = request('/0');
var rt = route('/{param: array}');
testMatch(req[0], rt[0], Match.None);
});
it('will not match route array parameter with request object', () => {
var req = request('/{}');
var rt = route('/{param: array}');
testMatch(req[0], rt[0], Match.None);
});
it('will match route any parameter with request array', () => {
var req = request('/[ [1,2,3], [4,5,6], [7,8,9]]');
var rt = route('/{param: any}');
testMatch(req[0], rt[0], Match.Any);
});
});
describe('object parameter tests', () => {
it('will match route object parameter with request object', () => {
var req = request('/{ "a": [1,2,3], "b": { "c": 123, "d": [7,8,9] } }');
var rt = route('/{param: object}');
testMatch(req[0], rt[0], Match.Type);
});
it('will not match route object parameter with request string', () => {
var req = request('/a-string-route');
var rt = route('/{param: object}');
testMatch(req[0], rt[0], Match.None);
});
it('will not match route object parameter with request number', () => {
var req = request('/0');
var rt = route('/{param: object}');
testMatch(req[0], rt[0], Match.None);
});
it('will not match route object parameter with request array', () => {
var req = request('/[]');
var rt = route('/{param: object}');
testMatch(req[0], rt[0], Match.None);
});
it('will match route any parameter with request array', () => {
var req = request('/{}');
var rt = route('/{param: any}');
testMatch(req[0], rt[0], Match.Any);
});
});
describe('multi part tests', () => {
it('will match a route multi (prefix and suffix) with request part', () => {
var rt = route('/pre{param}post');
var req = request('/preSOMEWORDSpost');
testMatch(req[0], rt[0], Match.Mixed);
});
it('will match a route multi (prefix only) with request part', () => {
var rt = route('/pre{param: number}');
var req = request('/pre1234');
testMatch(req[0], rt[0], Match.Mixed);
});
it('will match a route multi (suffix only) with request part', () => {
var rt = route('/{param: number}post-word');
var req = request('/1234post-word');
testMatch(req[0], rt[0], Match.Mixed);
});
it('will not match a route multi with a request part where prefix is not the same', () => {
var rt = route('/pre{param}post');
var req = request('/proSOMEWORDSpost');
testMatch(req[0], rt[0], Match.None);
});
it('will not match a route multi with a request part where suffix is not the same', () => {
var rt = route('/pre{param}post');
var req = request('/preSOMEWORDSpast');
testMatch(req[0], rt[0], Match.None);
});
it('will not match a route multi with a request part where prefix and suffix are not the same', () => {
var rt = route('/pre{param}post');
var req = request('/praSOMEWORDSpast');
testMatch(req[0], rt[0], Match.None);
});
});
});
function testMatch(reqPart: Types.RequestPart, routePart: Types.RoutePart, expected: Match) {
var result = match(reqPart, routePart);
expect(matchString(result)).to.equal(matchString(expected));
}
function matchString(match: Match) {
switch (match) {
case Match.Literal:
return 'Part';
case Match.Type:
return 'Type';
case Match.Any:
return 'Any';
default:
return 'None';
};
}
|
4150a95b20a7d818b7c5368b4892b2dd69d20d79 | TypeScript | starsoccer/cryptotithe | /src/utils/keyByValue/index.ts | 3.15625 | 3 | export default function keyByValue(value: unknown, object: Record<string, unknown>): undefined | string {
const keys = Object.keys(object);
for (const key of keys) {
if (object[key] === value) {
return key;
}
}
return undefined;
}
|
16208c7fa206e6ee9dbbb5385ef73b3771e2fbd0 | TypeScript | Naucana/appts | /app4.ts | 3.171875 | 3 | import { Usuario } from './class/usuario';
// Ejemplos con la clase usuario, la cual extiende de la clase abstracta Persona
let u1: Usuario;
u1 = new Usuario(1, "Antonio", "Direccion", 40);
console.log(u1.toString());
let u2: Usuario;
u2 = new Usuario(2, "Jose", "Direccion", 40);
console.log(u2.toString());
let u3: Usuario;
u3 = new Usuario(3, "Verdiro", "Direccion", 40);
console.log(u3.toString());
|
eacfb697df4981066f8c531723f9fa94d9f34d8f | TypeScript | ChALkeR/kaiwa | /src/js/storage/disco.ts | 2.59375 | 3 | export default class DiscoStorage {
constructor (public storage) {}
setup (db) {
if (db.objectStoreNames.contains('disco')) {
db.deleteObjectStore('disco');
}
db.createObjectStore('disco', {
keyPath: 'ver'
});
}
transaction (mode) {
const trans = this.storage.db.transaction('disco', mode);
return trans.objectStore('disco');
}
add (ver, disco, cb) {
cb = cb || function () {};
const data = {
ver: ver,
disco: disco
};
const request = this.transaction('readwrite').put(data);
request.onsuccess = function () {
cb(false, data);
};
request.onerror = cb;
}
get (ver, cb) {
cb = cb || function () {};
if (!ver) {
return cb('not-found');
}
const request = this.transaction('readonly').get(ver);
request.onsuccess = function (e) {
const res = request.result;
if (res === undefined) {
return cb('not-found');
}
cb(false, res.disco);
};
request.onerror = cb;
}
value = DiscoStorage;
}
|
85a92f3a640538be19ffaa6680e5122af9394cbb | TypeScript | quilljs/delta | /src/Op.ts | 3.0625 | 3 | import AttributeMap from './AttributeMap';
interface Op {
// only one property out of {insert, delete, retain} will be present
insert?: string | Record<string, unknown>;
delete?: number;
retain?: number | Record<string, unknown>;
attributes?: AttributeMap;
}
namespace Op {
export function length(op: Op): number {
if (typeof op.delete === 'number') {
return op.delete;
} else if (typeof op.retain === 'number') {
return op.retain;
} else if (typeof op.retain === 'object' && op.retain !== null) {
return 1;
} else {
return typeof op.insert === 'string' ? op.insert.length : 1;
}
}
}
export default Op;
|
23f10e8dd9cf1634cc7786b6b3c4e8f902a85030 | TypeScript | ctc87/proyectoCremas | /src/app/pipes/app.pipe.respuestas.ts | 2.78125 | 3 | import {Pipe} from '@angular/core';
// Tell Angular2 we're creating a Pipe with TypeScript decorators
@Pipe({
name: 'res'
})
export class ResPipe {
// Transform is the new "return function(value, args)" in Angular 1.x
transform(value, args?) {
// ES6 array destructuring
let [id] = args;
return value.filter(respuesta => {
return respuesta.id = /*+*/id;
});
}
} |
dc24122247aba6f77c1d29f67fb979869cd181b5 | TypeScript | sprengerjo/stryker | /packages/api/testResources/module/useReport.ts | 2.609375 | 3 | import {
Reporter,
MutantResult,
MutantStatus,
ReporterFactory,
SourceFile,
MatchedMutant
} from '@stryker-mutator/api/report';
import { Config } from '@stryker-mutator/api/config';
class EmptyReporter {}
class AllReporter implements Reporter {
public onSourceFileRead(file: SourceFile) {}
public onAllSourceFilesRead(files: SourceFile[]) {}
public onMutantTested(result: MutantResult) {}
public onAllMutantsTested(results: MutantResult[]) {}
public onAllMutantsMatchedWithTests(mutants: ReadonlyArray<MatchedMutant>) {}
public wrapUp() {
return new Promise<void>(r => r());
}
}
ReporterFactory.instance().register('empty', EmptyReporter);
ReporterFactory.instance().register('all', AllReporter);
console.log(ReporterFactory.instance().knownNames());
const emptyReporter = ReporterFactory.instance().create('empty', new Config());
const allReporter = ReporterFactory.instance().create('all', new Config());
if (!(emptyReporter instanceof EmptyReporter)) {
throw Error('Something wrong with empty reporter');
}
if (!(allReporter instanceof AllReporter)) {
throw Error('Something wrong with all reporter');
}
const result: MutantResult = {
id: '13',
location: null,
mutatedLines: 'string',
mutatorName: 'string',
originalLines: 'string',
range: [1, 2],
replacement: 'string',
sourceFilePath: 'string',
status: MutantStatus.TimedOut,
testsRan: ['']
};
allReporter.onMutantTested(result);
console.log(result);
console.log(
`Mutant status runtime error: ${MutantStatus[MutantStatus.RuntimeError]}`
);
console.log(
`Mutant status transpile error: ${MutantStatus[MutantStatus.TranspileError]}`
);
const matchedMutant: MatchedMutant = {
fileName: 'string',
id: '13',
mutatorName: '',
replacement: 'string',
scopedTestIds: [52],
timeSpentScopedTests: 52
};
allReporter.onAllMutantsMatchedWithTests([Object.freeze(matchedMutant)]);
const allMutants = Object.freeze([matchedMutant]);
allReporter.onAllMutantsMatchedWithTests(allMutants);
|
6975cd812b4254f73f3328c73da09181819af699 | TypeScript | l0ll098/ACTT | /src/app/services/log.service.ts | 2.53125 | 3 | import { Injectable } from "@angular/core";
import { environment } from "../../environments/environment";
import { IndexedDBService } from "./indexedDb.service";
// Logs will be written to IDB if the specific variable is set to true of if the app is in production.
const enableIDBLog = environment.enableIDBLog || environment.production;
@Injectable()
export class LoggerService {
constructor(
private indexedDBService: IndexedDBService
) { }
get info() {
if (!enableIDBLog) {
// tslint:disable-next-line:no-console
return console.info.bind(console);
} else {
return proxyConsole("info", this.indexedDBService);
}
}
get log() {
if (!enableIDBLog) {
return console.log.bind(console);
} else {
return proxyConsole("log", this.indexedDBService);
}
}
get warn() {
if (!enableIDBLog) {
return console.warn.bind(console);
} else {
return proxyConsole("warn", this.indexedDBService);
}
}
get error() {
if (!enableIDBLog) {
return console.error.bind(console);
} else {
return proxyConsole("error", this.indexedDBService);
}
}
get group() {
if (!enableIDBLog) {
return console.group.bind(console);
} else {
return proxyConsole("group", this.indexedDBService);
}
}
get groupEnd() {
if (!enableIDBLog) {
return console.groupEnd.bind(console);
} else {
return proxyConsole("groupEnd", this.indexedDBService);
}
}
}
function proxyConsole(method: string, indexedDBService: IndexedDBService) {
// Keep a pointer to the original console
const original = console[method];
// Overwrite it
console[method] = (...args) => {
indexedDBService.writeLogs(JSON.stringify(args));
original.apply(this, args);
};
// Call the console method using the proxied console
const log = console[method].bind(console) || Function.prototype.bind.call(console[method], console);
// Restore the original console
console[method] = original;
// Return the proxied console to the calling method
return log;
}
|
ddcc9fd5dd831bfe013479c71de7a4a392b84be2 | TypeScript | KeithTuttle/Map-Pin | /frontend/src/store/UserStore.ts | 2.6875 | 3 | import { EventEmitter } from 'events';
import { User } from '../viewModels/UserWithErrorMessage';
import Dispatcher from './dispatcher';
class UserStore extends EventEmitter {
user: User | null = null;
constructor(){
super();
}
setUser(user: User | null){
this.user = user;
this.emit("change");
}
getUser(){
return this.user;
}
//not type safe
handleActions(action: any){
switch(action.type){
case "SET_USER": {
this.setUser(action.user);
}
}
}
}
const userStore = new UserStore;
Dispatcher.register(userStore.handleActions.bind(userStore));
export default userStore;
|
c8dc4069416b8cb7623e57fdf2836eb602000e41 | TypeScript | viictorcamposs/blockbuster-api | /src/routes/categories.routes.ts | 2.515625 | 3 | import { Router } from "express";
import { CategoriesRepository } from "../repositories/CategoriesRepository";
import { CreateCategoryService } from "../services/CreateCategoryService";
const categoriesRoutes = Router();
const categoriesRepository = new CategoriesRepository();
categoriesRoutes.get("/", (request, response) => {
const all = categoriesRepository.list();
return response.status(200).json(all);
});
categoriesRoutes.post("/", (request, response) => {
const { name } = request.body;
const createCategoryService = new CreateCategoryService(categoriesRepository);
const newCategory = createCategoryService.execute(name);
return response.status(201).json(newCategory);
});
categoriesRoutes.patch("/", (request, response) => {
const { name: editedName } = request.body;
const { id } = request.headers;
const verifyIfCategoryExists = categoriesRepository.findById(String(id));
if (!verifyIfCategoryExists) {
return response.status(400).json({
error: "Couldn't edit category.",
});
}
const editedCategory = categoriesRepository.edit(String(id), editedName);
return response.status(200).json(editedCategory);
});
categoriesRoutes.delete("/", (request, response) => {
const { id } = request.headers;
const verifyIfCategoryExists = categoriesRepository.findById(String(id));
if (!verifyIfCategoryExists) {
return response.status(400).json({
error: "Couldn't delete category.",
});
}
categoriesRepository.remove(String(id));
return response.status(200).send();
});
export { categoriesRoutes };
|
9956d5a2f22053d6b3d2f446498c98ecf5ad86b7 | TypeScript | simp42/inventory | /frontend/src/data/StockRepository.ts | 2.53125 | 3 | import * as BSON from "bson";
import * as Realm from "realm-web";
import {Article} from "./Article";
import {ArticleCountChange, CountableArticle} from "./CountableArticle";
export default class StockRepository {
private readonly app: Realm.App;
private readonly service: string;
private readonly database: string;
private readonly db?: globalThis.Realm.Services.MongoDBDatabase;
constructor(app: Realm.App, service: string, database: string) {
this.app = app;
this.service = service;
this.database = database;
this.db = app.currentUser?.mongoClient(service).db(database);
}
private _stock = 'stock';
getOwnerFilter(userId: string): any {
return userId ? {user_id: userId} : {};
}
async countAllStock(userId: string): Promise<number> {
try {
const filter = this.getOwnerFilter(userId);
return await this.db!.collection(this._stock).count(filter);
} catch (e) {
alert(e);
}
return 0;
}
async countCountedStock(userId: string): Promise<number> {
try {
const filter = {
...this.getOwnerFilter(userId),
'count': {
'$gt': 0,
'$exists': true
}
};
return await this.db!.collection(this._stock).count(filter);
} catch (e) {
alert(e);
}
return 0;
}
async getAllStock(userId: string): Promise<CountableArticle[] | null> {
try {
const filter = this.getOwnerFilter(userId);
return await this.db!.collection(this._stock).find(filter);
} catch (e) {
alert(e);
}
return null;
}
async deleteAllStock(userId: string, updateUi:(removed: number) => void): Promise<any> {
const stocksCollection = this.db!.collection(this._stock);
const allStocks = await stocksCollection.find(this.getOwnerFilter(userId));
const submitDeleteBatch = async (batch: any[]) => {
if (batch.length === 0) {
return;
}
const ids = batch.map((stock) => stock._id);
await stocksCollection.deleteMany({
'_id': {
"$in": ids
}
});
await updateUi(batch.length);
};
let batch = [];
for(const stock of allStocks) {
batch.push(stock);
if (batch.length >= 50) {
await submitDeleteBatch(batch);
batch = [];
}
}
await submitDeleteBatch(batch);
}
async recreateStockFromArticles(userId: string, userEmail: string, articles: Article[]): Promise<boolean> {
let stock = [];
const stockCollection = this.db!.collection(this._stock);
for (const article of articles) {
const newStock: CountableArticle = {
...article,
article_id: article._id,
user_id: userId,
user_email: userEmail,
counted: [],
count: 0
};
// Remove id of article
delete newStock._id;
stock.push(newStock);
}
try {
const insertResult = await stockCollection.insertMany(stock);
return insertResult.insertedIds.length === articles.length;
} catch (e) {
alert(e);
return false;
}
}
async searchStock(userId: string, schema: any, search: any): Promise<CountableArticle[]> {
let orQuery = [];
for (let i = 0; i < schema.length; i++) {
let queryPart: any = {};
// for upc type columns we only search the beginning and end
if (schema[i].type === 'upc') {
queryPart[schema[i].key] = new RegExp('^' + search, 'i');
orQuery.push(queryPart);
queryPart = {};
queryPart[schema[i].key] = new RegExp(search + '$', 'i');
orQuery.push(queryPart);
} else {
queryPart[schema[i].key] = new RegExp(search, 'i');
orQuery.push(queryPart);
}
}
const query = {
user_id: userId,
'$or': orQuery
};
try {
return await this.db!.collection(this._stock).find(query);
} catch (e) {
alert(e);
return [];
}
}
async getStockById(stockId: string): Promise<CountableArticle | null> {
const id = new BSON.ObjectId(stockId);
try {
const stockRemote = await this.db!.collection(this._stock).find({_id: id});
const stocks = await stockRemote;
if (stocks.length === 0) {
console.error('Stock not found');
return null;
}
if (stocks.length > 1) {
console.error('More than one stock entry with id ' + stockId + ' found!?!');
return null;
}
return stocks[0];
} catch (e) {
alert(e);
}
return null;
}
async addCountToStock(stock: CountableArticle, additionalCount: number): Promise<boolean> {
if (!stock._id) {
console.error('Stock does not have an id');
}
const newCount: ArticleCountChange = {
created_at: new Date(),
change: additionalCount
};
stock.count = stock.count + additionalCount;
stock.counted.push(newCount);
try {
const collection = this.db!.collection(this._stock);
const updateResult = await collection.updateOne(
{_id: stock._id},
stock
);
return updateResult.modifiedCount === 1;
} catch (e) {
alert(e);
}
return false;
}
}
|
a6f2f11657157eae37ea547a30de62baf31aa2f0 | TypeScript | aashishmaheshwar/misc-view-performance | /src/hooks/useUtilityFns.ts | 2.515625 | 3 | import { Comment } from "pages/DataViews";
import { useCallback } from "react";
export const useUtilityFns = () => {
const groupByPostId = useCallback((data: Array<Comment>) => {
const groupedDataSet = data.reduce((groupedComments, comment) => {
const { postId, ...rest } = comment;
if (!groupedComments.has(postId)) {
groupedComments.set(postId, [rest]);
} else {
const comments = groupedComments.get(postId);
groupedComments.set(postId, [...comments, rest]);
}
return groupedComments;
}, new Map());
return Array.from(groupedDataSet, ([postId, comments]: [string, Comment[]]) => ({
postId,
comments,
}));
}, []);
return {groupByPostId};
}; |
9b4b43afc3d20e30695e648f6642954098e270e3 | TypeScript | BLZbanme/leetcode | /0501-0600/0501-0550/0529Minesweeper/demo.ts | 3.3125 | 3 | function updateBoard(board: string[][], click: number[]): string[][] {
check(board, click[0], click[1]);
return board;
};
function check(board: string[][], i: number, j: number): void {
if (i < 0 || j < 0 || i === board.length || j === board[0].length) {
return;
}
if (board[i][j] === 'M') {
board[i][j] = 'X';
return ;
}
if (board[i][j] === 'E') {
let num = count(board, i + 1, j) + count(board, i - 1, j) + count(board, i, j + 1) + count(board, i, j - 1)
+ count(board, i + 1, j + 1) + count(board, i - 1, j - 1) + count(board, i - 1, j + 1) + count(board, i + 1, j - 1);
if (num) {
board[i][j] = '' + num;
}
else {
board[i][j] = 'B';
check(board, i, j + 1)
check(board, i, j - 1)
check(board, i + 1, j)
check(board, i - 1, j)
check(board, i + 1, j + 1)
check(board, i + 1, j - 1)
check(board, i - 1, j + 1)
check(board, i - 1, j - 1)
}
}
return ;
}
function count(board: string[][], i: number, j: number): number {
if (i < 0 || j < 0 || i === board.length || j === board[0].length) {
return 0;
}
if (board[i][j] === 'M') {
return 1;
}
return 0;
} |
6a09db5c36d5b4290ae48afd10728e26c7df2df7 | TypeScript | ajun568/data-structures-and-algorithms | /src/leetcode/leetcode_239_1.ts | 3.296875 | 3 | // 239. 滑动窗口最大值
// test6~8
// 测试用例超时
const maxSlidingWindow = (nums: number[], k: number) => {
let queue: number[] = [];
let maxArr: number[] = [];
nums.forEach(item => {
if (queue.length <= k) {
queue.push(item);
}
if (queue.length === k) {
let max = queue[0];
for (let i = 1; i < queue.length; i++) {
if (queue[i] > max) max = queue[i];
}
maxArr.push(max);
queue.shift();
}
})
return maxArr;
}
export default maxSlidingWindow;
|
9e7db53e5654d913ec1fa71b3c024ee2eb09b07d | TypeScript | DomiR/rxjs-commented-operators | /src/operators/sampleTime.ts | 3 | 3 | /**
* Sample time operator
*
* @author Dominique Rau [domi.github@gmail.com](mailto:domi.github@gmail.com)
* @version 0.0.1
*/
import { Observable, of, Subscription, timer, interval, Subscribable, Subject } from 'rxjs';
import { take } from 'rxjs/operators';
import { sampleTime as sampleTimeOriginal } from 'rxjs/operators';
export function sampleTime<T>(period: number) {
return (source: Observable<T>) => {
return new Observable<T>(observer => {
let lastValue = null;
const sourceSubscription = source.subscribe(
value => {
lastValue = value;
},
err => observer.error(),
() => observer.complete()
);
const interval = setInterval(() => {
if (lastValue != null) {
observer.next(lastValue);
lastValue = null;
}
}, period);
// return subscription, which will unsubscribe from inner observable
return new Subscription(() => {
sourceSubscription.unsubscribe();
clearInterval(interval);
});
});
};
}
interval(100)
.pipe(take(5), sampleTimeOriginal(400))
.subscribe(
v => {
console.log('value: ', v);
},
null,
() => {
console.log('====');
interval(100)
.pipe(take(5), sampleTime(400))
.subscribe(v => {
console.log('value: ', v);
});
}
);
|
dd79d7530b7e2fe059177e7019d14d0620cbe063 | TypeScript | hwawrzacz/MatrixCalculator | /src/matrix/Matrix.ts | 2.796875 | 3 | import MatrixControls from "./MatrixControls";
import ElementBuilder from "../builders/ElementBuilder";
import ControlsBuilder from "../builders/ControlsBuilder";
export default class Matrix {
private _tableWrapper: Element;
private _DOMTable: Element;
private _rows: number;
private _cols: number;
private _matrixControls: MatrixControls;
private _controlsBuilder: ControlsBuilder;
private _elementBuilder: ElementBuilder;
constructor(rows: number, cols: number) {
this._rows = rows;
this._cols = cols;
this._controlsBuilder = new ControlsBuilder();
this._elementBuilder = new ElementBuilder();
this.initializeTable();
}
public getMatrixWrapper(): Element {
return this._tableWrapper;
}
private initializeTable() {
const addColumnButton = this._controlsBuilder.createAddButton('add-column');
const addRowButton = this._controlsBuilder.createAddButton('add-row');
addColumnButton.addEventListener('click', this.addColumn);
addRowButton.addEventListener('click', this.addRow);
this._tableWrapper = this._elementBuilder.createTableWrapper();
this._DOMTable = this._elementBuilder.createTable(this._rows, this._cols);
this._tableWrapper.appendChild(this._DOMTable);
this._tableWrapper.appendChild(addColumnButton);
this._tableWrapper.appendChild(addRowButton);
this._matrixControls = new MatrixControls(this._DOMTable);
}
private addColumn = () => {
this._cols++;
this._matrixControls.addColumn();
}
private addRow = () => {
this._rows++;
this._matrixControls.addRow(this._cols);
}
}
|
65a1fea86649a12d459f190c19be2c6c857eb62a | TypeScript | joostlubach/swagger-ts-generator | /src/helpers/sanitizeKey.ts | 2.75 | 3 | import * as Handlebars from 'handlebars'
import {quote} from './quote'
import options, {Casing} from '../CommandLineOptions'
import {camelCase, upperFirst, kebabCase, snakeCase} from 'lodash'
Handlebars.registerHelper('sanitizeKey', function (key: string, opts: Handlebars.HelperOptions) {
return new Handlebars.SafeString(sanitizeKey(key))
})
export function sanitizeKey(key: any) {
if (typeof key !== 'string') {
return `[${JSON.stringify(key)}]`
}
key = caseKey(key)
if (/[^_a-zA-Z]/.test(key)) {
return quote(key)
}
return key
}
export function caseKey(key: string) {
if (options.casing == null) { return key }
switch (options.casing) {
case Casing.kebab: return kebabCase(key)
case Casing.snake: return snakeCase(key)
case Casing.camel: return camelCase(key)
case Casing.pascal: return upperFirst(camelCase(key))
}
} |
f16bad3f91758cb73d97914884b20b82dd16865a | TypeScript | otofu-square/GraphQL-BFF-with-graphql-yoga | /src/Users/Query.ts | 2.625 | 3 | import { User } from './types';
import { api } from './api';
type UserQuery = (a1: any, a2: { id: number }) => Promise<User>;
const userQuery: UserQuery = async (_, { id }) => {
const user = await api.show(id);
return { ...user };
};
type UsersQuery = () => Promise<User[]>;
const usersQuery: UsersQuery = async () => {
const users = await api.index();
return [...users];
};
export const Query = {
user: userQuery,
users: usersQuery,
};
|
4f5b861f3bf7f3f9ec34374d2d38977a82b229b2 | TypeScript | Everythingmaybe/cook-book | /client/src/store/reducers/config.reducer.ts | 2.703125 | 3 | import {ActionType, getType} from "typesafe-actions";
import * as actions from '../actions/config.actions';
import {ConfigState, initialConfigState} from "../states/config.state";
type Action = ActionType<typeof actions>;
export const configReducer = (state: ConfigState = initialConfigState, action: Action): ConfigState => {
switch (action.type) {
case getType(actions.configSetAction): {
return (Object.assign({}, state, { loading: action.payload }) as ConfigState);
}
default:
return state;
}
};
|
41fe746078a510f0dce10804a3407cb20ef2d3b6 | TypeScript | AdithyaBhat17/habit-tracker | /lib/fetcher.ts | 3.078125 | 3 | export interface FetchProps {
url: string;
method?: "GET" | "POST" | "PUT" | "DELETE";
token?: string | undefined;
body?: any | undefined;
}
export async function fetcher<ApiResponse>({
url,
method = "POST",
token = "",
body,
}: FetchProps): Promise<ApiResponse | any> {
try {
const r = await fetch(url, {
method,
headers: {
"Content-type": "application/json",
Accept: "application/json",
token,
},
credentials: "same-origin",
body: JSON.stringify(body),
});
return await r.json();
} catch (e) {
throw e;
}
}
|
751f0ce88e3658725d63942b5259843ed8c5d028 | TypeScript | shivijain93/guvi | /extends_TypeScript/animal.ts | 3.578125 | 4 | class Cat{
name;
constructor(catName){
this.name=catName;
let catImage= document.createElement("img");
catImage.src= "http://pngimg.com/uploads/cat/cat_PNG50539.png";
catImage.onclick= this.catOnClick();
document.body.appendChild(catImage);
}
catOnClick(){
return()=> {
alert("this "+this.name+" is clicked");
};
}
}
class Dog{
name;
constructor(dogName){
this.name= dogName;
let dogImage= document.createElement("img");
dogImage.src= "http://pngimg.com/uploads/dog/dog_PNG50348.png";
dogImage.onclick= this.dogOnClick();
document.body.appendChild(dogImage);
}
dogOnClick(){
return()=> {
alert("this "+this.name+" is clicked");
};
}
}
let createCat = ()=> {
let name = prompt("Cat Name");
new Cat(name);
};
let createDog = ()=> {
let name = prompt("Dog Name");
new Dog(name);
}; |
9e72357e9fdff5215972fb0c5b077d23348dfee9 | TypeScript | manuth/TypeScriptESLintPlugin | /src/Diagnostics/LintDiagnosticMap.ts | 3.421875 | 3 | import { ILintDiagnostic } from "./ILintDiagnostic";
/**
* Provides a set of lint-diagnostics.
*/
export class LintDiagnosticMap
{
/**
* The problems.
*/
private map = new Map<string, ILintDiagnostic>();
/**
* Gets the problem with the specified start and end.
*
* @param start
* The start-position of the problem.
*
* @param end
* The end-position of the problem.
*
* @returns
* The diagnostic at the specified range.
*/
public Get(start: number, end: number): ILintDiagnostic
{
return this.map.get(this.Key(start, end));
}
/**
* Adds a problem to the map with the specified {@link start `start`}- and {@link end `end`}-position.
*
* @param start
* The start-position of the problem.
*
* @param end
* The end-position of the problem.
*
* @param item
* The item to add.
*/
public Set(start: number, end: number, item: ILintDiagnostic): void
{
this.map.set(this.Key(start, end), item);
}
/**
* Gets the problems.
*/
public get Values(): IterableIterator<ILintDiagnostic>
{
return this.map.values();
}
/**
* Generates a key for a problem.
*
* @param start
* The start-position of the problem.
*
* @param end
* The end-position of the problem.
*
* @returns
* The key for the specified range.
*/
private Key(start: number, end: number): string
{
return JSON.stringify([start, end]);
}
}
|
47b081bffce7b8d667f1e80baa0f10a6cf42c7eb | TypeScript | yhong4/WebsiteInformationComparator | /webclient/src/store/mutations.ts | 2.59375 | 3 | import stateType from './type'
import {IState} from './state'
import { MutationTree } from 'vuex'
import Vue from 'vue';
const mutations:MutationTree<any> = {
[stateType.SET_NEW_CATEGORIES](state:any, data:any):void{
state.newCategories = [];
state.newCategories = Object.assign([], data.categoryList);
},
[stateType.SET_CATEGORIES](state:any, data:any):void {
state.categories = [];
state.dailyList = [];
state.mondayList = [];
state.wednesdayList = [];
state.unassginedList = [];
data.categorydailyList.forEach( (item:any) => {
item.category = "0. Daily"
state.dailyList.push(item)
});
data.categorymondayandthursdayList.forEach( (item:any) => {
item.category = "1. Monday,Thursday"
state.mondayList.push(item)
});
data.categorytuesdayandfridayList.forEach( (item:any) => {
item.category = "2. Tuesday,Friday"
state.thuesdayList.push(item)
});
data.categorywednesdayandsaturdayList.forEach( (item:any) => {
item.category = "3.Wednesday,Saturday"
state.wednesdayList.push(item)
});
data.categoryunassignedList.forEach( (item:any) => {
item.category = "4.Unassigned"
state.unassginedList.push(item)
});
state.categories = [
{
name:"Daily",
data:state.dailyList
},
{
name:"Monday, Thursday",
data:state.mondayList
},
{
name:"Tuesday,Friday",
data:state.thuesdayList
},
{
name:"Wednesday, Saturday",
data:state.wednesdayList
},
{
name:"Unassigned",
data:state.unassginedList
}
]
},
[stateType.SET_STATE_CATEGORIES](state:any, data:any):void {
state.stateCategories = [];
state.statedailyList = [];
state.statemondayList = [];
state.statewednesdayList = [];
state.stateunassginedList = [];
data.categorydailyList.forEach( (item:any) => {
item.category = "0. Daily"
state.statedailyList.push(item)
});
data.categorymondayandthursdayList.forEach( (item:any) => {
item.category = "1. Monday,Thursday"
state.statemondayList.push(item)
});
data.categorytuesdayandfridayList.forEach( (item:any) => {
item.category = "2. Tuesday,Friday"
state.statethuesdayList.push(item)
});
data.categorywednesdayandsaturdayList.forEach( (item:any) => {
item.category = "3.Wednesday,Saturday"
state.statewednesdayList.push(item)
});
data.categoryunassignedList.forEach( (item:any) => {
item.category = "4.Unassigned"
state.stateunassginedList.push(item)
});
state.stateCategories = [
{
name:"Daily",
data:state.statedailyList
},
{
name:"Monday, Thursday",
data:state.statemondayList
},
{
name:"Tuesday,Friday",
data:state.statethuesdayList
},
{
name:"Wednesday, Saturday",
data:state.statewednesdayList
},
{
name:"Unassigned",
data:state.stateunassginedList
}
]
},
[stateType.SET_MARGIN_CATEGORIES](state:any, data:any):void{
let margins = Object.assign([],data.categorymarginsList);
state.marginCategories = {};
for(let item of margins){
let margin = {
end: item.margin.end,
start: item.margin.start,
target: parseFloat(item.margin.target).toFixed(2)
}
let marginItem = {
id:item.id,
margin: margin
}
if(!Object.keys(state.marginCategories).includes(item.name)){
Vue.set(state.marginCategories,item.name,[marginItem])
}else{
let marginList = state.marginCategories[item.name]
marginList.push(marginItem)
Vue.set(state.marginCategories,item.name,marginList)
}
}
},
[stateType.SET_COMPETITORS](state:any, data:any):void {
state.competitors = data;
state.tierOneCompetitors = data.competitorstieroneList
state.tierTwoCompetitors = data.competitorstiertwoList
},
[stateType.SET_COMPETITORSONE](state:any,data:any):void{
state.tierOneCompetitors = data;
},
[stateType.SET_COMPETITORSTWO](state:any,data:any):void{
state.tierTwoCompetitors = data;
},
[stateType.ADD_COMPETITORS](state:any, data:{tier:string,competitorName:string}):void {
if(data.tier === "Tier 1"){
state.tierOneCompetitors.push(data.competitorName);
}else{
state.tierTwoCompetitors.push(data.competitorName);
}
},
[stateType.SET_PRODUCTCOMPARISON](state:any,data:any):void{
state.productComparisonData = [];
let tableData = Object.assign({},data)
let row:{
id:string;
productcode:string;
productdescription:string;
costprice:string;
keywords:string;
salesprice:string;
competitorpricesList:string[]
}
tableData.productcomparisonList.forEach( (item:any) => {
let competitorprices:string[] = []
item.competitorpricesList.forEach( (competitorprice:{name:string,price:number})=>{
competitorprices.push(`${competitorprice.name} AU$${competitorprice.price.toFixed(2)}`)
})
row = {
id: item.productcode,
productcode: item.productcode,
productdescription: item.productdescription,
keywords: item.keywords,
// costprice: `AU$${item.costprice.toFixed(2)}`,
// salesprice:`AU$${item.salesprice.toFixed(2)}`,
costprice: item.costprice.toFixed(2),
salesprice:item.salesprice.toFixed(2),
competitorpricesList:competitorprices
}
state.productComparisonData.push(row)
});
},
[stateType.SET_TABLE_DATA_LOADING](state:any,data:boolean){
Object.assign({},state.isTableDataLoading,data);
},
[stateType.SET_HEIHGT](state:any,data:number){
Object.assign({},state.height,data);
}
}
export default mutations;
|
ff7a477dfe8d2f725f789b7e1f82b8df1f7415b5 | TypeScript | Metatavu/pakkasmarja-berries | /src/test/product-test.ts | 2.59375 | 3 | import * as test from "blue-tape";
import * as request from "supertest";
import auth from "./auth";
import { Product, ProductPrice } from "../rest/model/models";
import ApplicationRoles from "../rest/application-roles";
import database from "./database";
import TestConfig from "./test-config";
const testDataDir = `${__dirname}/../../src/test/data/`;
const productData = require(`${testDataDir}/product.json`);
/**
* Creates product
*
* @param token token
* @returns promise for product
*/
const createProduct = (token: string): Promise<Product> => {
const payload: Product = productData[0];
return request(TestConfig.HOST)
.post("/rest/v1/products")
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.send(payload)
.expect(200)
.then((response) => {
return response.body;
});
}
/**
* Creates product price
*
* @param token token
* @param product product
* @returns promise for product
*/
const createProductPrice = async (token: string, product: Product) => {
const payload: ProductPrice = {
id: null,
productId: product.id || "",
unit: "€ / kg",
price: "100",
createdAt: new Date(),
updatedAt: new Date()
};
return request(TestConfig.HOST)
.post(`/rest/v1/products/${product.id}/prices`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.send(payload)
.expect(200)
.then((response) => {
return response.body;
});
}
/**
* Updates product
*
* @param token token
* @param id id
* @returns promise for product
*/
const updateProduct = (token: string, id: string): Promise<Product> => {
const payload: Product = productData[1];
return request(TestConfig.HOST)
.put(`/rest/v1/products/${id}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.send(payload)
.expect(200)
.then((response) => {
return response.body;
});
}
/**
* Finds product
*
* @param token token
* @param id id
* @returns promise for product
*/
const findProduct = (token: string, id: string): Promise<Product> => {
return request(TestConfig.HOST)
.get(`/rest/v1/products/${id}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.expect(200)
.then((response) => {
return response.body;
});
}
/**
* Lists products
*
* @param token token
* @param userId userid
* @returns promise for list of products
*/
const listProducts = (token: string, userId?: string): Promise<Product[]> => {
let params = "";
if (userId) {
params = `?userId=${userId}`
}
return request(TestConfig.HOST)
.get(`/rest/v1/products${params}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.expect(200)
.then((response) => {
return response.body;
});
}
test("Create product", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.DELETE_PRODUCTS]);
try {
const createdProduct = await createProduct(token);
t.notEqual(createdProduct, null);
t.notEqual(createdProduct.id, null);
t.equal(createdProduct.itemGroupId, productData[0].itemGroupId);
t.equal(createdProduct.name, productData[0].name);
t.equal(createdProduct.unitName, productData[0].unitName);
t.equal(createdProduct.unitSize, productData[0].unitSize);
t.equal(createdProduct.active, productData[0].active);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
});
test("Update product", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.UPDATE_OTHER_WEEK_DELIVERY_PREDICTION, ApplicationRoles.DELETE_PRODUCTS]);
try {
const createdProduct = await createProduct(token);
const updatedProduct = await updateProduct(token, createdProduct.id || "");
t.notEqual(updatedProduct, null);
t.notEqual(updatedProduct.id, null);
t.equal(updatedProduct.name, productData[1].name);
t.equal(updatedProduct.itemGroupId, productData[1].itemGroupId);
t.equal(updatedProduct.unitName, productData[1].unitName);
t.equal(updatedProduct.unitSize, productData[1].unitSize);
t.equal(updatedProduct.active, productData[1].active);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.UPDATE_OTHER_WEEK_DELIVERY_PREDICTION]);
});
test("Find product", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.DELETE_PRODUCTS]);
try {
const createdProduct = await createProduct(token);
const foundProduct = await findProduct(token, createdProduct.id || "");
t.notEqual(foundProduct, null);
t.notEqual(foundProduct.id, null);
t.equal(foundProduct.name, productData[0].name);
t.equal(foundProduct.itemGroupId, productData[0].itemGroupId);
t.equal(foundProduct.unitName, productData[0].unitName);
t.equal(foundProduct.unitSize, productData[0].unitSize);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.DELETE_PRODUCTS]);
});
test("List products", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS]);
try {
const listWithZeroItems = await listProducts(token);
t.equal(0, listWithZeroItems.length);
await createProduct(token);
const listWithOneItem = await listProducts(token);
t.equal(1, listWithOneItem.length);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.LIST_ALL_WEEK_DELIVERY_PREDICTION]);
});
test("Delete product", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.DELETE_PRODUCTS]);
try {
const createdProduct = await createProduct(token);
await request(TestConfig.HOST)
.delete(`/rest/v1/products/${createdProduct.id}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.expect(204);
const dbItems = await listProducts(token);
t.equal(0, dbItems.length);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
});
test("Delete product - Forbidden", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1();
try {
const createdProduct = await createProduct(token);
await request(TestConfig.HOST)
.delete(`/rest/v1/products/${createdProduct.id}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.expect(204);
const dbItems = await listProducts(token);
t.equal(0, dbItems.length);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
});
test("Delete product created by other user", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token1 = await auth.getTokenUser1([ApplicationRoles.DELETE_WEEK_DELIVERY_PREDICTIONS]);
const token2 = await auth.getTokenUser2();
try {
const createdProduct = await createProduct(token2);
await request(TestConfig.HOST)
.delete(`/rest/v1/products/${createdProduct.id}`)
.set("Authorization", `Bearer ${token1}`)
.set("Accept", "application/json")
.expect(204);
const dbItems = await listProducts(token2);
t.equal(0, dbItems.length);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
});
test("Delete product - Forbidden", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token1 = await auth.getTokenUser1();
const token2 = await auth.getTokenUser2();
await auth.removeUser2Roles([ApplicationRoles.DELETE_WEEK_DELIVERY_PREDICTIONS]);
try {
const createdProduct = await createProduct(token1);
await request(TestConfig.HOST)
.delete(`/rest/v1/products/${createdProduct.id}`)
.set("Authorization", `Bearer ${token2}`)
.set("Accept", "application/json")
.expect(403);
const dbItems = await listProducts(token1);
t.equal(1, dbItems.length);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
});
test("Create product price", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.MANAGE_PRODUCT_PRICES]);
try {
const createdProduct = await createProduct(token);
t.notEqual(createdProduct, null);
t.notEqual(createdProduct.id, null);
const createdProductPrice = await createProductPrice(token, createdProduct);
t.notEqual(createdProductPrice, null);
t.notEqual(createdProductPrice.id, null);
t.equal(createdProductPrice.unit, "€ / kg");
t.equal(createdProductPrice.price, "100");
t.equal(createdProductPrice.productId, createdProduct.id);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
});
test("Delete product price", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.MANAGE_PRODUCT_PRICES]);
try {
const createdProduct = await createProduct(token);
t.notEqual(createdProduct, null);
t.notEqual(createdProduct.id, null);
const createdProductPrice = await createProductPrice(token, createdProduct);
t.notEqual(createdProductPrice, null);
t.notEqual(createdProductPrice.id, null);
await request(TestConfig.HOST)
.delete(`/rest/v1/products/${createdProduct.id}/prices/${createdProductPrice.id}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.expect(204);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
});
test("Find product price", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.MANAGE_PRODUCT_PRICES]);
try {
const createdProduct = await createProduct(token);
t.notEqual(createdProduct, null);
t.notEqual(createdProduct.id, null);
const createdProductPrice = await createProductPrice(token, createdProduct);
t.notEqual(createdProductPrice, null);
t.notEqual(createdProductPrice.id, null);
const foundPrice = await request(TestConfig.HOST)
.get(`/rest/v1/products/${createdProduct.id}/prices/${createdProductPrice.id}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.expect(200)
.then((response) => {
return response.body;
});
t.notEqual(foundPrice, null);
t.notEqual(foundPrice.id, null);
t.equal(foundPrice.unit, "€ / kg");
t.equal(foundPrice.price, "100");
t.equal(foundPrice.productId, createdProduct.id);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
});
test("List product prices", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.MANAGE_PRODUCT_PRICES]);
try {
const createdProduct = await createProduct(token);
t.notEqual(createdProduct, null);
t.notEqual(createdProduct.id, null);
const createdProductPrice = await createProductPrice(token, createdProduct);
t.notEqual(createdProductPrice, null);
t.notEqual(createdProductPrice.id, null);
let prices = await request(TestConfig.HOST)
.get(`/rest/v1/products/${createdProduct.id}/prices?sort=CREATED_AT_ASC`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.expect(200)
.then((response) => {
return response.body;
});
t.notEqual(prices, null);
t.equals(prices.length, 1);
await createProductPrice(token, createdProduct);
prices = await request(TestConfig.HOST)
.get(`/rest/v1/products/${createdProduct.id}/prices?sort=CREATED_AT_ASC`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.expect(200)
.then((response) => {
return response.body;
});
t.notEqual(prices, null);
t.equals(prices.length, 2);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
});
test("List product prices - 400 - no product id", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.MANAGE_PRODUCT_PRICES]);
try {
await request(TestConfig.HOST)
.get(`/rest/v1/products/${undefined}/prices`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.expect(400)
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
});
test("Update product price", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.MANAGE_PRODUCT_PRICES]);
try {
const createdProduct = await createProduct(token);
t.notEqual(createdProduct, null);
t.notEqual(createdProduct.id, null);
let createdProductPrice = await createProductPrice(token, createdProduct);
createdProductPrice.price = "200";
createdProductPrice.unit = "$ / lb";
t.notEqual(createdProductPrice, null);
t.notEqual(createdProductPrice.id, null);
const updatedProductPrice = await request(TestConfig.HOST)
.put(`/rest/v1/products/${createdProduct.id}/prices/${createdProductPrice.id}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.send(createdProductPrice)
.expect(200)
.then((response) => {
return response.body;
});
t.equal(updatedProductPrice.unit, "$ / lb");
t.equal(updatedProductPrice.price, "200");
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
});
test("Update product price - 404 - wrong product id", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.MANAGE_PRODUCT_PRICES]);
try {
const createdProduct = await createProduct(token);
t.notEqual(createdProduct, null);
t.notEqual(createdProduct.id, null);
const createdProductPrice = await createProductPrice(token, createdProduct);
t.notEqual(createdProductPrice, null);
t.notEqual(createdProductPrice.id, null);
await request(TestConfig.HOST)
.put(`/rest/v1/products/fake-uuid/prices/${createdProductPrice.id}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.send(createdProductPrice)
.expect(404);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
});
test("Update product price - 404 - wrong product price id", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.MANAGE_PRODUCT_PRICES]);
try {
const createdProduct = await createProduct(token);
t.notEqual(createdProduct, null);
t.notEqual(createdProduct.id, null);
const createdProductPrice = await createProductPrice(token, createdProduct);
t.notEqual(createdProductPrice, null);
t.notEqual(createdProductPrice.id, null);
await request(TestConfig.HOST)
.put(`/rest/v1/products/${createdProduct.id}/prices/fake-uuid`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.send(createdProductPrice)
.expect(404);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
});
test("Update product price - 400 - no price", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.MANAGE_PRODUCT_PRICES]);
try {
const createdProduct = await createProduct(token);
t.notEqual(createdProduct, null);
t.notEqual(createdProduct.id, null);
const createdProductPrice = await createProductPrice(token, createdProduct);
t.notEqual(createdProductPrice, null);
t.notEqual(createdProductPrice.id, null);
const updatedProductPrice = {
id: createdProductPrice.id,
unit: "€",
productId: createdProduct.id
};
await request(TestConfig.HOST)
.put(`/rest/v1/products/${createdProduct.id}/prices/${createdProductPrice.id}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.send(updatedProductPrice)
.expect(400);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
});
test("Update product price - 400 - no unit", async (t) => {
await database.executeFiles(testDataDir, ["product-test-setup.sql"]);
const token = await auth.getTokenUser1([ApplicationRoles.CREATE_PRODUCTS, ApplicationRoles.MANAGE_PRODUCT_PRICES]);
try {
const createdProduct = await createProduct(token);
t.notEqual(createdProduct, null);
t.notEqual(createdProduct.id, null);
const createdProductPrice = await createProductPrice(token, createdProduct);
t.notEqual(createdProductPrice, null);
t.notEqual(createdProductPrice.id, null);
const updatedProductPrice = {
id: createdProductPrice.id,
productId: createdProduct.id,
price: "200"
};
await request(TestConfig.HOST)
.put(`/rest/v1/products/${createdProduct.id}/prices/${createdProductPrice.id}`)
.set("Authorization", `Bearer ${token}`)
.set("Accept", "application/json")
.send(updatedProductPrice)
.expect(400);
} finally {
await database.executeFiles(testDataDir, ["product-test-teardown.sql"]);
}
await auth.removeUser1Roles([ApplicationRoles.CREATE_PRODUCTS]);
}); |
66c07337f1a48a2b8a721d11e325e9379f373cb9 | TypeScript | reggi/mongo-operation-design | /src/collection.ts | 2.5625 | 3 | import { FindAndModifyCommand } from './commands/find_and_modify';
import { Db } from './db'
import { ClientOptions, ClientOptionsInput } from './client_options'
import { MongoDB } from "./types"
import { maybePromise } from './utility/maybe_promise'
import { Server } from './server';
type Query = Exclude<MongoDB.Command.FindAndModify['query'], undefined>
type Sort = Exclude<MongoDB.Command.FindAndModify['sort'], undefined>
type Document = Exclude<MongoDB.Command.FindAndModify['update'], undefined>
type Options = MongoDB.CommandUserOption.FindAndModify
type Cb = MongoDB.Return.Document.Callback
type P = MongoDB.Return.Document.Promise
type OrCB<T> = T | Cb
export class Collection {
options: ClientOptions
db: Db
name: string
constructor (opt: {
options?: ClientOptionsInput
db: Db
name: string
}) {
this.name = opt.name
this.db = opt.db
this.options = this.db.options.clone(opt.options)
}
findAndModify (): P
findAndModify (callback: Cb): undefined
findAndModify (query: Query): P
findAndModify (query: Query, callback: Cb): undefined
findAndModify (query: Query, sort: Sort): P
findAndModify (query: Query, sort: Sort, callback: Cb): undefined
findAndModify (query: Query, sort: Sort, document: Document): P
findAndModify (query: Query, sort: Sort, document: Document, callback: Cb): undefined
findAndModify (query: Query, sort: Sort, document: Document, options: Options): P
findAndModify (query: Query, sort: Sort, document: Document, options: Options, callback: Cb): undefined
findAndModify (
query?: OrCB<Query>,
sort?: OrCB<Sort>,
document?: OrCB<Document>,
options?: OrCB<Options>,
callback?: Cb
): P | undefined {
const _query = () => {
if (typeof query === 'function') return {}
return query
}
const _sort = () => {
if (typeof sort === 'function') return []
return query
}
const _update = () => {
if (typeof document === 'function') return {}
if (typeof document === 'undefined') return {}
return document
}
const _callback = () => {
if (typeof callback === 'function') return callback
if (typeof options === 'function') return options
if (typeof document === 'function') return document
if (typeof sort === 'function') return sort
if (typeof query === 'function') return query
return undefined
}
const command = new FindAndModifyCommand({
findAndModify: this.name,
$db: this.db.name,
$readPreference: this.options.readPreference,
...(this.options.writeConcern ? {writeConcern: this.options.writeConcern} : {}),
query: _query(),
sort: _sort(),
update: _update()
})
return maybePromise(_callback(), (wrap) => {
const server = new Server(8);
return wrap(null, command.command(server))
})
}
}
|
07cd4d2811a0d7b225f20a7135e4b1a90c92cc9e | TypeScript | kkatzen/health-equity-tracker | /frontend/src/data/query/BreakdownFilter.ts | 3.296875 | 3 | import { ALL } from "../utils/Constants";
/**
* Specifies a set of filters to apply to a breakdown. When `include` is true,
* filters the results so that only the specified values are included. When
* `include` is false, removes the specified values and leaves the rest.
*/
export default interface BreakdownFilter {
readonly values: Readonly<string[]>;
readonly include: boolean;
}
const STANDARD_RACES = [
"American Indian and Alaska Native (Non-Hispanic)",
"Asian (Non-Hispanic)",
"Black or African American (Non-Hispanic)",
"Hispanic or Latino",
"Native Hawaiian and Pacific Islander (Non-Hispanic)",
"Some other race (Non-Hispanic)",
"Two or more races (Non-Hispanic)",
"White (Non-Hispanic)",
ALL,
];
const DECADE_AGE_BRACKETS = [
"0-9",
"10-19",
"20-29",
"30-39",
"40-49",
"50-59",
"60-69",
"70-79",
"80+",
];
export function exclude(...valuesToExclude: string[]): BreakdownFilter {
return { include: false, values: [...valuesToExclude] };
}
export function onlyInclude(...valuesToInclude: string[]): BreakdownFilter {
return { include: true, values: [...valuesToInclude] };
}
export function onlyIncludeStandardRaces(): BreakdownFilter {
return onlyInclude(...STANDARD_RACES);
}
export function onlyIncludeDecadeAgeBrackets(): BreakdownFilter {
return onlyInclude(...DECADE_AGE_BRACKETS);
}
export function excludeAll(): BreakdownFilter {
return exclude(ALL);
}
|