Datasets:

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
496800c63b0a4c44b09c138ea40b33ea1c8f07ab
TypeScript
taenito/jway-tools
/src/models/cor/DoctypeCor.ts
2.625
3
import { Document } from "../Document"; import { DoctypeNode } from "../nodes/DoctypeNode"; import { ACor } from "./ACor"; export class DoctypeCor extends ACor { addNode(doc: Document, s: string): boolean { let node: DoctypeNode = new DoctypeNode(doc.current); node.value = s; doc.current.childs.push(node); return true; } condition(s: string): boolean { return /^<!DOCTYPE /.test(s); } }
d64f0a56829bae6d637b3d3f100cebc28a7b7309
TypeScript
awave1/cursor
/src/styles/theme.ts
2.640625
3
import { FontTheme, fontsLightTheme, fontsDarkTheme } from './fonts' import { ColorTheme, colorLightTheme, colorDarkTheme } from './color' export interface Theme { readonly type: 'light' | 'dark' readonly font: FontTheme readonly colors: ColorTheme } export const lightTheme: Theme = { type: 'light', font: fontsLightTheme, colors: colorLightTheme, } export const darkTheme: Theme = { type: 'dark', font: fontsDarkTheme, colors: colorDarkTheme, }
4d8828e035ad33633f6ce6449c454a1d5d80bd2e
TypeScript
koen-serneels/knooppuntnet
/client/src/app/kpn/shared/node-integrity-check.ts
2.578125
3
// this class is generated, please do not modify export class NodeIntegrityCheck { constructor(readonly nodeName: string, readonly nodeId: number, readonly actual: number, readonly expected: number, readonly failed: boolean) { } public static fromJSON(jsonObject): NodeIntegrityCheck { if (!jsonObject) { return undefined; } return new NodeIntegrityCheck( jsonObject.nodeName, jsonObject.nodeId, jsonObject.actual, jsonObject.expected, jsonObject.failed ); } }
5e79e5b487ec8f3607d379c51c27e63c35aad441
TypeScript
Ethicoders/gcms-backend
/src/utils/json.ts
2.6875
3
import * as path from 'path'; import { writeFile, readFile } from '@/async/fs'; export default class { private path; public constructor(filePath: string) { this.path = path.normalize(filePath) } public async read() { return JSON.parse(await readFile(this.path)); } public write(data: any[] | {}) { return writeFile(this.path, JSON.stringify(data, null, 2)); } }
0e76bfac59c19229bed5ffe0f7c7a06c48526f92
TypeScript
maxshymchuk/UnoRetranslator
/src/transliteration.ts
2.984375
3
function getAssociation(char: string) { const upCaseChar = char.toUpperCase(); const isUpperCase = upCaseChar == char; switch (upCaseChar) { case 'А': return isUpperCase ? 'A' : 'a'; case 'Б': return isUpperCase ? 'B' : 'b'; case 'В': return isUpperCase ? 'V' : 'v'; case 'Г': return isUpperCase ? 'G' : 'g'; case 'Д': return isUpperCase ? 'D' : 'd'; case 'Е': return isUpperCase ? 'E' : 'e'; case 'Ё': return isUpperCase ? 'JO' : 'jo'; case 'Ж': return isUpperCase ? 'ZH' : 'zh'; case 'З': return isUpperCase ? 'Z' : 'z'; case 'И': return isUpperCase ? 'I' : 'i'; case 'Й': return isUpperCase ? 'J' : 'j'; case 'К': return isUpperCase ? 'K' : 'k'; case 'Л': return isUpperCase ? 'L' : 'l'; case 'М': return isUpperCase ? 'M' : 'm'; case 'Н': return isUpperCase ? 'N' : 'n'; case 'О': return isUpperCase ? 'O' : 'o'; case 'П': return isUpperCase ? 'P' : 'p'; case 'Р': return isUpperCase ? 'R' : 'r'; case 'С': return isUpperCase ? 'S' : 's'; case 'Т': return isUpperCase ? 'T' : 't'; case 'У': return isUpperCase ? 'U' : 'u'; case 'Ф': return isUpperCase ? 'F' : 'f'; case 'Х': return isUpperCase ? 'H' : 'h'; case 'Ц': return isUpperCase ? 'C' : 'c'; case 'Ч': return isUpperCase ? 'CH' : 'ch'; case 'Ш': return isUpperCase ? 'SH' : 'sh'; case 'Щ': return isUpperCase ? 'SHCH' : 'shch';; case 'Ы': return isUpperCase ? 'Y' : 'y'; case 'Э': return isUpperCase ? 'JE' : 'je'; case 'Ю': return isUpperCase ? 'JU' : 'ju'; case 'Я': return isUpperCase ? 'JA' : 'ja'; case 'Ь': return '\''; case 'Ъ': return '#'; default: return char; } } export function getTranslit(s: string) { return s.split('').map(getAssociation).join(""); }
6526c444728808f2bdfc2933aad068942e6e80cf
TypeScript
Skp80/Verdant
/verdant/verdant-model/history/store/node-history.ts
2.90625
3
import { Nodey } from "../../nodey"; import { OriginPointer } from "./origin-pointer"; import { log } from "../../notebook"; const DEBUG = false; /* * Just a container for a list of nodey versions */ export class NodeHistory<T extends Nodey> { originPointer: OriginPointer | null = null; protected versions: T[] = []; getAllVersions(): T[] { return this.versions.slice(0); } addVersion(nodey: T): void { let ver = this.versions.push(nodey); nodey.version = ver - 1; } getVersion(ver: number): T | undefined { return ver > -1 ? this.versions[ver] : undefined; } find( callbackfn: (value: T, index: number, array: T[]) => boolean ): T | undefined { return this.versions.find(callbackfn); } foreach(callbackfn: (value: T, index: number, array: T[]) => void): void { return this.versions.forEach(callbackfn); } // wrap to allow override implementation of filter filter(callbackfn: (value: T, index: number, array: T[]) => unknown): T[] { return this.versions.filter(callbackfn); } // wrap to allow override implementation of map map(callbackfn: (value: T, index?: number, array?: T[]) => any): any[] { return this.versions.map(callbackfn); } get name() { let latest = this.versions[this.versions.length - 1]; if (latest) return ( latest.typeChar + "." + (latest.id !== undefined ? latest.id : "???") ); } get latest(): T { return this.versions[this.versions.length - 1]; } get length() { return this.versions.length; } addOriginPointer(origin: Nodey) { this.originPointer = new OriginPointer(origin); } toJSON(): NodeHistory.SERIALIZE { return this.serialize(this.versions); } fromJSON( jsn: NodeHistory.SERIALIZE, factory: (dat: Nodey.SERIALIZE) => T, id?: number ) { if (DEBUG) log("FACTORY DATA", jsn); this.versions = jsn.versions.map( (nodeDat: Nodey.SERIALIZE, version: number) => { if (nodeDat.origin) this.originPointer = new OriginPointer(nodeDat.origin); let nodey = factory(nodeDat); nodey.id = id; nodey.version = version; //log("MADE NODEY FROM DATA", nodey, nodeDat); return nodey; } ); } sliceByTime(fromTime: number, toTime: number): NodeHistory.SERIALIZE { let slice: T[] = []; // get the first index of versions that happen on or after fromTime let i = this.versions.findIndex((nodey) => { return nodey.created >= fromTime && nodey.created < toTime; }); let nodey: T = this.versions[i]; // check each nodey to see if it is within time while (nodey && nodey.created >= fromTime && nodey.created < toTime) { slice.push(nodey); i++; nodey = this.versions[i]; } return this.serialize(slice); } sliceByVer(fromVer: number, toVer: number): NodeHistory.SERIALIZE { let slice = this.versions.slice(fromVer, toVer); return this.serialize(slice); } // helper method protected serialize(vers: T[]): NodeHistory.SERIALIZE { let data: Nodey.SERIALIZE[] = vers.map((node) => node.toJSON()); if (this.originPointer && data.length > 0) data[data.length - 1].origin = this.originPointer.origin; return { artifact_name: this.name || "", versions: data }; } } export namespace NodeHistory { export type SERIALIZE = { artifact_name: string; versions: Nodey.SERIALIZE[]; }; }
e8d6c0fc49334035f7609c1510ec49639fce6f19
TypeScript
Aleix1379/click-counter-web
/src/app/services/local-storage/local-storage.service.ts
2.90625
3
import {Injectable} from '@angular/core'; import {Token} from '../../interfaces/token'; @Injectable({ providedIn: 'root' }) export class LocalStorageService { /** * value = storage[key] */ private static getItem<T>(key: string): T { const item = localStorage.getItem(key); if (item) { return JSON.parse(item); } return null; } /** * Returns the name of the nth key in the list, or null if n is greater * than or equal to the number of key/value pairs in the object. */ private static key(index: number): string | null { return localStorage.key(index); } /** * delete storage[key] */ private static removeItem(key: string): void { localStorage.removeItem(key); } /** * storage[key] = value */ private static setItem<T>(key: string, value: T): void { localStorage.setItem(key, JSON.stringify(value)); } constructor() { } public getAuthToken(): Token { return LocalStorageService.getItem('auth-token'); } public setAuthToken(authToken: Token): void { LocalStorageService.setItem('auth-token', authToken); } public removeAuthToken() { LocalStorageService.removeItem('auth-token'); } }
a87dc965dc07c4662048b97cda10cfccc87f4324
TypeScript
funya/zerro
/src/helpers/useSearchParam.ts
2.640625
3
import { useCallback } from 'react' import { useHistory, useLocation } from 'react-router' function getModifiedPath(key: string, value?: string | null) { const url = new URL(window.location.href) url.searchParams.delete(key) if (value) url.searchParams.append(key, value) const path = url.pathname + url.search return path } export function useSearchParam( key: string ): [string | null, (id?: string | null) => void] { const history = useHistory() const location = useLocation() const value = new URLSearchParams(location.search).get(key) const setValue = useCallback( (id?: string | null) => { history.push(getModifiedPath(key, id)) }, [history, key] ) return [value, setValue] }
6745b611f123cbc9563f8b5379b2fff53c2dc8df
TypeScript
artronics/pepper-graphics
/src/graphics/measure/Transformation.ts
3.015625
3
import { Coordinate } from './Rect'; export type Transformation = [ [number, number, number], [number, number, number], [0, 0, 1] ]; const unit = (): Transformation => [ [1, 0, 0], [0, 1, 0], [0, 0, 1], ]; export const move = ([x, y]: Coordinate, transformation?: Transformation): Transformation => { const t = transformation ?? unit(); t[0][2] = t[0][2] + x; t[1][2] = t[1][2] + y; return t; }; export type Translation = [number, number];
29d8dd60e7a80c7ab0da3415c29b6c1271f2334f
TypeScript
PatrickRose/advent-of-code
/typescript/src/2020/11_SeatingSystem.ts
3.53125
4
import getInput from "./util/getInput"; const input = getInput(11) type Position = { newPosition: (numAdjacent: number, partTwo: boolean) => Position, toString: () => string, } const floor: Position = { newPosition: () => floor, toString: () => '.', }; const occupied: Position = { newPosition(numAdjacent, partTwo): Position { const maxAdjacent = partTwo ? 5 : 4; return numAdjacent >= maxAdjacent ? emptySeat : occupied; }, toString: () => '#', } const emptySeat: Position = { newPosition(numAdjacent): Position { return numAdjacent == 0 ? occupied : emptySeat; }, toString: () => 'L', } const charMap: Map<string, Position> = new Map<string, Position>(); charMap.set('#', occupied); charMap.set('L', emptySeat); charMap.set('.', floor); type Grid = Array<Array<Position>>; let baseGrid: Grid = input.split("\n").map( (row): Array<Position> => { return row.split('').map( (char): Position => { const mappedVal = charMap.get(char); if (mappedVal === undefined) { throw new Error(`Unknown char ${char}`) } return mappedVal; } ) } ); function occupiedAroundPoint(x: number, y: number, grid: Grid, checkforFirstSeat: boolean): number { const looper = [-1, 0, 1]; if (checkforFirstSeat) { return looper.reduce( (previous, xCheck): number => { return previous + looper.filter( (yCheck): boolean => { if (xCheck == 0 && yCheck == 0) { return false; } let xPos = x + xCheck; let yPos = y + yCheck; while (grid[yPos] !== undefined && grid[yPos][xPos] !== undefined) { const position = grid[yPos][xPos]; switch (position) { case floor: yPos += yCheck; xPos += xCheck; break; case emptySeat: return false; case occupied: return true; } } return false; } ).length }, 0 ); } else { return looper.reduce( (previous, xCheck): number => { const xPos = x + xCheck; if (xPos < 0 || xPos >= grid[0].length) { return previous; } return previous + looper.filter( (yCheck): boolean => { const yPos = y + yCheck; if (yPos == y && xPos == x) { return false; } if (yPos < 0 || yPos >= grid.length) { return false; } return grid[yPos][xPos] == occupied; } ).length }, 0 ); } } function goUntilStable(baseGrid: Grid, part2: boolean): number { let grid: Grid = baseGrid.map(row => row.slice()); let changeMade: boolean; let i = 0; do { i += 1; const newGrid: Grid = []; changeMade = false; grid.forEach( (row, y) => { const newRow: Array<Position> = []; row.forEach( (position, x) => { const numAdjacent = occupiedAroundPoint(x, y, grid, part2); const newPosition = position.newPosition(numAdjacent, part2); newRow.push(newPosition) changeMade = changeMade || newPosition != position; } ); newGrid.push(newRow); } ); grid = newGrid; } while (changeMade) return grid.reduce( (prev, row): number => { return prev + row.filter(p => p == occupied).length }, 0 ); } console.log(`Part 1: ${goUntilStable(baseGrid, false)}`) console.log(`Part 2: ${goUntilStable(baseGrid, true)}`)
e34cad39cd2649fd23951f755c34032bafd36fa0
TypeScript
mohankumart/typescript
/interfaces/app-functions.ts
3.40625
3
interface DoubleValueFunc { (number1: number, number2: number): number; } let myDoubleFunction: DoubleValueFunc; myDoubleFunction = function(value1: number, value2: number){ return (value1 + value2) * 2; } console.log(myDoubleFunction(10, 20));
56f3e9d52a03f30e881fea6bcfe9c3290cb38a3d
TypeScript
ArkEcosystem/core
/packages/core-kernel/src/services/attributes/attribute-map.ts
2.96875
3
import { get, has, set, unset, cloneDeep } from "@arkecosystem/utils"; import { strictEqual } from "assert"; import { assert } from "../../utils"; import { AttributeSet } from "./attribute-set"; export class AttributeMap { /** * @private * @type {object} * @memberof AttributeMap */ private attributes: object = {}; /** * Creates an instance of AttributeMap. * * @param {AttributeSet} knownAttributes * @memberof AttributeMap */ public constructor(private readonly knownAttributes: AttributeSet) {} /** * @returns {object} * @memberof AttributeMap */ public all(): object { return this.attributes; } /** * @template T * @param {string} key * @param {T} [defaultValue] * @returns {(T | undefined)} * @memberof AttributeMap */ public get<T>(key: string, defaultValue?: T): T { this.assertKnown(key); const value: T | undefined = get(this.attributes, key) ?? defaultValue; assert.defined<T>(value); return value; } /** * @template T * @param {string} key * @param {T} value * @returns {boolean} * @memberof AttributeMap */ public set<T>(key: string, value: T): boolean { this.assertKnown(key); set(this.attributes, key, value); return this.has(key); } /** * @param {string} key * @returns {boolean} * @memberof AttributeMap */ public forget(key: string): boolean { this.assertKnown(key); unset(this.attributes, key); return !this.has(key); } /** * @returns {boolean} * @memberof AttributeMap */ public flush(): boolean { this.attributes = {}; return Object.keys(this.attributes).length === 0; } /** * @param {string} key * @returns {boolean} * @memberof AttributeMap */ public has(key: string): boolean { this.assertKnown(key); return has(this.attributes, key); } /** * @returns {AttributeMap} * @memberof AttributeMap */ public clone(): AttributeMap { const cloned = new AttributeMap(this.knownAttributes); cloned.attributes = cloneDeep(this.attributes); return cloned; } /** * @private * @param {string} key * @memberof AttributeMap */ private assertKnown(key: string): void { strictEqual(this.knownAttributes.has(key), true, `Unknown attribute: ${key}`); } }
61f40b57d65f06c7b50ed5cff65a4b8357349b4a
TypeScript
bhuvinth/travel-aggregator
/src/core/applicationService/flightService.spec.ts
2.625
3
import FlightSourceApiAdapter, { flights, flights as flightsMockData, } from './mocks/flightSourceApiAdapter.mock'; import FlightSourceApiFailAdapter from './mocks/flightSourceApiAdapter.fail.mock'; import FlightService from './flightService'; describe('Test Flight Service for unique flight data being returned', () => { it('Should return unique data > when both data source returns same data.', async () => { const flightSource1Adapter = new FlightSourceApiAdapter(flights); const flightSource1AdapterSpy = jest.spyOn(flightSource1Adapter, 'getFlightDetails'); const flightServiceObj = new FlightService([flightSource1Adapter, flightSource1Adapter]); const flightResponse = await flightServiceObj.getFlightDetailsFromAllSources(); expect(flightSource1AdapterSpy).toHaveBeenCalledTimes(2); expect(flightResponse).toEqual(flightsMockData); }); it('Should return unique data > when both data source returns data with duplicates.', async () => { const mockFlights = [...flightsMockData]; mockFlights.push(mockFlights[0]); const flightSource1Adapter = new FlightSourceApiAdapter(mockFlights); const flightSource1AdapterSpy = jest.spyOn(flightSource1Adapter, 'getFlightDetails'); const flightServiceObj = new FlightService([flightSource1Adapter, flightSource1Adapter]); const flightResponse = await flightServiceObj.getFlightDetailsFromAllSources(); expect(flightSource1AdapterSpy).toHaveBeenCalledTimes(2); expect(flightResponse).toEqual(flightsMockData); }); it('Should return data > when one source returns an error and other source returns data', async () => { const flightSource1Adapter = new FlightSourceApiAdapter(flightsMockData); const flightSource2Adapter = new FlightSourceApiFailAdapter(); const flightSource1AdapterSpy = jest.spyOn(flightSource1Adapter, 'getFlightDetails'); const flightSource2AdapterSpy = jest.spyOn(flightSource2Adapter, 'getFlightDetails'); const flightServiceObj = new FlightService([flightSource1Adapter, flightSource2Adapter]); const flightResponse = await flightServiceObj.getFlightDetailsFromAllSources(); expect(flightSource1AdapterSpy).toHaveBeenCalledTimes(1); expect(flightSource2AdapterSpy).toHaveBeenCalledTimes(1); expect(flightResponse).toEqual(flightsMockData); }); });
74e7612899ea2b1608dc406a8621888202e1241d
TypeScript
AndonMitev/Work
/work/src/app/store/reducers/user.reducers.ts
2.921875
3
import * as UserActions from '../actions/user.actions'; import { UserState } from '../state/user.state'; const INITIAL_STATE: UserState = { userState: null, }; function sendUserValueToService (state, userInputValue) { state.inputValue = userInputValue; return state; } function loadUser(state: UserState, payload) { state.userState = payload; return state; } export function userReducer(state: UserState = INITIAL_STATE, action: UserActions.Types) { switch (action.type) { case UserActions.SEND_VALUE_FROM_INPUT_TO_SERVICE: return sendUserValueToService(state, action.payload); case UserActions.LOAD_USER: return loadUser(state, action.payload); default: return state; } }
f6b05d972cfaf6a89a7bbdf2336ae0d08364c668
TypeScript
andrerpena/chatjs
/ChatJs/js/jquery.chatjs.friendswindow.ts
2.828125
3
/// <reference path="../../Scripts/Typings/jquery/jquery.d.ts"/> /// <reference path="jquery.chatjs.interfaces.ts"/> /// <reference path="jquery.chatjs.adapter.ts"/> /// <reference path="jquery.chatjs.utils.ts"/> /// <reference path="jquery.chatjs.window.ts"/> /// <reference path="jquery.chatjs.userlist.ts"/> interface JQueryStatic { chatFriendsWindow: (options: ChatFriendsWindowOptions) => ChatFriendsWindow; } class ChatFriendsWindowState { isMaximized: boolean; } class ChatFriendsWindowOptions { adapter: IAdapter; // the title for the friend list titleText: string; // room id roomId: number; // content height contentHeight: number; // whether or not this window is maximized isMaximized: boolean; // called when the user minimizes or maximizes the window onStateChanged: (isMaximized: boolean) => void; // number of pixel this window is far from the right edge offsetRight: number; // when the user clicks another user in the user list userClicked: (userId: number) => void; // current user id userId: number; emptyRoomText: string; } // window that contains a list of friends. This component is used as opposed to "jquery.chatjs.rooms". The "rooms" component // should be used when the user has the ability to select rooms and broadcast them. The "friends window" is used when you want a // Facebook style friends list. class ChatFriendsWindow implements IWindow<ChatFriendsWindowState> { constructor(options: ChatFriendsWindowOptions) { var defaultOptions = new ChatFriendsWindowOptions(); defaultOptions.titleText = "Friends"; defaultOptions.isMaximized = true; defaultOptions.offsetRight = 10; defaultOptions.emptyRoomText = "No users available for chatting."; this.options = $.extend({}, defaultOptions, options); this.options.adapter.server.enterRoom(this.options.roomId, () => { // loads the user list }); var chatWindowOptions = new ChatWindowOptions(); chatWindowOptions.title = this.options.titleText; chatWindowOptions.canClose = false; chatWindowOptions.height = 300; chatWindowOptions.isMaximized = this.options.isMaximized; chatWindowOptions.onMaximizedStateChanged = (chatWindow: ChatWindow, isMaximized: boolean) => { this.options.onStateChanged(isMaximized); }; chatWindowOptions.onCreated = window => { // once the chat window is created, it's time to add content var userListOptions = new UserListOptions(); userListOptions.adapter = this.options.adapter; userListOptions.roomId = this.options.roomId; userListOptions.userId = this.options.userId; userListOptions.height = this.options.contentHeight; userListOptions.excludeCurrentUser = true; userListOptions.emptyRoomText = this.options.emptyRoomText; userListOptions.userClicked = this.options.userClicked; window.$windowInnerContent.userList(userListOptions); }; this.chatWindow = $.chatWindow(chatWindowOptions); this.chatWindow.setRightOffset(this.options.offsetRight); } focus() { } setRightOffset(offset: number): void { this.chatWindow.setRightOffset(offset); } getWidth(): number { return this.chatWindow.getWidth(); } getState(): ChatFriendsWindowState { var state = new ChatFriendsWindowState(); state.isMaximized = this.chatWindow.getState(); return state; } setState(state: ChatFriendsWindowState) { this.chatWindow.setState(state.isMaximized); } options: ChatFriendsWindowOptions; chatWindow: ChatWindow; } $.chatFriendsWindow = options => { var friendsWindow = new ChatFriendsWindow(options); return friendsWindow; };
ce0966ba0b4719d265dd0af6665d3746096a88b5
TypeScript
patriciasfabbri/MinervaCNH
/src/util/roulette.ts
2.734375
3
export class Roulette { computVisionSubs(req: any, callBack: Function) { if (!global.computVisionCalls || global.computVisionCalls == null) { global.computVisionCalls = 0; } if (global.computVisionCalls >= 74) { global.computVisionCalls = 0; } global.computVisionCalls += 1; // console.log("global.computVisionCalls==> " + global.computVisionCalls.toString()); // console.log("IntDiv " + Math.floor(global.computVisionCalls/10).toString()); req.computVisionSub = Math.floor(global.computVisionCalls / 5); // console.log("global.computVisionCalls"); // console.log(global.computVisionCalls); // console.log("typeof(global.computVisionCalls)"); // console.log(typeof(global.computVisionCalls)); //req.computVisionSub = global.arrComputVisionSubs[Math.floor(global.computVisionCalls/10)] // console.log("Subs " + req.computVisionSub); callBack(); } computVsnOCRsubs(req: any, callBack: Function) { if (!global.computVsnOCRCalls || global.computVsnOCRCalls == null) { global.computVsnOCRCalls = 0; } if (global.computVsnOCRCalls >= 19) { global.computVsnOCRCalls = 0; } global.computVsnOCRCalls += 1; req.computVsnOCRSub = Math.floor(global.computVsnOCRCalls / 10); callBack(); } luisOCRSubs(req: any, callBack: Function) { if (!global.luisOCRCalls || global.luisOCRCalls == null) { global.luisOCRCalls = 0; } global.luisOCRCalls += 1; if (global.luisOCRCalls >= 10) { global.luisOCRCalls = 0; } req.luisOCRsub = global.luisOCRCalls; callBack(); } faceRecogSubs(req: any, callBack: Function) { if (!global.faceRecogCalls || global.faceRecogCalls == null) { global.faceRecogCalls = 0; } if (global.faceRecogCalls >= 149) { global.faceRecogCalls = 0; } global.faceRecogCalls += 1; req.faceRecogSub = Math.floor(global.faceRecogCalls / 10); // console.log("global.faceRecogSub"); // console.log(global.faceRecogCalls); // console.log("typeof(global.faceRecogCalls)"); // console.log(typeof(global.faceRecogCalls)); callBack(); } }
6e7a376803d9ae681baa9faff484bcabd6faf463
TypeScript
charleslana/nestjs
/src/courses/courses.service_backup.ts
2.890625
3
import {HttpException, HttpStatus, Injectable} from '@nestjs/common'; import {Course} from './entities/course.entity'; @Injectable() export class CoursesService { private courses: Course[] = [ { id: 1, name: 'Course NestJs', description: 'Course NestJs description', tags: [ 'node.js', 'nestjs', 'javascript' ] } ]; findAll(): Course[] { return this.courses; } findById(id: string): Course { const courseExists = this.courses.find((course: Course) => course.id === Number(id)); if (!courseExists) { throw new HttpException(`Course ID ${id} not found.`, HttpStatus.NOT_FOUND); } return courseExists; } create(createCourseDto: any): any { this.courses.push(createCourseDto); return createCourseDto; } update(id: string, updateCourseDto: any): any { const indexCourse = this.courses.findIndex((course: Course) => course.id === Number(id)); this.courses[indexCourse] = updateCourseDto; } delete(id: string): any { const indexCourse = this.courses.findIndex((course: Course) => course.id === Number(id)); if (indexCourse >= 0) { this.courses.splice(indexCourse, 1); } } }
909a6d90538c477867872f4ce959035c29d07f5a
TypeScript
rodzewich/playground
/lib/compiler/compiler.ts
2.75
3
/// <reference path="../../types/node/node.d.ts" /> import {isDefined} from "../utils/common"; import {IException as IExceptionBase} from "../exception"; import {IException} from "./exception"; import {ICssErrorsHelper, CssErrorsHelper} from "./helpers/cssErrorsHelper"; import {IWebRootDirectoryHelper, WebRootDirectoryHelper} from "./helpers/webRootDirectoryHelper"; import {ICacheHelper, CacheHelper} from "./helpers/cacheHelper"; import {ISourcesDirectoryHelper, SourcesDirectoryHelper} from "../helpers/sourcesDirectoryHelper"; import {IFilenameHelper, FilenameHelper} from "./helpers/filenameHelper" export interface IOptions { filename:string; sourcesDirectory:string; errorBackgroundColor?:string; errorTextColor?:string; errorBlockPadding?:string; errorFontSize?:string; webRootDirectory?:string; useCache?:boolean; } export interface ICompiler { compile(callback:(errors:IException[], result:any) => void):void; } export abstract class Compiler implements ICompiler { private _filenameHelper:IFilenameHelper; private _cacheHelper:ICacheHelper; private _webRootDirectoryHelper:IWebRootDirectoryHelper; private _cssErrorsHelper:ICssErrorsHelper; private _sourcesDirectoryHelper:ISourcesDirectoryHelper; protected createCacheHelper():ICacheHelper { return new CacheHelper(); } protected getCacheHelper():ICacheHelper { if (!this._cacheHelper) { this._cacheHelper = this.createCacheHelper(); } return this._cacheHelper; } protected createWebRootDirectoryHelper():IWebRootDirectoryHelper { return new WebRootDirectoryHelper(); } protected getWebRootDirectoryHelper():IWebRootDirectoryHelper { if (!this._webRootDirectoryHelper) { this._webRootDirectoryHelper = this.createWebRootDirectoryHelper(); } return this._webRootDirectoryHelper; } protected createCssErrorsHelper():ICssErrorsHelper { return new CssErrorsHelper(); } protected getCssErrorsHelper():ICssErrorsHelper { if (!this._cssErrorsHelper) { this._cssErrorsHelper = this.createCssErrorsHelper(); } return this._cssErrorsHelper; } protected createSourcesDirectoryHelper():ISourcesDirectoryHelper { return new SourcesDirectoryHelper(); } protected getSourcesDirectoryHelper():ISourcesDirectoryHelper { if (!this._sourcesDirectoryHelper) { this._sourcesDirectoryHelper = this.createSourcesDirectoryHelper(); } return this._sourcesDirectoryHelper; } protected createFilenameHelper():IFilenameHelper { return new FilenameHelper(); } protected getFilenameHelper():IFilenameHelper { if (!this._filenameHelper) { this._filenameHelper = this.createFilenameHelper(); } return this._filenameHelper; } constructor(options?:IOptions) { if (options && isDefined(options.filename)) { this.setFilename(options.filename); } if (options && isDefined(options.sourcesDirectory)) { this.setSourcesDirectory(options.sourcesDirectory); } if (options && isDefined(options.errorBackgroundColor)) { this.setCssErrorsBackgroundColor(options.errorBackgroundColor); } if (options && isDefined(options.errorTextColor)) { this.setCssErrorsTextColor(options.errorTextColor); } if (options && isDefined(options.errorBlockPadding)) { this.setCssErrorsBlockPadding(options.errorBlockPadding); } if (options && isDefined(options.errorFontSize)) { this.setCssErrorsFontSize(options.errorFontSize); } if (options && isDefined(options.useCache)) { this.setIsCacheUsed(options.useCache); } if (options && isDefined(options.webRootDirectory)) { this.setWebRootDirectory(options.webRootDirectory); } } protected isCacheUsed():boolean { return this.getCacheHelper().isUsed(); } protected getIsCacheUsed():boolean { return this.getCacheHelper().getIsUsed(); } protected setIsCacheUsed(value:boolean):void { return this.getCacheHelper().setIsUsed(value); } protected getSourcesDirectory():string { return this.getSourcesDirectoryHelper().getLocation(); } protected setSourcesDirectory(value:string):void { this.getSourcesDirectoryHelper().setLocation(value); } protected getWebRootDirectory():string { return this.getWebRootDirectoryHelper().getLocation(); } protected setWebRootDirectory(value:string):void { this.getWebRootDirectoryHelper().setLocation(value); } protected getCssErrorsBackgroundColor():string { return this.getCssErrorsHelper().getBackgroundColor(); } protected setCssErrorsBackgroundColor(value:string):void { this.getCssErrorsHelper().setBackgroundColor(value); } protected getCssErrorsTextColor():string { return this.getCssErrorsHelper().getTextColor(); } protected setCssErrorsTextColor(value:string):void { this.getCssErrorsHelper().setTextColor(value); } protected getCssErrorsBlockPadding():string { return this.getCssErrorsHelper().getBlockPadding(); } protected setCssErrorsBlockPadding(value:string):void { this.getCssErrorsHelper().setBlockPadding(value); } protected getCssErrorsFontSize():string { return this.getCssErrorsHelper().getFontSize(); } protected setCssErrorsFontSize(value:string):void { return this.getCssErrorsHelper().setFontSize(value); } protected createCssErrors(errors:IExceptionBase[]):string { return this.getCssErrorsHelper().create(errors) } protected getFilename():string { return this.getFilenameHelper().getFilename(); } protected setFilename(filename:string):void { this.getFilenameHelper().setFilename(filename); } abstract compile(callback:(errors:IException[], result:any) => void):void; }
1201da7bdf5e23cac036285988e30745013c70ad
TypeScript
simplegis/sakura-node-ts
/src/test/sqlquery/testupdatequery_stock_issue.ts
2.5625
3
// Copyright 2016 Frank Lin (lin.xiaoe.f@gmail.com). All rights reserved. // Use of this source code is governed a license that can be found in the LICENSE file. import * as chai from "chai"; import {TableName, Column} from "../../base/decorator"; import {Model, SqlType, SqlFlag} from "../../base/model"; import {UpdateQuery} from "../../sqlquery/updatequery"; @TableName("stocks") export class Stock extends Model { @Column("stock_id", SqlType.VARCHAR_255, SqlFlag.NOT_NULL, "股票代码,如 SZ000333") stockId: string; @Column("uid", SqlType.INT, SqlFlag.NOT_NULL, "用户 ID") uid: number; @Column("diluted_cost", SqlType.INT, SqlFlag.NOT_NULL, "摊薄成本") dilutedCost: number; // in RMB fen. @Column("carrying_cost", SqlType.INT, SqlFlag.NOT_NULL, "持仓成本") carryingCost: number; // in RMB fen. @Column("sizing", SqlType.INT, SqlFlag.NOT_NULL, "持仓数") sizing: number; // in unit share. @Column("expect_out", SqlType.INT, SqlFlag.NOT_NULL, "期望卖出价格(单位:分)") expectOut: number = 0; // in RMB fen. @Column("expect_in", SqlType.INT, SqlFlag.NOT_NULL, "期望买进价格(单位:分)") expectIn: number = 0; // in RMB fen. init(uid: number, stockId: string, dilutedCost: number, carryingCost: number, sizing: number, expectOut?: number, expectIn?: number): void { this.uid = uid; this.stockId = stockId; this.dilutedCost = dilutedCost; this.carryingCost = carryingCost; this.sizing = sizing; if (expectIn) this.expectIn = expectIn; if (expectOut) this.expectOut = expectOut; } } describe("Test UpdateQuery (issues)", () => { let stock: Stock = new Stock(); stock.init(19900106, "SZ000333", 0, 0, 0, 0, 0); it("Stock update sql should include carryingCost and dilutedCost while they are equal to 0", () => { const sql: string = new UpdateQuery().fromModel(stock).where(`stock_id='${stock.stockId}'`, `uid=${stock.uid}`).build(); const expectSql: string = `UPDATE stocks SET stock_id='SZ000333',uid=19900106,diluted_cost=0,carrying_cost=0,sizing=0,expect_out=0,expect_in=0 WHERE stock_id='SZ000333' AND uid=19900106;`; chai.expect(sql).to.equal(expectSql); }); });
a237abc990e2f58ec9f2870c16bd4be8e20db592
TypeScript
clementFrade/OnTientLeBonBout2
/OnTientLeBonBout/src/main/webapp/app/shared/model/media.model.ts
2.71875
3
export interface IMedia { id?: number; adresse?: string; type?: string; nom?: string; } export class Media implements IMedia { constructor(public id?: number, public adresse?: string, public type?: string, public nom?: string) {} }
698fbee86f8d0e4302772ca637e1d168620cb42b
TypeScript
PluginSystem-StudyManager/Server
/src/homepage/home.ts
2.828125
3
let slideIndex = 1; showSlides(slideIndex); // Next/previous controls function plusSlides(n) { showSlides(slideIndex += n); } // Thumbnail image controls function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { let i; let slides = <HTMLCollectionOf<HTMLDivElement>>document.getElementsByClassName("mySlides"); if (n > slides.length) { slideIndex = 1 } if (n < 1) { slideIndex = slides.length } for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } slides[slideIndex - 1].style.display = "block"; } setInterval(plusSlides, 6000, 1)
f5b145071f0123f8ac954cacf6e9c4f9e093d6da
TypeScript
huaweicloud/huaweicloud-sdk-nodejs-v3
/services/ces/v2/model/ListAlarmHistoriesRequest.ts
2.59375
3
export class ListAlarmHistoriesRequest { private 'alarm_id'?: string; public name?: string; public status?: string; public level?: number; public namespace?: string; private 'resource_id'?: string; public from?: string; public to?: string; public offset?: number; public limit?: number; public constructor() { } public withAlarmId(alarmId: string): ListAlarmHistoriesRequest { this['alarm_id'] = alarmId; return this; } public set alarmId(alarmId: string | undefined) { this['alarm_id'] = alarmId; } public get alarmId(): string | undefined { return this['alarm_id']; } public withName(name: string): ListAlarmHistoriesRequest { this['name'] = name; return this; } public withStatus(status: string): ListAlarmHistoriesRequest { this['status'] = status; return this; } public withLevel(level: number): ListAlarmHistoriesRequest { this['level'] = level; return this; } public withNamespace(namespace: string): ListAlarmHistoriesRequest { this['namespace'] = namespace; return this; } public withResourceId(resourceId: string): ListAlarmHistoriesRequest { this['resource_id'] = resourceId; return this; } public set resourceId(resourceId: string | undefined) { this['resource_id'] = resourceId; } public get resourceId(): string | undefined { return this['resource_id']; } public withFrom(from: string): ListAlarmHistoriesRequest { this['from'] = from; return this; } public withTo(to: string): ListAlarmHistoriesRequest { this['to'] = to; return this; } public withOffset(offset: number): ListAlarmHistoriesRequest { this['offset'] = offset; return this; } public withLimit(limit: number): ListAlarmHistoriesRequest { this['limit'] = limit; return this; } }
c7b2cedb21d81c7ec20a1c4bd24c3084949d3760
TypeScript
TaHuuCong/nash-training
/src/app/hero-thc/super-hero-list-in-star-war/super-hero-list-in-star-war.component.ts
2.546875
3
import { Component, OnInit, ViewEncapsulation, ElementRef, ViewChild } from '@angular/core'; import { SuperHero } from './superhero'; @Component({ selector: 'thc-super-hero-list-in-star-war', templateUrl: './super-hero-list-in-star-war.component.html', styleUrls: ['./super-hero-list-in-star-war.component.css'], // encapsulation: ViewEncapsulation.None, }) export class SuperHeroListInStarWarComponent implements OnInit { styleBorder = { 'border': '1px solid red' }; // thuộc tính superhero là 1 mảng các SuperHero (SuperHero là class đã tạo ở superhero.ts) superhero: SuperHero[] = [ { name: 'Tạ Hữu Công 1', weight: 70, height: 178, image: { url: 'https://www.tiepphan.com/assets/uploads/2016/12/component-hierarchy.png' } }, { name: 'Tạ Hữu Công 2', weight: 70, height: 178, image: { url: 'https://www.tiepphan.com/assets/uploads/2016/12/component-hierarchy.png' } }, { name: 'Tạ Hữu Công 3', weight: 70, height: 178, image: null }, ]; image: any = {}; message = 'Hello Công'; printable = true; index; collection; textes = []; // public txtName: string; @ViewChild('yourName') herName: ElementRef; doClick() { this.message = 'Đẹp trai'; setTimeout(() => { this.message = 'Hot'; }, 1000); } hideMess() { this.printable = !this.printable; } changeTab(index) { this.index = index; } constructor() { this.collection = [{ id: 1 }, { id: 2 }, { id: 3 }]; } ngOnInit() { this.image.url = 'https://www.tiepphan.com/assets/uploads/2016/12/component-hierarchy.png'; } getItems() { this.collection = this.getItemsFromServer(); } getItemsFromServer() { return [{ id: 1 }, { id: 3 }, { id: 2 }, {id: 4}]; } // mỗi item là 1 phần tử của collection, index là chỉ số tương ứng của item // return theo index thì sự cập nhật sẽ khác return theo item.id trackByFn(index, item) { // return item.id; return index; } onClick() { console.log('123'); } onInput(test) { console.log(test); this.textes.push(test.target.value); // push() thêm 1 phần tử vào cuối mảng } onGetData(txtName): void { console.log(txtName.value); } onGetData2(): void { console.log(this.herName.nativeElement.value); } }
87935d97ff5efd76caf304b9285e895f3e352a8b
TypeScript
zavarock/gostack-desafio-database-upload
/src/config/upload.ts
2.515625
3
import { Request } from 'express'; import path from 'path'; import crypto from 'crypto'; import multer, { FileFilterCallback } from 'multer'; const uploadPath = path.resolve(__dirname, '..', '..', 'tmp'); const uploadFilter = ( request: Request, file: Express.Multer.File, callback: FileFilterCallback, ): void => { if (file.mimetype !== 'text/csv') { return callback(new Error('Only CSV files are accepted!')); } return callback(null, true); }; const config = { destination: uploadPath, storage: multer.diskStorage({ destination: uploadPath, filename(request, file, callback) { const fileHash = crypto.randomBytes(10).toString('HEX'); const fileName = `${fileHash}-${file.originalname}`; return callback(null, fileName); }, }), fileFilter: uploadFilter, }; export default config;
ce7b89c26396f2d2de15bad9447b6bd7238be511
TypeScript
HemSoft/ESO
/HemSoft.Eso.Web/app/characters/characterInventoryController.ts
2.59375
3
module App.CharacterInventoryController { interface ICharacterInventoryiewModel { title: string; characters: App.Domain.ICharacter[]; // TODO: inventory: any[]; dataAccessService: App.Common.DataAccessService; inventorySortType: string; inventorySortReverse: boolean; } class CharacterInventoryController implements ICharacterInventoryiewModel { title: string; characters: App.Domain.ICharacter[]; inventory: any[]; dataAccessService: App.Common.DataAccessService; inventorySortType: string; inventorySortReverse: boolean; static $inject = ["dataAccessService"]; constructor(private dataService: App.Common.DataAccessService) { this.title = "Upcoming"; this.dataAccessService = dataService; this.getAllInventory(); this.inventorySortType = "Completed"; this.inventorySortReverse = true; } getAllInventory() { var res = this.dataAccessService.getAllInventory(); res.query((data: App.Domain.ICharacter[]) => { this.inventory = data; }); } } angular.module("app").controller("characterInventoryController", CharacterInventoryController); }
b11dd5e56ae304762ac4571880aa7deb75e09665
TypeScript
filefoxper/generator-dc
/app/templates/web-pc-simple/src/utils/cookie/index.ts
2.8125
3
export const getCookie = (key: string) => { const reg = new RegExp(`(^| )${encodeURIComponent(key)}=([^;]*)(;|$)`); const arr: RegExpMatchArray | null = window.document.cookie.match(reg); if (arr) { return decodeURIComponent(arr[2]); } }; export const deleteCookie = (key: string, path = '/') => { const value = getCookie(key); const date = new Date(); date.setTime(date.getTime() - 1); if (value) { window.document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent( value )};expires=${date.toUTCString()};path=${path}`; } }; const getExpires = (expiredays?: Date) => { return expiredays ? `;expires=${expiredays.toUTCString()}` : ''; }; export const setCookie = ( key: string, value: string, expires: Date, path = '/' ) => { const current = getCookie(key); if (current) { deleteCookie(key); } window.document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent( value )}${getExpires(expires)};path=${path}`; };
103bd6442800fb55a990515e4010687b9379f564
TypeScript
AndyDecker/fhir-ts
/packages/fhir-types/src/R4/Resource.ts
2.625
3
/** * Resource Module */ import * as primitives from "@tangdrew/primitives"; import * as t from "io-ts"; import { Element } from "./Element"; import { Meta } from "./Meta"; /** * Base Resource */ export interface Resource { /** The type of resource */ resourceType?: "Resource"; /** Logical id of this artifact */ id?: primitives.R4.id; /** Extension of id element */ _id?: Element; /** Metadata about the resource */ meta?: Meta; /** A set of rules under which this content was created */ implicitRules?: primitives.R4.uri; /** Extension of implicitRules element */ _implicitRules?: Element; /** Language of the resource content */ language?: primitives.R4.code; /** Extension of language element */ _language?: Element; } /** * Base Resource */ export const Resource: t.Type<Resource> = t.recursion<Resource>( "Resource", () => t.intersection([ t.type({}), t.partial({ /** The type of resource */ resourceType: t.literal("Resource"), /** Logical id of this artifact */ id: primitives.R4.id, /** Extension of id element */ _id: Element, /** Metadata about the resource */ meta: Meta, /** A set of rules under which this content was created */ implicitRules: primitives.R4.uri, /** Extension of implicitRules element */ _implicitRules: Element, /** Language of the resource content */ language: primitives.R4.code, /** Extension of language element */ _language: Element }) ]) );
aeb4f689149f7a85692dc5568cdf59d2e4dd0502
TypeScript
zylozs/NyxBotJs
/src/utils/typeutils.ts
3.375
3
import { DiscordRole, DiscordGuild, DiscordSnowflake, DiscordGuildMember, Collection } from "../discord/discordtypes"; export class TypeUtils { public static ToBool(value:any):boolean | null { if (typeof(value) == 'boolean') { return <boolean>value; } else if (typeof(value) == 'string') { if (value.toLowerCase() == 'true') { return true; } else if (value.toLowerCase() == 'false') { return false; } } return null; } public static ToNum(value:any):number | null { const temp:any = +value; if (temp == NaN) return null; return <number>temp; } public static ToDiscordRole(value:string, guild:DiscordGuild):DiscordRole | null { if (guild == undefined) { return null; } const roles:Collection<DiscordSnowflake, DiscordRole> = guild.roles; const snowflakeValue:string = value.substr(3, value.length - 4); let outRole:DiscordRole | null = null; roles.some((discordRole:DiscordRole, snowflake:DiscordSnowflake):boolean => { if (discordRole.name === value || snowflake === value || snowflake === snowflakeValue) { outRole = discordRole; return true; } return false; }); return outRole; } public static ToDiscordGuildMember(value:string, guild:DiscordGuild):DiscordGuildMember | null { if (guild == undefined) { return null; } const members:Collection<DiscordSnowflake, DiscordGuildMember> = guild.members; const snowflakeValue:string = value.substr(3, value.length - 4); let outMember:DiscordGuildMember | null = null; members.some((discordMember:DiscordGuildMember, snowflake:DiscordSnowflake):boolean => { // Support pretty much every possible way to uniquely identify a user // Prioritize guild specific stuff first since we are attempting to get a guild member out of this and not a user // This is case sensitive on purpose because we don't want to deal with name collisions if (discordMember.displayName === value || discordMember.nickname === value || snowflake === value || snowflake === snowflakeValue || discordMember.user.tag === value || discordMember.user.username === value) { outMember = discordMember; return true; } return false; }); return outMember; } }
c8752518de953e64998a3bb997e3d0c9a1820cad
TypeScript
material-theme/vsc-material-theme
/src/webviews/ui/release-notes/index.ts
2.578125
3
import sanityClient from '@sanity/client'; import {IPost, IPostNormalized} from '../../interfaces'; // eslint-disable-next-line @typescript-eslint/explicit-function-return-type const getClient = () => sanityClient({ projectId: 'v475t82f', dataset: 'production' }); const getReleaseNotes = async (): Promise<object[]> => { const query = '*[_type == "release"] | order(version desc)'; const client = getClient(); return client.fetch(query); }; const renderTemplate = (posts: IPostNormalized[]): string => { return `${posts.reduce((acc, {version, title, fixed, new: newItems, breaking}) => acc.concat(`<section class="Release"> <header class="Release__Header"> <span class="Release__Number">${version}</span> <h2 class="Release__Title">${title}</h2> </header> <ul class="Release-List"> ${fixed.reduce((accc: string, src) => src.length > 0 ? accc.concat(`<li data-type="fixed">${src}</li>`) : '', '')} ${newItems.reduce((accc: string, src) => src.length > 0 ? accc.concat(`<li data-type="new">${src}</li>`) : '', '')} ${breaking.reduce((accc: string, src) => src.length > 0 ? accc.concat(`<li data-type="breaking">${src}</li>`) : '', '')} </ul> </section>`), '')}`; }; getReleaseNotes().then((res: IPost[]) => { const normalized = res.reduce((acc, src) => acc.concat({ ...src, fixed: src.fixed ? src.fixed.map(item => item.children[0].text) : [], new: src.new ? src.new.map(item => item.children[0].text) : [], breaking: src.breaking ? src.breaking.map(item => item.children[0].text) : [] }), []); document.querySelector('.Container').innerHTML = renderTemplate(normalized); });
bccbcdba6493d641bfbe2e9f5fb9f33bc0385f82
TypeScript
cellbang/malagu
/dev-packages/testing/src/await-url.ts
2.65625
3
import axios from 'axios'; export function awaitUrl(url: string, tries = 150, interval = 1000) { return new Promise<void>((resolve, reject) => { const attempt = async (count: number) => { try { await axios.head(url, { timeout: 10000 }); resolve(); } catch (error) { if (error.code !== 'ECONNREFUSED') { resolve(); } else if (count > 1) { setTimeout(attempt, interval, count - 1); } else { reject(error); } } }; attempt(tries).catch(reject); }); };
e096ca133f644002d83e7924bec5c4bb4801da33
TypeScript
webdevavi/twitter-clone-backend
/src/utils/getHashtags.ts
2.703125
3
import { hashtags as hashtagRegex } from "./regexp"; export const getHashtags = (text: string, prefix: boolean = true): string[] => { const hashtags = new Set<string>(); const matches = [...text.matchAll(hashtagRegex)].map((match) => match[0]); matches.map((match) => { if (prefix) { return hashtags.add(match); } return hashtags.add(match.replace(/#/g, "")); }); return [...hashtags]; };
823accc198fc48fa0d1d7fdbf34b3252925fd9ea
TypeScript
untlsn-old/fylo-data
/src/hooks/useBoolState.ts
3.109375
3
import {useState} from 'react'; type useBoolResult<T> = [ T, (force?: boolean) => void ] const useBoolState = (initialState?: boolean): useBoolResult<boolean> => { const [value, changeValue] = useState(initialState == true); return [ value, (force) => changeValue(old => force ?? !old) ]; }; useBoolState.replace = <T>(trueRep: T, falseRep: T, initialState?: boolean): useBoolResult<T> => { const [bool, changeBool] = useBoolState(initialState); return [ bool ? trueRep : falseRep, changeBool ]; }; export default useBoolState;
f109abacd0a78c26161ef9837eaf497625759e73
TypeScript
Roms1383/definitive-guide-nestjs-guard-passport
/src/hit.service.ts
2.6875
3
import { Injectable } from '@nestjs/common' import { Hit } from './hit.entity' @Injectable() export class HitService { private hits: Hit[] = [] record(ip: string, timestamp: number) { const index = this.hits.findIndex(access => access.ip === ip) if (index !== -1) this.hits[index].timestamp = timestamp else this.hits.push({ ip, timestamp }) } last(ip: string): number { const index = this.hits.findIndex(access => access.ip === ip) return index !== -1 ? this.hits[index].timestamp : NaN } }
84b7fdd4a39ba0e3240abab6dd0321dbc0dd520b
TypeScript
syuilo/misskey-file
/src/utils/cli/progressbar.ts
3.25
3
import * as ev from 'events'; import * as readline from 'readline'; import * as chalk from 'chalk'; /** * Progress bar */ class ProgressBar extends ev.EventEmitter { public max: number; public value: number; public text: string; private indicator: number; constructor(max: number, text: string = null) { super(); this.max = max; this.value = 0; this.text = text; this.indicator = 0; this.draw(); const iclock = setInterval(() => { this.indicator = (this.indicator + 1) % 4; this.draw(); }, 200); this.on('complete', () => { clearInterval(iclock); }); } public increment(): void { this.value++; this.draw(); // on complete if (this.value === this.max) { this.indicator = null; cll(); process.stdout.write(`${this.render()} -> ${chalk.bold('Complete')}\n`); this.emit('complete'); } } public draw(): void { const str = this.render(); cll(); process.stdout.write(str); } private render(): string { const width = 30; const t = this.text ? this.text + ' ' : ''; const v = Math.floor((this.value / this.max) * width); const vs = new Array(v + 1).join('*'); const p = width - v; const ps = new Array(p + 1).join(' '); const percentage = Math.floor((this.value / this.max) * 100); const percentages = chalk.gray(`(${percentage}%)`); let i: string; switch (this.indicator) { case 0: i = '-'; break; case 1: i = '\\'; break; case 2: i = '|'; break; case 3: i = '/'; break; case null: i = '+'; break; default: break; } return `${i} ${t}[${vs}${ps}] ${this.value}/${this.max} ${percentages}`; } } export default ProgressBar; /** * Clear current line */ function cll(): void { readline.clearLine(process.stdout, 0); // clear current text readline.cursorTo(process.stdout, 0, null); // move cursor to beginning of line }
bff4c09239832eea74a1f255982eaad260ccad27
TypeScript
pedrofrohmut/todos-nextjs
/server/use-cases/users/implementations/create-user.use-case.ts
2.65625
3
import ICreateUserService from "../../../services/users/create-user-service.interface" import IFindUserByEmailService from "../../../services/users/find-user-by-email-service.interface" import ICreateUserUseCase from "../create-user-use-case.interface" import { CreateUserType } from "../../../types/user.types" import EmailAlreadyInUseError from "../../../errors/users/email-already-in-use.error" export default class CreateUserUseCase implements ICreateUserUseCase { private readonly findUserByEmailService: IFindUserByEmailService private readonly createUserService: ICreateUserService public constructor( findUserByEmailService: IFindUserByEmailService, createUserService: ICreateUserService ) { this.findUserByEmailService = findUserByEmailService this.createUserService = createUserService } public async execute(newUser: CreateUserType): Promise<void> { const foundUser = await this.findUserByEmailService.execute(newUser.email) if (foundUser !== null) { throw new EmailAlreadyInUseError() } await this.createUserService.execute(newUser) } }
b40f7907e367a7194fc0a1d0d7b180e1757ba213
TypeScript
fortSQ/web-console
/src/TypeScript/CityList.ts
3.296875
3
interface ICityList { list: {} nameList: {} transfer(idList: number[], typeTo: string): void } class CityList implements ICityList { static ACTIVE = 'active' static INACTIVE = 'inactive' static VORONEZH = 36 static UKHTA = 11 static MOSCOW = 77 static SAINT_PETERSBURG = 78 public list = { [CityList.ACTIVE]: [CityList.VORONEZH, CityList.UKHTA], [CityList.INACTIVE]: [CityList.MOSCOW, CityList.SAINT_PETERSBURG], } public nameList = { [CityList.VORONEZH]: 'Воронеж', [CityList.UKHTA]: 'Ухта', [CityList.MOSCOW]: 'Москва', [CityList.SAINT_PETERSBURG]: 'Санкт-Петербург', } public transfer(idList: number[], typeTo: string): void { let typeFrom = typeTo == CityList.ACTIVE ? CityList.INACTIVE : CityList.ACTIVE idList.forEach((id) => { if (!this.list[typeFrom].includes(id) || this.list[typeTo].includes(id) ) return // если вдруг не нашли элемент в извлекаемом списке или он уже есть в нужном this.list[typeTo].push(id) }) this.list[typeFrom] = this.list[typeFrom].filter((id) => !idList.includes(id)) } }
9afebe5d8274970f82f7201f8a1f98bfa6fde98d
TypeScript
mustafapc19/deno
/std/jwt/test.ts
2.921875
3
import { create, decode, Header, Payload, verify } from "./mod.ts"; import { assertEquals, assertThrows, assertThrowsAsync, } from "../testing/asserts.ts"; const header: Header = { alg: "HS256", typ: "JWT", }; const payload: Payload = { name: "John Doe", }; const key = "secret"; Deno.test({ name: "[jwt] create", fn: async function () { assertEquals( await create("", key), "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9..B0lmJDC8zSfMJstPqLdOAWfM265-5Svj0XrACZm8DKa1y6VJA0W7d0VoGGKJo0quKxWUdf1B1ueElNk2Yl_cLw", ); assertEquals( await create({}, key), "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.e30.dGumW8J3t2BlAwqqoisyWDC6ov2hRtjTAFHzd-Tlr4DUScaHG4OYqTHXLHEzd3hU5wy5xs87vRov6QzZnj410g", ); assertEquals( await create({ foo: "bar" }, key), "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.WePl7achkd0oGNB8XRF_LJwxlyiPZqpdNgdKpDboAjSTsWq-aOGNynTp8TOv8KjonFym8vwFwppXOLoLXbkIaQ", ); assertEquals( await create("null", key), "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.bnVsbA.tv7DbhvALc5Eq2sC61Y9IZlG2G15hvJoug9UO6iwmE_UZOLva8EC-9PURg7IIj6f-F9jFWix8vCn9WaAMHR1AA", ); assertEquals( await create("[]", key), "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.W10.BqmZ-tVI9a-HDx6PpMiBdMq6lzcaqO9sW6pImw-NRajCCmRrVi6IgMhEw7lvOG6sxhteceVMl8_xFRGverJJWw", ); }, }); Deno.test({ name: "[jwt] verify", fn: async function () { assertEquals( await verify(await create("", key, { header: header }), key, { algorithm: "HS256", }), "", ); assertEquals( await verify( await create("abc", key, { header: header }), key, { algorithm: "HS256", }, ), "abc", ); await assertEquals( await verify(await create("null", key), key), null, ); await assertEquals( await verify(await create("true", key), key), true, ); assertEquals( await verify( await create(payload, key, { header: header }), key, { algorithm: "HS256", }, ), payload, ); await assertEquals( await verify(await create({}, key), key), {}, ); await assertEquals( await verify(await create("[]", key), key), [], ); await assertEquals( await verify(await create(`["a", 1, true]`, key), key), ["a", 1, true], ); await assertThrowsAsync( async () => { // payload = { "exp": false } await verify( "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOmZhbHNlfQ.LXb8M9J6ar14CTq7shnqDMWmSsoH_zyIHiD44Rqd6uI", key, ); }, Error, "The token is invalid.", ); await assertThrowsAsync( async () => { await verify("", key); }, Error, "The serialization is invalid.", ); await assertThrowsAsync( async () => { await verify("invalid", key); }, Error, "The serialization is invalid.", ); await assertThrowsAsync( async () => { await verify( await create({ // @ts-ignore */ exp: "invalid", }, key), key, ); }, Error, "The token is invalid.", ); }, }); Deno.test({ name: "[jwt] decode", fn: async function () { assertEquals( decode( "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.TVCeFl1nnZWUMQkAQKuSo_I97YeIZAS8T1gOkErT7F8", ), { header: { alg: "HS256", typ: "JWT" }, payload: {}, signature: "4d509e165d679d959431090040ab92a3f23ded87886404bc4f580e904ad3ec5f", }, ); assertThrows( () => { decode("aaa"); }, TypeError, "The serialization is invalid.", ); assertThrows( () => { decode("a"); }, TypeError, "Illegal base64url string!", ); assertThrows( () => { // "ImEi" === base64url("a") decode("ImEi.ImEi.ImEi.ImEi"); }, TypeError, "The serialization is invalid.", ); const jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"; const header: Header = { alg: "HS256", typ: "JWT", }; const payload = { sub: "1234567890", name: "John Doe", iat: 1516239022, }; assertEquals(decode(jwt), { header, payload, signature: "49f94ac7044948c78a285d904f87f0a4c7897f7e8f3a4eb2255fda750b2cc397", }); assertEquals(await create(payload, "your-256-bit-secret", { header }), jwt); }, }); Deno.test({ name: "[jwt] expired token", fn: async function () { const payload = { iss: "joe", jti: "123456789abc", exp: 20000, }; const header: Header = { alg: "HS256", dummy: 100, }; await assertThrowsAsync( async () => { await verify(await create({ exp: 0 }, key), key); }, Error, "The token is expired.", ); await assertThrowsAsync( async () => { await verify( await create(payload, key, { header }), key, { algorithm: "HS256" }, ); }, Error, "The token is expired.", ); }, }); Deno.test({ name: "[jwt] none algorithm", fn: async function () { const payload = { iss: "joe", jti: "123456789abc", }; const header: Header = { alg: "none", dummy: 100, }; const jwt = await create(payload, key, { header }); const validatedPayload = await verify(jwt, "keyIsIgnored", { algorithm: "none", }); assertEquals(validatedPayload, payload); }, }); Deno.test({ name: "[jwt] HS256 algorithm", fn: async function () { const header: Header = { alg: "HS256", typ: "JWT", }; const payload = { sub: "1234567890", name: "John Doe", iat: 1516239022, }; const jwt = await create(payload, key, { header }); const validatedPayload = await verify(jwt, key, { algorithm: "HS256" }); assertEquals( jwt, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.XbPfbIHMI6arZ3Y922BhjWgQzWXcXNrz0ogtVhfEd2o", ); assertEquals(validatedPayload, payload); assertThrowsAsync( async () => { const invalidJwt = // jwt with not supported crypto algorithm in alg header: "eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.bQTnz6AuMJvmXXQsVPrxeQNvzDkimo7VNXxHeSBfClLufmCVZRUuyTwJF311JHuh"; await verify(invalidJwt, "", { algorithm: "HS256", }); }, Error, `The token's algorithm does not match the specified algorithm 'HS256'.`, ); }, }); Deno.test({ name: "[jwt] HS512 algorithm", fn: async function () { const header: Header = { alg: "HS512", typ: "JWT" }; const payload = { sub: "1234567890", name: "John Doe", admin: true, iat: 1516239022, }; const jwt = await create(payload, key, { header }); const validatedPayload = await verify(jwt, key, { algorithm: "HS512" }); assertEquals(validatedPayload, payload); }, });
eec63fad54e184afd7b8ebd375aded0660437816
TypeScript
Varmaji/NodeJs
/TSExample.ts
3.78125
4
let num:number;//[optional initial value] num=10; console.log(num); function show():void{ console.log('show() called'); return; } show(); function fnWithArgs(id:number,name:string):string{ return `ID:${id},Name:${name}`; } console.log(fnWithArgs(10,'Canarys')); let arr=new Array(10); arr[11]='welcome' console.log(arr[11]); let numArr:Array<number>=new Array<number>(10); numArr[0]=parseInt("10"); console.log(numArr[0]); //spread operators let fruits=["apple","mango","Orange"]; //let a =fruits[0]; //let b=fruits[1]; let[a,b,c]=[...fruits]; console.log(a,b,c); //Rest Operator function fnWithVarArgs(...args) { console.log(args.length); } fnWithVarArgs(); fnWithVarArgs(1); fnWithVarArgs(1,2,3); fnWithVarArgs(1,2,4,4,3,4,3,2,3,2,3); let[...args]=[1,2,3,4,4,3,,4,3,4,3,2,4,3,3];//REST OPERATOR
a04907a71032ed923d98d07e9a4aab93cb748058
TypeScript
joehakimrahme/JSR
/src/app/roulette/roulette.component.ts
2.515625
3
import { Component, OnInit } from '@angular/core'; import { Roulette } from '../roulette'; import { RACES, FIGHT_SKILLS, NEUTRAL_SKILLS, TRADE_SKILLS, HANDICAPS, QUESTS, CONDITIONS } from '../fixtures'; import { choice, shuffle} from '../utils'; @Component({ selector: 'app-roulette', templateUrl: './roulette.component.html', styleUrls: ['./roulette.component.css'] }) export class RouletteComponent implements OnInit { result: Roulette; _skills: Array<string>; constructor() { const lastRoulette = localStorage.getItem('last-used'); if (lastRoulette) { this.result = JSON.parse(lastRoulette); } else { this.result = { race: '', major: [], minor: [], handicaps: [], quest: '', }; } } ngOnInit() { } isValid() { for (const cond in CONDITIONS) { if (!CONDITIONS[cond](this.result)) { console.log('Reshuffle: ' + cond); return false; } } return true; } generateHandicap() { // Go over the list of handicaps and run a check to see if it procs. // Every time a handicap procs, the odds of subsequent ones is halved. let i; let odds = 8; const result = []; for (i = 0; i < HANDICAPS.length; i++) { if (Math.random() * 100 < odds) { result.push(HANDICAPS[i]); odds /= 2; } } return result; } ngOnSelect() { this._skills = FIGHT_SKILLS.concat(TRADE_SKILLS); this._skills = this._skills.concat(NEUTRAL_SKILLS); do { shuffle(this._skills); this.result = { race: choice(RACES), major: this._skills.slice(0, 3), minor: this._skills.slice(3, 6), handicaps: this.generateHandicap(), quest: choice(QUESTS), }; } while (!this.isValid()); localStorage.setItem('last-used', JSON.stringify(this.result)); } }
58cb3ced934f6a4934a17d65323da9d1c852884f
TypeScript
schneider-simon/questionnaire-dsl
/src/form/form_errors.ts
3.0625
3
import { getTypeString } from "./type_checking/type_assertions"; import { FieldType } from "./FieldType"; import FieldNode from "./nodes/fields/FieldNode"; import Expression from "./nodes/expressions/Expression"; export class FormError extends Error { constructor(m: string) { super(m); Object.setPrototypeOf(this, FormError.prototype); } } export class TypeCheckError extends FormError { expectedType: string; receivedType: string; static make(expectedType: string, receivedType: string, message?: string) { if (typeof message === 'undefined') { message = `Type check failed. Expected "${expectedType}" but received "${receivedType}".`; } const error = new TypeCheckError(message); Object.setPrototypeOf(error, TypeCheckError.prototype); error.expectedType = expectedType; error.receivedType = receivedType; return error; } } export class ValuesNotComparableError extends FormError { left: any; right: any; static make(left: string, right: string, message?: string) { if (typeof message === 'undefined') { message = `Cannot compare ${left} [${getTypeString(left)}] to ${right} [${getTypeString(right)}].`; } const error = new ValuesNotComparableError(message); Object.setPrototypeOf(error, ValuesNotComparableError.prototype); error.left = left; error.right = right; return error; } } export class TypesNotComparableError extends FormError { left: FieldType; right: FieldType; static make(left: FieldType, right: FieldType, message?: string) { if (typeof message === 'undefined') { message = `Cannot compare type ${left} to ${right}.`; } const error = new TypesNotComparableError(message); error.left = left; error.right = right; Object.setPrototypeOf(error, TypesNotComparableError.prototype); return error; } } export class DivisionByZeroError extends FormError { static make(message?: string) { if (typeof message === 'undefined') { message = `Division by zero is not possible. `; } const error = new DivisionByZeroError(message); Object.setPrototypeOf(error, DivisionByZeroError.prototype); return error; } } export class NotImplementedYetError extends Error { static make(feature: string, message?: string) { if (typeof message === 'undefined') { message = `Feature not implemented yet: "${feature}".`; } return new NotImplementedYetError(message); } } export class UnkownFieldError extends FormError { fieldIdentifier: string; static make(identifier: string, message?: string) { if (typeof message === 'undefined') { message = `Unkown field ${identifier}.`; } const error = new UnkownFieldError(message); error.fieldIdentifier = identifier; Object.setPrototypeOf(error, UnkownFieldError.prototype); return error; } } export class UnkownVariableIdentifierError extends FormError { variableIdentifier: string; static make(identifier: string, message?: string) { if (typeof message === 'undefined') { message = `Unkown variable identifier: "${identifier}"`; } const error = new UnkownVariableIdentifierError(message); error.variableIdentifier = identifier; Object.setPrototypeOf(error, UnkownVariableIdentifierError.prototype); return error; } } export class UnkownDefaultValueError extends FormError { fieldType: string; static make(type: FieldType, message?: string) { if (typeof message === 'undefined') { message = `No default value for type: "${type}"`; } const error = new UnkownDefaultValueError(message); error.fieldType = type; Object.setPrototypeOf(error, UnkownDefaultValueError.prototype); return error; } } export class EmptyVariableScopeStackError extends FormError { identifier: string; static make(identifier: string, message?: string) { if (typeof message === 'undefined') { message = `Cannot add variable ${identifier} to empty stack.`; } const error = new EmptyVariableScopeStackError(message); error.identifier = identifier; Object.setPrototypeOf(error, EmptyVariableScopeStackError.prototype); return error; } } export class FieldAlreadyDeclaredError extends FormError { field: FieldNode; static make(field: FieldNode, message?: string) { if (typeof message === 'undefined') { message = `Field "${field.identifier}" was already declared before. Please use another name.`; } const error = new FieldAlreadyDeclaredError(message); error.field = field; Object.setPrototypeOf(error, FieldAlreadyDeclaredError.prototype); return error; } } export class VariableNotInScopeError extends FormError { expression: Expression; identifier: string; static make(expression: Expression, identifier: string, message?: string) { if (typeof message === 'undefined') { message = `Unknown identifier "${identifier}" used in expression.`; } const error = new VariableNotInScopeError(message); error.identifier = identifier; error.expression = expression; Object.setPrototypeOf(error, VariableNotInScopeError.prototype); return error; } } export class ValueIsNaNError extends FormError { value: any; static make(value: any, message?: string) { if (typeof message === 'undefined') { message = `Value cannot be parsed as a number: ${value}.`; } const error = new ValueIsNaNError(message); error.value = value; Object.setPrototypeOf(error, ValueIsNaNError.prototype); return error; } } export class CannotFindCommonFieldTypeError extends FormError { left: FieldType; right: FieldType; static make(left: FieldType, right: FieldType, message?: string) { if (typeof message === 'undefined') { message = `Cannot find common field type for ${left} and ${right}.`; } const error = new CannotFindCommonFieldTypeError(message); error.left = left; error.right = right; Object.setPrototypeOf(error, CannotFindCommonFieldTypeError.prototype); return error; } } export class ValueIsInvalidDateError extends FormError { value: string; static make(value: string, message?: string) { if (typeof message === 'undefined') { message = `Cannot parse date since it is invalid ${value}.`; } const error = new ValueIsInvalidDateError(message); error.value = value; Object.setPrototypeOf(error, ValueIsInvalidDateError.prototype); return error; } }
caf3f5df0fa1b25aea2a5c15da536efcb0affeed
TypeScript
charlesr1971/blog-cms-2
/src/app/util/updateCdkOverlayThemeClass.ts
2.578125
3
export function updateCdkOverlayThemeClass(className1: string, className2: string): void { const debug = false; const cdkoverlaycontainerArray = Array.prototype.slice.call(document.querySelectorAll('.cdk-overlay-container')); if(Array.isArray(cdkoverlaycontainerArray) && cdkoverlaycontainerArray.length) { if(debug) { console.log('updateCdkOverlayThemeClass: cdkoverlaycontainerArray.length: ', cdkoverlaycontainerArray.length); } cdkoverlaycontainerArray.map( (element) => { element.classList.remove(className1); element.classList.add(className2); }) } }
35cde1a1d4943627a4bf5d51124502ac7c1574af
TypeScript
FCLans/new_social_network
/src/redux/profileReducer.test.ts
2.96875
3
import { PostDataType, ProfileInfoType } from '../types/types' import profileReducer, { addPostActionCreator, deletePostAC } from './profileReducer' const initialState = { profileInfo: null as ProfileInfoType, postsData: [ { id: 1, message: 'Привет, мой первый пост!', likesCount: 120 }, { id: 2, message: 'Разгоняемся и летим)))', likesCount: 20 }, ] as Array<PostDataType>, status: '', } it('Add post', () => { //1. test data const action = addPostActionCreator('Текст нового поста') //2. action const newState = profileReducer(initialState, action) //3. expection expect(newState.postsData.length).toBe(3) }) it('New post text matches post text in state', () => { //1. test data const action = addPostActionCreator('Текст нового поста') //2. action const newState = profileReducer(initialState, action) //3. expection expect(newState.postsData[newState.postsData.length - 1].message).toBe('Текст нового поста') }) it('Delete post', () => { //1. test data const action = deletePostAC(2) //2. action const newState = profileReducer(initialState, action) //3. expection expect(newState.postsData.length).toBe(1) })
f31ff54dbf8308ae3438cdc766f5a260e1d1dc1d
TypeScript
Stepan-Demchenko/questionnaire
/src/app/shared/select/select/select.component.ts
2.59375
3
import { Component, ChangeDetectionStrategy, forwardRef, Input } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; export interface SelectOption { title: string; value: string | number; } @Component({ selector: 'app-select', templateUrl: './select.component.html', styleUrls: ['./select.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => SelectComponent), multi: true } ], changeDetection: ChangeDetectionStrategy.OnPush }) export class SelectComponent implements ControlValueAccessor { @Input() items: SelectOption[] = []; value = ''; disabled = false; constructor() {} private onChange = (value: any) => {}; private onTouched = () => {}; registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: () => {}): void { this.onTouched = fn; } setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } writeValue(val: any): void { this.value = val; this.onChange(val); } updateValue(insideValue: string): void { this.value = insideValue; this.onChange(insideValue); this.onTouched(); } }
8f35c7b009d5efbda68f5899b30aa71c09b2f507
TypeScript
MunifTanjim/node-bitbucket
/src/plugins/pagination/get-page.ts
2.578125
3
import { HTTPError } from '../../error' type APIClient = import('./types').APIClient type Direction = import('./types').Direction type PaginatedResponseData<T> = import('./types').PaginatedResponseData<T> type Response<T> = import('./types').Response<T> export function getPage<T>( client: APIClient, direction: Direction, responseData: PaginatedResponseData<T> ): Promise<Response<T>> { const url = responseData[direction] if (!url) { throw new HTTPError(`not found: ${direction} page`, 404) } return client.request({ method: 'GET', url }) }
10e7f68b167aa399b26dd2d7c3e22e3739c8a5a7
TypeScript
DefinitelyTyped/DefinitelyTyped
/types/fbjs/lib/Heap.d.ts
2.921875
3
declare class Heap { constructor(items?: any[], comparator?: (a: any, b: any) => boolean); empty(): boolean; pop(): any; push(item: any): void; size(): number; peek(): any; _heapify(): void; _bubbleUp(index: number): void; _sinkDown(index: number): void; } declare namespace Heap {} export = Heap;
a965d5b5b28a470093d7241e9fad9f20e2d7c1d0
TypeScript
harpreet-singh-au7/bootcamp
/Backend/db/Database/sqlConnector.ts
2.671875
3
import mysql from 'mysql'; export var pool = mysql.createPool({ host: process.env.SQLDATABASEHOST, user: process.env.SQLDATABASEUSER, password: process.env.SQLDATABASEPASSWORD, database: process.env.SQLDATABASENAME, connectionLimit: 500, queueLimit: 0, waitForConnections: true, }); export const sqlDbConnection = function () { return new Promise<mysql.PoolConnection>((resolve, reject) => { pool.getConnection(function (err, connection) { if (err) { reject(err); return; } resolve(connection); //connection.release(); }); }); }; export function simpleStringify (object:any){ var simpleObject:any = {}; for (var prop in object ){ if (!object.hasOwnProperty(prop)){ continue; } if (typeof(object[prop]) == 'object'){ continue; } if (typeof(object[prop]) == 'function'){ continue; } simpleObject[prop] = object[prop]; } return JSON.stringify(simpleObject); // returns cleaned up JSON }; export default function mySqlDbConnection() { const connection = mysql.createConnection({ host: process.env.SQLDATABASEHOST, user: process.env.SQLDATABASEUSER, password: process.env.SQLDATABASEPASSWORD, database: process.env.SQLDATABASENAME, }); connection.connect(function(err) { if (err) throw err; console.error("err" + err); }) console.log(" coneccttttionn") return connection; }
9a9db36aaeb3eb40115294d714da8ce612edf3c6
TypeScript
Airwarfare/cap
/lib/Network/Link/Link.ts
2.640625
3
export interface Link { offset: number; type: number; parse(buffer: Buffer): Link; }
dbd657c3da3c20610a96d0cfb718aa73a7cfe9cb
TypeScript
manuth/dataskop-electron
/src/providers/youtube/utils.ts
2.609375
3
import _ from 'lodash'; import { Lookup, ScrapingResultSaved } from '../../db'; const getThumbnails = (id: string) => { /** * Returns all thumbnails to given YT video it. https://yt-thumb.canbeuseful.com/en */ // the first image is the `default` image. const small = [1, 2, 3].map( (x) => `https://img.youtube.com/vi/${id}/${x}.jpg`, ); small.unshift(`https://img.youtube.com/vi/${id}/default.jpg`); const defaultImage = { mq: `https://img.youtube.com/vi/${id}/mqdefault.jpg`, hq: `https://img.youtube.com/vi/${id}/hqdefault.jpg`, sd: `https://img.youtube.com/vi/${id}/sddefault.jpg`, maxRes: `https://img.youtube.com/vi/${id}/maxresdefault.jpg`, }; return { small, default: defaultImage }; }; const getVideoUrl = (id: string) => `https://www.youtube.com/watch?v=${id}`; const filterLookupBySession = ( results: ScrapingResultSaved[], lookups: Lookup[], ) => { const videoIds = new Set(); results.forEach((x) => { if ('slug' in x && x.slug === 'yt-user-watch-history') { x.fields.videos.forEach(({ id }) => videoIds.add(id)); } }); return lookups.filter((x) => videoIds.has(x.info.videoId)); }; const redactWatchHistory = ( results: ScrapingResultSaved[], lookups: Lookup[], ) => { // - private videos are not in lookups (cause they have no meta infos) // - videos that are not unlisted are public // - safe the amount of videos before redaction + number of unlisted videos const publicVideos = new Set( lookups .filter((x) => !x.info.unlisted) .map(({ info: { videoId } }) => videoId), ); const unlistedVideos = new Set( lookups .filter((x) => x.info.unlisted) .map(({ info: { videoId } }) => videoId), ); results.forEach((x) => { if ('slug' in x && x.slug === 'yt-user-watch-history') { x.fields.numVideosBeforeRedaction = x.fields.videos.length; x.fields.videos = x.fields.videos.filter((video) => publicVideos.has(video.id), ); x.fields.numVideosRedactedUnlisted = x.fields.videos.filter((video) => unlistedVideos.has(video.id), ).length; } }); return results; }; // data wrangling const groupByFollowId = (x: any[]) => Object.values(_.groupBy(x, (y) => y.fields.followId)); const getVideos = (data: any[]) => data.filter((x) => x.slug && x.slug.includes('video-page') && x.success); const getFollowGroups = (data: any[]) => groupByFollowId(data.filter((x) => x.slug && x.slug.includes('video-page'))); export { filterLookupBySession, redactWatchHistory, getThumbnails, getVideoUrl, getFollowGroups, getVideos, };
d33a723ab36089f530b746402e7eec568f251cf2
TypeScript
Duru23/vscode-versionlens
/src/infrastructure.providers/dotnet/src/options/nugetOptions.ts
2.625
3
import { IFrozenRepository } from 'core.generics'; import { Options } from 'core.configuration'; enum NugetContributions { Sources = 'sources', } export class NugetOptions extends Options { constructor(config: IFrozenRepository, section: string) { super(config, section); } get sources(): Array<string> { return this.get<Array<string>>(NugetContributions.Sources); } }
e0d16d88b1785ccbfbdde74e8af2f132221015ce
TypeScript
Neone-character-creator/only-war-plugin
/src/main/resources/js/app/finalize/FinalizePageController.ts
2.53125
3
import {Characteristic} from "../types/character/Characteristic"; import { CharacteristicAdvancement, SkillAdvancement, TalentAdvancement, PsychicPowerAdvancement } from "../types/character/advancements/CharacterAdvancement"; import {Aptitudes} from "../types/character/Aptitudes"; /** * Created by Damien on 7/29/2016. */ export class FinalizePageController { constructor($q, $scope, characterService, characterOptions, dice) { $q.all({ armor: characterOptions.armor, items: characterOptions.items, powers: characterOptions.powers, skills: characterOptions.skills, talents: characterOptions.talents, traits: characterOptions.traits, vehicles: characterOptions.vehicles, weapons: characterOptions.weapons, xpCosts: characterOptions.xpCost, fatePointRolls: characterOptions.fatePointRolls }).then(function (characterOptions) { $scope.character = characterService.character; $scope.rollWounds = function () { characterService.character.wounds.rolled = dice.roll(1, 5); }; $scope.rollFP = function () { $scope.fpRoll = dice.roll(1, 10); characterService.character.fatePoints = characterOptions.fatePointRolls[$scope.fpRoll]; $scope.character = characterService.character; }; $scope.availableXp = characterService.character.experience.available; $scope.categories = [{ id: 1, value: "Characteristics" }, { id: 2, value: "Skills" }, { id: 3, value: "Talents" }, { id: 4, value: "Psychic Powers" } ].filter(function (element) { return element.value !== "Psychic Powers" || characterService.character.traits.find(function (trait) { return trait.name === "Psyker"; }); }); $scope.selectedCategory; $scope.options; $scope.displayedOption; function setDisplayedOptions(options) { $scope.options = options; }; $scope.toggleDisplayedCategory = function () { switch ($scope.selectedCategory.value) { case "Skills": setDisplayedOptions(characterOptions.skills.filter(function (skill) { var characterSkill = characterService.character.skills[skill.name]; return !characterSkill || characterSkill.advancements < 4; })); break; case "Talents": setDisplayedOptions(characterOptions.talents.filter(function (talent) { return characterService.character.talents.indexOf(talent) === -1; })); break; case "Psychic Powers": setDisplayedOptions(characterOptions.powers.filter(function (power) { return characterService.character.powers().all().indexOf(power) === -1; })); break; case "Characteristics": setDisplayedOptions(Array.from(Characteristic.characteristics.values())); break; } ; }; $scope.displayXpCost = function () { if ($scope.displayedOption) { var matchingAptitudes = 0; if ($scope.selectedCategory.value !== 'Psychic Powers') { for (var a = 0; a < $scope.displayedOption.aptitudes.length; a++) { if (characterService.character.aptitudes.indexOf($scope.displayedOption.aptitudes[a]) !== -1) { matchingAptitudes++; } } } var advancement; switch ($scope.selectedCategory.value) { case "Characteristics": { //Characteristic.characteristics.get($) advancement = new CharacteristicAdvancement($scope.displayedOption); break; } case "Skills": { advancement = new SkillAdvancement($scope.displayedOption); break; } case "Talents": advancement = new SkillAdvancement($scope.displayedOption); break; case "Psychic Powers": advancement = new PsychicPowerAdvancement($scope.displayedOption); break; } $scope.optionXpCost = advancement.calculateExperienceCost($scope.character); } } $scope.buyAdvancement = function () { var property = [$scope.selectedCategory.value]; var value; var advancement; switch ($scope.selectedCategory.value) { case "Characteristics": property.push($scope.displayedOption.name); value = Characteristic.characteristics.get($scope.displayedOption.name); advancement = new CharacteristicAdvancement(value); break; case "Skills": value = (characterService.character.skills().byName($scope.displayedOption.name.toLowerCase()) | -1) + 1; advancement = new SkillAdvancement(value); break; case "Talents": value = $scope.displayedOption.name; advancement = new TalentAdvancement(value); break; } characterService.character.experience.addAdvancement(advancement); $scope.availableXp = characterService.character.experience.available; }; $scope.duplicateAptitudes = characterService.character.aptitudes.filter((aptitude, index, original)=> { return original.indexOf(aptitude, index + 1) !== -1; }); $scope.availableAptitudes = Array.from(Characteristic.characteristics.keys()).filter(function (aptitude) { var possessedAptitudes = characterService.character.aptitudes; return possessedAptitudes.indexOf(aptitude) === -1; }); $scope.chosenBonusAptitudes = []; $scope.$watch("chosenBonusAptitudes", function (newValue, oldValue) { if (newValue !== oldValue) { for (var aptitude of oldValue) { $scope.character.aptitudes.splice($scope.character.aptitudes.indexOf(aptitude)); } $scope.character.aptitudes = $scope.character.aptitudes.concat(newValue); } }); }) } private $q; private $scope; private characterService; private characteroption; private dice; }
30732054a2f7dba0e6742a9903a713e97b6dc86d
TypeScript
wardenfeng/feng3d-AsToTs
/src/me/feng3d/fagal/params/ShaderParams.ts
2.546875
3
module feng3d { /** * 渲染参数 * <p>? 是否需要限定组件为ShaderParamsComponent</p> * @author feng 2014-11-4 */ export class ShaderParams extends Component { /** 取样标记字典 */ private sampleFlagsDic; /** 是否使用贴图分层细化 */ public useMipmapping: boolean; /** 是否使用平滑纹理 */ public useSmoothTextures: boolean; /** 是否重复纹理 */ public repeatTextures: boolean; /** * 是否为入射光 */ public incidentLight: boolean; public specularModelType: string; public diffuseModulateMethod: Function; public modulateMethod: Function; public alphaPremultiplied: boolean; /** * 创建一个渲染参数 */ constructor() { super(); this.addEventListener(ComponentEvent.ADDED_COMPONET, this.onAddedComponet); } protected onAddedComponet(event: ComponentEvent) { var shaderParam: Object = event.data.child; if (shaderParam.hasOwnProperty("this.init")) { shaderParam["this.init"](); } if (shaderParam.hasOwnProperty("this.preRun")) { shaderParam["this.preRun"](); } } /** * 初始化渲染参数 */ public initParams() { this.init(); this.components.forEach(shaderParam => { if (shaderParam.hasOwnProperty("this.init")) { shaderParam["this.init"](); } }); } /** * 渲染前初始化 */ public preRunParams() { this.preRun(); this.components.forEach(shaderParam => { if (shaderParam.hasOwnProperty("this.preRun")) { shaderParam["this.preRun"](); } }); } /** * 初始化 */ public init() { this.sampleFlagsDic = {}; } /** * 运行渲染程序前 */ public preRun() { } /** * 添加纹理取样参数 * @param dataTypeId 纹理数据缓冲类型编号 * @param texture 纹理代理 * @param forceWrap 强制重复纹理参数 */ public addSampleFlags(dataTypeId: string, texture: TextureProxyBase, forceWrap: string = null) { this.sampleFlagsDic[dataTypeId] = null; if (texture) { var flags = TextureUtils.getFlags(this.useMipmapping, this.useSmoothTextures, this.repeatTextures, texture, forceWrap); this.sampleFlagsDic[dataTypeId] = flags; } } /** * 设置取样标记 * @param dataTypeId 纹理数据缓冲类型编号 * @param flags 纹理取样标记 */ public setSampleFlags(dataTypeId: string, flags) { this.sampleFlagsDic[dataTypeId] = flags; } /** * 获取取样标记 * @param dataTypeId 纹理数据缓冲类型编号 * @return 纹理取样标记 */ public getFlags(dataTypeId: string) { return this.sampleFlagsDic[dataTypeId]; } } }
2790b0213a05731d46c7634901e8688911296f8f
TypeScript
green-fox-academy/vis0rka
/week-04/day-1/write-single-line/write-single-line.ts
3.109375
3
import { fileURLToPath } from "url"; 'use strict'; export { }; // Open a file called 'my-file.txt' // Write your name in it as a single line // If the program is unable to write the file, // then it should print an error message like: 'Unable to write file: my-file.txt' const fs = require('fs'); function appendTofile(name: string, data: string) { try { if (fs.existsSync(name)) { console.log(`added to ${name} to ${data}`); return fs.appendFileSync(name, data); } console.log(`Unable to write file: ${name}`); } catch (e) { console.log(`Unable to write file: ${name}`); } } appendTofile("my-file.txt", "blalba");
b221d07f92d99e2e27496e7852128cd3a5a78039
TypeScript
swc-project/swc
/crates/swc_ecma_parser/tests/tsc/objectLiteralNormalization.ts
3.828125
4
// @strict: true // @declaration: true // Object literals in unions are normalized upon widening let a1 = [{ a: 0 }, { a: 1, b: "x" }, { a: 2, b: "y", c: true }][0]; a1.a; // number a1.b; // string | undefined a1.c; // boolean | undefined a1 = { a: 1 }; a1 = { a: 0, b: 0 }; // Error a1 = { b: "y" }; // Error a1 = { c: true }; // Error let a2 = [{ a: 1, b: 2 }, { a: "abc" }, {}][0]; a2.a; // string | number | undefined a2.b; // number | undefined a2 = { a: 10, b: 20 }; a2 = { a: "def" }; a2 = {}; a2 = { a: "def", b: 20 }; // Error a2 = { a: 1 }; // Error // Object literals containing spreads are not normalized declare let b1: { a: string, b: string } | { b: string, c: string }; let b2 = { ...b1, z: 55 }; let b3 = { ...b2 }; // Before widening {} acts like { [x: string]: undefined }, which is a // subtype of types with all optional properties declare let opts: { foo?: string, bar?: string, baz?: boolean }; let c1 = !true ? {} : opts; let c2 = !true ? opts : {}; let c3 = !true ? { a: 0, b: 0 } : {}; let c4 = !true ? {} : { a: 0, b: 0 }; // Normalization applies to nested properties let d1 = [{ kind: 'a', pos: { x: 0, y: 0 } }, { kind: 'b', pos: !true ? { a: "x" } : { b: 0 } }][0]; d1.kind; d1.pos; d1.pos.x; d1.pos.y; d1.pos.a; d1.pos.b; declare function f<T>(...items: T[]): T; declare let data: { a: 1, b: "abc", c: true }; // Object literals are inferred as a single normalized union type let e1 = f({ a: 1, b: 2 }, { a: "abc" }, {}); let e2 = f({}, { a: "abc" }, { a: 1, b: 2 }); let e3 = f(data, { a: 2 }); let e4 = f({ a: 2 }, data);
9c8bbc7792d94bee283e147f94d93193be3f3439
TypeScript
ForNeVeR/vscode-rewrap
/src/DocumentTypes.ts
2.859375
3
import { TextDocument } from 'vscode' import { extname } from 'path' import DocumentProcessor from './DocumentProcessor' import Standard from './Parsers/Standard' import LaTeX from './Parsers/LaTeX' import Markdown from './Parsers/Markdown' import Xml from './Parsers/Xml' export { fromDocument, fromLanguage, fromExtension } /** Gets a DocumentProcessor for a document, taken from its file type */ function fromDocument(doc: TextDocument): DocumentProcessor { return fromLanguage(doc.languageId) || fromExtension(extname(doc.fileName)) // Hack for now. Use as default standard processor with an unlikely comment // marker for plaintext/unknown files. || new Standard({line: '!@#$%'}) } /** Gets a DocumentProcessor for a given language id. Returns null if the id is * not known */ function fromLanguage(id: string): DocumentProcessor { switch(id) { case 'ahk': return new Standard({ start: '\\/\\*', end: '\\*\\/', line: ';' }) case 'bat': return new Standard({ line: '(?:rem|::)' }) // There can be slight differences in all of these but they're all basically // the same case 'c': case 'csharp': case 'cpp': case 'css': case 'go': case 'groovy': case 'java': case 'javascript': case 'javascriptreact': case 'json': case 'less': case 'objective-c': case 'scss': case 'shaderlab': case 'swift': case 'typescript': case 'typescriptreact': return new Standard({ start: '\\/\\*\\*?', end: '\\*\\/', line: '\\/{2,3}' }) case 'clojure': // todo return null case 'coffeescript': return new Standard({ start: '###\\*?', end: '###', line: '#' }) case 'diff': // Not sure what this is return null case 'dockerfile': case 'makefile': case 'perl': case 'r': case 'shellscript': case 'toml': case 'yaml': // These all seem not to have standard multi-line comments return new Standard({ line: '#' }) // These not provided by vscode case 'elm': case 'haskell': case 'purescript': return new Standard({ start: '{-', end: '-}', line: '--' }) case 'fsharp': return new Standard({ start: '\\(\\*', end: '\\*\\)', line: '\\/\\/' }) case 'git-commit': case 'git-rebase': // These are plain text return null case 'handlebars': // Todo: handlebars template comments: // {{!-- --}} and {{! }} return new Xml(true) case 'html': return new Xml(true) case 'ini': return new Standard({ line: '[#;]' }) case 'jade': // Jade block comments are a bit different and might need some more thought return new Standard({ line: '\\/\\/' }) // Not out of the box in vscode case 'latex': case 'tex': return new LaTeX() case 'lua': return new Standard({ start: '--\\[\\[', end: '\\]\\]', line: '--' }) case 'markdown': return new Markdown() case 'perl6': case 'ruby': // Todo: multi-line comments in Perl 6 // https://docs.perl6.org/language/syntax#Comments return new Standard({ start: '^=begin', end: '^=end', line: '#' }) case 'php': return new Standard({ start: '\\/\\*', end: '\\*\\/', line: '(?:\\/\\/|#)' }) case 'powershell': return new Standard({ start: '<#', end: '#>', line: '#' }) case 'python': return new Standard({ start: "('''|\"\"\")", end: "('''|\"\"\")", line: '#' }) case 'razor': // todo return null case 'rust': return new Standard({ line: '\\/{2}(?:\\/|\\!)?' }) case 'sql': return new Standard({ start: '\\/\\*', end: '\\*\\/', line: '--' }) case 'vb': return new Standard({ line: "'" }) case 'xml': case 'xsl': return new Xml(false) default: return null; } } /** Gets a DocumentProcessor for a given file extension (with period). Return * null if the extension is not known. */ function fromExtension(extension: string): DocumentProcessor { switch(extension) { case '.ahk': return fromLanguage('ahk') case '.bbx': case '.cbx': case '.cls': case '.sty': return fromLanguage('tex') case '.cs': return fromLanguage('csharp') case '.elm': return fromLanguage('elm') case '.purs': return fromLanguage('purescript') case '.hs': return fromLanguage('haskell') case '.sass': // Pretend .sass comments are the same as .scss for basic support. // Actually they're slightly different. // http://sass-lang.com/documentation/file.INDENTED_SYNTAX.html return fromLanguage('scss') case '.tex': return fromLanguage('latex') case '.toml': return fromLanguage('toml') default: return null } }
2e16b71f53e6420477806b0714179f065c4e1110
TypeScript
HOI4-Modding-Tools/hoi4-file-parsers
/src/start.ts
2.625
3
import * as yargs from "yargs"; import * as process from "process"; import * as fs from "fs"; import * as path from "path"; import * as util from "util"; import * as os from "os"; import * as chokidar from "chokidar"; import ModDescriptorReader from "./parsers/ModDescriptorReader"; const args = yargs.argv; console.log("Starting up parser."); let directory:string = args.directory as string; if(!directory) { console.log("No directory was specified, so watch the current working directory"); directory = process.cwd(); } const platformSpecificPathReader = process.platform === "win32" ? path.win32 : path.posix; readDescriptorFile(platformSpecificPathReader.join(directory, "descriptor.mod")); chokidar.watch(platformSpecificPathReader.join(directory, "descriptor.mod")).on('change', path => { console.log(path + " changed, reading again."); readDescriptorFile(path); }) // search for mod descriptor file in target directory. function readDescriptorFile(atPath: string) { util.promisify(fs.readFile)(atPath, "utf8").then(fileContents => { const {errors, content} = new ModDescriptorReader().read(fileContents); if(errors?.length) { console.error("Errors in " + atPath); const sortedErrors = errors.sort((a, b) => a.line - b.line); for(const error of sortedErrors) { if(error.stack) { console.error(error); } else { console.error(error.message); } } } else { console.log("Successfully read " + atPath); } }, error => { console.error("System error while trying to read file", error); }); }
a9ede489c2bac5f1f1776fad8acc361ad3d8937a
TypeScript
danielisaacgeslin/reservations-offices
/app/filters/repeatObjectToArray.filter.ts
2.625
3
(() => { 'use strict'; angular.module('app').filter('repeatObjectToArrayFilter', repeatObjectToArrayFilter); function repeatObjectToArrayFilter(): Function { function orderThis(a: any, b: any, orderKey: string): number { var aValue = a[orderKey]; var bValue = b[orderKey]; if (aValue.getTime && bValue.getTime) { aValue = aValue.getTime(); bValue = bValue.getTime(); } if (aValue > bValue) { return 1; } else { return -1; } } return function(items: any[], orderArray: string[]): any[] { var itemsArray = []; for (let key in items) { if (items.hasOwnProperty(key)) { itemsArray.push(items[key]); } } orderArray.forEach((orderKey: string) => { itemsArray = <any[]>itemsArray.sort((a: any, b: any) => { return <number>orderThis(a, b, orderKey); }); }); return <any[]>itemsArray; }; } })();
81fa5fc2a534c9f442014270e6fe622e9b09f202
TypeScript
mosqlee/ts-lodash
/src/array/dropRight/dropRight.test.ts
3.796875
4
/** * Given an array of items * and a number of items to drop (defaults to 1) * it should return a new array with items dropped from the end of the array */ import { dropRight as dRight } from 'lodash' import dropRight from './dropRight' describe('#dropRight', () => { it('should return an array', () => { expect(dropRight([1, 2, 3])).toBeInstanceOf(Array) }) it('should drop 1 from the end', () => { const inputArray = [1, 2, 3] const expected = dRight(inputArray) const actual = dropRight(inputArray) expect(actual).toEqual(expected) }) const inputs = 'abcdefghijk'.split('') for (let idx = 0; idx < inputs.length; idx++) { const expected = dRight(inputs, idx) const actual = dropRight(inputs, idx) it(`should drop ${idx} items from then end of ${inputs}`, () => { expect(actual).toEqual(expected) }) } it('should reuturn an empty array for n >= array length', () => { const expected1 = dRight(inputs, inputs.length) const actual1 = dropRight(inputs, inputs.length) expect(actual1).toEqual(expected1) const expected2 = dRight(inputs, inputs.length + 1) const actual2 = dropRight(inputs, inputs.length + 1) expect(actual2).toEqual(expected2) }) it('should treat negative numbers the same way that lodash does', () => { const expected = dRight(inputs, -1) const actual = dropRight(inputs, -1) expect(actual).toEqual(expected) }) })
9c0ba82d5137f2121b45d99b584a60891139839d
TypeScript
quangbestdev/uniforms
/packages/uniforms-bridge-graphql/src/GraphQLBridge.ts
2.65625
3
import * as graphql from 'graphql/type/definition'; import invariant from 'invariant'; import lowerCase from 'lodash/lowerCase'; import memoize from 'lodash/memoize'; import upperFirst from 'lodash/upperFirst'; import { Bridge, joinName } from 'uniforms'; function extractValue(x: boolean | null | string | undefined, y: string) { return x === false || x === null ? '' : x !== true && x !== undefined ? x : y; } // FIXME: What type is it? Maybe there's a helper in `graphql` for that? function extractFromNonNull(x: any) { return x && graphql.isNonNullType(x.type) ? { ...x, type: x.type.ofType } : x; } function toHumanLabel(label: string) { return upperFirst(lowerCase(label)); } export default class GraphQLBridge extends Bridge { constructor( public schema: graphql.GraphQLInputObjectType | graphql.GraphQLObjectType, public validator: (model: Record<string, any>) => any, public extras: Record<string, any> = {}, ) { super(); // Memoize for performance and referential equality. this.getField = memoize( this.getField, (name, returnExtracted = true) => `${name}:${returnExtracted}`, ); this.getSubfields = memoize(this.getSubfields); this.getType = memoize(this.getType); } getError(name: string, error: any) { return ( // FIXME: Correct type for `error`. error?.details?.find?.((error: any) => error.name === name) || null ); } getErrorMessage(name: string, error: any) { const scopedError = this.getError(name, error); return scopedError?.message || ''; } getErrorMessages(error: any) { if (error) { if (Array.isArray(error.details)) { // FIXME: Correct type for `error`. return (error.details as any[]).map(error => error.message); } if (error.message) { return [error.message]; } } if (error !== undefined) { return [error]; } return []; } getField(name: string, returnExtracted = true) { return joinName(null, name).reduce((definition, next, index, array) => { if (next === '$' || next === '' + parseInt(next, 10)) { invariant( graphql.isListType(definition.type), 'Field not found in schema: "%s"', name, ); definition = { type: extractFromNonNull(definition.type.ofType) }; // @ts-ignore: Not public API. } else if (definition.type && definition.type._fields) { // @ts-ignore: Not public API. definition = definition.type._fields[next]; } else { // @ts-ignore: Incorrect `definition` type. definition = definition[next]; } invariant(definition, 'Field not found in schema: "%s"', name); const isLast = array.length - 1 === index; if (isLast && !returnExtracted) { return definition; } const extracted = extractFromNonNull(definition); if ( (isLast && returnExtracted) || !graphql.isObjectType(extracted.type) ) { return extracted; } invariant( extracted.type.getFields, 'Field not found in schema: "%s"', name, ); return extracted.type.getFields(); }, this.schema.getFields()); } getInitialValue(name: string, props: Record<string, any> = {}): any { const type = this.getType(name); if (type === Array) { const item = this.getInitialValue(joinName(name, '0')); const items = (props.initialCount as number) || 0; return Array.from({ length: items }, () => item); } if (type === Object) { return {}; } const defaultValue = this.getField(name).defaultValue; return defaultValue === undefined ? this.extras[name]?.initialValue : defaultValue; } // eslint-disable-next-line complexity getProps(nameNormal: string, props: Record<string, any> = {}) { const nameGeneric = nameNormal.replace(/\.\d+/g, '.$'); const field = this.getField(nameGeneric, false); const fieldType = extractFromNonNull(field).type; const ready = { required: graphql.isNonNullType(field.type), ...this.extras[nameGeneric], ...this.extras[nameNormal], }; if (graphql.isScalarType(fieldType) && fieldType.name === 'Float') { ready.decimal = true; } // @ts-ignore: `field.name` is not a string? ready.label = extractValue(ready.label, toHumanLabel(field.name)); const options = props.options || ready.options; if (options) { if (!Array.isArray(options)) { ready.transform = (value: any) => options[value]; ready.allowedValues = Object.keys(options); } else { ready.transform = (value: any) => options.find(option => option.value === value).label; ready.allowedValues = options.map(option => option.value); } } return ready; } getSubfields(name?: string) { if (!name) { return Object.keys(this.schema.getFields()); } const fieldType = this.getField(name).type; if ( graphql.isObjectType(fieldType) || graphql.isInputObjectType(fieldType) ) { return Object.keys(fieldType.getFields()); } return []; } getType(name: string) { const fieldType = this.getField(name).type; if (graphql.isListType(fieldType)) return Array; if (graphql.isObjectType(fieldType)) return Object; if (graphql.isInputObjectType(fieldType)) return Object; if (graphql.isScalarType(fieldType)) { if (fieldType.name === 'ID') return String; if (fieldType.name === 'Int') return Number; if (fieldType.name === 'Float') return Number; if (fieldType.name === 'String') return String; if (fieldType.name === 'Boolean') return Boolean; } return fieldType; } getValidator(/* options */) { return this.validator; } }
6fe1b9ebeddfcc24d6bfd506aac29da9c9a5d365
TypeScript
ksc-fe/kpc
/components/slider/useValue.ts
2.71875
3
import {useInstance} from 'intact'; import type {Slider} from './'; import {useReceive} from '../../hooks/useReceive'; import {NormalizedGetStep} from '../spinner/useStep'; import {minMaxStep} from '../spinner/useValue'; import {error} from 'intact-shared'; import {isEqualArray} from '../utils'; import {useState} from '../../hooks/useState'; export type Value<Range extends boolean = boolean> = Range extends true ? [number, number] : number export function useValue(getStep: NormalizedGetStep, getDragging: () => boolean) { const instance = useInstance() as Slider<boolean>; const showValue = useState<Value>(instance.get('value')!, isEqualValue); useReceive<Slider>(['min', 'max', 'step', 'value'], () => { if (getDragging()) return; fixValue(instance.get('value')!, true); }); instance.on('$change:value', (newValue, oldValue) => { if (getDragging()) return; instance.trigger('change', newValue!, oldValue!); }); function isEqualValue(newValue: Value, oldValue: Value) { return newValue === oldValue || isEqualArray(newValue, oldValue); } function fixValue(value: Value, fixShowValue: boolean) { const fixedValue = getFixedValue(value); showValue.set(fixShowValue ? fixedValue: value); setValue(fixedValue); } function setValue(value: Value) { if (isEqualValue(value, instance.get('value')!)) return; instance.set({value}); } function getFixedValue(value: Value): Value { const {min, range} = instance.get(); let fixedValue: Value; if (range) { if (!Array.isArray(value)) { const tmp = fix(value); fixedValue = [tmp, tmp]; } else { fixedValue = [fix(value[0]), fix(value[1])]; } } else { fixedValue = fix(value as number); } return fixedValue; } function fix(value: number): number { const {max, forceStep} = instance.get(); const [step, min] = getStep(value); if (min > max!) { if (process.env.NODE_ENV !== 'production') { error(`[Slider] min must less than or equal to max, but got min: ${min} max: ${max}`); return 0; } } return minMaxStep(value, min, max!, forceStep ? step : null); } function onSpinnerChange(v: Value) { showValue.set(v); instance.set({value: v}); } function onLeftSpinnerChange(v: number) { const secondValue = (showValue.value as Value<true>)[1]; onSpinnerChange([v, Math.max(v, secondValue)]); } function onRightSpinnerChange(v: number) { const firstValue = (showValue.value as Value<true>)[0]; onSpinnerChange([Math.min(v, firstValue), v]); } function triggerChangeEvent(oldValue: Value) { const {value} = instance.get(); if (isEqualValue(value!, oldValue)) return; instance.trigger('change', value!, oldValue); } return { showValue, onSpinnerChange, onLeftSpinnerChange, onRightSpinnerChange, setValue, triggerChangeEvent, fixValue, }; }
671fe3320537be9e0520781c17912be2ad15f685
TypeScript
seektor/Canvas_renderer
/src/app/components/ConfigSection/ConfigSection.ts
2.734375
3
import { Utils } from '../../utils/Utils'; import { Switch } from '../Switch/Switch'; import ConfigSectionAttributeHooks from './structures/ConfigSectionAttributeHooks'; import ConfigSectionClassHooks from './structures/ConfigSectionClassHooks'; export class ConfigSection { private componentElement: HTMLElement; private visible: boolean; constructor(container: HTMLElement, themeChangeCallback: (isChecked: boolean) => void) { this.onTransitionEnd = this.onTransitionEnd.bind(this); this.construct(container, themeChangeCallback); this.visible = false; } private construct(hostElement: HTMLElement, themeChangeCallback: (isChecked: boolean) => void): void { const template: string = require('./config-section.html'); const templateFragment: DocumentFragment = Utils.convertToDocumentFragment(template); this.componentElement = templateFragment.firstChild as HTMLElement; this.componentElement.style.display = 'none'; hostElement.append(this.componentElement); const themeSection: HTMLElement = Utils.getElementByAttribute(this.componentElement, ConfigSectionAttributeHooks.sectionTheme); new Switch(themeSection, themeChangeCallback); } public getToggleCallback(): () => void { return () => this.toggle(); } private onTransitionEnd(): void { this.componentElement.style.display = 'none'; } private toggle(): void { if (this.visible) { this.visible = false; this.componentElement.addEventListener('transitionend', this.onTransitionEnd) this.componentElement.classList.add(ConfigSectionClassHooks.hidden); } else { this.visible = true; this.componentElement.removeEventListener('transitionend', this.onTransitionEnd); this.componentElement.classList.remove(ConfigSectionClassHooks.hidden); this.componentElement.style.display = 'block'; } } }
a6b7507c2357c8371d573825e01136b3b0b540e1
TypeScript
siongesteban/crwn-clothing-client
/src/reducers/sample.reducer.ts
3.03125
3
import { SampleState, Action, ActionType } from 'types'; const INITIAL_STATE: SampleState = { name: 'John', age: 99, job: { title: 'Developer', description: 'React Developer', }, }; export const sampleReducer = ( state: SampleState = INITIAL_STATE, action: Action, ): SampleState => { switch (action.type) { case ActionType.UPDATE_SAMPLE_NAME: const { name } = action.payload; return { ...state, name, }; case ActionType.UPDATE_SAMPLE_AGE: const { age } = action.payload; return { ...state, age, }; default: return state; } };
b4c4128c326bff2d3f048438893751df61215980
TypeScript
jeremy-coleman/esbuild-vs-omnify-r3f
/tools/omnify/bundler/deps-sort.ts
2.546875
3
import { Transform } from "stream" import { shasum } from "./shasum" type DepsSortOptions = { expose?: {} | [] dedupe?: any index?: any } export function depsSort(opts: { expose?: {} | []; dedupe?: any; index?: any }) { if (!opts) opts = {} var rows = [] return new Transform({ objectMode: true, write: function write(row, enc, next) { rows.push(row) next() }, flush: function flush() { rows.sort((a: { id: any; hash: any }, b: { id: any; hash: any }) => { return a.id + a.hash < b.id + b.hash ? -1 : 1 }) var expose = opts.expose || {} if (Array.isArray(expose)) { expose = expose.reduce(function (acc, key) { acc[key] = true return acc }, {}) } var hashes = {} var deduped = {} var _depsMap = new Map() //{} var _hashesMap = new Map() //{} function sameDepsAdd(row: { id: string | number; deps: any }, hash: any) { _depsMap.set(row.id, row.deps) _hashesMap.set(row.id, hash) } function sameDepsCmp(a: { [x: string]: any }, b: { [x: string]: any }, limit: number = undefined) { if (!a && !b) return true if (!a || !b) return false var keys = Object.keys(a) if (keys.length !== Object.keys(b).length) return false for (var i = 0; i < keys.length; i++) { var k = keys[i] var ka = a[k] var kb = b[k] var ha = _hashesMap.get(ka) var hb = _hashesMap.get(kb) var da = _depsMap.get(ka) var db = _depsMap.get(kb) if (ka === kb) continue if (ha !== hb || (!limit && !sameDepsCmp(da, db, 1))) { return false } } return true } if (opts.dedupe) { rows.forEach((row) => { var h = shasum(row.source) sameDepsAdd(row, h) if (hashes[h]) { hashes[h].push(row) } else { hashes[h] = [row] } }) Object.keys(hashes).forEach((h) => { var rows = hashes[h] while (rows.length > 1) { var row = rows.pop() row.dedupe = rows[0].id row.sameDeps = sameDepsCmp(rows[0].deps, row.deps) deduped[row.id] = rows[0].id } }) } if (opts.index) { var index = {} var offset = 0 rows.forEach(function (row, ix) { if (row.id in expose) { //if (has(expose, row.id)) { row.index = row.id offset++ if (expose[row.id] !== true) { index[expose[row.id]] = row.index } } else { row.index = ix + 1 - offset } index[row.id] = row.index }) rows.forEach((row) => { row.indexDeps = {} Object.keys(row.deps).forEach((key) => { var id = row.deps[key] row.indexDeps[key] = index[id] }) if (row.dedupe) { row.dedupeIndex = index[row.dedupe] } this.push(row) }) } else { rows.forEach((row) => { this.push(row) }) } this.push(null) }, }) }
eb6fe3c5c599fa7c0d2afef59b5881c7c74102c1
TypeScript
Qdigital/expo
/packages/expo-network/src/Network.types.ts
2.609375
3
export type NetworkState = { type?: NetworkStateType; isConnected?: boolean; isInternetReachable?: boolean; }; export enum NetworkStateType { NONE = 'NONE', UNKNOWN = 'UNKNOWN', CELLULAR = 'CELLULAR', WIFI = 'WIFI', BLUETOOTH = 'BLUETOOTH', ETHERNET = 'ETHERNET', WIMAX = 'WIMAX', VPN = 'VPN', OTHER = 'OTHER', }
da628a3b90c7a1f72d1e7424bdef65361d99db29
TypeScript
ojkelly/wahn
/src/index.ts
2.6875
3
import * as mm from "micromatch"; import * as debug from "debug"; import { AuthorizationDeniedError } from "./errors"; import { evaluateAccess, matchPolicies } from "./evaluate"; const info: debug.IDebugger = debug("wahn:info"); const log: debug.IDebugger = debug("wahn:log"); const warn: debug.IDebugger = debug("wahn:warn"); /** * Policy Based Access Control Engine */ class Wahn { private policies: Policy[]; private loggingCallback: LoggingCallback | undefined; constructor(options: WahnConstructorOptions) { this.policies = options.policies; if (typeof options.loggingCallback === "function") { this.loggingCallback = options.loggingCallback; } } /** * Return all current policies */ public getPolicies(): Policy[] { return this.policies; } /** * Return all polices attached to the roles provided * @param roles */ private getPolicesForRole(roles: string[]): Policy[] { const policies: Policy[] = this.policies.filter((policy: Policy) => { const matchedPolicy: boolean = mm.some(roles, policy.roles, { nocase: true, }); if (matchedPolicy) { return policy; } }); return policies; } public evaluateAccess({ context, action, resource, }: WahnEvaluationOptions): boolean { try { // 1. Outcome defaults to: `deny`. let outcome: boolean = false; // 2. Find all applicable policies. const policies: Policy[] = this.getPolicesForRole( context.user.roles, ); outcome = evaluateAccess({ policies, context, action, resource, }); return outcome; } catch (AuthorizationDeniedError) { this.evaluationFailCallback({ policy: AuthorizationDeniedError.policy, context, action, resource, reason: AuthorizationDeniedError.reason, }); // Throw all denied errors throw AuthorizationDeniedError; } } /** * A callback for logging every request that fails. * @param options */ private evaluationFailCallback({ context, action, reason, resource, policy, }: WahnEvaluationFailedOptions): void { info("evaluationFailCallback", { policy, context, action, reason }); if (typeof this.loggingCallback === "function") { this.loggingCallback({ policy, context, action, reason, resource, }); } } } // [ Types ]---------------------------------------------------------------------------------------- type WahnConstructorOptions = { policies: Policy[]; loggingCallback?: LoggingCallback; }; type WahnEvaluationOptions = { context: RequestContext; action: string; resource: string; }; type WahnEvaluationFailedOptions = { policy: Policy; context: RequestContext; resource: string; action: string; reason: string; }; type ContextUser = { id: string; roles: string[]; [key: string]: any; }; type RequestContext = { user: ContextUser; resource?: any; request?: { ip?: string; [key: string]: any; }; [key: string]: any; }; enum PolicyEffect { Allow = "Allow", Deny = "Deny", } enum PolicyOperator { match = "match", notMatch = "notMatch", lessThan = "lessThan", greaterThan = "greaterThan", } type PolicyCondition = { // A dot path to the value on context field: string; // Expected value expected?: (number | string)[]; // A dot path to the context object expectedOnContext?: string[]; operator: PolicyOperator; }; type Policy = { actions: string[]; resources: string[]; // id must be unqiue id: string; effect: PolicyEffect; // Optional denyType to be thown denyType?: string; // Multiple conditions are evaluated as AND (ie all conditions must be true) conditions?: PolicyCondition[]; // Roles can have a glob roles: string[]; }; interface LoggingCallback { (LoggingCallbackLog): void; } type LoggingCallbackLog = { policy?: Policy | null; context: RequestContext; action: string; reason: string; resource: string; }; // [ Export ]--------------------------------------------------------------------------------------- export { Wahn, // Policy Exports Policy, PolicyEffect, PolicyCondition, PolicyOperator, // Logging Exports LoggingCallback, LoggingCallbackLog, RequestContext, ContextUser, WahnConstructorOptions, WahnEvaluationOptions, AuthorizationDeniedError, };
5d28526eaca968760db85bda7259e06a21be4faf
TypeScript
joseavilees/SCode
/1. Presentation/SCode.Client.Student.WebApp/SCode.Client.Student.WebApp/ClientApp/src/app/application/helpers/MonacoHelper.ts
2.796875
3
import { StringHelper } from "./StringHelper"; export class MonacoHelper { static getLanguageByFileName(fileName: string) { const extension = StringHelper .getFileNameExtension(fileName); switch (extension) { case "js": case "mjs": return "javascript"; case "ts": return "typescript"; case "md": return "markdown"; case "cs": return "csharp"; case "kt": case "kts": case "ktm": return "kotlin"; default: return extension; } } }
28129783bf7a62334c423c9b2785afc5d29c756a
TypeScript
optics-team/hal-client
/src/fetchAll.ts
2.796875
3
import { Resource } from './Resource'; import { Link } from './Link'; export interface Options { embed: string; params?: {}; progress?: (total: number, complete: number) => void; } export const fetchAll = async<T extends Resource>(link: Link, { embed, params, progress }: Options) => { let items: T[] = []; let currentPage = await link.fetch(params); while (true) { if (currentPage.hasEmbedded(embed)) { items = items.concat(currentPage.embedded(embed) as T[]); if (progress) { progress(currentPage.properties.count, items.length); } } if (!currentPage.hasLink('next')) { return { items, total: items.length } } currentPage = await currentPage.link('next').fetch(params); } }
cdd9d181883f3b51b3829a7b42a17934be9d51a1
TypeScript
GavinHe322/learning
/design/18-接口和面向接口编程/21.5.ts
2.71875
3
interface Command { execute: Function } const log: Function = console.log class RefreshMenuBarCommand implements Command { constructor() {} execute() { log('刷新菜单界面') } } class AddSubMenuCommand implements Command { constructor() {} execute() { log('添加子菜单') } } var refreshMenuBarCommand: RefreshMenuBarCommand = new RefreshMenuBarCommand() refreshMenuBarCommand.execute() var addSubMenuCommand: AddSubMenuCommand = new AddSubMenuCommand() addSubMenuCommand.execute()
52d9f164fbd18a4dbc30e1e5194f69bff5ad2124
TypeScript
breck7/virtual-unfolding
/src/common/MutableTypedArray.ts
3.546875
4
import { readBin, getBinUseNull, getBinNumElements, writeBin, writeBinHeader, readDataAsType } from './io'; import { isPositiveInteger, typeOfTypedArray, isNonNegativeInteger, nullValForType, isArray, dataSizeForType } from './utils'; import { Vector3, Vector2 } from 'three'; import { Type, TypedArray } from './types'; import { closeSync, openSync } from 'fs'; const tempArray: number[] = []; const GROW_INCREMENT = 1000000; /** * Typed array that can grow */ export default class MutableTypedArray { private useNull: Readonly<boolean>; private nullVal?: Readonly<number>; numElementsPerIndex: Readonly<number>; type: Readonly<Type>; private data: TypedArray; private length: number; static initFromFile(path: string, filename: string) { const file = openSync(`${path}${filename}.bin`, 'r'); const useNull = getBinUseNull(path, filename, file); const numElementsPerIndex = getBinNumElements(path, filename, file); const data = readBin(path, filename, file); closeSync(file); return new MutableTypedArray(data, useNull, numElementsPerIndex); } /** * @constructor * @param {TypedArray} data initial data. * @param {boolean} useNull flag telling if this data contains nulls * @param {number} numElementsPerIndex number of elements that should be grouped together * @param {number} length number of indices in data (only used in clone() operations) */ constructor(data: TypedArray, useNull: boolean, numElementsPerIndex = 1, length = data.length / numElementsPerIndex) { // Check input params. if (!isPositiveInteger(numElementsPerIndex)) { throw new Error('numElementsPerVox for MutableTypedArray must be a positive integer.'); } // Store input params. this.numElementsPerIndex = numElementsPerIndex; this.type = typeOfTypedArray(data); this.useNull = useNull; this.data = data;//.slice(0, length * numElementsPerIndex);// Make copy of data. // Init other params. this.length = length; if (!isNonNegativeInteger(this.length)) { throw new Error('Input data length of MutableTypedArray is not integer multiple of numElementsPerIndex.'); } if (this.useNull) { this.nullVal = nullValForType(this.type); } } /** * Clears all data (to either 0 or null). */ clear() { let clearVal = 0; if (this.useNull) { clearVal = this.nullVal!; } for (let i = 0; i < this.data.length; i++) { this.data[i] = clearVal; } } /** * Returns 'length' of array. * Note that each entry of a MutableTypedArray may contain multiple values. * @returns {number} number of entries in MutableTypedArray */ getLength() { return this.length; } /** * Returns value(s) or null at index. * @param {number} index lookup index * @returns {number|array|null} value(s) stored at given index or null */ get(index: number): number | null; get(index: number, array: number[]): number[] | null get(index: number, array?: number[]) { // Check input param. if (index < 0 || index >= this.length) { throw new Error(`Index out of bounds: ${index}`); } // Get first element stored at index. const firstVal = this.data[this.numElementsPerIndex * index]; if (this.useNull && firstVal === this.nullVal) return null; // If only one element per index, return a single number. if (this.numElementsPerIndex === 1) { return firstVal; } // Otherwise, return an array of values or null. if (array === undefined) { throw new Error('No array passed to MutableTypedArray.get().'); } // Else, add vals to array until a null value or numElementsPerIndex is reached. array.length = 0; array.push(firstVal); for (let i = 1; i < this.numElementsPerIndex; i++) { const val = this.data[(this.numElementsPerIndex * index) + i]; if (this.useNull && val === this.nullVal) return array; array.push(val); } return array; } /** * Returns Vector3 at index. * @param {number} index lookup index * @returns {Vector3} Vector3 stored at given index or null */ getVector3(index: number, v: Vector3) { // Check input param. if (this.numElementsPerIndex !== 3) { throw new Error('Cannot call getVector3() on MutableTypedArray with numElementsPerIndex != 3.'); } // Call standard get function. const data = this.get(index, tempArray); if (data === null) return null; // Return array as Vector3. if (data.length !== 3) { throw new Error(`Voxel at index ${index} contains less than three elements.`); } return v.set(data[0], data[1], data[2]); // if (v) return v.set(data[0], data[1], data[2]); // return new Vector3(data[0], data[1], data[2]); } /** * Returns Vector2 at index. * @param {number} index lookup index * @returns {Vector2} Vector2 stored at given index or null */ getVector2(index: number, v: Vector2) { // Check input param. if (this.numElementsPerIndex !== 2) { throw new Error('Cannot call getVector2() on MutableTypedArray with numElementsPerIndex != 2.'); } // Call standard get function. const data = this.get(index, tempArray); if (data === null) return null; // Return array as Vector2. if (data.length !== 2) { throw new Error(`Voxel at index ${index} contains less than two elements.`); } return v.set(data[0], data[1]); // if (v) return v.set(data[0], data[1]); // return new Vector2(data[0], data[1]); } /** * Sets data at index. * @param {number} index lookup index * @param {number|array|null} val value(s) or null */ set(index: number, val: number | number[] | null) { if (index < 0 || index >= this.length) { throw new Error(`Index out of bounds: ${index}`); } if (val === null) { if (this.useNull) { for (let i = 0; i < this.numElementsPerIndex; i++) { this.data[index * this.numElementsPerIndex + i] = this.nullVal as number; } } else { throw new Error('Null value not valid for this MutableTypedArray.'); } } else if (this.numElementsPerIndex === 1) { if (isArray(val)){ throw new Error('MutableTypedArray.set() val must be number or null for numElementsPerIndex === 1.'); } this.data[index] = val as number; } else { if (!isArray(val)){ throw new Error('MutableTypedArray.set() val must be array or null for numElementsPerIndex > 1.'); } val = val as number[]; if (this.numElementsPerIndex !== val.length && !this.useNull) { // If not using nulls, numElementsPerIndex must equal val.length. throw new Error('MutableTypedArray.set() val param must be same length as numElementsPerIndex.'); } if (this.numElementsPerIndex < val.length) { throw new Error('MutableTypedArray.set() val param is too long.'); } for (let i = 0; i < this.numElementsPerIndex; i++) { // Fill this._data with val[i] or null. this.data[this.numElementsPerIndex * index + i] = (i < val.length) ? val[i] : this.nullVal as number; } } } /** * Sets Vector3 at index. * @param {number} index lookup index * @param {Vector3|null} val Vector3 or null */ setVector3(index: number, val: Vector3 | null) { // Check input params. if (this.numElementsPerIndex !== 3) { throw new Error('Must be exactly three elements per index to call setVector3().'); } if (index < 0 || index >= this.length) { throw new Error(`Out of bound index ${index} for MutableTypedArray of length ${this.length}.`); } // Set data. if (val === null) { if (this.useNull) { this.data[3 * index] = this.nullVal as number; this.data[3 * index + 1] = this.nullVal as number; this.data[3 * index + 2] = this.nullVal as number; } else throw new Error('Null value not valid for this MutableTypedArray.'); } else { this.data[3 * index] = val.x; this.data[3 * index + 1] = val.y; this.data[3 * index + 2] = val.z; } } /** * Sets Vector2 at index. * @param {number} index lookup index * @param {Vector2|null} val Vector3 or null */ setVector2(index: number, val: Vector2) { // Check input params. if (this.numElementsPerIndex !== 2) { throw new Error('Must be exactly two elements per index to call setVector2().'); } if (index < 0 || index >= this.length) { throw new Error(`Out of bound index ${index} for MutableTypedArray of length ${this.length}.`); } // Set data. if (val === null) { if (this.useNull) { this.data[2 * index] = this.nullVal as number; this.data[2 * index + 1] = this.nullVal as number; } else throw new Error('Null value not valid for this MutableTypedArray.'); } else { this.data[2 * index] = val.x; this.data[2 * index + 1] = val.y; } } // /** // * Sets large window of data at once. // * @param {TypedArray} data new data // * @param {number} [startIndex] starting index to set data // * @param {number} [numIndices] number of indices to set // */ // setData(data, startIndex, numIndices) { // // Set default params. // const start = startIndex || 0; // const length = numIndices || data.length / this.numElementsPerIndex; // // Check input params. // if (length * this.numElementsPerIndex > data.length) { // throw new Error('setData() error, data array is not long enough for numIndices.'); // } // // Set data. // // this._data.set(data, start * this.numElementsPerIndex); // const num = length * this.numElementsPerIndex; // for (let i = 0; i < num; i++) { // this._data[(start * this.numElementsPerIndex) + i] = data[i]; // } // } private growDataArray() { if (this.data.length === this.length * this.numElementsPerIndex) { // Grow data array by adding a million extra entries. const length = this.numElementsPerIndex * (this.length + GROW_INCREMENT); // Check that we haven't exceed a max. // TODO: handle these cases. if (length * dataSizeForType(this.type) > (2 ** 31) - 1) { throw new Error('Mutable typed array is too long.'); } let newData; switch (this.type) { case 'uint8': newData = new Uint8Array(length); break; case 'int16': newData = new Int16Array(length); break; case 'uint16': newData = new Uint16Array(length); break; case 'int32': newData = new Int32Array(length); break; case 'uint32': newData = new Uint32Array(length); break; case 'float32': newData = new Float32Array(length); break; default: throw new Error(`Unknown type ${this.type}.`); } // Populate new array with old data. for (let i = 0, length = this.length * this.numElementsPerIndex; i < length; i++) { newData[i] = this.data[i]; } // Fill the rest will null, if needed. if (this.useNull) { for (let i = this.length * this.numElementsPerIndex, length = newData.length; i < length; i++) { newData[i] = this.nullVal!; } } // Set this._data. this.data = newData; } } /** * Pushes data to end of array. * @param {number|array|null} val value(s) or null to push. */ push(val: number[] | number | null) { this.growDataArray(); // Get index. const index = this.length; // Increment length. this.length += 1; // Set value(s) or null with regular setter. this.set(index, val); } /** * Pushes Vector3 to end of array. * @param {Vector3|null} vec Vector3 or null */ pushVector3(val: Vector3 | null) { this.growDataArray(); // Get index. const index = this.length; // Increment length. this.length += 1; // Set value(s) or null with regular setter. this.setVector3(index, val); } /** * Pushes Vector2 to end of array. * @param {Vector2|null} vec Vector3 or null */ pushVector2(val: Vector2) { this.growDataArray(); // Get index. const index = this.length; // Increment length. this.length += 1; // Set value(s) or null with regular setter. this.setVector2(index, val); } forEach(callback: (val: number | number[] | null, index: number) => void) { for (let i = 0, length = this.length; i < length; i++) { callback(this.get(i), i); } } forEachVector3(callback: (val: Vector3 | null, index: number) => void) { const v = new Vector3(); for (let i = 0, length = this.length; i < length; i++) { callback(this.getVector3(i, v), i); } } forEachVector2(callback: (val: Vector2 | null, index: number) => void) { const v = new Vector2(); for (let i = 0, length = this.length; i < length; i++) { callback(this.getVector2(i, v), i); } } // /** // * Returns a copy of a portion of the this._data array. // * @param {number} [startIndex=0] starting index to copy from // * @param {number} [endIndex=this.length] ending index to copy from // */ // getData(startIndex, endIndex) { // // Set default params, if necessary. // const start = startIndex || 0; // const end = endIndex || this.length; // // Check params. // if (!utils.isNonNegativeInteger(start)) { // throw new Error(`Invalid startIndex: ${start}`); // } // if (start >= end) { // throw new Error('startIndex must be strictly less than endIndex.'); // } // if (!utils.isInteger(end) || end > this.length) { // throw new Error(`Invalid endIndex: ${end}`); // } // return this._data.slice(start * this.numElementsPerIndex, end * this.numElementsPerIndex); // } /** * Returns this.data, this is called externally to avoid unecessary copies. */ getData() { return this.data; } /** * Saves data as a .vol file. * @param {string} path path for save * @param {*} filename filename for save */ saveAsBin(path: string, filename: string) { writeBin(path, filename, this.data, this.numElementsPerIndex, this.useNull, this.getLength() * this.numElementsPerIndex); } /** * Opens a new file and saves header. * @param {string} path path for save * @param {*} filename filename for save * @returns {integer} file pointer */ saveHeader(path: string, filename: string) { return writeBinHeader(path, filename, this.data, this.numElementsPerIndex, this.useNull, this.getLength() * this.numElementsPerIndex); } /** * Clears all memory for garbage collection. */ destroy() { // Clear properties for garbage collection. // delete this.data; } /** * Returns a deep copy of current instance. * @returns {MutableTypedArray} clone of current instance */ clone() { return new MutableTypedArray(this.data, this.useNull, this.numElementsPerIndex, this.length); } // TODO: remove this. convertToVector2() { if (this.numElementsPerIndex !== 3 || this.type !== 'float32') { throw new Error('bad Vector 3 array'); } const data = new Float32Array(this.length * 2); for (let i = 0; i < this.length; i++) { data[2 * i] = this.data[3 * i]; data[2 * i + 1] = this.data[3 * i + 2]; } return new MutableTypedArray(data, this.useNull, 2); } // TODO: remove this. static initFromVol(path: string, filename: string, type: Type, useNull: boolean, numElementsPerIndex: number) { const fullPath = `${path}${filename}.vol`; const file = openSync(fullPath, 'r'); const data = readDataAsType(fullPath, type, 0, undefined, file); closeSync(file); return new MutableTypedArray(data, useNull, numElementsPerIndex); } }
7bbc703fe980916023ad4b134079a3cf0489484c
TypeScript
kristianmandrup/js-ts-language-implementation-patterns
/ts-src/interpreter/tree/TokenStream.ts
2.53125
3
export class TokenStream { toString(startIndex: number, stopIndex: number): string { return ""; } }
e14c0c49d60001a7ac5443753a8ab39a0b14b871
TypeScript
checkupjs/checkup
/packages/core/src/data/formatters.ts
2.828125
3
export function toPercent(numeratorOrValue: number, denominator?: number): string { let value: number = typeof denominator === 'number' ? numeratorOrValue / denominator : numeratorOrValue; return `${(value * 100).toFixed(0)}%`; }
d6716bfcfa808ecb1910859324f8d489ca309110
TypeScript
dretechtips/librecommerce-server
/src/app/api/sale/shipping/Shipping.interface.ts
2.734375
3
import AddressSchema from "src/app/common/model/schema/Address.schema"; import CostSchema from "../../billing/cost/Cost.schema"; import { Transactable } from "../../billing/transaction/Transaction.interface"; import { PackageDOT } from "./package/Package.interface"; export interface ShippingDOT extends Transactable { /** * Shipping Vendor */ provider: ShippingProvider; /** * Is Cancelled */ cancelled: boolean; /** * Amount of Days */ days: number; /** * Package IDs */ packageIDs: string[]; /** * Ship From Account ID */ shipFromID: string; /** * Ship To Account ID */ shipToID: string; /** * Has been shipped? */ hasShipped: boolean; } export interface ShippingParty { contact: ContactSchema; company?: string; } export enum ShippingProvider { // FEDEX, // USPS, UPS, NONE } /** * One - One Communication to different shipping API * `NOTE:` That this service will assume that all shipping are unilateral shippings, thus * shipper cannot be assigned to other company and all shipping fee will be put on this company. */ export interface ShippingProviderService { /** * Makes request to see if the server / microservice is alive and working. */ isAvailable(): Promise<boolean>; /** * Gets the costs associated witht his shipping provider * @param packages Standard Package * @param days */ getCosts( days: number, packages: PackageDOT[], shipFrom: ShippingParty, shipTo: ShippingParty ): Promise<CostSchema[]>; /** * Cancels vendor shipping * @param shipingID Database Shipping ID */ cancel(shipingID: string): Promise<void>; /** * Sends the shipping to the address, from the store provide * @param days Package days in transit * @param packages Package details * @param store The store that the shipping module chooses to ship from * @param shipTo Details on where the package is going to */ ship( days: number, packages: PackageDOT[], shipFrom: ShippingParty, shipTo: ShippingParty ): Promise<ShippingDOT>; /** * Returns the shipping back to the nearest facility * @param shipping ShippingDOT */ return( packages: PackageDOT[], shipFrom: ShippingParty, shipTo: ShippingParty ): Promise<ShippingDOT>; /** * Gives the current location of where the shipping is located for reference * @param shipping ID */ track(shippingID: string): Promise<AddressSchema>; /** * Checks if the location is valid for the vendor * @param address Location */ addressValidation(address: AddressSchema): Promise<boolean>; } export interface ShippingDependentDOT { shippingID: string; /** * Vendor Shipping Identification */ vShippingID: string; tracking: string; }
d4c0ac830b0f609864e5430088fe28020b63ae42
TypeScript
inigo001/bizkaibus-service
/src/services/petitions/Pdf.ts
2.59375
3
import Axios, { AxiosResponse } from 'axios'; import { PetitionBase } from './_PetitionBase'; import { Line } from '@data/models'; import { ROUTES } from '@data/routes'; export class Pdf extends PetitionBase { public petition(line: string | Line, direction: 'I' | 'V' = 'I') { const lineString: string = `${this.formatLineString(line)}${direction.toLowerCase()}.pdf`; return Axios({ method: 'get', url: ROUTES.pdf + lineString, timeout: this.timeout, }).then((response: AxiosResponse) => this.processData(response)); } private processData(response: AxiosResponse) { if (response.status === 200 && response.headers['content-type'] === 'application/pdf') { return Promise.resolve(response.data); } else { return Promise.reject('ERROR'); } } }
0de39ab8b5442d62e39ae1f310a5ec7c68c707b4
TypeScript
Liinkiing/use-mercure
/src/providers/mercure.ts
2.640625
3
import { createContext, createElement } from 'react' interface ProviderOptions { hubUrl: string, withCredentials?: boolean } interface Props { options: ProviderOptions } export const MercureContext = createContext<ProviderOptions>({ hubUrl: '', withCredentials: false }) const MercureProvider: React.FC<Props> = props => { const { options: { hubUrl, withCredentials = false }, children } = props return createElement(MercureContext.Provider, { value: { hubUrl, withCredentials } }, children) } export default MercureProvider
b876c55db053a93774b156232e7b68fd1e0f51d0
TypeScript
yubin-code/md-doc-block
/src/state/menu.ts
2.90625
3
import _ from "lodash"; import doc from '../utils/document'; /** * 菜单方法用于生成修改添加等等操作 */ const MenuMap = new Map(); // 菜单平行数据 const MenuFlat = {}; /** * 替换菜单中内容 * @param menuTree 菜单树 * @param attr 被替换的内容 */ const replaceMenu = (menuPath:string, attr: any, menuTree:any) => { let isUpdate = false; for(let i in menuTree){ const item = menuTree[i]; // 判断是否是目录 if(item.isDir){ const replace:any = replaceMenu(menuPath, attr, item.children ); item.children = replace.menuTree; isUpdate = replace.isUpdate; } // 找到一直的值 if(item.path === menuPath){ const newItem = {...item, ...attr} // 判断属性是否发生改变 if(!_.isEqual(item, newItem)){ menuTree[i] = newItem; isUpdate = true; } } // 让他不存在引用关系 const itemFlat = JSON.parse(JSON.stringify(menuTree[i])); delete itemFlat.children; // 保存平行数据 MenuFlat[item.path] = itemFlat; } // 对数据排序 menuTree = menuTree.sort((a, b) => a.sort - b.sort); return { menuTree, isUpdate }; } /** * 搜索菜单 * @param menuTree 菜单树 * @param MenuPath 菜单路径 */ const searchMenu = (MenuPath: string, menuTree: any) => { let menuItem = {}; for(let i in menuTree){ const item = menuTree[i]; if(item.path === MenuPath){ return item; } // 搜索子类 if(item.children){ const children:any = searchMenu(MenuPath, item.children); if(!_.isEmpty(children)){ return children } } } return menuItem; } /** * 合并菜单 * 用于用户新建文件的时候使用 * @param menuTree */ const mergeMenu = (menuTree:any) => { for(let i in menuTree){ const item = menuTree[i]; // 判断是否是目录 if(item.isDir){ const replace:any = mergeMenu(item.children); item.children = replace; } if(MenuFlat[item.path]){ menuTree[i] = Object.assign(item, MenuFlat[item.path]); } } return menuTree; } export default { /** * 创建菜单 * @param menuPath 菜单存放地址 * @param menuTree 菜单结构 */ create(menuTree:any){ MenuMap.set('menu', mergeMenu(menuTree)); }, /** * 更新菜单 * @param docsPath 文档路径 * @param newItem 菜单新的item */ update(docsPath:string, newItem: any){ const menuTree = MenuMap.get('menu'); const newMenu = replaceMenu(docsPath, newItem, menuTree); // 判断是否更新数组 if(newMenu.isUpdate){ MenuMap.set('menu', newMenu.menuTree); } }, /** * 获取菜单详细信息 * @param docsPath 菜单路径 * @param content 当前菜单的内容 * @returns */ getInfo(docsPath: string, content: string){ const key = `/${docsPath.replace("html", "md")}`; const newItem = doc.getAttr(content); this.update(key, newItem); return searchMenu(key, MenuMap.get('menu')) }, /** * 获取菜单 * @returns */ get(){ // 不是多文档模式直接返回menu return MenuMap.get('menu'); } }
bc784c257a8a6ac4ebc32c40d85c85ba77d7d8c8
TypeScript
raphaelcarreiro/tiasburger-rn
/src/pages/account/address/addressReducer.ts
2.78125
3
import { ViaCepResponse } from '../../../services/postalCodeSearch'; import { Address } from '../../../@types/address'; const addressInitialState: Address = {} as Address; interface AddressChangeAction { type: 'ADDRESS_CHANGE'; index: string; value: string; } interface SetAddressAction { type: 'SET_ADDRESS'; address: Address; } interface SetAddressViaCepAction { type: 'SET_ADDRESS_VIACEP'; address: ViaCepResponse; } export type AddressActionsType = AddressChangeAction | SetAddressAction | SetAddressViaCepAction; export function addressChange(index: string, value: string): AddressActionsType { return { type: 'ADDRESS_CHANGE', index, value, }; } export function setAddress(address: Address): AddressActionsType { return { type: 'SET_ADDRESS', address, }; } export function setAddressViaCep(address: ViaCepResponse): AddressActionsType { return { type: 'SET_ADDRESS_VIACEP', address, }; } export default function addressReducer(state = addressInitialState, action: AddressActionsType): Address { switch (action.type) { case 'ADDRESS_CHANGE': { return { ...state, [action.index]: action.value, }; } case 'SET_ADDRESS': { return action.address; } case 'SET_ADDRESS_VIACEP': { return { ...state, address: action.address.logradouro, address_complement: action.address.complemento, district: action.address.bairro, city: action.address.localidade, region: action.address.uf, }; } default: { return state; } } }
bf0f0ba7d59258742a3841359fbf1e5207fed4c1
TypeScript
aivarsliepa/game-platform
/src/data/User.ts
3.203125
3
export interface User { name: string; id: string; room: string; } export class UserData { private users: User[] = []; addUser(user: User | User[]): void { this.users = this.users.concat(user); } removeUser(id: string): User | undefined { const removedUser = this.getUserById(id); this.users = this.users.filter(user => user.id !== id); return removedUser; } getUserById(id: string): User | undefined { return this.users.find(user => user.id === id); } getUserByName(name: string | undefined): User | undefined { return this.users.find(user => user.name === name); } getUserListForRoom(room: string): User[] { return this.users.filter(user => user.room === room); } getUserNamesForRoom(room: string): string[] { return this.users.filter(user => user.room === room).map(user => user.name); } }
2556913b8446dc4c5019ebd119866c676d3ba5bd
TypeScript
milangstojkovic/servicebook
/src/Containers/PresentationProvider/PresentationProvider.reducer.ts
2.53125
3
import ACTION_TYPE from '../../Store/actionTypes' import {IPresentationProviderActions} from './PresentationProvider.actions' import {IPresentationProviderState} from './PresentationProvider.state' import {PageStatus} from '../../Models/Model' const initState: IPresentationProviderState = { pageStatus: PageStatus.Home }; export default (state = initState, action: IPresentationProviderActions) => { switch(action.type) { case ACTION_TYPE.SET_PAGE_STATUS: return { ...state, pageStatus:action.payload } default: return state; } }
926406a185f6f722cfe9f0970e820c5df0f240c5
TypeScript
lambGirl/hooks
/packages/hooks/src/useThrottleFn/index.ts
3.203125
3
/** * 截流 * 采用hooks的方式便携式 */ import { DependencyList, useCallback, useEffect, useRef } from 'react'; // 优化Effect更新的规则 // 第一次初始化时,打标记为true; 设置成true后,执行 import useUpdateEffect from '../useUpdateEffect'; // 声明一个方法 type noop = (...args: any[]) => any; export interface ReturnValue<T extends any[]> { run: (...args: T) => void; cancel: () => void; } /** * 方法重载 * @param fn * @param wait */ function useThrottleFn<T extends any[]>(fn: (...args: T) => any, wait: number): ReturnValue<T>; /** * 方法重载 * @param fn * @param deps * @param wait */ function useThrottleFn<T extends any[]>( fn: (...args: T) => any, deps: DependencyList, wait: number, ): ReturnValue<T>; function useThrottleFn<T extends any[]>( fn: (...args: T) => any, deps: DependencyList | number, wait?: number, ): ReturnValue<T> { const _deps: DependencyList = (Array.isArray(deps) ? deps : []) as DependencyList; const _wait: number = typeof deps === 'number' ? deps : wait || 0; // 声明定时器 const timer = useRef<any>(); // 定义fn的ref const fnRef = useRef<noop>(fn); fnRef.current = fn; // 当前的Args数据的Ref const currentArgs = useRef<any>([]); // 清除定时器 const cancel = useCallback(() => { if (timer.current) { clearTimeout(timer.current); } timer.current = undefined; }, []); // 执行方法, useCallback性能处理 const run = useCallback( (...args: any) => { currentArgs.current = args; // 如果timer当前对象不存在则执行 if (!timer.current) { timer.current = setTimeout(() => { // 将当前的args传入fnRef; fnRef.current(...currentArgs.current); timer.current = undefined; }, _wait); } }, [_wait, cancel], ); // 初始化执行方法,当decps[],run改变时执行 /** * 封装Effect,优化Effect的更新 */ useUpdateEffect(() => { run(); }, [..._deps, run]); // 首次执行时,执行清除定时器操作 useEffect(() => cancel, []); return { run, cancel, }; } export default useThrottleFn;
57677c9964c6ddee9ffcca9b8a100c145796d6b3
TypeScript
shaunbennett/image-generating-nn
/src/nn/Util.ts
3.234375
3
export class Util { public static clamp(arg, min, max){ if(arg < min) return min; if(arg > max) return max; return arg; } public static sigmoid(z){ return 1 / (1 + Math.exp(-z)); } public static sigmoidPrime(z){ return Util.sigmoid(z) * (1 - Util.sigmoid(z)); } public static dot(xs, ys){ if(xs.length != ys.length){ throw new Error("Util.dot: xs and ys not same length."); } var z = 0; for(var i=0; i < xs.length; ++i){ z += xs[i] * ys[i]; } return z; } public static hadamard(xs, ys){ if(xs.length != ys.length) throw new Error("Util.hadamard: xs and ys not same length"); var res = new Float64Array(xs.length); for(var i=0; i < xs.length; ++i){ res[i] = xs[i] * ys[i]; } return res; } public static rand(){ return Math.random() - Math.random(); } public static shuffle(o){ for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } }
dfa57e1b761a58c4736b8a71783d1f071e912d07
TypeScript
tomek401273/webshop
/src/app/model/dto/shipping-address-dto.ts
2.609375
3
export class ShippingAddressDto { private login: string; private country: string; private city: string; private postCode: string; private street: string; private name: string; private surname: string; private supplier: string; private code: string; private search: string; private house: number; private apartment: number; constructor(login: string, country: string, city: string, postCode: string, street: string, name: string, surname: string, supplier: string, code: string, search: string, house: number, apartment: number) { this.login = login; this.country = country; this.city = city; this.postCode = postCode; this.street = street; this.name = name; this.surname = surname; this.supplier = supplier; this.code = code; this.search = search; this.house = house; this.apartment = apartment; } }
be78ea8e5d35b3e7922faa12770431ca4a02ec1c
TypeScript
r2d2m/curves
/src/src/keyframes/HSVColorKeyframe.ts
2.90625
3
import Keyframe from './Keyframe'; import { HSVColor } from '../interfaces/HSVColor'; import NumberKeyframe from './NumberKeyframe'; class HSVColorKeyframe extends Keyframe<HSVColor> { interpolate(keyframe: HSVColorKeyframe, time: number): HSVColor { const floatKeyframes = this.toFloatKeyframe(); const nextFloatKeyframes = keyframe.toFloatKeyframe(); return { h: floatKeyframes[0].interpolate(nextFloatKeyframes[0], time), s: floatKeyframes[1].interpolate(nextFloatKeyframes[1], time), v: floatKeyframes[2].interpolate(nextFloatKeyframes[2], time), }; } toFloatKeyframe(): NumberKeyframe[] { return [ new NumberKeyframe(this.time, this.value.h, this.inEasing, this.outEasing), new NumberKeyframe(this.time, this.value.s, this.inEasing, this.outEasing), new NumberKeyframe(this.time, this.value.v, this.inEasing, this.outEasing), ]; } } export default HSVColorKeyframe;
1bdab0a1600c31f21228bd632ceb74552508877c
TypeScript
swcurran/aries-vcr-issuer-agency
/agency/src/utils/sleep.ts
2.59375
3
import { ServiceAddons } from '@feathersjs/feathers'; import { ServiceEventResult } from '../models/event'; import { WebhookData } from '../models/webhooks'; export function sleep<T>(ms: number): Promise<T> { return new Promise<T>(resolve => setTimeout(resolve, ms)); } export function deferServiceOnce<T>( id: string, service: T & ServiceAddons<T>, options?: { order?: number, cb?: (res: ServiceEventResult) => void, timeout?: number, rejectOnTimeout?: boolean, rejectOnError?: boolean, } ): Promise<ServiceEventResult> { const processCb = (res: ServiceEventResult): void => { if (options?.cb && typeof options?.cb === 'function') { options?.cb(res); } }; let res: ServiceEventResult = { id, success: true, order: options?.order }; return new Promise<ServiceEventResult>((resolve, reject) => { const timeoutId = setTimeout(() => { res.success = false; res.error = `Timeout received for ID: ${id}`; processCb(res); if (options?.rejectOnTimeout) { return reject(res); } return resolve(res); }, options?.timeout); service.once(id, (data: WebhookData) => { clearTimeout(timeoutId); res = { ...res, data }; if (data.error_msg) { res.success = false; res.error = data.error_msg; } processCb(res); if (res.error && options?.rejectOnError) { return reject(res); } return resolve(res); }); }); }
21f266df511c9333e7dfba70097a0a6edc6c6c9c
TypeScript
athielking/AceCalendar
/ClientApp/app/components/calendar/week/week-cell.component.ts
2.53125
3
import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core' import * as dateFns from 'date-fns'; import { DayView } from '../common/models' import * as dateTools from '../../../tools/dateTools'; @Component({ selector: 'ac-week-cell', templateUrl: './week-cell.component.html', styleUrls: ['../common/calendar-card.scss', './week-cell.component.scss'] }) export class WeekCellComponent implements OnInit { @Input() dayView: DayView; @Input() isReadonly: boolean = false; @Output() copyDayRequested: EventEmitter<CopyDayRequest> = new EventEmitter(); @Output() deleteJobsFromDayRequest: EventEmitter<Date> = new EventEmitter(); public otherDays: Date[]; ngOnInit(){ this.otherDays = []; let sunday = dateFns.startOfWeek(this.dayView.calendarDay.date); let saturday = dateFns.endOfWeek(this.dayView.calendarDay.date); for( let i:number=0; dateFns.addDays(sunday, i) <= saturday; i++) { let weekDay = dateFns.addDays(sunday, i); if( dateTools.equal(weekDay, this.dayView.calendarDay.date)) continue; this.otherDays.push(weekDay); } } public copyToDay(date: Date){ this.copyDayRequested.emit({dayFrom: this.dayView.calendarDay.date, dayTo: date}); } public deleteAllJobsFromDay(){ this.deleteJobsFromDayRequest.emit(this.dayView.calendarDay.date); } } export interface CopyDayRequest{ dayFrom: Date; dayTo: Date; }
e59b54d578bae4875d0291bdf5947127a81ecfc6
TypeScript
dexterthemsb/giphy-task-api
/src/middlewares/authentication.ts
2.84375
3
import { Request, Response, NextFunction } from "express"; import * as jwt from "jsonwebtoken"; // token error handler const handleJWTErrors = (err: Error) => { switch (err.name) { case "TokenExpiredError": return "Session expired. Login Again."; case "JsonWebTokenError": return "Invalid Session. Login Again."; case "NotBeforeError": return "Token not active. Login."; default: return "Something went wrong. Login Again."; } }; // validation middleware export const validateJWT = (req: Request, res: Response, next: NextFunction) => { let token = req.headers["authorization"]; if (token) { try { const decodedToken = jwt.verify(token, process.env.JWT_TOKEN_PRIVATE_KEY!); if (decodedToken) { res.locals.decodedToken = decodedToken; next(); } } catch (err) { console.log(err); res.status(401).json({ msg: handleJWTErrors(err) }); } } else res.status(404).json({ msg: "Token not found" }); }; // compare JWT token ID with request ID // call this after validateJWT export const compareTokenID = (req: Request, res: Response, next: NextFunction) => { if (res.locals.decodedToken && res.locals.decodedToken._id === req.params.userID) next(); else res.status(401).json({ msg: "Unauthorised" }); };
591ab97fd49eebc3177656ed10216264dfbc5977
TypeScript
goramaciej/ng-gh
/gh-app/src/app/actions/user-equipment.actions.ts
2.59375
3
import { Action } from '@ngrx/store'; import { EquipmentItemModel } from './../models/equipment-item.model'; export const ADD_ITEM = '[EQUIPMENT] AddItem'; export const REMOVE_ITEM = '[EQUIPMENT] RemoveItem'; export const ADD_ITEM_AND_OPEN = '[EQUIPMENT] AddItemAndOpen'; export class AddItemAction implements Action { readonly type = ADD_ITEM; constructor( public payload: EquipmentItemModel ) { } } export class RemoveItemAction implements Action { readonly type = REMOVE_ITEM; constructor( public payload: number ) { //console.log('Numer do usunięcia: ' + payload); } } export class AddItemAndOpenAction implements Action{ readonly type = ADD_ITEM_AND_OPEN; constructor( public payload: EquipmentItemModel ) { console.log('Numer do usunięcia: ' + payload); } } export type Actions = AddItemAction | RemoveItemAction | AddItemAndOpenAction
a60861949700b9da7c2396f0a6302919c92c308f
TypeScript
davidedc/Algebrite
/tests/rect.ts
2.65625
3
import { run_test } from '../test-harness'; run_test([ // check when not assuming real variables ---------- 'assumeRealVariables = 0', '', 'rect(a)', 'rect(a)', // same as rect(a) + i*rect(b) // where rect(b) is abs(b)*(cos(arg(b)) + i*sin(arg(b))) 'rect(a+i*b)', 'rect(a)-abs(b)*sin(arg(b))+i*abs(b)*cos(arg(b))', 'assumeRealVariables = 1', '', // -------------------------------------------------- 'rect(a)', 'a', 'rect(a+i*b)', 'a+i*b', 'rect(exp(a+i*b))', 'i*exp(a)*sin(b)+exp(a)*cos(b)', 'rect(1+exp(i*pi/3))', '3/2+1/2*i*3^(1/2)', 'z=(a+b*i)/(c+d*i)', '', 'rect(z)-real(z)-i*imag(z)', '0', 'z=quote(z)', '', 'rect((-1)^(2/3))', '-1/2+1/2*i*3^(1/2)', 'rect(exp(-3/4*i*pi))', '-1/2*2^(1/2)-1/2*i*2^(1/2)', 'rect(exp(-1/4*i*pi))', '1/2*2^(1/2)-1/2*i*2^(1/2)', 'rect(exp(-2/4*i*pi))', '-i', 'rect(exp(-3/4*i*pi))', '-1/2*2^(1/2)-1/2*i*2^(1/2)', 'rect(exp(-4/4*i*pi))', '-1', 'rect(((-1)^(1/2)/(3^(1/2)))^(1/2))', 'i*2^(1/2)/(2*3^(1/4))+2^(1/2)/(2*3^(1/4))', 'rect((-1)^(1/6) - (-1)^(5/6))', '3^(1/2)', ]);
c9f90ed60b2cd598c42ff2ade40f11af73dd071e
TypeScript
bviale/Babylon.js
/src/Instrumentation/babylon.sceneInstrumentation.ts
2.71875
3
module BABYLON { /** * This class can be used to get instrumentation data from a Babylon engine */ export class SceneInstrumentation implements IDisposable { private _captureActiveMeshesEvaluationTime = false; private _activeMeshesEvaluationTime = new PerfCounter(); private _captureRenderTargetsRenderTime = false; private _renderTargetsRenderTime = new PerfCounter(); private _captureFrameTime = false; private _frameTime = new PerfCounter(); // Observers private _onBeforeActiveMeshesEvaluationObserver: Nullable<Observer<Scene>> = null; private _onAfterActiveMeshesEvaluationObserver: Nullable<Observer<Scene>> = null; private _onBeforeRenderTargetsRenderObserver: Nullable<Observer<Scene>> = null; private _onAfterRenderTargetsRenderObserver: Nullable<Observer<Scene>> = null; private _onBeforeRenderObserver: Nullable<Observer<Scene>> = null; private _onAfterRenderObserver: Nullable<Observer<Scene>> = null; // Properties /** * Gets the perf counter used for active meshes evaluation time */ public get activeMeshesEvaluationTime(): PerfCounter { return this._activeMeshesEvaluationTime; } /** * Gets the active meshes evaluation time capture status */ public get captureActiveMeshesEvaluationTime(): boolean { return this._captureActiveMeshesEvaluationTime; } /** * Enable or disable the active meshes evaluation time capture */ public set captureActiveMeshesEvaluationTime(value: boolean) { if (value === this._captureActiveMeshesEvaluationTime) { return; } if (value) { this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(()=>{ Tools.StartPerformanceCounter("Active meshes evaluation"); this._activeMeshesEvaluationTime.beginMonitoring(); }); this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(()=>{ Tools.EndPerformanceCounter("Active meshes evaluation"); this._activeMeshesEvaluationTime.endMonitoring(); }); } else { this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver); this._onBeforeActiveMeshesEvaluationObserver = null; this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver); this._onAfterActiveMeshesEvaluationObserver = null; } } /** * Gets the perf counter used for render targets render time */ public get renderTargetsRenderTimeCounter(): PerfCounter { return this._renderTargetsRenderTime; } /** * Gets the render targets render time capture status */ public get captureRenderTargetsRenderTime(): boolean { return this._captureRenderTargetsRenderTime; } /** * Enable or disable the render targets render time capture */ public set captureRenderTargetsRenderTime(value: boolean) { if (value === this._captureRenderTargetsRenderTime) { return; } if (value) { this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(()=>{ Tools.StartPerformanceCounter("Render targets rendering"); this._renderTargetsRenderTime.beginMonitoring(); }); this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(()=>{ Tools.EndPerformanceCounter("Render targets rendering"); this._renderTargetsRenderTime.endMonitoring(false); }); } else { this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver); this._onBeforeRenderTargetsRenderObserver = null; this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver); this._onAfterRenderTargetsRenderObserver = null; } } /** * Gets the perf counter used for frame time capture */ public get frameTimeCounter(): PerfCounter { return this._frameTime; } /** * Gets the frame time capture status */ public get captureFrameTime(): boolean { return this._captureFrameTime; } /** * Enable or disable the frame time capture */ public set captureFrameTime(value: boolean) { this._captureFrameTime = value; } public constructor(public scene: Scene) { this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(() => { if (this._captureActiveMeshesEvaluationTime) { this._activeMeshesEvaluationTime.fetchNewFrame(); } if (this._captureRenderTargetsRenderTime) { this._renderTargetsRenderTime.fetchNewFrame(); } if (this._captureFrameTime) { Tools.StartPerformanceCounter("Scene rendering"); this._frameTime.beginMonitoring(); } }); this._onAfterRenderObserver = scene.onAfterRenderObservable.add(() => { if (this._captureFrameTime) { Tools.EndPerformanceCounter("Scene rendering"); this._frameTime.endMonitoring(); } }); } public dispose() { this.scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); this._onBeforeRenderObserver = null; this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver); this._onAfterRenderObserver = null; this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver); this._onBeforeActiveMeshesEvaluationObserver = null; this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver); this._onAfterActiveMeshesEvaluationObserver = null; this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver); this._onBeforeRenderTargetsRenderObserver = null; this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver); this._onAfterRenderTargetsRenderObserver = null; (<any>this.scene) = null; } } }
c3a952d93d167927ebe9ed2671cf04c242d91c7d
TypeScript
capy-pl/pnlab
/server/models/Promotions.ts
2.921875
3
import mongoose, { Document, Schema } from 'mongoose'; export type PromotionType = 'combination' | 'direct'; export interface PromotionInterface extends Document { name: string; type: PromotionType; groupOne: string[]; groupTwo?: string[]; startTime: Date; endTime: Date; } const PromotionSchema = new Schema<PromotionInterface>({ name: { type: String, required: true, unique: true, }, type: { type: String, required: true, enum: ['combination', 'direct'], }, groupOne: { type: [String], required: true, }, groupTwo: [String], startTime: { type: Date, required: true, }, endTime: { type: Date, required: true, }, }); export default mongoose.model<PromotionInterface>('promotion', PromotionSchema);
93b5188098e5ea86a8e7b016b57e2f8232d03376
TypeScript
JoseMarkos/FCCIntermediateAlgorithms
/SmallestCommonMultiple.ts
3.484375
3
const getSixBasedNumersOne = (n: number): number => 6 * n - 1; const getSixBasedNumersTwo = (n: number): number => 6 * n + 1; const getFirstCollection = (max: number) => { if (max == 2) { return [max]; } if (max == 3 || max == 4) { return [2, 3]; } let collection = [2, 3]; for (let index = 1; collection[collection.length - 1] < max; index++) { let nextPrime = getSixBasedNumersOne(index); if (nextPrime > max) { break; } collection.push(nextPrime); if (collection[collection.length - 1] < max) { nextPrime = getSixBasedNumersTwo(index); if (nextPrime > max) { break; } collection.push(nextPrime); } } return collection; } const getBooleansCollection = (collection: number[]): boolean[] => Array.from(collection, x => true); const getPrimes = (max: number) => { const firstCollection = getFirstCollection(max); const booleanCollection = getBooleansCollection(firstCollection); const getNextFilterCollection = (collection: number[], start: number): void => { const nextPrime = collection[start]; let index = 1; let indexTwo = 1; let item = 6 * index * nextPrime - nextPrime; let itemTwo = 6 * index * nextPrime + nextPrime; while(collection.includes(item)) { booleanCollection[collection.indexOf(item)] = false; index++; item = 6 * index * nextPrime - nextPrime; } while(collection.includes(itemTwo)) { booleanCollection[collection.indexOf(itemTwo)] = false; indexTwo++; itemTwo = 6 * indexTwo * nextPrime + nextPrime; } } firstCollection.forEach(x => { if(booleanCollection[firstCollection.indexOf(x)]) { getNextFilterCollection(firstCollection, firstCollection.indexOf(x)); } }); return firstCollection.filter(x => booleanCollection[firstCollection.indexOf(x)] === true); } const items = function* (initial: number) { let n = initial; while (true) { yield n++; } }; interface NumberArray { [index: string]: number; } const getANumberArray = ():NumberArray => { return { "2": 0, "3": 0, "5": 0, "7": 0, } } const isFactorOfTwo = (n: number): boolean => n % 2 === 0; const isFactorOfThree = (n: number): boolean => n % 3 === 0; const isFactorOfFive = (n: number): boolean => n % 5 === 0; const isOnOfTheExeptions = (n: number): boolean => n === 2 || n === 3 || n === 5 || n === 7; const getFirstFactor = (n: number, collection: number[]):number => { if (isPrime(n, collection)) { return n; } let factor:number = 1; for (let index = 0; index < collection.length; index++) { if (n % collection[index] === 0) { factor = collection[index]; break; } } return factor; } const isPrime = (n: number, collection:number[]): boolean => collection.includes(n); const getFactorsObjet = (n: number, collection: number[]):NumberArray => { const obj: NumberArray = getANumberArray(); if (isPrime(n, collection)) { obj[n] = 1; return obj; } const firstFactor:number = getFirstFactor(n, collection); const divided:number = n / firstFactor; obj[firstFactor]++; if (divided !== 1) { const nextObj = getFactorsObjet(divided, collection); for (const key in nextObj) { if (obj[key] === undefined) { obj[key] = nextObj[key]; continue; } obj[key] += nextObj[key]; } } return obj; }; const getLCMCollection = (arr: NumberArray[]):number[] => { const obj: NumberArray = getANumberArray(); let collection: number[] = []; arr.forEach((x: NumberArray) => { for (const key in x) { if (obj[key] === undefined) { obj[key] = x[key]; break; } const max = Math.max(obj[key], x[key]); obj[key] = max; } }); for (const key in obj) { let current = 1; while(obj[key] >= current) { collection.push(Number(key)); current++ } } return collection; }; function smallestCommons(arr: number[]): number { const max = Math.max(...arr); const min = Math.min(...arr); const genItems = items(min); const primes = getPrimes(max); let current: number = genItems.next().value; let collection: NumberArray[] = []; let factors: number[] = []; while (current <= max) { if (current != 1) { collection.push(getFactorsObjet(current, primes)); } current = genItems.next().value; } factors = getLCMCollection(collection); return factors.reduce((a, c) => a * c); } console.log(smallestCommons([1, 13]));
0074e89d5072d4d36b1682262996923c9e950ea1
TypeScript
owliehq/neatsio
/packages/querier/test/queries.test.ts
2.5625
3
import * as request from 'supertest' import * as qs from 'query-string' import * as fs from 'fs' import * as path from 'path' import app from './mocks/app' import sequelize from './mocks/db' import { Querier } from '../src/querier' import User from './mocks/models/user' // May require additional time for downloading MongoDB binaries jasmine.DEFAULT_TIMEOUT_INTERVAL = 600000 describe('Build some queries object', () => { describe('Params: $select', () => { it('should have $select', () => { const query = Querier.query({ stringify: false }) .select('lastname') .generate() expect(query.$select).toBe('lastname') }) it('should have ability of multiple select', () => { const query = Querier.query({ stringify: false }) .select('lastname') .select('firstname') .generate() expect(query.$select).toBe('lastname firstname') }) it('should have ability to add negative select', () => { const query = Querier.query({ stringify: false }) .select('lastname') .unselect('firstname') .generate() expect(query.$select).toBe('lastname -firstname') }) it('should return negative when select and unselect next same attribute', () => { const query = Querier.query({ stringify: false }) .select('lastname') .unselect('lastname') .generate() expect(query.$select).toBe('-lastname') }) it('should return selected after an unselect', () => { const query = Querier.query({ stringify: false }) .unselect('lastname') .select('lastname') .generate() expect(query.$select).toBe('lastname') }) }) describe('Params: $conditions', () => { it('should have $conditions params with correct values by raw conditions', () => { const query = Querier.query({ stringify: false }) .rawConditions({ lastname: 'DOE' }) .generate() expect(query.$conditions).toMatchObject({ lastname: 'DOE' }) }) it('should have multiple & complex $conditions from raw conditions', () => { const query = Querier.query({ stringify: false }) .rawConditions({ lastname: 'DOE', firstname: { $or: ['John', 'Jane'] } }) .generate() expect(query.$conditions).toMatchObject({ lastname: 'DOE', firstname: { $or: ['John', 'Jane'] } }) }) }) describe('Params: $limit', () => { it('should have $limit param', () => { const query = Querier.query({ stringify: false }) .limit(10) .generate() expect(query.$limit).toBe(10) }) }) describe('Params: $skip', () => { it('should have $skip param', () => { const query = Querier.query({ stringify: false }) .skip(10) .generate() expect(query.$skip).toBe(10) }) }) describe('Params: $skip & limit via page', () => { it('should have $skip & $limit param when page is active', () => { const query = Querier.query({ stringify: false, resultsPerPage: 20 }) .page(2) .generate() expect(query).toMatchObject({ $limit: 20, $skip: 20 }) }) it('should have $skip & $limit param when page is active but without resultPerPage option', () => { const query = Querier.query({ stringify: false }) .page(4) .generate() expect(query).toMatchObject({ $limit: 10, $skip: 30 }) }) }) describe('Params: $sort', () => { it('should have $sort param by sorting desc', () => { const query = Querier.query({ stringify: false }) .sortDesc('lastname') .generate() expect(query.$sort).toBe('-lastname') }) it('should have $sort param by sorting asc', () => { const query = Querier.query({ stringify: false }) .sort('lastname') .generate() expect(query.$sort).toBe('lastname') }) }) describe('Params: $populate', () => { it('should have $populate param', () => { const query = Querier.query({ stringify: false }) .populate('role') .generate() expect(query.$populate).toBe('role') }) it('should have $populate param with multiple call', () => { const query = Querier.query({ stringify: false }) .populate('role') .populate('manager') .generate() expect(query.$populate).toBe('role manager') }) it('should have $populate param with multiple call and subpopulate', () => { const query = Querier.query({ stringify: false }) .populate('role') .populate('manager.team') .generate() expect(query.$populate).toBe('role manager.team') }) }) describe('Mixed params', () => { it('should return complex query', () => { const query = Querier.query({ encode: false, resultsPerPage: 25, stringify: false }) .page(4) .sortDesc('lastname') .rawConditions({ notation: { $and: [{ $lt: 1 }, { $gt: 4 }] } }) .select('lastname') .select('firstname') .generate() expect(query).toMatchObject({ $limit: 25, $skip: 75, $sort: '-lastname', $conditions: { notation: { $and: [{ $lt: 1 }, { $gt: 4 }] } }, $select: 'lastname firstname' }) }) }) }) describe('Build some query strings', () => { it('should be string result', () => { const query = Querier.query({ baseUrl: '/users', encode: false }) .select('lastname') .generate() expect(query).toBe('/users?$select=lastname') }) /*it('should return complex query', () => { const query = Querier.query({ resultsPerPage: 25 }) .page(4) .sortDesc('lastname') .rawConditions({ notation: { $and: [{ $lt: 1 }, { $gt: 4 }] } }) .select('lastname') .select('firstname') .generate() expect(query).toMatchObject({ $limit: 25, $skip: 75, $sort: '-lastname', $conditions: { notation: { $and: [{ $lt: 1 }, { $gt: 4 }] } }, $select: 'lastname firstname' }) })*/ }) /** * */ /*describe('Play with users', () => { beforeAll(async done => { await sequelize.authenticate() await sequelize.sync({ force: true }) done() }) afterAll(async done => { await sequelize.close() try { fs.unlinkSync(path.join(__dirname, '../mocks', 'database.sqlite')) } catch (err) { console.error(err) } done() }) describe('GET: Users', () => { beforeAll(async () => { await sequelize.sync({ force: true }) await User.create({ firstname: 'John', lastname: 'DOE', email: 'john.doe@acme.com', active: true }) await User.create({ firstname: 'Alan', lastname: 'SMITH', email: 'alan.smith@acme.com', active: true }) await User.create({ firstname: 'Enora', lastname: 'PLIRA', email: 'enora.plira@acme.com', active: false }) }) afterAll(async () => { await User.destroy({ where: {}, truncate: true, restartIdentity: true }) }) it('should') }) })*/
0be0eff696dd799ad6bef2250b25838b7cec8120
TypeScript
jsaribeirolopes/gojs-angular
/projects/gojs-angular/src/lib/diagram.component.ts
2.609375
3
import { Component, ElementRef, EventEmitter, Input, NgZone, Output, ViewChild } from '@angular/core'; import * as go from 'gojs'; import { NgDiagramHelper } from './ng-diagram-helper'; @Component({ selector: 'gojs-diagram', template: '<div #ngDiagram [className]=divClassName></div>' }) export class DiagramComponent { /** * Diagram initialization function. Returns a go.Diagram. * Do not initialize model data in this function. */ @Input() public initDiagram: () => go.Diagram; /** Node data for diagram */ @Input() public nodeDataArray: Array<go.ObjectData>; /** Link data for diagram. Optional. */ @Input() public linkDataArray: Array<go.ObjectData> = null; /** Model data for diagram. Optional. */ @Input() public modelData: go.ObjectData = null; /** Diagram div class name. Use this name to style your diagram in CSS. */ @Input() public divClassName: string; /** Model changed listener function for diagram */ public modelChangedListener: ((e: go.ChangedEvent) => void) | null = null; /** Whether or not to skip merging app data with GoJS model data (set to true if update is coming from GoJS, false if coming from app-level, usually) */ @Input() public skipsDiagramUpdate: boolean = false; /** Event emitter -- fires when diagram model changes. Capture this emitted event in parent component */ @Output() public modelChange: EventEmitter<go.IncrementalData> = new EventEmitter<go.IncrementalData>(); /** The DIV element holding the Diagram */ @ViewChild('ngDiagram', { static: true }) public diagramDiv: ElementRef; /** The Diagram itself */ public diagram: go.Diagram = null; constructor(public zone: NgZone) { } /** * Initializes diagram / model after view init */ public ngAfterViewInit() { if (!this.diagramDiv) { throw new Error("diagramDiv is not defined"); } this.diagram = this.initDiagram(); if (!(this.diagram instanceof go.Diagram)) { throw new Error("initDiagram function did not return a go.Diagram"); } // reduces change detection on mouse moves, boosting performance NgDiagramHelper.makeMouseMoveRunOutsideAngularZone(this.diagram, this.zone); // assign the Diagram's div, which (among many other things) will attach a bunch of listeners to the canvas, // using the overridden addEventListener function defined in makeMouseMoveRunOutsideAngularZone const divRef = this.diagramDiv.nativeElement; if (divRef === null) return; this.diagram.div = divRef; // initialize the diagram model with the provided node / link / model data NgDiagramHelper.initializeModel(this.diagram, this.nodeDataArray, this.linkDataArray, this.modelData); // initializer model listener NgDiagramHelper.initializeModelChangedListener(this); } // end ngAfterViewInit /** * If a change has occured on an @Input property, merge the app-level changes with GoJS */ public ngOnChanges() { if (!this.diagram || !this.diagram.model || this.skipsDiagramUpdate) return; NgDiagramHelper.mergeAppDataWithModel(this); } // end ngOnChanges public ngOnDestroy() { this.diagram.div = null; // removes event listeners } }
7652b961cbbc670d9d9a0c22fccb3223b5d3c77f
TypeScript
Pet-projects/d3_sleep_chart
/src/report/data/transform.ts
2.984375
3
import * as d3 from "d3"; import DataIntervalTree from 'node-interval-tree' import {Activity, ActivityTree, ActivityType, DayDataRow, DaysDataArray} from "../domain"; import {dateTimeToEpoch} from "../utils/time"; const ONE_SECOND = 1000; const ONE_MINUTE = 60 * ONE_SECOND; const ONE_HOUR = 60 * ONE_MINUTE; const ONE_DAY = 24 * ONE_HOUR; export function toDaysArray(rawData: d3.DSVParsedArray<any>): DaysDataArray { let daysDataMap = new Map<string, DayDataRow>(); // Identify all the days in the data-set for (let rawDataRow of rawData) { if ("Date" in rawDataRow && rawDataRow["Date"] != "" && "TimeStart" in rawDataRow && rawDataRow["TimeStart"] != "" && "TimeEnd" in rawDataRow && rawDataRow["TimeEnd"] != "") { let dayLabel = rawDataRow["Date"]; let dayStartEpoch = dateTimeToEpoch(dayLabel, "00:00"); let dayEndEpoch = dayStartEpoch + ONE_DAY; daysDataMap.set(dayLabel, new DayDataRow(dayLabel, dayStartEpoch, dayEndEpoch)) } } // Extract the unique values for days sorted in descending order return Array.from(daysDataMap, tuple => tuple[1]) .sort((a, b) => b.dayStartEpoch - a.dayStartEpoch); } /** * Converts a CSV of type: * Date,Day,ActivityId,ActivityName,TimeStart,TimeEnd * 6-Aug-2018,Mon,0,SLEEP,00:00,05:40 * 6-Aug-2018,Mon,1,FEED,05:40,06:00 * 6-Aug-2018,Mon,0,SLEEP,06:00,06:00 * */ export function toActivityTree(rawData: d3.DSVParsedArray<any>): ActivityTree { let activityTree = new DataIntervalTree<Activity>(); for (let rawDataRow of rawData) { let currentDate:string = rawDataRow["Date"]; let activityType:ActivityType = +rawDataRow["ActivityId"]; let timeStart:number = dateTimeToEpoch(currentDate, rawDataRow["TimeStart"]); let timeEnd:number = dateTimeToEpoch(currentDate, rawDataRow["TimeEnd"]); if (timeEnd < timeStart) { // Assume the time end refers to the next day and we adjust accordingly timeEnd += ONE_DAY; } activityTree.insert(timeStart, timeEnd, new Activity(timeStart, timeEnd, activityType)); } return activityTree; }
78fcb87d38dcad5fad0140e095cf1a86801329ec
TypeScript
wadewadewadewadewadewade/ineffectua-firebase-functions
/functions/src/Users.ts
2.78125
3
import * as admin from 'firebase-admin'; import { firebaseUserDocumentToUser, User, UserUser, UserTag } from "./Types"; export const getUserById = ( userId: string ): Promise<User> => { const db = admin.firestore(); return new Promise<User>((resolve, reject) => { db.collection('users') .doc(userId) .get() .then( ( value: FirebaseFirestore.DocumentSnapshot< FirebaseFirestore.DocumentData > ) => { const userData = value.data(); if (userData === undefined) { reject('No user information was returned'); } else { const user: User = firebaseUserDocumentToUser(userId, userData); resolve(user); } } ) .catch(reject); }); }; export const addUser = ( user: UserUser, userId: string ): Promise<User> => { const db = admin.firestore(); return new Promise<User>((resolve, reject) => { getUserById(userId) .then(u => { // it's an update const { uid, ...newUser} = user; db.collection('users') .doc(userId) .set(newUser, {merge: true}) .then(() => getUserById(userId).then(resolve).catch(reject)) .catch(reject); }) .catch(() => { // it's an addition db.collection('users') .add(user) .then((value: FirebaseFirestore.DocumentReference<FirebaseFirestore.DocumentData>) => { const uid = value.id; getUserById(uid).then(resolve).catch(reject) }) .catch(reject); }); }); }; const convertDocumentDataToUserTag = ( data: FirebaseFirestore.DocumentData ): UserTag => { const doc = data.data(); return { key: data.id, tagId: doc.tagId }; }; export const getTagsForUser = ( userId: string ) => { const db = admin.firestore(); return new Promise<Array<UserTag>>((resolve, reject) => { if (!userId) { resolve(new Array<UserTag>()); } else { db.collection('users') .doc(userId) .collection('tags') .get() .then((querySnapshot: FirebaseFirestore.QuerySnapshot) => { const userTags = querySnapshot.docs.map((tagIdDoc) => convertDocumentDataToUserTag(tagIdDoc) ); resolve(userTags); }) .catch(reject); } }); }; export const addUserTag = ( user: admin.auth.DecodedIdToken, tag: UserTag ) => { const db = admin.firestore(); return new Promise<UserTag>((resolve, reject) => { if (user) { if (tag.key !== '' && typeof tag.key !== 'undefined') { // its an update /*const { key, searchableIndex, ...data } = tag tag.searchableIndex = createIndex(tag.name)*/ const {key, ...data} = tag; db.collection('users') .doc(user.uid) .collection('tags') .doc(key) .update(data) .then(() => resolve(tag)) .catch(reject); } else { // it's a new record const {key, ...rest} = tag; const newTag = {...rest}; db.collection('users') .doc(user.uid) .collection('tags') .add(newTag) .then( ( value: FirebaseFirestore.DocumentReference< FirebaseFirestore.DocumentData > ) => { const data = {...newTag, key: value.id}; resolve(data as UserTag); } ) .catch(reject); } } }); }; export const deleteUserTag = async ( userId: string, tag: UserTag ) => { const db = admin.firestore(); return new Promise<UserTag>(async (resolve, reject) => { try { if (tag.key !== '' && typeof tag.key !== 'undefined') { db.collection('users') .doc(userId) .collection('tags') .doc(tag.key) .delete() .then(() => resolve(tag)) .catch(reject); } else { reject('Tag ID missing'); } } catch (err) { reject(err); } }); };
71e1ecebb0617536df6aece81b2acd31a8d45f03
TypeScript
AgentGhost/ShareMe
/src/app/contents/SuG.ts
2.640625
3
import { Song } from "./Contents" // SuG (s/S) export const SuG: Song[] = [ { number: 1, name: "Ach bleib mit deiner Gnade" }, { number: 2, name: "All ihr Geschöpfe unsres Herrn" }, { number: 2, name: "Kommt, preist Ihn! Halleluja!" }, { number: 3, name: "Alle Ehre sei meinem Retter" }, { number: 4, name: "Allein Deine Gnade genügt" }, { number: 5, name: "Alles ist bezahlt (Jesus starb für mich)" }, { number: 6, name: "Alles vergeben" }, { number: 7, name: "Alles will ich Jesus weihen" }, { number: 8, name: "Anker in der Zeit" }, { number: 9, name: "Befiehl du deine Wege" }, { number: 10, name: "Bei Dir, Jesus, will ich bleiben" }, { number: 11, name: "Bleibend ist Deine Treu" }, { number: 12, name: "Christus hält mich fest" }, { number: 12, name: "Wenn mein Glaube schwinden will" }, { number: 13, name: "Christus ist auferstanden" }, { number: 13, name: "Seht, welch ein Morgen" }, { number: 14, name: "Christus ist mein Herr" }, { number: 15, name: "Christus sehn" }, { number: 15, name: "Lass uns sehn" }, { number: 16, name: "Danke, Jesus" }, { number: 17, name: "Das alt rauhe Kreuz" }, { number: 17, name: "Dort auf Golgatha stand" }, { number: 18, name: "Dein Reich komme, Herr" }, { number: 19, name: "Deine Gnade hat mich erwählt" }, { number: 20, name: "Der Herr ist mein Hirte" }, { number: 21, name: "Die Herrlichkeit des Herrn" }, { number: 22, name: "Die Herrlichkeit von Golgatha" }, { number: 23, name: "Dir, Dir, o Höchster, will ich singen" }, { number: 24, name: "Dir gebührt die Ehre" }, { number: 25, name: "Dir gehört mein Lob" }, { number: 26, name: "Du bist erhoben" }, { number: 27, name: "Du bist mein Zufluchtsort im Sturm" }, { number: 28, name: "Du großer Gott" }, { number: 29, name: "Du hast Erbarmen" }, { number: 29, name: "Wer ist ein Gott wie Du" }, { number: 30, name: "Du meine Seele, singe" }, { number: 31, name: "Durch Dein Wort" }, { number: 32, name: "Ehre sei Gott für immer" }, { number: 33, name: "Ein feste Burg" }, { number: 34, name: "Ein für alle Mal" }, { number: 35, name: "Ein Gott, der redet" }, { number: 36, name: "Er ist der Erlöser" }, { number: 37, name: "Er lebt für immer, Amen" }, { number: 37, name: "Komm und sing mit mir das Lied von der Befreiung" }, { number: 38, name: "Erzählt von der Größe Gottes 8 Es gibt bedingungslose Liebe" }, { number: 39, name: "Es ist Jesus" }, { number: 39, name: "Welch ein Schatz" }, { number: 40, name: "Fels des Heils" }, { number: 41, name: "Für mich gingst Du nach Golgatha" }, { number: 41, name: "Herr, deine Liebe ist so groß" }, { number: 42, name: "Glaube an Jesus" }, { number: 43, name: "Gott handelt" }, { number: 43, name: "Mein Gott, ich trau auf Dich" }, { number: 44, name: "Gott ist gegenwärtig" }, { number: 45, name: "Gott von Ewigkeit" }, { number: 45, name: "Du bist der wahre Hirte" }, { number: 46, name: "Wie wunderbar ist Gottes große Liebe" }, { number: 46, name: "Gottes große Liebe" }, { number: 47, name: "Groß ist das Geheimnis" }, { number: 48, name: "Größer als ich es verstehe" }, { number: 49, name: "Großer Gott, wir loben Dich" }, { number: 50, name: "Heilger Gott (The Gospel Song)" }, { number: 50, name: "The Gospel Song (Heilger Gott)" }, { number: 51, name: "Heilig, heilig, heilig (Herr, mein Gott und König)" }, { number: 52, name: "Heilige mein Herz (Lehre mich, Herr)" }, { number: 52, name: "Lehre mich, Herr" }, { number: 53, name: "Herbei, o ihr Gläubigen" }, { number: 54, name: "Herr, Dein Wille soll geschehn" }, { number: 54, name: "Soll ich Segen von Dir, Herr, nehmen" }, { number: 55, name: "Herr, weil mich festhält Deine starke Hand" }, { number: 56, name: "Herrlicher Gott" }, { number: 57, name: "Herz und Herz vereint zusammen" }, { number: 58, name: "Ich bete an die Macht der Liebe" }, { number: 59, name: "Ich bin durch die Welt gegangen" }, { number: 60, name: "Ich bin entschieden zu folgen Jesus" }, { number: 61, name: "Ich blicke voll Beugung und Staunen" }, { number: 62, name: "Ich habe nun den Grund gefunden" }, { number: 63, name: "Ich seh das Kreuz" }, { number: 64, name: "Ich steh an Deiner Krippe hier" }, { number: 65, name: "Ich will Dich anbeten" }, { number: 65, name: "Licht dieser Welt" }, { number: 66, name: "Im Glauben leben" }, { number: 66, name: "Durch Glauben können wir verstehn" }, { number: 67, name: "In Christus" }, { number: 68, name: "In dem Kreuz liegt die Kraft" }, { number: 69, name: "In Ewigkeit beim Vater" }, { number: 68, name: "Welch ein dunkler Tag" }, { number: 69, name: "Christus, Du bist der Herr" }, { number: 70, name: "In mir lebt Hoffnung" }, { number: 71, name: "Ist Gott für mich, so trete" }, { number: 72, name: "Jauchzet, ihr Himmel, frohlocket, ihr Engel" }, { number: 73, name: "Jesus, höchster Name" }, { number: 74, name: "Er ist der Friedefürst" }, { number: 75, name: "Jesus ist kommen" }, { number: 76, name: "Jesus, Mitte meines Lebens" }, { number: 77, name: "Jesus, zieh zum Kreuze mich" }, { number: 78, name: "Kann es denn sein" }, { number: 79, name: "In keinem Namen sonst" }, { number: 79, name: "Kein Name sonst" }, { number: 80, name: "Komm, Du Quelle " }, { number: 81, name: "Kommt, preist und lobet unsern Gott" }, { number: 82, name: "König Jesus (Jesus, Weg der Wahrheit)" }, { number: 82, name: "Jesus, Weg der Wahrheit" }, { number: 83, name: "Krönt Ihn, krönt unsern Herrn" }, { number: 84, name: "Lobe den Herren, den mächtigen König" }, { number: 85, name: "Wer diesem Felsen fest vertraut" }, { number: 85, name: "Mein Glaube fest sich bauen kann" }, { number: 86, name: "Mein Jesus, ich lieb Dich" }, { number: 87, name: "Mein Mund besinge tausendfach" }, { number: 88, name: "Mir ist Erbarmung widerfahren" }, { number: 89, name: "Näher, mein Gott, zu Dir" }, { number: 90, name: "Nicht uns" }, { number: 91, name: "Nun danket alle Gott" }, { number: 92, name: "Nun gehören unsre Herzen" }, { number: 93, name: "Nur das Blut des Lammes Jesu" }, { number: 94, name: "O die tiefe Liebe Jesu" }, { number: 95, name: "O du fröhliche" }, { number: 96, name: "O Gnade Gottes" }, { number: 97, name: "O Gott, Dir sei Ehre" }, { number: 98, name: "O Haupt voll Blut und Wunden" }, { number: 99, name: "Mein Herr und Gott" }, { number: 99, name: "Schau auf den Herrn" }, { number: 100, name: "Jesus, komm, schein in unsre Nacht" }, { number: 100, name: "Schein in unsre Nacht" }, { number: 101, name: "Seht unsern Gott" }, { number: 102, name: "Sei gnädig, o Herr" }, { number: 103, name: "Seligstes Wissen" }, { number: 104, name: "Sieh, das Lamm Gottes" }, { number: 105, name: "Siehst du das Lamm" }, { number: 106, name: "So groß ist der Herr" }, { number: 106, name: "Ein König voller Pracht" }, { number: 107, name: "So nimm denn meine Hände" }, { number: 108, name: "Soli Deo Gloria" }, { number: 108, name: "Allein zu Deiner Ehre" }, { number: 109, name: "Sonne der Gerechtigkeit" }, { number: 110, name: "Sprich, o Herr" }, { number: 111, name: "Stern, auf den ich schaue" }, { number: 112, name: "Vater, komm und lehre Du uns" }, { number: 113, name: "Vereint" }, { number: 113, name: "Wir sind vereint" }, { number: 114, name: "Von guten Mächten treu und still umgeben" }, { number: 115, name: "Vor Gottes Thron" }, { number: 115, name: "Im Himmel dort vor Gottes Thron" }, { number: 116, name: "Vor Grundlegung der Welt" }, { number: 117, name: "Was Gott tut, das ist wohlgetan" }, { number: 118, name: "Weiß ich den Weg auch nicht" }, { number: 119, name: "Welch ein Freund ist unser Jesus" }, { number: 120, name: "Welch ein Tag" }, { number: 120, name: "Der größte Tag für alle Zeit" }, { number: 121, name: "Wenn Friede mit Gott" }, { number: 121, name: "Mir ist wohl in dem Herrn" }, { number: 122, name: "Wenn ich, o Schöpfer" }, { number: 123, name: "Wenn nach der Erde Leid, Arbeit und Pein" }, { number: 124, name: "Wie groß bist Du" }, { number: 125, name: "Wie tief muss Gottes Liebe sein" }, { number: 126, name: "Wir sehnen uns nach Dir" }, { number: 126, name: "Jesus, Sohn des Höchsten" }, { number: 127, name: "Gemeinsam kommen wir zu Dir" }, { number: 127, name: "Wir sind Gottes Kinder" }, { number: 128, name: "Wo ich auch stehe" }, { number: 129, name: "Woher wissen wir" }, { number: 130, name: "Herr, wohin sonst" }, { number: 130, name: "Wohin sonst" }, { number: 131, name: "Wunderbar großer Erlöser" }, { number: 132, name: "Wunderbarer Hirt" }, { number: 132, name: "Du bist ein wunderbarer Hirt" }, { number: 133, name: "Wunderbarer König" }, { number: 134, name: "Würdig das Lamm, das geopfert ist" }, { number: 135, name: "Würdig ist das Lamm" }, { number: 135, name: "Danke für das Kreuz" }, { number: 136, name: "Komm und lobe den Herrn" }, { number: 136, name: "Zehntausend Gründe" }, ]
4d07db081c9524093c37c599127e073653af8bcd
TypeScript
fwcd/logcore
/src/logger/Logger.ts
3.34375
3
import { LoggerConfiguration } from "./LoggerConfiguration"; /** * A logging interface that consumes * parameterized messages of arbitrary * log levels. * * The most common log levels have convenience * methods that should be delegated to 'log'. */ export interface Logger { readonly config: LoggerConfiguration; /** * Logs a message at the desired level, automatically * substituting parameters in the message by the * arguments passed as rest parameters. * * Currently two placeholders are supported: * * * `{}` indicates that the object should be converted * to a normal string representation * * * `{?:}` indicates that a JSON representation of * the output should be used * * @param level The logging level (highest: never, lowest: always) * @param msg The parameterized message to log * @param args The arguments which are inserted into the parameters */ log(level: number, msg: string, ...args: any[]): Promise<void>; /** * Logs a message at the `Error` level. For more * detailed documentation regarding the format * of these messages see the `log` method. */ error(msg: string, ...args: any[]): Promise<void>; /** * Logs a message at the `Warn` level. For more * detailed documentation regarding the format * of these messages see the `log` method. */ warn(msg: string, ...args: any[]): Promise<void>; /** * Logs a message at the `Info` level. For more * detailed documentation regarding the format * of these messages see the `log` method. */ info(msg: string, ...args: any[]): Promise<void>; /** * Logs a message at the `Debug` level. For more * detailed documentation regarding the format * of these messages see the `log` method. */ debug(msg: string, ...args: any[]): Promise<void>; /** * Logs a message at the `Trace` level. For more * detailed documentation regarding the format * of these messages see the `log` method. */ trace(msg: string, ...args: any[]): Promise<void>; /** * Logs a message at the `DeepTrace` level. For more * detailed documentation regarding the format * of these messages see the `log` method. */ deepTrace(msg: string, ...args: any[]): Promise<void>; }
3ba18e16639e607faeff5a3cc87112caa38dc241
TypeScript
jdists/handlebars
/lib/index.ts
3.0625
3
import * as handlebars from 'handlebars' import * as jdistsUtil from 'jdists-util' interface IHandlebarsAttrs extends jdistsUtil.IAttrs { /** * 数据来源 */ data?: string /** * 扩展函数 */ extend?: string } /** * handlebars 模板渲染 * * @param content 文本内容 * @param attrs 属性 * @param attrs.data 数据项,支持 JSON 和 YAML * @param attrs.extend 扩展函数 * @param scope 作用域 * @param scope.execImport 导入数据 * @return 返回渲染后的结果 * @example processor():base ```js let attrs = { data: '#name' } let scope = { execImport: function (importion) { return { name: 'tom', age: 13 } }, } console.log(processor('<b>{{name}} - {{age}}</b>', attrs, scope)) // > <b>tom - 13</b> ``` * @example processor():data is undefined & extend ```js let attrs = { extend: ` require('handlebars-helpers')({ handlebars: handlebars }) ` } let scope = { execImport: function (importion) { return importion }, } console.log(processor('{{ordinalize 1}}', attrs, scope)) // > 1st ``` * @example processor():content is null ```js console.log(processor(null)) // > null ``` */ export = (function (content: string, attrs: IHandlebarsAttrs, scope: jdistsUtil.IScope): string { if (!content) { return content } let render = handlebars.compile(content) let data = null if (attrs.data) { data = scope.execImport(attrs.data, true) } let extend = null if (attrs.extend) { extend = jdistsUtil.buildFunction(String(scope.execImport(attrs.extend)), 'handlebars') extend(handlebars) } return render(data) }) as jdistsUtil.IProcessor
99e4f3066a97e4ec6da03907fd9ec5b22f7550c5
TypeScript
davejlin/coursera
/NandToTetris/projects/08/VMTranslator/src/Processor.ts
2.96875
3
import { Coder } from "./Coder"; import { Parser } from "./Parser"; import { commentSymbol, CommandType, spaceSymbol } from "./Constants"; import os = require("os"); export class Processor { private currentFunctionName = ""; constructor( private parser: Parser, private coder: Coder ) {} public init(): string { this.coder.init(); this.currentFunctionName = ""; return this.coder.writeBootstrap(); } public process(line: string, filename: string): string { let processedLine = ""; const cleanLine = this.parser.clean(line); if (cleanLine) { processedLine += `${commentSymbol} ${cleanLine}${os.EOL}`; const { commandType, command, arg1, arg2 } = this.parser.parse(line); switch(commandType) { case CommandType.arithmetic: processedLine += this.coder.writeArithmetic(command, filename); break; case CommandType.pop: case CommandType.push: processedLine += this.coder.writePushPop(command, arg1, arg2, filename); break; case CommandType.label: processedLine += this.coder.writeLabel(arg1, this.currentFunctionName); break; case CommandType.goto: processedLine += this.coder.writeGoto(arg1, this.currentFunctionName); break; case CommandType.ifgoto: processedLine += this.coder.writeIfGoto(arg1, this.currentFunctionName); break; case CommandType.function: this.currentFunctionName = arg1; processedLine += this.coder.writeFunction(this.currentFunctionName, arg2); break; case CommandType.call: processedLine += this.coder.writeCall(arg1, arg2, filename); break; case CommandType.return: processedLine += this.coder.writeReturn(); break; } } return processedLine; } }
cebf9c153ed578ba5d96f2e0d063c62d617ca2d6
TypeScript
svarelave/dirmod-test-react
/src/utils/handlerError.ts
2.6875
3
import { showError } from "./general"; import i18n from "./i18n"; export const INTERNAL_SERVER_ERROR = 500; export const NOT_FOUND_ERROR = 404; export const UNAUTHORIZED = 401; export const UNPROCESSABLE_ENTITY = 422; export const FORBIDDEN = 403; export const handlerError = (error: any) => { const { message, response } = error; console.log(message, response, error, "ERROR"); switch (response?.status) { case NOT_FOUND_ERROR: showError(i18n.t("errors.not_found")); return; case INTERNAL_SERVER_ERROR: showError(i18n.t("errors.internal_server")); return; case UNAUTHORIZED: showError(i18n.t("errors.unathorized")); return; case UNPROCESSABLE_ENTITY: showError(response.data[0]); return; case FORBIDDEN: showError(i18n.t("errors.forbidden")); return; } if (isNetworkError(message)) { showError(i18n.t("errors.network")); return; } }; const isNetworkError = (message: string): boolean => message.indexOf("Network Error") > -1;
7178c74e269989b56ce169906f75268eb816c1e2
TypeScript
Oxicode/marble
/packages/core/src/effects/effects.helpers.spec.ts
2.65625
3
import { mapTo } from 'rxjs/operators'; import { isEffect, isGroup } from './effects.helpers'; import { Effect, GroupedEffects } from './effects.interface'; describe('Effects helpers', () => { it('#isGroup checks if parameters is GroupedEffects type', () => { expect(isGroup({ path: '/test', effects: [] })).toBe(true); expect(isGroup({ path: '/test', effects: {} } as GroupedEffects)).toBe(false); expect(isGroup({ path: '/test', effects: {} } as GroupedEffects)).toBe(false); expect(isGroup({ effects: [] } as any as GroupedEffects)).toBe(false); }); it('#isEffect checks if parameters is GroupedEffects type', () => { const effect$: Effect = request$ => request$.pipe(mapTo({})); const groupedEffects = { path: '/test', effects: [effect$] }; expect(isEffect(effect$)).toBe(true); expect(isEffect(groupedEffects)).toBe(false); }); });
06583f5a61710923df91da8066d3adc1c1d60ddc
TypeScript
kenchoong/expo-react-bunny
/src/stores/sys/reducer.ts
2.703125
3
import {SysActions} from "./actions"; import {Sys} from "../../types/models"; import {ESys} from "../../types/constants"; export const initialState: Sys = { error: "", warn: "", }; export function sysStateReducer(state: Sys = initialState, {type, payload}: SysActions): Sys { switch (type) { case ESys.ERROR: { return { ...state, ...payload, }; } case ESys.WARN: { return { ...state, ...payload, }; } default: return state; } }