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
ec199119c7d14ea54908e9c28986c0d73891f9f7
TypeScript
Simeon1/noteAPI
/src/server.ts
2.578125
3
import express, {Request, Response} from 'express'; import { NoteController } from './controller/note.controller'; import { createConnection } from "typeorm"; class Server { private noteController: NoteController; private app: express.Application; constructor(){ this.app = express(); this.configuration(); this.noteController = new NoteController(); this.routes(); } public configuration(){ this.app.set('port', process.env.PORT || 3001); } public async routes(){ await createConnection({ type: "postgres", host: "localhost", port: 5434, username: "note", password: "note", database: "note", entities: ["build/database/entities/**/*.js"], synchronize: true, name: "note" }); this.noteController = new NoteController(); this.app.get( "/", (req: Request, res: Response ) => { res.send("Hello world!" ); }) this.app.use(`/api/notes/`, this.noteController.router); } public start(){ this.app.listen(this.app.get(`port`), () => { console.log(`server is listening ${this.app.get('port')} port.`) }); } } const server = new Server(); server.start();
57cb84497862b899efaed1264390492ba1a754cd
TypeScript
DOSYCORPS/big-associative
/src/test/internal/Writable.ts
2.71875
3
export type Writable<T> = { -readonly [P in keyof T]: T[P]; } export function Writable<T>(elem: T): Writable<T> { return elem as Writable<T>; }
afeaf764be652fe4125b12bf17f060bfc17f4b98
TypeScript
daveg7lee/instaclone-backend
/src/user/createAccount/createAccount.resolvers.ts
2.515625
3
import bcrypt from 'bcrypt'; import client from '../../client'; import { Resolvers } from '../../types'; import { checkEmail, checkUsername } from '../user.utils'; const resolvers: Resolvers = { Mutation: { createAccount: async ( _, { firstName, lastName, username, email, password } ) => { try { // Check Username or Email is already taken const existingUsername = username && (await checkUsername(username)); const existingEmail = email && (await checkEmail(email)); if (existingEmail || existingUsername) { throw new Error( existingEmail && existingUsername ? 'Username and Email is already taken' : existingUsername ? 'Username is already taken' : 'Email is already taken' ); } // hashing password for security const hashedPassword = await bcrypt.hash(password, 10); // create User await client.user.create({ data: { firstName, lastName, username, email, password: hashedPassword, }, }); // return User with ok return { success: true, }; } catch (e) { return { success: false, error: e.message, }; } }, }, }; export default resolvers;
36be753f70070d1525e45ffd720c7eaa8f75f14e
TypeScript
ScottMGerstl/express-api-seed
/src/framework/logging/logging.service.ts
2.765625
3
import * as moment from 'moment'; import { Container } from 'typedi'; import { ConfigService } from '../config/config.service'; import { IErrorTrackingConfig } from '../config/config.interface'; export class LoggingService { public static log(error: Error): void { let timestamp: moment.Moment = moment(); // Make logging non-bloacking setTimeout(() => { LoggingService.executeLogging(error, timestamp); }); } private static executeLogging(error: any, timestamp: moment.Moment): void { let errorTrackingConfig: IErrorTrackingConfig = Container.get(ConfigService).errorTrackingConfigs; LoggingService.makeErrorSerializable(); let readableTimestamp: string = timestamp.toISOString(); console.error(`${readableTimestamp}: ${JSON.stringify(error)}`); } /** * Adds property to Error that lets JSON.stringify() serialize {Error}. Will only run if not yet run. * Solution from http://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify#answer-18391400 * * @private * @static */ private static makeErrorSerializable() { if (!('toJSON' in Error.prototype)) { Object.defineProperty(Error.prototype, 'toJSON', { value: function () { let alt = {}; Object.getOwnPropertyNames(this).forEach(function (key) { alt[key] = this[key]; }, this); return alt; }, configurable: true, writable: true }); } } }
226f84751126e0fc15ca63f2cd216cfa31d96dc2
TypeScript
miguelyoobic95/ngIfModalBug
/design-system/stencil/src/components/form/form-color-picker/form-color-picker.spec.ts
2.515625
3
import { TestWindow } from '@stencil/core/testing'; import { YooFormColorPickerComponent, DEFAULT_COLOR } from './form-color-picker'; describe('YooFormColorPickerComponent', () => { it('should build', () => { expect(new YooFormColorPickerComponent()).toBeTruthy(); }); describe('Rendering', () => { it ('Should render with no prop', async () => { let window = new TestWindow(); let element = await window.load({ components: [YooFormColorPickerComponent], html: '<yoo-form-color-picker></yoo-form-color-picker>' }); expect(element).toMatchSnapshot(); }); it ('Should render with a color as prop', async () => { let window = new TestWindow(); let element = await window.load({ components: [YooFormColorPickerComponent], html: '<yoo-form-color-picker color="#fa2367"></yoo-form-color-picker>' }); expect(element).toMatchSnapshot(); }); it ('Should render without label', async () => { let window = new TestWindow(); let element = await window.load({ components: [YooFormColorPickerComponent], html: '<yoo-form-color-picker hide-label="true"></yoo-form-color-picker>' }); expect(element).toMatchSnapshot(); }); }); describe('Prop rendering', () => { it ('Should re-render when color prop is updated', async () => { let window = new TestWindow(); let element = await window.load({ components: [YooFormColorPickerComponent], html: '<yoo-form-color-picker color="#fa2367"></yoo-form-color-picker>' }); expect(element.color).toEqual('#fa2367'); element.color = '#aa34aa'; await window.flush(); expect(element.color).toEqual('#aa34aa'); expect(element).toMatchSnapshot(); }); it ('Should re-render when hide-label prop is updated', async () => { let window = new TestWindow(); let element = await window.load({ components: [YooFormColorPickerComponent], html: '<yoo-form-color-picker></yoo-form-color-picker>' }); expect(element.hideLabel).toEqual(false); element.hideLabel = true; await window.flush(); expect(element.hideLabel).toEqual(true); expect(element).toMatchSnapshot(); }); }); describe('Prop Validation', () => { it('Should use default color if the color is not a valid color', async () => { let element = new YooFormColorPickerComponent(); element.colorValidation('someColor'); expect(element.currentColor).toEqual(DEFAULT_COLOR); element.colorValidation('wrongColor'); expect(element.currentColor).toEqual(DEFAULT_COLOR); }); it('Should change color if input is a valid color', async () => { let element = new YooFormColorPickerComponent(); element.colorValidation('#aacc23'); expect(element.currentColor).toEqual('#aacc23'); }); }); describe('events', () => { let element = new YooFormColorPickerComponent(); element.colorSelected = { emit: () => {} }; it('should emit event on input change', () => { let res = '#aacc23'; const colorSelectedSpy = jest.spyOn(element.colorSelected, 'emit'); element.onInputChange({target: {value: '#aacc23'}}); expect(element.currentColor).toEqual(res); expect(colorSelectedSpy).toHaveBeenCalledWith(res); }); }); });
a4127b00e6d8612dad0a59f72147ea8f1436f2c4
TypeScript
JohnCSimon/typescript-express-starter
/src/dto/votes.ts
2.71875
3
import * as url from 'url'; export type UpVote = { votedUrl: url.Url; upvotes: number; downvotes: number; } export class UpVoteDTO { votedUrl: url.Url; upvotes: number; downvotes: number; constructor(votedUrl: url.Url, upvotes: number, downvotes: number ) { this.votedUrl = votedUrl; this.upvotes = upvotes; this.downvotes = downvotes; } }
5a059da6e534abfc94e1cd70b547ec212d1cfa14
TypeScript
eliriand/DigitalOffice-frontend
/src/app/data/api/company-service/models/department.ts
2.671875
3
/* tslint:disable */ /* eslint-disable */ /** * Specific department data. */ export interface Department { /** * Department description. */ description: string; /** * Specific director user id this department. */ directorUserId?: string; /** * Department name. */ name: string; }
b4bfad849b47e44e9b41b43e3c66d53122b8d985
TypeScript
FeatureNinjas/logpack-vscode
/src/LogPackEntry.ts
2.546875
3
import * as vscode from 'vscode' import * as fs from 'fs' export class LogPackEntry extends vscode.TreeItem { constructor( public readonly label: string, public readonly path: fs.PathLike, public readonly file: fs.Dirent ) { super(label, file.isDirectory() ? vscode.TreeItemCollapsibleState.Collapsed : vscode.TreeItemCollapsibleState.None) if (file.isFile()) { this.command = { command: 'logpack.selectLogPackEntry', title: 'select logpack entry', arguments: [this] } } } get localPath(): fs.PathLike { return this.path } }
44f9728fe1fee04877cb2cabbe45d759a1b61f49
TypeScript
davcaro/marketplace
/client/src/app/chat/chat.model.ts
2.546875
3
import { User } from '../users/user.model'; import { Item } from '../items/item.model'; import { ChatMessage } from './chat-message.model'; export class Chat { public id: number; public item: Item; public users: { userId: number; archived: boolean; user: User }[]; public messages: { pagination: { limit: number; offset: number; total: number }; data: ChatMessage[] }; public unreadMessages: number; constructor(unreadMessages: number = 0) { this.unreadMessages = unreadMessages; } getOtherUser(userId: number) { return this.users.find(user => user.userId !== userId).user; } isArchived(userId: number): boolean { return this.users.find(user => user.userId === userId).archived; } }
451680eaee390ce858ab8ba5eed5683f87be0866
TypeScript
aimhubio/aim
/src/aimcore/web/ui/src/utils/app/updateUrlParam.ts
2.859375
3
import { PathEnum } from 'config/enums/routesEnum'; import getUrlWithParam from 'utils/getUrlWithParam'; import { setItem } from 'utils/storage'; /** * function updateURL has 2 major functionalities: * 1. Keeps URL in sync with the incoming argument "data" * 2. Stores updated URL in localStorage if App is not in the bookmark state * @data ex. {IAppConfig} configData - the current state of the app config */ export default function updateUrlParam({ data, appName, }: { data: { [key: string]: string }; appName: string; }): void { const url: string = getUrlWithParam(data); if (url === `${window.location.pathname}${window.location.search}`) { return; } const isExistBasePath = (window as any).API_BASE_PATH !== '{{ base_path }}'; const appId: string = window.location.pathname.split('/')[isExistBasePath ? 4 : 3]; if (!appId) { let fullURL = url; if (isExistBasePath) { fullURL = fullURL.replace((window as any).API_BASE_PATH, ''); } if (fullURL.startsWith(`${PathEnum.Explorers}/${appName}?`)) { setItem(`${appName}Url`, fullURL); } } window.history.pushState(null, '', url); }
198efae5a06ba55c5c56090087582b14e03f724e
TypeScript
jymfony/jymfony
/src/Component/Security/types/Role/RoleHierarchy.d.ts
2.71875
3
declare namespace Jymfony.Component.Security.Role { /** * Represents a role hierarchy. */ export class RoleHierarchy extends implementationOf(RoleHierarchyInterface) { private _hierarchy: Record<string, Set<string>>; /** * Constructor. */ __construct(hierarchy: Record<string, string[]>): void; constructor(hierarchy: Record<string, string[]>); /** * @inheritdoc */ getReachableRoles(roles: Role[]): Role[]; /** * Builds a map for the reachable roles. */ private _buildRoleMap(): void; } }
31099f7ee7e9fe6fb186a1f1ef40526c5a344954
TypeScript
ughoavgfhw/kqstats
/src/twitch/chat.ts
2.65625
3
import * as websocket from 'websocket'; import * as IRC from './IRC'; const TWITCH_SOCKET_HOST = 'wss://irc-ws.chat.twitch.tv:443/'; interface ChannelData { joinHandler?: (_?: any) => void; joinTimeout?: any; } export class TwitchChatClient { private client: websocket.client = new websocket.client(); private connection?: websocket.connection = undefined; private connectedUsername: string; private channels: { [cd: string]: ChannelData; } = {}; private postLoginHandler: (_?: any) => void; private loginTimeout: any; public get connected(): boolean { return this.connection !== undefined; } public get username(): string { return this.connectedUsername; } public get channelNames(): string[] { return Object.keys(this.channels); } public async connect(username: string, password: string): Promise<void> { this.connectedUsername = username; return new Promise<void>((resolve, reject) => { this.client.on('connectFailed', (err) => { reject(err); }); this.client.on('connect', (connection) => { this.connection = connection; connection.on('close', () => { delete this.connection; }); connection.on('message', (data) => { if (data !== undefined && data.utf8Data !== undefined) { const message = data.utf8Data.toString(); this.processMessage(message); } }); this.postLoginHandler = err => { clearTimeout(this.loginTimeout); delete this.postLoginHandler; delete this.loginTimeout; if (err !== undefined) { reject(err); this.disconnect(); } else { resolve(); } }; this.loginTimeout = setTimeout(() => { if (this.postLoginHandler !== undefined) { this.postLoginHandler( `could not connect as ${username}`); } }, 5000); this.sendRaw(`PASS ${password}`); this.sendRaw(`NICK ${username}`); }); this.client.connect(TWITCH_SOCKET_HOST, 'irc'); }); } public async join(channel: string): Promise<void> { if (this.connection === undefined) { return Promise.reject('not connected to the Twitch server'); } if (this.channels[channel] !== undefined) { return Promise.reject(`already on channel ${channel}`); } const cd: ChannelData = {}; this.channels[channel] = cd; return new Promise<void>((resolve, reject) => { cd.joinHandler = err => { clearTimeout(cd.joinTimeout); delete cd.joinHandler; delete cd.joinTimeout; if (err !== undefined) { reject(err); } else { resolve(); } }; cd.joinTimeout = setTimeout(() => { if (cd.joinHandler !== undefined) { cd.joinHandler(`could not join channel ${channel}`); } }, 5000); this.sendRaw(`JOIN ${channel}`); }); } public leave(channel: string) { if (this.channels[channel] === undefined) { return; } delete this.channels[channel]; this.sendRaw(`PART ${channel}`); } public disconnect() { if (this.connection === undefined) { return; } const channelNames = Object.keys(this.channels); for (let channel of channelNames) { this.leave(channel); } this.connection.close(); } public sendMessage(channel: string, message: string) { this.sendRaw(`PRIVMSG #${channel} :${message}`); } public broadcastMessage(message: string) { const channels = Object.keys(this.channels); if (channels.length === 0) { return; } // Note: This could send to channels which are still being joined. this.sendMessage(channels.join(',#'), message); } private processMessage(message: string) { for (let line of message.split('\r\n')) { if (line === '') { continue; } const parsed = IRC.parseMessage(line); if (parsed.command === 'PING') { this.sendRaw(`PONG :${parsed.params[0]}`); } else if (parsed.command === 'JOIN') { const channel = parsed.params[0]; if (this.channels[channel] !== undefined) { const handler = this.channels[channel].joinHandler; if (handler !== undefined) { handler(); } } } else if (/^\d\d\d$/.test(parsed.command)) { const code = Number(parsed.command); if (code === 1 && this.postLoginHandler !== undefined) { this.postLoginHandler(); } if (code >= 400 && code < 600) { console.error('Error from IRC', line); } } } } private sendRaw(message: string) { if (this.connection === undefined) { return; } this.connection.sendUTF(message); } }
1d0d77249e7541a37a9e45617a559bbb54174018
TypeScript
reimagined/resolve-cloud-common
/utils/mergeEnvironmentVariables.ts
2.890625
3
export function mergeEnvironmentVariables( original: Record<string, string>, extending: Record<string, string | null> ): Record<string, string> { const result = { ...original } for (const [key, value] of Object.entries(extending)) { if (value == null) { delete result[key] } else { result[key] = value } } return result }
d76f8d6f97e087ef62777e3a33a2bbe24017b6d5
TypeScript
Chris-Johnston/github-web-launcher
/lib/chrome_launch.ts
2.8125
3
import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import * as parseGitConfig from 'parse-git-config'; import { By, Capabilities } from 'selenium-webdriver'; import { Driver, ServiceBuilder } from 'selenium-webdriver/chrome'; import { ChromeDriver } from 'webdriver-manager-replacement'; let outDir = path.resolve(__dirname, '..', 'downloads'); let chromeDriverFile = path.resolve(outDir, 'chromedriver'); let installationFile = path.resolve(outDir, 'installation.info') /** * Asynchronous download for the ChromeDriver binary using webdriver-manager. * @returns A promise. */ export async function setupChromeDriver(): Promise<void> { let chromeDriver = new ChromeDriver(); chromeDriver.outDir = outDir; await chromeDriver.updateBinary(); } /** * Get the Chrome installation. This is accomplished by trying to read the * installation file. If the file is unavailable, launch Chrome with * ChromeDriver via the selenium-webdriver lib. Navigating to * 'chrome://version' and get the text for the command line. Parse out the * installation and write it to the installation file so it can be available * for future lookups. * @returns The Chrome installation that can be executed via command line. */ export async function getChromeInstallation(): Promise<string> { try { return fs.readFileSync(installationFile).toString(); } catch(err) { // Get the ChromeDriver binaries await setupChromeDriver(); // Launch Chrome directly with ChromeDriver. After testing headless does // not work when navigating to chrome://version. let service = new ServiceBuilder(chromeDriverFile).build(); const chromeCapabilities = Capabilities.chrome(); let driver = Driver.createSession(chromeCapabilities, service); await driver.get('chrome://version'); // Parse out the command line for Chrome, write it to file, // and return the value. let text = await driver.findElement(By.id('command_line')).getText(); let chromeInstallation = text.split('--')[0].trim(); await driver.quit(); fs.writeFileSync(installationFile, chromeInstallation); return chromeInstallation; } } /** * Get the git config url. * @param remoteName The remote name (e.g. 'origin') * @param remoteBranch The branch we want to look at (e.g. 'master') * @param currentPath The current path of the directory. * @param appendPath As we navigate to the parent, append child folders here. * @returns Either the url or null if there is no .git/config */ export function getGitConfigUrl( remoteName: string, remoteBranch: string, currentPath: string, appendPath: string): string|null { // If we have navigated to the windows main drive or the root directory, // return null. if ((os.type() === 'Windows_NT' && currentPath.endsWith(':\\')) || currentPath === '/') { return null; } try { // Try to look up a .git/config and parse the file for the url let statSync = fs.statSync(path.resolve(currentPath, '.git')); if (statSync.isDirectory()) { let gitConfig = parseGitConfig.sync( {path: path.resolve(currentPath, '.git', 'config')}); let remote: string = gitConfig[`remote "${remoteName}"`]['url']; if (remote.startsWith('http')) { return remote; } else { return remote.replace(':', '/').replace('git@', 'https://') + '/tree/' + remoteBranch + '/' + appendPath; } } else { // if the .git is not a folder, then return null. return null; } } catch (err) { // Update both the current and appended path. let newPath = path.resolve(currentPath, '..'); appendPath = currentPath.replace(newPath, '') .replace(path.sep, '') + '/' + appendPath; // Recursively call this method. return getGitConfigUrl( remoteName, remoteBranch, path.resolve(currentPath, '..'), appendPath); } }
4b279a5d33bc22604134e58590359ca0c0b2abfb
TypeScript
mikamo3/gas-suppli-common
/src/model/SuppliAmount.ts
2.84375
3
import { Suppli } from "./Suppli"; import { HasId } from "./types"; export type ISuppliAmountValues = Omit<SuppliAmount, "suppli">; export class SuppliAmount implements HasId { id: number; amount: number; suppliId: number; private getSuppli: () => Suppli; constructor(suppliAmountWithoutRelation: ISuppliAmountValues, getSuppli: () => Suppli) { this.id = suppliAmountWithoutRelation.id; this.amount = suppliAmountWithoutRelation.amount; this.suppliId = suppliAmountWithoutRelation.suppliId; this.getSuppli = getSuppli; } get suppli() { return this.getSuppli(); } }
8ea808c487fc5ce3808f2717f7892e28ed23f105
TypeScript
segardd/projetHalterFront
/src/DAO/daoAPI.ts
2.609375
3
import {GQLAPIManager} from '../datasourceManagement/graphQLAPIManager'; import {dao} from './dao'; import {gql} from 'apollo-angular'; export abstract class daoAPI<T extends Object> implements dao<T>{ public find(id: string,query: any[], type: {new(): T}): T{ var objet = new type(); return <T>objet; } public create(object: T, query: Object, type: {new(): T}): T{ var objet:T = new type(); return <T>objet; } public update( object: T, query: Object, type: {new(): T}): T{ var objet:T = new type(); return <T>objet; } public delete(object: T): void{ } public saveall(objects: T[]): void{ } public findall(query: any[], type:{new (): T}):Promise<T[]>{ var objects: [] =[]; // Creating Query var objet = new type(); var queryString =`query{\n${objet.constructor.name}Many{ \n`; query.forEach((element)=>{ console.log("in each") if (element instanceof Object){ console.log("in instanceof") queryString += `{\n`; element.forEach((subElement:Object) => { queryString += `${subElement}\n` }); queryString += `}\n`; } queryString += `${element}\n`; }) queryString += `}\n}\n`; console.log('queryString: \n'+queryString) let myQuery = gql`${queryString}` myQuery = gql`query{ CompetitorMany{ _id name firstname } }` // Execute Query var gqlManager: GQLAPIManager<T[]> = GQLAPIManager.getInstance(); return new Promise<T[]>((resolve,reject)=>{ //var data:any = gqlManager.getData(myQuery) //console.log("data: "+data) var result = gqlManager.getData(myQuery).then(data => { console.log("data in daoAPI: "+data) resolve(<T[]>data.data) }).catch( error => { console.error("error: "+error); reject('error: '+error) }) /*.then(value =>{ console.log('value: '+value) resolve(value.data); }) .catch((error)=>{ console.error(error) reject(new Error(error)) })*/ }) //objects = data; //return objects; } }
d93651de95a2642fa912b486c9fa9af992270adc
TypeScript
ComMouse/hackathon-nyu
/site/src/scene/StartScene.ts
2.53125
3
/** * Created by ComMouse on 2015/11/8. */ module scene { export class StartScene extends BaseScene { private text:egret.TextField; private count:number; public create() { this.count = 0; this.createLayout(); this.touchEnabled = true; this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouch, this); setTimeout(this.onTouch, 2000); } public update() { //this.text.y = (SceneManager.stage.stageHeight - this.text.height) / 2 + Math.sin(++this.count / (SceneManager.stage.frameRate * 2) * Math.PI / 2); if (++this.count > 30 && this.count <= 60) { this.text.alpha = Math.cos((30 - this.count) / 30 * Math.PI / 2); } } public destroy() { this.removeChild(this.text); this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouch, this); } private createLayout():void { this.text = new egret.TextField(); this.text.fontFamily = '\'Microsoft YaHei Light\', SimHei, sans-serif'; this.text.textColor = 0xffffff; this.text.textAlign = 'center'; this.text.verticalAlign = 'middle'; this.text.text = '保卫你的旗帜 / Hold Your Flag'; this.text.background = true; this.text.backgroundColor = 0xaaaaaa; this.text.width = SceneManager.stage.stageWidth; this.text.height = 120; this.text.x = 0; this.text.y = (SceneManager.stage.stageHeight - this.text.height) / 2; this.addChild(this.text); } private onTouch(event:egret.TouchEvent = null):void { SceneManager.transfer(MainScene); } } }
dbf1492b19d008ad3941f16fea6bd597720a1e35
TypeScript
scp504677840/Angular
/StructuralDirectives/src/app/unless.directive.ts
2.921875
3
import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core'; /** * 除非条件为真,否则将模板内容添加到DOM。 * 如果分配给“appUnless”的表达式计算为真值,那么将模板元素从DOM中移除,将模板元素(重新)插入到DOM中。 */ @Directive({ selector: '[appUnless]' }) export class UnlessDirective { private hasView = true; /** * 构造函数 * * @param {TemplateRef} templateRef * @param {ViewContainerRef} viewContainer */ constructor(private templateRef: TemplateRef, private viewContainer: ViewContainerRef) { } @Input() set appUnless(condition: boolean) { if (!condition && !this.hasView) { // 创建一个嵌入式视图 this.viewContainer.createEmbeddedView(this.templateRef); // 已经有视图了 this.hasView = true; } else if (condition && this.hasView) { // 清理容器里的视图 this.viewContainer.clear(); // 没有视图 this.hasView = false; } } }
207e6fdcbfd3f33acdba921a0fcbd62a7c74a1b5
TypeScript
Coffeekraken/coffeekraken
/packages/tools/s-bench/src/shared/interface/SBenchSettingsInterface.ts
2.609375
3
// @ts-nocheck import __SInterface from '@coffeekraken/s-interface'; /** * @name SBenchSettingsInterface * @namespace shared.interface * @type Class * @extends SInterface * @interface * @status beta * @platform js * @platform node * * This interface represent the SBench settings. * * @since 2.0.0 * @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io) */ export default class SBenchSettingsInterface extends __SInterface { static get _definition() { return { title: { description: 'Specify a title for your bench that will be used in the log', type: 'String', }, body: { description: 'Specify a body for your bench that will be used in the log', type: 'String', }, }; } }
f4f26be80ada9961d3614b16e8eded70a6c577ac
TypeScript
aadilelectronics/mini-task-mgr-devza
/src/app/models/task.model.ts
2.9375
3
import { Priority } from '../shared/enums'; // ?------------------------------------------------------------------------- export interface Task { id: number; message: string; due_date?: string; priority?: Priority; assigned_to?: number; assigned_name?: string; created_on?: string; } // ?------------------------------------------------------------------------- export function taskComparator(t1: Task, t2: Task): number { const diff = t1.id - t2.id; // prettier-ignore return (diff > 0) ? 1 : ((diff < 0) ? -1 : 0); }
5013ed8eac588ac12a0bd4af2671e55406b6b739
TypeScript
abdulsalaam/story-mean-biz
/backend-biz/src/api/stories/story.ts
2.578125
3
/* @abdul : 07-07-2019 */ import * as Mongoose from "mongoose"; export interface IStory extends Mongoose.Document { userId: string; title: string; description: string; viewCount:number; published: boolean; status: boolean; createdAt: Date; updateAt: Date; } export const StorySchema = new Mongoose.Schema( { userId: { type: String, required: true }, viewCount: { type: Number, required: false }, title: String, description: String, status: Boolean, published: Boolean }, { timestamps: true } ); StorySchema.virtual('ID').get(function() { return this._id; }); export const StoryModel = Mongoose.model<IStory>("Story", StorySchema);
5307a891a59dee68a737c51ae85f6cfda9b3fc91
TypeScript
deanmoses/tacocat-gallery-redux
/src/redux/selectors/draft-selectors.ts
2.984375
3
// // Redux selector functions // // The job of a selector function is to "select" (aka retrieve) some bit of state // out of the Redux store. // // The Redux store should store plain javascript objects so this is a good place // to turn that plain object into a specific class. // import { RootState } from '@src/redux/reducers/root-state'; import { Draft } from '@src/models/models'; /** * Retrieve draft at specified path */ export function getDraft(state: RootState, path: string): Draft { const draft = state.draftsByPath[path]; return draft; }
bde4f81ff6fa9aa246b2d9ea7c2d3f5dcfeab421
TypeScript
zjkipping/angular-environment-specific-service-implementation
/src/app/data-layer/book/book.service.ts
2.5625
3
import { Observable } from 'rxjs'; export interface Book { id: string; name: string; } export abstract class BookService { abstract books: Observable<Book[]>; abstract async addBook(name: string): Promise<void>; abstract async updateBook(book: Book): Promise<void>; abstract async removeBook(id: string): Promise<void>; }
4ad7d543f73cb8a9e417d2f9d3442a9bd9993a2c
TypeScript
amplication/amplication
/packages/amplication-server/src/core/git/dto/inputs/RemoteGitRepositoriesWhereUniqueInput.ts
2.546875
3
import { Field, InputType } from "@nestjs/graphql"; import { EnumGitProvider } from "../enums/EnumGitProvider"; import { Min, Max, IsInt } from "class-validator"; @InputType() export class RemoteGitRepositoriesWhereUniqueInput { @Field(() => String, { nullable: false }) gitOrganizationId!: string; @Field(() => EnumGitProvider, { nullable: false }) gitProvider!: EnumGitProvider; @Field(() => Number, { nullable: false, defaultValue: 10, description: "The number of items to return per page", }) @IsInt() @Min(10) @Max(100) perPage!: number; @Field(() => Number, { nullable: false, defaultValue: 1, description: "The page number. One-based indexing", }) @IsInt() @Min(1) page!: number; @Field(() => String, { nullable: true }) groupName?: string; }
6fd069333a8c4801cc1248bf967463243f16c363
TypeScript
arflit/movies-explorer-api
/src/models/user.ts
2.84375
3
import mongoose, { Document, Model } from 'mongoose'; import bcrypt from 'bcryptjs'; import { ErrorWithStatusCode } from '../middlewares/error-with-status-code'; export interface IUser extends Document { name: string; email: string; password: string; } export interface IUserAPI extends Model<IUser> { findUserByCredentials(a: string, b: string): Promise<IUser>; } const userSchema = new mongoose.Schema({ name: { type: String, required: true, minlength: 2, maxlength: 30, }, email: { type: String, required: true, unique: true, validate: { validator(v: string) { return /[-.\w]+@([\w-]+\.)+[\w-]+/i.test(v); }, message: 'передан некорректный адрес электронной почты', }, }, password: { type: String, required: true, select: false, }, }); userSchema.statics.findUserByCredentials = function findUserByCredentials(email, password) { return (this as mongoose.Model<IUser>).findOne({ email }).select('+password') .then((user) => { if (!user) { return Promise.reject(new ErrorWithStatusCode(401, 'Неправильные почта или пароль')); } return bcrypt.compare(password, user.password) .then((matched) => { if (!matched) { return Promise.reject(new ErrorWithStatusCode(401, 'Неправильные почта или пароль')); } return user; }); }); }; export const User = mongoose.model<IUser, IUserAPI>('user', userSchema);
c5078f99772173c78a9963ff51c03e2006220136
TypeScript
chenz24/globs
/lib/exports.ts
2.546875
3
import { MutableRefObject } from "react" import { getCommonBounds, getNodeBounds, getGlobBounds } from "lib/bounds-utils" import { IData } from "./types" class Exports { copyToSvg( data: IData, elements: Record<string, MutableRefObject<SVGElement>> ) { const { globs, nodes, globIds, nodeIds, selectedGlobs, selectedNodes, } = data const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg") const globbedNodes = new Set<string>([]) const hasSelected = globIds.length + nodeIds.length > 0 const globIdsToCopy = hasSelected ? selectedGlobs.length ? selectedGlobs : [] : globIds for (const globId of globIdsToCopy) { globbedNodes.add(globs[globId].nodes[0]) globbedNodes.add(globs[globId].nodes[1]) try { const copy = elements[globId].current.cloneNode(true) svg.appendChild(copy) } catch (e) { console.warn("Could not copy id", globId) } } const nodeIdsToCopy = (hasSelected ? data.selectedNodes.length ? selectedNodes : [] : nodeIds ).filter((id) => !globbedNodes.has(id)) for (const nodeId of nodeIdsToCopy) { try { const copy = elements[nodeId].current.cloneNode(true) svg.appendChild(copy) } catch (e) { console.warn("Could not copy id: " + e) } } const bounds = getCommonBounds( ...globIdsToCopy .map((id) => globs[id]) .filter((glob) => glob.points !== null) .map((glob) => getGlobBounds( glob, nodes[glob.nodes[0]], nodes[glob.nodes[1]], data.camera.zoom ) ), ...nodeIdsToCopy.map((id) => getNodeBounds(nodes[id], data.camera.zoom)) ) // No content if (!bounds) return const padding = 16 // Resize the element to the bounding box svg.setAttribute( "viewBox", [ bounds.minX - padding, bounds.minY - padding, bounds.width + padding * 2, bounds.height + padding * 2, ].join(" ") ) svg.setAttribute("width", String(bounds.width)) svg.setAttribute("height", String(bounds.height)) // Take a snapshot of the element const s = new XMLSerializer() const svgString = s.serializeToString(svg) // Copy to clipboard! try { navigator.clipboard.writeText(svgString) } catch (e) { Exports.copyStringToClipboard(svgString) } } static copyStringToClipboard(string: string) { let textarea: HTMLTextAreaElement let result: boolean | null try { textarea = document.createElement("textarea") textarea.setAttribute("position", "fixed") textarea.setAttribute("top", "0") textarea.setAttribute("readonly", "true") textarea.setAttribute("contenteditable", "true") textarea.style.position = "fixed" // prevent scroll from jumping to the bottom when focus is set. textarea.value = string document.body.appendChild(textarea) textarea.focus() textarea.select() const range = document.createRange() range.selectNodeContents(textarea) const sel = window.getSelection() sel.removeAllRanges() sel.addRange(range) textarea.setSelectionRange(0, textarea.value.length) result = document.execCommand("copy") } catch (err) { console.error(err) result = null } finally { document.body.removeChild(textarea) } // manual copy fallback using prompt if (!result) { return false } return true } } export default new Exports()
b5121fd98e8d58a7bb7d722d015a8fc5683b90e8
TypeScript
i9or/dungeon.ts
/src/game/PlayerCharacter.ts
2.953125
3
import { DungeonManager } from "./DungeonManager"; import { Entity } from "./Entity"; import { OBSTACLES, FLOOR_TILE, HERO_TILE } from "../constants"; export class PlayerCharacter implements Entity { private movementPoints: number; private cursors?: Phaser.Types.Input.Keyboard.CursorKeys; private x: number; private y: number; private readonly sprite: number; private standingAtSprite: number; private dungeonManager: DungeonManager; constructor(x: number, y: number) { this.dungeonManager = DungeonManager.getInstance(); this.movementPoints = 1; this.cursors = this.dungeonManager.gameScene.input.keyboard.createCursorKeys(); this.x = x; this.y = y; this.sprite = HERO_TILE; this.standingAtSprite = this.dungeonManager.gameMap.getTileAt(x, y).index; this.dungeonManager.gameMap.putTileAt(this.sprite, this.x, this.y); } over(): boolean { return this.movementPoints === 0; } refresh(): void { this.movementPoints = 1; } turn(): void { const oldX = this.x; const oldY = this.y; let moved = false; if (this.movementPoints > 0) { if (this.cursors?.left.isDown) { this.x -= 1; moved = true; } if (this.cursors?.right.isDown) { this.x += 1; moved = true; } if (this.cursors?.up.isDown) { this.y -= 1; moved = true; } if (this.cursors?.down.isDown) { this.y += 1; moved = true; } if (moved) { this.movementPoints -= 1; } } const tileAtDestination = this.dungeonManager.gameMap.getTileAt( this.x, this.y )?.index; if (tileAtDestination && OBSTACLES.includes(tileAtDestination)) { this.x = oldX; this.y = oldY; } if (this.x !== oldX || this.y !== oldY) { this.dungeonManager.gameMap.putTileAt(this.sprite, this.x, this.y); this.dungeonManager.gameMap.putTileAt(this.standingAtSprite, oldX, oldY); this.standingAtSprite = tileAtDestination; } } }
a701d769da87caef7d7fa1e183657b27b5507f02
TypeScript
x1n13y84issmd42/aller-hack-oscar
/src/app/lib/render/IFramesExtractor.ts
2.859375
3
import { VideoDesc, ClipDesc } from "./Types"; export interface IFramesExtractor<FT> { get(i: number): Promise<FT[]>; } export type VideoMap = { [k: string]: VideoDesc; }; export type VideoClipMap = { [k: string]: ClipDesc[]; }; export namespace VideoClipMap { export function put(vcm: VideoClipMap, vID: string, clip: ClipDesc) { if (!vcm[vID]) { vcm[vID] = []; } vcm[vID].push(clip); } } export abstract class DecodingFlow { constructor( private videoMap: VideoMap, private clipMap: VideoClipMap, ) {} } /** * A simpleton of decoding flows, it just starts a decoder process for each clip. */ export class NaiveDecodingFlow extends DecodingFlow { } /** * This one tries to avoid unnecessary hassle by merging together several clips * from the same video,the redistributing the frames. */ export class MergingDecodingFlow extends DecodingFlow { }
17757749aab1a0486e70491e699c06ce5e6365e7
TypeScript
declspec/aemo-technical-test
/src/app/utils/error-collection.ts
3.421875
3
// Simple utility class for managing errors associated with unique field names. export class ErrorCollection { private errors: { field: string, message: string }[] = []; public add(fieldName: string, ...messages: string[]) { messages.forEach(m => this.errors.push({ field: fieldName, message: m })); return this; } public clear(...fieldNames: string[]) { this.errors = this.errors.filter(e => fieldNames.length && fieldNames.indexOf(e.field) < 0); return this; } public getFirst(fieldName?: string) { const error = fieldName ? this.errors.find(e => e.field === fieldName) : this.errors[0]; return error?.message; } public getAll(...fieldNames: string[]) { const errors = fieldNames.length ? this.errors.filter(e => fieldNames.indexOf(e.field) >= 0) : this.errors; return errors.map(e => e.message); } public hasAny(...fieldNames: string[]) { return fieldNames.length ? this.errors.some(e => fieldNames.indexOf(e.field) >= 0) : this.errors.length > 0; } }
9720d94297d5291fd26f261f0b584b6ee1aecdb2
TypeScript
flyover/three.ts
/src/math/Interpolant.ts
3.21875
3
/** * Abstract base class of interpolants over parametric samples. * * The parameter domain is one dimensional, typically the time or a path * along a curve defined by the data. * * The sample values can have any dimensionality and derived classes may * apply special interpretations to the data. * * This class provides the interval seek in a Template Method, deferring * the actual interpolation to derived classes. * * Time complexity is O(1) for linear access crossing at most two points * and O(log N) for random access, where N is the number of positions. * * References: * * http://www.oodesign.com/template-method-pattern.html * * @author tschw */ export class Interpolant { parameterPositions: number[] | Float32Array | Float64Array; resultBuffer: number[] | Float32Array | Float64Array; _cachedIndex: number; sampleValues: number[] | Float32Array | Float64Array; valueSize: number; constructor(parameterPositions: number[] | Float32Array | Float64Array, sampleValues: number[] | Float32Array | Float64Array, sampleSize: number, resultBuffer?: number[] | Float32Array | Float64Array) { this.parameterPositions = parameterPositions; this._cachedIndex = 0; this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new (sampleValues.constructor as any)(sampleSize); this.sampleValues = sampleValues; this.valueSize = sampleSize; } evaluate(t: number): any { const pp = this.parameterPositions; let i1 = this._cachedIndex; let t1 = pp[ i1 ]; let t0 = pp[ i1 - 1 ]; validate_interval: { seek: { let right; linear_scan: { //- See http://jsperf.com/comparison-to-undefined/3 //- slower code: //- //- if (t >= t1 || t1 === undefined) { forward_scan: if (! (t < t1)) { for (let giveUpAt = i1 + 2; ; ) { if (t1 === undefined) { if (t < t0) break forward_scan; // after end i1 = pp.length; this._cachedIndex = i1; return this.afterEnd_(i1 - 1, t, t0); } if (i1 === giveUpAt) break; // this loop t0 = t1; t1 = pp[ ++ i1 ]; if (t < t1) { // we have arrived at the sought interval break seek; } } // prepare binary search on the right side of the index right = pp.length; break linear_scan; } //- slower code: //- if (t < t0 || t0 === undefined) { if (! (t >= t0)) { // looping? const t1global = pp[ 1 ]; if (t < t1global) { i1 = 2; // + 1, using the scan for the details t0 = t1global; } // linear reverse scan for (let giveUpAt = i1 - 2; ; ) { if (t0 === undefined) { // before start this._cachedIndex = 0; return this.beforeStart_(0, t, t1); } if (i1 === giveUpAt) break; // this loop t1 = t0; t0 = pp[ -- i1 - 1 ]; if (t >= t0) { // we have arrived at the sought interval break seek; } } // prepare binary search on the left side of the index right = i1; i1 = 0; break linear_scan; } // the interval is valid break validate_interval; } // linear scan // binary search while (i1 < right) { const mid: number = (i1 + right) >>> 1; if (t < pp[ mid ]) { right = mid; } else { i1 = mid + 1; } } t1 = pp[ i1 ]; t0 = pp[ i1 - 1 ]; // check boundary cases, again if (t0 === undefined) { this._cachedIndex = 0; return this.beforeStart_(0, t, t1); } if (t1 === undefined) { i1 = pp.length; this._cachedIndex = i1; return this.afterEnd_(i1 - 1, t0, t); } } // seek this._cachedIndex = i1; this.intervalChanged_(i1, t0, t1); } // validate_interval return this.interpolate_(i1, t0, t, t1); } settings: any = null; // optional, subclass-specific settings structure // Note: The indirection allows central control of many interpolants. // --- Protected interface DefaultSettings_ = {}; getSettings_(): any { return this.settings || this.DefaultSettings_; } protected copySampleValue_(index: number, t0?: number, t1?: number): any { // copies a sample value to the result buffer const result = this.resultBuffer; const values = this.sampleValues; const stride = this.valueSize; const offset = index * stride; for (let i = 0; i !== stride; ++ i) { result[ i ] = values[ offset + i ]; } return result; } // Template methods for derived classes: protected interpolate_(i1: number, t0: number, t: number, t1: number): any { throw new Error("call to abstract method"); // implementations shall return this.resultBuffer } protected intervalChanged_(i1: number, t0: number, t1: number): void { // empty } private beforeStart_(i: number, t0: number, t1: number): any { return this.copySampleValue_(i, t0, t1); //(0, t, t0), returns this.resultBuffer } private afterEnd_(i: number, t0: number, t1: number): any { return this.copySampleValue_(i, t0, t1); //(N-1, tN-1, t), returns this.resultBuffer } }
eae89282f5ae189c15694f03c0600eea64c124fc
TypeScript
edbentley/spectate
/src/core/state.ts
3.28125
3
import { Component } from "./components"; import { EffectResult, EffectResultState, EffectVal } from "./effects"; import { SpecBase } from "./spec"; import { isVariable, Variable, getInitValue, VariableValue, VariableComparitor, } from "./variables"; export type SpecState<Spec> = { state: SpecStateVars<Spec>; focus: Component | null; }; type SpecStateVars<Spec> = { [K in keyof Spec]: Spec[K] extends Variable ? VariableValue<Spec[K]> : never; }; /** * Recursively lookup a variable's primitive value within state */ export function getValueFromState<Spec extends SpecBase, Val extends EffectVal>( variable: Variable | VariableComparitor<Variable> | EffectResult<Val>, variables: { name: string; variable: Variable }[], specState: SpecState<Spec>, resultState: EffectResultState ): string | string[] { if (typeof variable === "string") return variable; if (Array.isArray(variable)) { return variable.map( (val) => getValueFromState(val, variables, specState, resultState) as string ); } if (variable.type === "effectResult") { const lookupResult = resultState.find((r) => r.effect === variable.effect); if (!lookupResult) { // No result stored yet (can happen when comparing actions) return ""; } return lookupResult.state as string | string[]; } const lookupVariable = variables.find((v) => v.variable === variable)!; return specState.state[lookupVariable.name] as string; } export function getInitSpecState<Spec extends SpecBase>( spec: Spec ): SpecState<Spec> { const specStateVars: Partial<SpecStateVars<Spec>> = {}; Object.entries(spec).forEach(([specName, specField]) => { // Only state for Variable type if (isVariable(specField)) { specStateVars[specName as keyof Spec] = getInitValue( specField ) as SpecStateVars<Spec>[keyof Spec]; } }); return { state: specStateVars as SpecStateVars<Spec>, focus: null, }; } export function statesEqual<Spec extends SpecBase>( stateA: SpecState<Spec>, stateB: SpecState<Spec> ): boolean { return ( getSimilarityScore(stateA, stateB) === Object.keys(stateA.state).length ); } /** * Similarity scored based on variable values. If a variable is deemed the same, score + 1. */ export function getSimilarityScore<Spec extends SpecBase>( stateA: SpecState<Spec>, stateB: SpecState<Spec> ): number { return Object.entries(stateA.state).reduce( (total, [fieldName1, fieldVal1]) => { const fieldVal2 = stateB.state[fieldName1]; if (stateFieldsSimilar(fieldVal1, fieldVal2)) { return total + 1; } return total; }, 0 ); } type StateField = string | unknown[]; export function stateFieldsSimilar( fieldA: StateField, fieldB: StateField ): boolean { // For text arrays, only consider the array length. if (Array.isArray(fieldA) && Array.isArray(fieldB)) { return Boolean(fieldB.length) === Boolean(fieldA.length); } // For text variables, we consider if string is empty or not. if (typeof fieldA === "string" && typeof fieldB === "string") { return Boolean(fieldB) === Boolean(fieldA); } return false; }
2e5ba4c950c4f3530d6db89f949b7f57acce5312
TypeScript
tremho/humanTest
/src/ExchangeCommon.ts
3.21875
3
/** * Object structure returned by a test. * Tests return a Promise that resolves with an object with the following properties: * * | Property | Type | Purpose | * | :------- | :--- | :------ | * | passed | boolean | True if the test has passed, false if not; will be undefined for skip or error * | skipped | boolean | True if test was skipped, undefined otherwise * | comment | string | If defined, will contain any comment entered by the human tester for this test * | error | string | If defined, will signify an error has occurred, and will hold the error message * */ export class TestResponse { public passed?: boolean public skipped?: boolean public comment?: string public error?: string } /** * Options that *may* be passed to each command. * If not given, defaults for each value are used. * * _Note: in v0.3.0 the default test timeout was changed from 30 to 60_ * * | Property | Type | Default | Purpose | * | :------- | :--- | :------ | :----- | * | prompt | string | "Is this acceptable?" | The prompt to display to the user * | specialNotice | string | <none> | A message displayed in a modal alert dialog to gove the user special instruction * | title | string | previous | (since v0.3.0) Changes the main title. The title is initially set with startManualTest, and can be changed with any command. The title will persist beyond the life of the command, until changed again.| * | name | string | derived from command | (since v0.3.0) assigns the test naem that the results appear under in the HumanTest Report output * | timeout | number | 60 (120 for verifyHuman) | The number of seconds before a timeout occurs, and test skipped * | width | number | <none> | **(`imageView` Only)** Defines the width used for the image display, in pixels. If not provided, the full image width is displayed. | * | height | number | <none> | **(`imageView` Only)** Defines the height used for the image display, in pixels. If not provided, the full image height is displayed. | * */ export class TestOptions { public name?: string public prompt?: string public timeout?: number public specialNotice?: string public title?:string; public width?:number public height?: number } /** * Structure of a command argument. has both file and text slots. * The text of the file gets put into the text field by electronMain before sending to remote. * @ignore */ class CmdArg { public text?:string public file?:string } /** Contains the command that will be JSON-transmitted to the remote * @ignore */ export class Command { public cmd:string public cmdargs:CmdArg[] = [new CmdArg(), new CmdArg()] public options?:TestOptions }
3a0ea5fdf9d4a012bd9280a90e034823c5dd28bd
TypeScript
HamishBrindle/vue-typescript-starter
/src/lib/interfaces/CustomStore.interface.ts
2.8125
3
import { Store } from 'vuex'; /** * Interface for the CustomStore's root-state */ interface IRootState { version: string; } /** * Interface for our App's root state */ export interface ICustomStore extends Store<IRootState> { /** * Indicates if the Vuex state has been loaded from local storage * and is ready to use */ restored: Promise<boolean>; }
d22d9916712f0be1c4f9cca4045208e02ecc04b0
TypeScript
dan-kez/go-links
/api/src/entity/Link.ts
2.609375
3
import { IsNotEmpty, IsUrl } from 'class-validator'; import { BaseEntity, Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, } from 'typeorm'; @Entity() export default class Link extends BaseEntity { @PrimaryGeneratedColumn() public id!: number; @Column({ length: 100, unique: true, }) @IsNotEmpty() public shortUrl!: string; @Column({ length: 255, }) public ipAddress!: string; @Column({ type: 'longtext', }) @IsNotEmpty() @IsUrl() public destinationUrl!: string; @Column({ default: 0, }) public hits!: number; @CreateDateColumn() public created!: Date; }
004f98c9fac2d76063eeb7362c5d6e03611b2fd7
TypeScript
patryk-fuhrman/tibia-enemylist
/src/app/enemy-list/models/enemy.ts
2.65625
3
import { Attributes } from './attributes' export class Enemy { public id: number public type: string public attributes: Attributes constructor( id: number, type: string, attributes: Attributes, ) { this.id = id this.type = type this.attributes = Attributes.createInstance(attributes) } }
8f39b47fcce992be456360fb5039f8e0f29735a5
TypeScript
ricardofiorani/JSSCC
/src/canvas.ts
2.53125
3
class CanvasRenderer { canvasID: string; canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D; loader: AssetLoader; hitDetector: HitDetector; palette: Palette; paletteName: string; initialized: boolean; loadEvents: number; scale: number; song: Song; chan: Channel; offsetX: number; offsetY: number; continuouslyRender: boolean; constructor(loader: AssetLoader = new AssetLoader("assets/manifest.json"), song: Song, canvasID: string = "content", continuouslyRender: boolean = true) { this.loader = loader; this.initialized = false; this.loadEvents = 2; this.scale = 1; this.canvasID = canvasID; this.paletteName = "default"; this.palette = this.loader.palettes[this.paletteName]; this.song = song; this.chan = song.channels[0]; this.offsetX = 0; this.offsetY = 0; this.continuouslyRender = continuouslyRender; var onload = () => { this.loadEvents--; this.initCanvas(); this.rescale(); if (this.loadEvents === 0) { this.firstDraw(); } }; if (document.readyState === "complete") { onload(); } else { window.addEventListener("load", onload, false); } this.loader.onload.push(() => { this.loadEvents--; this.switchPalette(Cookies.get("palette", "default")); if (this.loadEvents === 0) { this.firstDraw(); } }); } public firstDraw() { this.clear(); this.redraw(); this.renderFrame(); } public switchPalette(name: string = "default"): void { if (name !== this.paletteName) { Cookies.write("palette", name); if (this.initialized) { var olddata = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height); this.clear(); this.ctx.fillStyle = this.palette.foreground; this.ctx.fillText("Loading...", this.canvas.width / 2, this.canvas.height / 2); // have a frame render with the "Loading..." text before switching window.setTimeout(() => { if (olddata !== undefined) { let newdata = new ImageData(olddata.width, olddata.height); AssetLoader.composite(newdata.data, olddata.data, olddata.data, this.palette, this.loader.palettes[name]); this.ctx.putImageData(newdata, 0, 0); } this.loader.switchPalette(this.paletteName, name); this.palette = this.loader.palettes[name]; this.paletteName = name; document.body.style.backgroundColor = this.palette.background; if (olddata === undefined && this.initialized) { this.clear(); this.redraw(); } }, 10); } else { this.loader.switchPalette(this.paletteName, name); this.palette = this.loader.palettes[name]; this.paletteName = name; document.body.style.backgroundColor = this.palette.background; } } } public initCanvas(): void { if (this.initialized) { return; } document.body.style.backgroundColor = this.palette.background; window.addEventListener("resize", () => { this.rescale(); }, false); this.canvas = <HTMLCanvasElement>document.getElementById(this.canvasID); this.canvas.width = 634; this.canvas.height = 444; var newCtx = this.canvas.getContext("2d"); if (newCtx === null) { console.error("couldn't get 2d context for main canvas"); return; } this.hitDetector = new HitDetector(newCtx); this.ctx = newCtx; this.ctx.textBaseline = "middle"; this.ctx.textAlign = "center"; this.ctx.font = "25px monospace"; this.initialized = true; this.rescale(); this.clear(); } public rescale(): void { if (!this.initialized) { return; } var widthScale: number = window.innerWidth / this.canvas.width; var heightScale: number = window.innerHeight / this.canvas.height; this.hitDetector.scale = this.scale = Math.max(1, Math.floor(Math.min(widthScale, heightScale))); this.ctx.canvas.style.height = (this.ctx.canvas.height * this.scale) + "px"; this.ctx.canvas.style.width = (this.ctx.canvas.width * this.scale) + "px"; } public clear(): void { if (!this.initialized) { return; } this.ctx.fillStyle = this.palette.background; this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); } public button(x: number, y: number, w: number, h: number, pressed: boolean = false): void { this.ctx.strokeStyle = pressed ? this.palette.background : this.palette.light; this.ctx.strokeRect(x + 1.5, y + 1.5, w - 2, h - 2); this.ctx.strokeStyle = pressed ? this.palette.light : this.palette.foreground; this.ctx.strokeRect(x + 2.5, y + 2.5, w - 3, h - 3); this.ctx.fillStyle = this.palette.dark; this.ctx.fillRect(x + 2, y + 2, w - 3, h - 3); this.ctx.strokeStyle = this.palette.foreground; this.ctx.strokeRect(x + 0.5, y + 0.5, w, h); } public strokeRect(x: number, y: number, w: number, h: number, color: string) { this.ctx.strokeStyle = color; this.ctx.strokeRect(x + 0.5, y + 0.5, w, h); } public filledRect(x: number, y: number, w: number, h: number, color: string) { this.ctx.fillStyle = color; this.ctx.fillRect(x, y, w, h); } public clearRect(x: number, y: number, w: number, h: number) { this.ctx.clearRect(x, y, w, h); } public image(image: string, x: number, y: number) { this.ctx.putImageData(this.loader.getImage(image), x, y); } public line(x1: number, y1: number, x2: number, y2: number, color: string) { x2 += this.offsetX; y2 += this.offsetY; this.ctx.strokeStyle = color; this.ctx.lineWidth = 1; this.ctx.beginPath(); this.ctx.moveTo(x1 + 0.5, y1 + 0.5); this.ctx.lineTo(x2 + 0.5, y2 + 0.5); this.ctx.stroke(); } public pbar(value: number, x: number, y: number, w: number, h: number, color: string) { this.ctx.fillStyle = color; this.ctx.fillRect(x, y, Math.round(w * value), h); } public text(size: "small" | "medium" | "large", text: string, x: number, y: number, color: string, rtl?: boolean, spaceWidth?: number) { var font = this.loader.getFont(size); if (spaceWidth === undefined) { this.loader.getFont(size).drawText(this.ctx, text, x, y, color, rtl); } else { font.spaceWidth = spaceWidth; font.drawText(this.ctx, text, x, y, color, rtl); font.spaceWidth = 1; } } public window(x: number, y: number, w: number, h: number, title?: string) { // the reason for all this raw ImageData manipulation is to dynamically // generate (because of palette changes) the gradients on the sides of // the window by scaling the corners' edges all the way across the sides // the corners also need compositing as parts of them are transparent // composite curved corners with background var upperLeft = this.loader.getImage("upperLeft"); var upperRight = this.loader.getImage("upperRight"); var lowerLeft = this.loader.getImage("lowerLeft"); var lowerRight = this.loader.getImage("lowerRight"); var compositedUpperLeft = new ImageData(upperLeft.width, upperLeft.height); var compositedUpperRight = new ImageData(upperRight.width, upperRight.height); var compositedLowerLeft = new ImageData(lowerLeft.width, lowerLeft.height); var compositedLowerRight = new ImageData(lowerRight.width, lowerRight.height); AssetLoader.composite(compositedUpperLeft.data, upperLeft.data, this.ctx.getImageData(x, y, upperLeft.width, upperLeft.height).data); AssetLoader.composite(compositedUpperRight.data, upperRight.data, this.ctx.getImageData(x + w - upperRight.width, y, upperRight.width, upperRight.height).data); AssetLoader.composite(compositedLowerLeft.data, lowerLeft.data, this.ctx.getImageData(x, y + h - lowerLeft.height, lowerLeft.width, lowerLeft.height).data); AssetLoader.composite(compositedLowerRight.data, lowerRight.data, this.ctx.getImageData(x + w - lowerRight.width, y + h - lowerRight.height, lowerRight.width, lowerRight.height).data); // draw main window surface this.ctx.fillStyle = this.palette.background; this.ctx.fillRect(x, y, w, h); // draw left edge for (var i = 0; i < upperLeft.width; i++) { let dataIdx = ((upperLeft.height - 1) * upperLeft.width + i) * 4; this.ctx.strokeStyle = AssetLoader.rgbToHex(upperLeft.data[dataIdx], upperLeft.data[dataIdx + 1], upperLeft.data[dataIdx + 2]); this.ctx.beginPath(); this.ctx.moveTo(x + i + 0.5, y + 0.5); this.ctx.lineTo(x + i + 0.5, y + h - 0.5); this.ctx.stroke(); } // draw right edge for (var i = 0; i < upperRight.width; i++) { let dataIdx = ((upperRight.height - 1) * upperRight.width + i) * 4; this.ctx.strokeStyle = AssetLoader.rgbToHex(upperRight.data[dataIdx], upperRight.data[dataIdx + 1], upperRight.data[dataIdx + 2]); this.ctx.beginPath(); this.ctx.moveTo(x + w - upperRight.width + i + 0.5, y + 0.5); this.ctx.lineTo(x + w - upperRight.width + i + 0.5, y + h - 0.5); this.ctx.stroke(); } // draw top edge for (var i = 0; i < upperLeft.height; i++) { let dataIdx = (upperLeft.width * i + (upperLeft.width - 1)) * 4; this.ctx.strokeStyle = AssetLoader.rgbToHex(upperLeft.data[dataIdx], upperLeft.data[dataIdx + 1], upperLeft.data[dataIdx + 2]); this.ctx.beginPath(); this.ctx.moveTo(x + 0.5, y + i + 0.5); this.ctx.lineTo(x + w - 0.5, y + i + 0.5); this.ctx.stroke(); } // draw bottom edge for (var i = 0; i < lowerLeft.height; i++) { let dataIdx = (lowerLeft.width * i + (lowerLeft.width - 1)) * 4; this.ctx.strokeStyle = AssetLoader.rgbToHex(lowerLeft.data[dataIdx], lowerLeft.data[dataIdx + 1], lowerLeft.data[dataIdx + 2]); this.ctx.beginPath(); this.ctx.moveTo(x + 0.5, y + h - lowerLeft.height + i + 0.5); this.ctx.lineTo(x + w - 0.5, y + h - lowerLeft.height + i + 0.5); this.ctx.stroke(); } this.ctx.putImageData(compositedUpperLeft, x, y); this.ctx.putImageData(compositedUpperRight, x + w - upperRight.width, y); this.ctx.putImageData(compositedLowerLeft, x, y + h - lowerLeft.height); this.ctx.putImageData(compositedLowerRight, x + w - lowerRight.width, y + h - lowerRight.height); // draw title if (title !== undefined) { this.loader.getFont("large").drawText(this.ctx, <string>title, x + 8, y + 7, this.palette.white); } } public polyToColor(poly: number) { return this.palette.foreground; // TODO } public pan(x: number, y: number, val: number | null) { for (var i = -8; i <= 8; i++) { if (i === 0) { continue; } else if (val === null) { this.ctx.strokeStyle = this.palette.dark; } else if (Math.abs(i) === 1) { this.ctx.strokeStyle = "#ff9f00"; } else if (val > 0 === i > 0 && Math.abs(val) >= Math.abs(i / 8)) { this.ctx.strokeStyle = this.palette.light; } else { this.ctx.strokeStyle = this.palette.dark; } var height = Math.floor(Math.abs(i) / 2 + 1.5); this.ctx.strokeRect(x + (i * 2) + (i > 0 ? 13 : 16) + 0.5, y + 5 - height, 0, height + 1); } } public waveform(x: number, y: number, width: number, color: string, checkWindow?: boolean) { this.ctx.fillStyle = color; if (this.chan.wave !== null) { this.ctx.fillStyle = this.palette.light; for (var i = 0; i < width; i++) { var val = Math.round(this.chan.wave(i / width) * 7.5); if (val >= 0) { val++; } this.ctx.fillRect(x + i + 1, y + 11, 1, -val); } } } public vuMeter(x: number, y: number, w: number, h: number, val: number) { for (var i = 0; i < h; i++) { this.ctx.fillStyle = val >= (h - i) / h ? this.palette.light : this.palette.dark; this.ctx.fillRect(x, y + i * 3, w + 1, 2); } } public drawChannel(idx: number, group?: string): void { var x = ((idx % 16) * 36) + 58; var y = (Math.floor(idx / 16) * 168) + 49; this.chan = this.song.channels[idx]; if (group !== undefined) { this.drawDGroup(group, x, y); } else { this.drawAllGroupsWithName("channel", x, y); } } public drawAllGroupsWithName(name: string, x?: number, y?: number) { for (var gn in this.loader.drawGroups) { if (typeof gn === "string" && gn.substring(0, name.length) === name) { this.drawDGroup(gn, x, y); } } } public drawDObject(drawObj: DrawObject) { if (drawObj[0] === "nop" || drawObj[0] === "bounds") { return; } // evaluate the arguments according to some rules: // - if the argument is not a string, don't do anything to it // - if the argument starts with "$", eval the rest of it and // set the arg to the result // - if the argument starts with "&", get the corresponding // color from the current palette (this could have been done) // with "$" and eval as above, but it's done often enough // that this shortcut/optimization makes sense // - if the argument starts with a "#", interpret it as a hex // code (the AssetLoader.canonicalizeHex function takes care // of the codes later, making sure the formatting is correct, // converting #F00 to #FF0000, etc.) var args: Array<string | number | boolean | undefined | null> = new Array(drawObj.length); var numbers = 0; for (var i = 0; i < drawObj.length; i++) { var arg = drawObj[i]; if (typeof arg === "string" && arg.length > 0) { switch (arg.charAt(0)) { case "$": args[i] = eval(arg.substr(1)); break; case "&": var color = arg.substr(1); args[i] = this.palette.hasOwnProperty(color) ? (<any>this.palette)[color] : drawObj[i]; break; default: args[i] = drawObj[i]; break; } } else if (numbers < 2 && typeof arg === "number") { args[i] = arg + (numbers === 0 ? this.offsetX : this.offsetY); numbers++; } else { args[i] = drawObj[i]; } } // if the object type is "nop", completely disregard it; this is put // after the argument transformation so it can run code to determine // if the draw is a nop (e.g. don't draw the waveform on a drum channel) if (args[0] === "nop" || args[0] === "bounds") { return; } var func = (<any>this)[<string>(<any>args[0])]; if (typeof func === "function") { func.apply(this, args.slice(1)); } else { console.warn("unrecognized UI item ", args); } } public drawDGroup(group: DrawObject[] | string, offsetX?: number, offsetY?: number) { if (offsetX !== undefined && offsetY !== undefined) { this.offsetX = offsetX; this.offsetY = offsetY; } if (typeof group === "string") { group = this.loader.drawGroups[group]; } for (var i = 0; i < group.length; i++) { this.drawDObject(group[i]); } // reset offsets if (this.offsetX !== 0 || this.offsetY !== 0) { this.offsetX = 0; this.offsetY = 0; } } public redraw(): void { for (var group in this.loader.drawGroups) { this.drawDGroup(group); } for (var idx = 0; idx < this.song.channels.length; idx++) { this.drawChannel(idx); } } public rebakeBounds(manifestURL?: string) { // channelButton won't render unless the channel is a drum channel // it doesn't matter that we're overwriting this as rebakeBounds // will redirect you to view the JSON anyway this.chan.drum = true; this.loader.rebakeBounds(this, manifestURL); } public autoRegion(name: string, autoRedraw: boolean = true, callback?: () => any, offsetX?: number, offsetY?: number): HitRegion { var group = this.loader.drawGroups[name]; if (group === undefined) { console.error("no group named " + name); } else if (group.length === 0) { console.error("zero length DGroup"); } var bounds = <BoundsMetadata>group[group.length - 1]; if (bounds === undefined || bounds.length < 5 || bounds[0] !== "bounds") { console.error("incorrect bounds list ", bounds); } if (offsetX !== undefined && offsetY !== undefined) { var region = new HitRegion(bounds[1] + offsetX, bounds[2] + offsetY, bounds[3], bounds[4]); } else { var region = new HitRegion(bounds[1], bounds[2], bounds[3], bounds[4]); } if (autoRedraw) { var onMouseUp = (e: MouseEvent) => { this.drawDGroup(name, offsetX, offsetY); window.removeEventListener("mouseup", onMouseUp, false); } region.onmousedown.push((x: number, y: number) => { this.drawDGroup(name, offsetX, offsetY); if (callback !== undefined) { callback(); } else { window.addEventListener("mouseup", onMouseUp, false); } }); } this.hitDetector.addHitRegion(region, name); return region; } public renderFrame() { if (!this.continuouslyRender) { return; } if (this.song.playState === PlayState.PLAYING || this.song.playState === PlayState.FASTFORWARD) { var pn = (performance.now() / 1000); for (var i = 0; i < 32; i++) { var x = (Waveform.sine(pn + (i / 10)) + 1) * 0.505; this.chan = this.song.channels[i]; this.chan.volume = x this.chan.expression = x this.chan.envelope = x this.chan.output = x; this.drawChannel(i, "channelVEN"); //this.drawChannel(i, "channelFrequency"); //this.drawChannel(i, "channelPoly"); } } window.requestAnimationFrame(() => { this.renderFrame(); }); } }
900cf8b501e28b86074d60669d078819a4e2bf00
TypeScript
cmakler/kgjs
/src/ts/controller/listeners/listener.ts
2.8125
3
/// <reference path="../../kg.ts" /> module KG { export interface ListenerDefinition extends UpdateListenerDefinition { param: string; expression?: string; } export interface IListener extends IUpdateListener { onChange: (scope: { params: {}, drag: {} }) => void; } /* A listener is defined by a param and an expression. When the interactionHandler senses a change, it generates a scope of the current state of the model. The listener then determines the current value of its expression within the context of that scope, and sends a signal to the model to update its param. */ export class Listener extends UpdateListener implements IListener { public param; public expression; constructor(def: ListenerDefinition) { setProperties(def, 'updatables',['expression']); setProperties(def, 'constants',['param']); super(def); } onChange(scope) { const l = this, compiledMath = math.compile(l.expression); let parsedMath = compiledMath.evaluate(scope); l.model.updateParam(l.param, parsedMath); } } }
06b18698bbbe81b28bcc47f6be7c7464e403a9b1
TypeScript
RyanCavanaugh/derny
/src/types.ts
2.609375
3
export interface Renderer { renderFiles(files: File[], opts: Options): string; parse(content: string): File[] | undefined; } export type File = { fileName: string, content: string }; export interface Options { wrap: boolean; }
148a36c143dc75f2c0e71529839234435d8fa934
TypeScript
gabrieluy/web-challenge
/api/src/posts/posts.service.ts
2.6875
3
import { Inject, Injectable, NotFoundException } from '@nestjs/common'; import { CreatePostDto } from './dtos/create-post.dto'; import { Post } from '../entities/post.entity'; import { UpdatePostDto } from './dtos/update-post.dto'; import { REPOSITORIES } from '../constants/constants'; import { Repository } from 'typeorm'; @Injectable() export class PostsService { constructor( @Inject(REPOSITORIES.POST) private readonly repository: Repository<Post>, ) {} async getMany(): Promise<Post[]> { return this.repository.find(); } async getOne(id: string): Promise<Post> { return this.find(id); } public async createOne(createPostDto: CreatePostDto): Promise<Post> { const post: Post = { title: createPostDto.title, content: createPostDto.content, lat: createPostDto.lat, long: createPostDto.long, image_url: createPostDto.image_url, }; return this.repository.save(post); } public async updateOne(updatePostDto: UpdatePostDto): Promise<Post> { const post = await this.find(updatePostDto.id); const updatedPost = { ...post, ...updatePostDto } as Post; return this.repository.save(updatedPost); } public async deleteOne(id: string): Promise<void> { const post = await this.find(id); await this.repository.remove(post); } private async find(id: string): Promise<Post> { const post = await this.repository.findOne({ id }); if (!post) { throw new NotFoundException('Post not found'); } return post; } }
45fdd04eddbb3295a69516950bcbaacfda3d5499
TypeScript
duvet86/docker-express-mongodb
/src/lib/utils.ts
3.234375
3
/** * Normalize a port into a number, string, or false. */ export const normalizePort = (val: string) => { const p = parseInt(val, 10); if (isNaN(p)) { // named pipe return val; } if (p >= 0) { // port number return p; } return false; };
f91fc2af25cf7753246b6f0da39cea2f47bac517
TypeScript
Firas-Hechmi/recipes-manager
/src/app/services/shopping-list.service.ts
2.734375
3
import { Subject } from "rxjs"; import { ShoppingList } from "../models/ShoppingList.model"; export class ShoppingListService{ shoppingListSubjet=new Subject<ShoppingList[]>(); private shoppingList: ShoppingList[]=[ new ShoppingList("ras zebi",3,"Pizza") ]; emitShoppingListSubjet(){ this.shoppingListSubjet.next(this.shoppingList.slice()); } addIngredient(ingredient : ShoppingList){ this.shoppingList.push(ingredient); this.emitShoppingListSubjet(); } updateIngredient(index :number,recipe : ShoppingList){ this.shoppingList[index]=recipe; this.emitShoppingListSubjet(); } deleteIngredient(index : number){ this.shoppingList.splice(index,1); this.emitShoppingListSubjet(); } getRecipeByIndex(index : number){ return this.shoppingList[index]; } }
12ab667c6c28783c17322022fab005f4236bdec2
TypeScript
damonpam/testing-tools
/packages/bdd_initializer/src/utils/Logger.ts
2.75
3
/* eslint-disable no-console */ import chalk from 'chalk'; import { emoji, get } from 'node-emoji'; class Logger { public redChalk = chalk.red; private greenChalk = chalk.green; private yellowChalk = chalk.yellow; public exit(message: string, code: number): void { console.log(this.redChalk(`${emoji.door} ${message}`)); process.exit(code); } public error(message: string, emoji = 'octagonal_sign'): void { throw new Error(this.redChalk(`${get(emoji)} Ops! ${message}`)); } public info(message: string, emoji?: string): void { const msg = emoji ? `${get(emoji)} ${message}` : message; console.log(msg); } public success(message: string, emoji = 'white_check_mark'): void { console.log(this.greenChalk(`${get(emoji)} ${message}`)); } public warning(message: string, emoji = 'warning'): void { console.log(this.yellowChalk(`${get(emoji)} ${message}`)); } } export const logger = new Logger();
02d429c8d29340bf7250641e98d4acef67547fc8
TypeScript
isso0424/spoedit-browser
/src/client/api/requester.ts
2.703125
3
import axios from "axios"; import {IRequester} from "../../usecase/requester"; const baseURL = "https://api.spotify.com/v1"; export class Requester implements IRequester { async getData( endpoint: string, queries?: Record<string, string>, headers?: Record<string, unknown> ): Promise<Record<string, unknown>> { const urlForEndpoint = baseURL + endpoint; const requestURL = Requester.embedQueriesToURL(urlForEndpoint, queries); const response = await axios.get(requestURL, {headers}); if (response.status < 200 || response.status >= 300) { throw "Error occurred in get token with status code " + response.status; } return response.data; } async post( endpoint: string, queries?: Record<string, string>, body?: Record<string, unknown>, headers?: Record<string, unknown> ): Promise<Record<string, unknown>> { const urlForEndpoint = baseURL + endpoint; const requestURL = Requester.embedQueriesToURL(urlForEndpoint, queries); const response = await axios.post(requestURL, body, {headers}); if (response.status < 200 || response.status >= 300) { throw "Error occurred in get token with status code " + response.status; } return response.data; } async put( endpoint: string, queries?: Record<string, string>, body?: Record<string, unknown>, headers?: Record<string, unknown> ): Promise<Record<string, unknown>> { const urlForEndpoint = baseURL + endpoint; const requestURL = Requester.embedQueriesToURL(urlForEndpoint, queries); const response = await axios.put(requestURL, body, {headers}); if (response.status < 200 || response.status >= 300) { throw "Error occurred in get token with status code " + response.status; } return response.data; } async delete( endpoint: string, queries?: Record<string, string>, body?: Record<string, unknown>, headers?: Record<string, unknown> ): Promise<Record<string, unknown>> { const urlForEndpoint = baseURL + endpoint; const requestURL = Requester.embedQueriesToURL(urlForEndpoint, queries); const response = await axios.delete(requestURL, {headers, data: body}); if (response.status < 200 || response.status >= 300) { throw "Error occurred in get token with status code " + response.status; } return response.data; } private static embedQueriesToURL( url: string, queries?: Record<string, string> ): string { if (queries == null || Object.entries(queries).length == 0) return url; Object.entries(queries).forEach(([key, value], index) => { url += `${index == 0 ? "?" : "&"}${key}=${value}`; }); return url; } }
80ad9eb6d096e50509778cfee15eb2628a48ae37
TypeScript
Doise/Social
/src/services/posts/toggleLike.ts
3.15625
3
import { IPost, IToggleLikeInput } from "../../interfaces/IPost"; import Post from "../../models/post"; /** * Toggles like/dislike for a post from a given user. * * @param { IToggleLikeInput } toggleLikeInput The user and the post to be liked. * @returns { Promise<IPost> } The post liked. */ export default async (toggleLikeInput: IToggleLikeInput): Promise<IPost> => { try { /** * find the post to toggle like. */ const post = await Post.findById(toggleLikeInput.postId); /** * chek if the user already liked it or not */ const likeIndex = post.likes.findIndex(user => `${user}` === `${toggleLikeInput.userId}`); /** * update the likes array and save the doc. */ if (likeIndex === -1) { post.likes.push(toggleLikeInput.userId); } else { post.likes.splice(likeIndex, 1); } await post.save(); return (await post.populate("author", "-password").populate("likes", "-password").execPopulate() as unknown) as IPost; } catch (e) { throw new Error("Post not found"); } };
4f46d2ea6b81c9af38df8943fba0a8c3e5bd47ed
TypeScript
Mikkael3/paytrail-lib
/src/rest/entities/payment.ts
3.015625
3
import { OrderDetails as OrderDetailsData, Payment as PaymentData, RequestData, } from "../interfaces"; import OrderDetails from "./order-details"; import paymentConsts from "../../consts/payment"; const CURRENCIES = ["EUR"]; const LOCALES = ["fi_FI", "sv_SE", "en_US"]; class Payment implements RequestData<PaymentData> { private orderNumber: string = ""; private referenceNumber?: number; private description?: string; private currency: string = "EUR"; private locale: string = "fi_FI"; private price?: number; private orderDetails?: OrderDetails; constructor(paymentData: PaymentData) { const { orderNumber, referenceNumber, description, currency, locale, orderDetails, price, }: PaymentData = paymentData; this.setOrderNumber(orderNumber); this.setReferenceNumber(referenceNumber); this.setDescription(description); this.setCurrency(currency); this.setLocale(locale); this.setOrderDetails(orderDetails); this.setPrice(price); } setOrderNumber = (orderNumber: string): void | never => { if (orderNumber.length > 64) { throw new Error("Order Number cannot be longer than 64 chars."); } this.orderNumber = orderNumber; }; setReferenceNumber = (referenceNumber: number | undefined): void | never => { //todo reference number validation if ( typeof referenceNumber !== "undefined" && `${referenceNumber}`.length > 22 ) { throw new Error("Reference Number cannot be longer than 22 chars."); } this.referenceNumber = referenceNumber; }; setDescription = (description: string | undefined): void | never => { if (typeof description !== "undefined" && description.length > 65000) { throw new Error("Description cannot be longer than 65000 chars."); } this.description = description; }; setCurrency = (currency: string | undefined): void | never => { if (!currency) return; if (!CURRENCIES.find((cur: string): boolean => cur === currency)) { throw new Error("Invalid currency."); } this.currency = currency; }; setLocale = (locale: string | undefined): void | never => { if (!locale) return; if (!LOCALES.find((loc: string): boolean => loc === locale)) { throw new Error("Invalid Locale."); } this.locale = locale; }; setOrderDetails = (orderDetails: OrderDetailsData | undefined): void => { if (!orderDetails) return; this.orderDetails = new OrderDetails(orderDetails); }; setPrice = (price: number | undefined): void | never => { if (!price) return; if (price < paymentConsts.MIN_PRICE || price > paymentConsts.MAX_PRICE) { throw new Error( `Invalid price. Min price: ${paymentConsts.MIN_PRICE} and max price : ${paymentConsts.MAX_PRICE}` ); } this.price = price; }; toJson = () => { if (this.price && this.orderDetails) throw Error( "Invalid payment: Payment can't contain both price and orderDetails" ); if (!this.price && !this.orderDetails) throw Error( "Invalid payment: Payment should have either price or orderDetails" ); let json: PaymentData = { orderNumber: this.orderNumber, currency: this.currency, locale: this.locale, }; if (this.referenceNumber) json.referenceNumber = this.referenceNumber; if (this.description) json.description = this.description; if (this.price) json.price = this.price; if (this.orderDetails) json.orderDetails = this.orderDetails.toJson(); return json; }; } export default Payment;
81034fbea622f27fb5c074ede91530d9f496d339
TypeScript
rajkrishnamurthy/quicktype
/src/JSONSchemaInput.ts
2.8125
3
"use strict"; import { List, OrderedSet, Map, fromJS, Set } from "immutable"; import * as pluralize from "pluralize"; import { MapType, ClassProperty } from "./Type"; import { panic, assertNever, StringMap, checkStringMap, assert, defined } from "./Support"; import { TypeGraphBuilder, TypeRef } from "./TypeBuilder"; import { TypeNames, makeTypeNames } from "./TypeNames"; import { unifyTypes } from "./UnifyClasses"; enum PathElementKind { Root, Definition, OneOf, AnyOf, Property, AdditionalProperty, Items } type PathElement = | { kind: PathElementKind.Root } | { kind: PathElementKind.Definition; name: string } | { kind: PathElementKind.OneOf; index: number } | { kind: PathElementKind.AnyOf; index: number } | { kind: PathElementKind.Property; name: string } | { kind: PathElementKind.AdditionalProperty } | { kind: PathElementKind.Items }; type Ref = List<PathElement>; function checkStringArray(arr: any): string[] { if (!Array.isArray(arr)) { return panic(`Expected a string array, but got ${arr}`); } for (const e of arr) { if (typeof e !== "string") { return panic(`Expected string, but got ${e}`); } } return arr; } function parseRef(ref: any): [Ref, string] { if (typeof ref !== "string") { return panic("$ref must be a string"); } let refName = "Something"; const parts = ref.split("/"); const elements: PathElement[] = []; for (let i = 0; i < parts.length; i++) { if (parts[i] === "#") { elements.push({ kind: PathElementKind.Root }); refName = "Root"; } else if (parts[i] === "definitions" && i + 1 < parts.length) { refName = parts[i + 1]; elements.push({ kind: PathElementKind.Definition, name: refName }); i += 1; } else { panic(`Could not parse JSON schema reference ${ref}`); } } return [List(elements), refName]; } function lookupDefinition(schema: StringMap, name: string): StringMap { const definitions = checkStringMap(schema.definitions); return checkStringMap(definitions[name]); } function lookupProperty(schema: StringMap, name: string): StringMap { const properties = checkStringMap(schema.properties); return checkStringMap(properties[name]); } function indexArray(cases: any, index: number): StringMap { if (!Array.isArray(cases)) { return panic("oneOf or anyOf value must be an array"); } return checkStringMap(cases[index]); } function getName(schema: StringMap, typeNames: TypeNames): TypeNames { if (!typeNames.areInferred) { return typeNames; } const title = schema.title; if (typeof title === "string") { return makeTypeNames(title, false); } else { return typeNames.makeInferred(); } } function checkTypeList(typeOrTypes: any): OrderedSet<string> { if (typeof typeOrTypes === "string") { return OrderedSet([typeOrTypes]); } else if (Array.isArray(typeOrTypes)) { const arr: string[] = []; for (const t of typeOrTypes) { if (typeof t !== "string") { return panic(`element of type is not a string: ${t}`); } arr.push(t); } const set = OrderedSet(arr); assert(!set.isEmpty(), "JSON Schema must specify at least one type"); return set; } else { return panic(`type is neither a string or array of strings: ${typeOrTypes}`); } } function makeImmutablePath(path: Ref): List<any> { return path.map(pe => fromJS(pe)); } export function schemaToType( typeBuilder: TypeGraphBuilder, topLevelName: string, rootJson: any, conflateNumbers: boolean ): TypeRef { const root = checkStringMap(rootJson); let typeForPath = Map<List<any>, TypeRef>(); function setTypeForPath(path: Ref, t: TypeRef): void { typeForPath = typeForPath.set(makeImmutablePath(path), t); } function lookupRef(local: StringMap, localPath: Ref, ref: Ref): [StringMap, Ref] { const first = ref.first(); if (first === undefined) { return [local, localPath]; } const rest = ref.rest(); if (first.kind === PathElementKind.Root) { return lookupRef(root, List([first]), ref.rest()); } localPath = localPath.push(first); switch (first.kind) { case PathElementKind.Definition: return lookupRef(lookupDefinition(local, first.name), localPath, rest); case PathElementKind.OneOf: return lookupRef(indexArray(local.oneOf, first.index), localPath, rest); case PathElementKind.AnyOf: return lookupRef(indexArray(local.anyOf, first.index), localPath, rest); case PathElementKind.Property: return lookupRef(lookupProperty(local, first.name), localPath, rest); case PathElementKind.AdditionalProperty: return lookupRef(checkStringMap(local.additionalProperties), localPath, rest); case PathElementKind.Items: return lookupRef(checkStringMap(local.items), localPath, rest); default: return assertNever(first); } } function makeClass( schema: StringMap, path: Ref, typeNames: TypeNames, properties: StringMap, requiredArray: string[] ): TypeRef { const required = Set(requiredArray); const result = typeBuilder.getUniqueClassType(getName(schema, typeNames), true); setTypeForPath(path, result); // FIXME: We're using a Map instead of an OrderedMap here because we represent // the JSON Schema as a JavaScript object, which has no map ordering. Ideally // we would use a JSON parser that preserves order. const props = Map(properties).map((propSchema, propName) => { const t = toType( checkStringMap(propSchema), path.push({ kind: PathElementKind.Property, name: propName }), makeTypeNames(pluralize.singular(propName), true) ); const isOptional = !required.has(propName); return new ClassProperty(t, isOptional); }); typeBuilder.setClassProperties(result, props.toOrderedMap()); return result; } function makeMap(path: Ref, typeNames: TypeNames, additional: StringMap): TypeRef { let valuesType: TypeRef | undefined = undefined; let mustSet = false; const result = typeBuilder.getLazyMapType(() => { mustSet = true; return valuesType; }); setTypeForPath(path, result); path = path.push({ kind: PathElementKind.AdditionalProperty }); valuesType = toType(additional, path, typeNames.singularize()); if (mustSet) { (result.deref()[0] as MapType).setValues(valuesType); } return result; } function fromTypeName(schema: StringMap, path: Ref, typeNames: TypeNames, typeName: string): TypeRef { typeNames = getName(schema, typeNames.makeInferred()); switch (typeName) { case "object": let required: string[]; if (schema.required === undefined) { required = []; } else { required = checkStringArray(schema.required); } if (schema.properties !== undefined) { return makeClass(schema, path, typeNames, checkStringMap(schema.properties), required); } else if (schema.additionalProperties !== undefined) { const additional = schema.additionalProperties; if (additional === true) { return typeBuilder.getMapType(typeBuilder.getPrimitiveType("any")); } else if (additional === false) { return makeClass(schema, path, typeNames, {}, required); } else { return makeMap(path, typeNames, checkStringMap(additional)); } } else { return typeBuilder.getMapType(typeBuilder.getPrimitiveType("any")); } case "array": if (schema.items !== undefined) { path = path.push({ kind: PathElementKind.Items }); return typeBuilder.getArrayType( toType(checkStringMap(schema.items), path, typeNames.singularize()) ); } return typeBuilder.getArrayType(typeBuilder.getPrimitiveType("any")); case "boolean": return typeBuilder.getPrimitiveType("bool"); case "string": if (schema.format !== undefined) { switch (schema.format) { case "date": return typeBuilder.getPrimitiveType("date"); case "time": return typeBuilder.getPrimitiveType("time"); case "date-time": return typeBuilder.getPrimitiveType("date-time"); default: return panic(`String format ${schema.format} not supported`); } } return typeBuilder.getStringType(typeNames, undefined); case "null": return typeBuilder.getPrimitiveType("null"); case "integer": return typeBuilder.getPrimitiveType("integer"); case "number": return typeBuilder.getPrimitiveType("double"); default: return panic(`not a type name: ${typeName}`); } } function convertToType(schema: StringMap, path: Ref, typeNames: TypeNames): TypeRef { typeNames = getName(schema, typeNames); function convertOneOrAnyOf(cases: any, kind: PathElementKind.OneOf | PathElementKind.AnyOf): TypeRef { if (!Array.isArray(cases)) { return panic(`oneOf or anyOf is not an array: ${cases}`); } // FIXME: This cast shouldn't be necessary, but TypeScript forces our hand. const types = cases.map( (t, index) => toType(checkStringMap(t), path.push({ kind, index } as any), typeNames).deref()[0] ); return unifyTypes(OrderedSet(types), typeNames, typeBuilder, true, true, conflateNumbers); } if (schema.$ref !== undefined) { const [ref, refName] = parseRef(schema.$ref); const [target, targetPath] = lookupRef(schema, path, ref); return toType(target, targetPath, typeNames.areInferred ? makeTypeNames(refName, true) : typeNames); } else if (schema.enum !== undefined) { return typeBuilder.getEnumType(typeNames, OrderedSet(checkStringArray(schema.enum))); } else if (schema.type !== undefined) { const jsonTypes = checkTypeList(schema.type); if (jsonTypes.size === 1) { return fromTypeName(schema, path, typeNames, defined(jsonTypes.first())); } else { const types = jsonTypes.map(n => fromTypeName(schema, path, typeNames, n).deref()[0]); return unifyTypes(types, typeNames, typeBuilder, true, true, conflateNumbers); } } else if (schema.oneOf !== undefined) { return convertOneOrAnyOf(schema.oneOf, PathElementKind.OneOf); } else if (schema.anyOf !== undefined) { return convertOneOrAnyOf(schema.anyOf, PathElementKind.AnyOf); } else { return typeBuilder.getPrimitiveType("any"); } } function toType(schema: StringMap, path: Ref, typeNames: TypeNames): TypeRef { // FIXME: This fromJS thing is ugly and inefficient. Schemas aren't // big, so it most likely doesn't matter. const immutablePath = makeImmutablePath(path); const maybeType = typeForPath.get(immutablePath); if (maybeType !== undefined) { return maybeType; } const result = convertToType(schema, path, typeNames); setTypeForPath(immutablePath, result); return result; } const rootPathElement: PathElement = { kind: PathElementKind.Root }; const rootType = toType(root, List<PathElement>([rootPathElement]), makeTypeNames(topLevelName, false)); return rootType; }
8925f24410832febe20d959f277392d9504fec30
TypeScript
nghiemnguyen99/IOT
/src/model/users/user.entity.ts
2.640625
3
import { Column, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn, } from "typeorm"; @Entity() class UserBase { @PrimaryGeneratedColumn("uuid") id: string; @Column("text", { nullable: true }) public firstname: string; @Column("text", { nullable: true }) public lastname: string; @Column("text", { nullable: true }) public email: string; @Column("text", { nullable: true }) public password: string; @Column("text", { nullable: true }) public role: string; } export default UserBase;
6d6d8296bc4c4754330e4dd389e47cde6c6193aa
TypeScript
sujeongy/openos
/src/reducer/tree.ts
2.625
3
import { EnodeGubun } from "../enum"; const initialState: TOrganizationState & TFavoriteState = { organizationTreeData: [], organizationExpandedKeys: [], favoriteTreeData: [], favoriteExpandedKeys: [], }; export const SET_ORGANIZATION_TREE_DATA = `tree/SET_ORGANIZATION_TREE_DATA` as const; export const SET_ORGANIZATION_EXPANDED_KEYS = `tree/SET_ORGANIZATION_EXPANDED_KEYS` as const; export const SET_FAVORITE_TREE_DATA = `tree/SET_FAVORITE_TREE_DATA` as const; export const SET_FAVORITE_EXPANDED_KEYS = `tree/SET_FAVORITE_EXPANDED_KEYS` as const; export const setTreeData = (treeData: TTreeNode[], type: string) => ({ type: type === `organization` ? SET_ORGANIZATION_TREE_DATA : SET_FAVORITE_TREE_DATA, payload: treeData, }); export const setExpandedKeys = (keys: (string | number)[], type: string) => ({ type: type === `organization` ? SET_ORGANIZATION_EXPANDED_KEYS : SET_FAVORITE_EXPANDED_KEYS, payload: keys, }); type TTreeAction = | ReturnType<typeof setTreeData> | ReturnType<typeof setExpandedKeys>; export default function tree( state: TOrganizationState & TFavoriteState = initialState, action: TTreeAction ) { switch (action.type) { case SET_ORGANIZATION_TREE_DATA: return { ...state, organizationTreeData: action.payload }; case SET_ORGANIZATION_EXPANDED_KEYS: return { ...state, organizationExpandedKeys: action.payload }; case SET_FAVORITE_TREE_DATA: return { ...state, favoriteTreeData: action.payload }; case SET_FAVORITE_EXPANDED_KEYS: return { ...state, favoriteExpandedKeys: action.payload }; default: return { ...state }; } }
f990bd23ef65f86688999a820699ca75e5b6f1b5
TypeScript
redaktor/nlp
/src/text/nlp/sentence/negate.ts
3.1875
3
"use script"; import _ = require("../_"); //negate makes s sentence mean s opposite thing. function negate(s) { //these are cheap ways to negate s meaning // ('none' is ambiguous because it could mean (all or some) ) let logic_negate = { //some logical ones work "everyone": "no one", "everybody": "nobody", "someone": "no one", "somebody": "nobody", // everything:"nothing", "always": "never", //copulas "is": "isn't", "are": "aren't", "was": "wasn't", "will": "won't", //modals "didn't": "did", "wouldn't": "would", "couldn't": "could", "shouldn't": "should", "can't": "can", "won't": "will", "mustn't": "must", "shan't": "shall", "shant": "shall", "did": "didn't", "would": "wouldn't", "could": "couldn't", "should": "shouldn't", "can": "can't", "must": "mustn't" } //loop through each term.. for (let i = 0; i < s.tokens.length; i++) { let tok = s.tokens[i] // handle ambiguous contractions if (tok.pos_reason === 'ambiguous_contraction') { tok.text = tok.normalised; } //turn 'is' into 'isn't', etc - make sure 'is' isnt followed by a 'not', too if (logic_negate[tok.normalised] && (!s.tokens[i + 1] || s.tokens[i + 1].normalised !== "not")) { tok.text = logic_negate[tok.normalised] tok.normalised = logic_negate[tok.normalised] if (tok.capitalised) { tok.text = _.toTitlecase(tok.text) } return s } // find s first verb.. if (tok.pos.parent === "verb") { // if verb is already negative, make it not negative if (tok.analysis.negative()) { if (s.tokens[i + 1] && s.tokens[i + 1].normalised === "not") { s.tokens.splice(i + 1, 1) } return s } //turn future-tense 'will go' into "won't go" if (tok.normalised.match(/^will /i)) { tok.text = tok.text.replace(/^will /i, "won't ") tok.normalised = tok.text if (tok.capitalised) { tok.text = _.toTitlecase(tok.text) } return s } // - INFINITIVE- // 'i walk' -> "i don't walk" if (tok.analysis.form === "infinitive" && tok.analysis.form !== "future") { tok.text = "don't " + (tok.analysis.conjugate().infinitive || tok.text) tok.normalised = tok.text.toLowerCase() return s } // - GERUND- // if verb is gerund, 'walking' -> "not walking" if (tok.analysis.form === "gerund") { tok.text = "not " + tok.text tok.normalised = tok.text.toLowerCase() return s } // - PAST- // if verb is past-tense, 'he walked' -> "he did't walk" if (tok.analysis.tense === "past") { tok.text = "didn't " + (tok.analysis.conjugate().infinitive || tok.text) tok.normalised = tok.text.toLowerCase() return s } // - PRESENT- // if verb is present-tense, 'he walks' -> "he doesn't walk" if (tok.analysis.tense === "present") { tok.text = "doesn't " + (tok.analysis.conjugate().infinitive || tok.text) tok.normalised = tok.text.toLowerCase() return s } // - FUTURE- // if verb is future-tense, 'will go' -> won't go. easy-peasy if (tok.analysis.tense === "future") { if (tok.normalised === "will") { tok.normalised = "won't" tok.text = "won't" } else { tok.text = tok.text.replace(/^will /i, "won't ") tok.normalised = tok.normalised.replace(/^will /i, "won't ") } if (tok.capitalised) { tok.text = _.toTitlecase(tok.text); } return s } return s } } return s } export = negate
afb51f4d96cd35c0a5a686f0fa1c60b18717a623
TypeScript
xuntee/vscode-sftp
/src/utils.ts
2.765625
3
export function flatten(items) { const accumulater = (result, item) => result.concat(item); return items.reduce(accumulater, []); }
d4efc1a1c73def83e29069db01779183e4a8f27b
TypeScript
KarynaMatsenko/multidesk-server
/src/types/botEventEmitter.ts
2.953125
3
type Arguments<ArgumentArray> = ArgumentArray extends unknown[] ? ArgumentArray : never; type ObjectKeys<Keys> = Keys extends keyof Record<string, unknown> ? Keys : never; export interface ITypedEventEmitter<BotEvents extends Record<string, unknown>> extends NodeJS.EventEmitter { on<Key extends ObjectKeys<keyof BotEvents>>(event: Key, listener: (...args: Arguments<BotEvents[Key]>) => void): this; on<Key extends string | symbol>(event: Exclude<Key, keyof BotEvents>, listener: (...args: unknown[]) => void): this; once<Key extends ObjectKeys<keyof BotEvents>>(event: Key, listener: (...args: Arguments<BotEvents[Key]>) => void): this; once<Key extends string | symbol>(event: Exclude<Key, keyof BotEvents>, listener: (...args: unknown[]) => void): this; emit<Key extends ObjectKeys<keyof BotEvents>>(event: Key, ...args: Arguments<BotEvents[Key]>): boolean; emit<Key extends string | symbol>(event: Exclude<Key, keyof BotEvents>, ...args: unknown[]): boolean; off<Key extends ObjectKeys<keyof BotEvents>>(event: Key, listener: (...args: Arguments<BotEvents[Key]>) => void): this; off<Key extends string | symbol>(event: Exclude<Key, keyof BotEvents>, listener: (...args: unknown[]) => void): this; removeAllListeners<Key extends ObjectKeys<keyof BotEvents>>(event?: Key): this; removeAllListeners<Key extends string | symbol>(event?: Exclude<Key, keyof BotEvents>): this; }
d28ff2525d8e97f231f6b9c65aa7b49a28f326a4
TypeScript
venkataramkishore/angular2rxjs
/src/client/app/shared/models/user.model.ts
2.59375
3
/* *Holds the user information * {"loginId":2,"lastLoginDatetime":null,"userName":"ramkishore@gmail.com", * "approvalFlows":[],"contracts":[],"roleId":1,"role":"Admin","firstName":"Ram","lastName":"Kishore"} */ export class User { public loginId: number; public lastLoginDatetime: string; public userName:string; public firstName: string; public lastName: string; public roleId: number; public role: string; public password: string; constructor() { //TODO:: } }; export class LoginForm { public userName: string; public password: string; constructor() { //TODO:: } };
540c711df8148a1404bb0ec336b42e795448d5b7
TypeScript
blendsdkarchived/dep_blend_ts_version
/src/ui/View.ts
2.703125
3
/// <reference path="../Blend" /> /// <reference path="../layout/Layout" /> /// <reference path="../dom/Dom" /> /// <reference path="../mvc/View" /> /// <reference path="../interface/BoxLayoutInterface" /> /// <reference path="../interface/ViewConfigInterface" /> /// <reference path="../interface/ViewBoundsInterface" /> module Blend.ui { export class View extends Blend.mvc.View { private eventsEnabled: boolean private layoutEnabled: boolean private sizeHash: string private isInALayoutContext: boolean private itemId: string //UI private visible: boolean protected cssClass: string|Array<string> protected borderCssClass: string protected layout: Blend.layout.Layout protected el: HTMLElement protected layoutTriggers: Array<string> /** * Destroys this View by setting the properties to null, * deleting them and removing its HTMLElement */ destroy() { var me = this; if (me.parent || me.el.parentNode) { me.el.parentNode.removeChild(me.el); } else { me.el = null; } Blend.forEach(me, function(value: any, key: string) { (<any>me)[key] = null; delete ((<any>me)[key]); }); } constructor(config?: ViewConfigInterface) { var me = this; super(config); me.isInALayoutContext = false; me.eventsEnabled = true; me.layoutEnabled = true; me.layout = me.createLayout(); me.layoutTriggers = [ 'redo-layout', 'boundsChanged', 'visibilityChanged' ]; me.visible = me.initialConfig.visible; me.borderCssClass = me.initialConfig.border === true ? <string>Blend.cssPrefix('border-normal') : null } protected initConfig(config?: ViewConfigInterface) { var defaultConfig: ViewConfigInterface = { width: null, height: null, top: null, left: null, visible: true, cssClass: null, margins: null, border: false }; return Blend.apply(Blend.apply(super.initConfig(), defaultConfig, true), config || {}, true); } /** * Creates an instance of Blend.layout.Layout for this View */ protected createLayout(): Blend.layout.Layout { return new Blend.layout.Layout({ view: this }); } // CSS class /** * Sets the CSS class names of this View */ setCssClass(value: string|Array<string>|DictionaryInterface) { var me = this; Blend.Dom.cssClass(me.el, value); me.redoLayout(); } /** * Retrives a DictionaryInterface object containing keys of * css class names set to true */ getCssClass() { return Blend.Dom.cssClass(this.el); } // Visibility /** * Sets the visibility state for this View */ setVisible(visible: boolean = true) { var me = this me.visible = Blend.isNullOrUndef(visible) ? true : visible; me.setStyle({ display: visible ? null : 'none' }); me.notifyVisibilityChanged(); } /** * gets the visibility state of this View */ isVisible() { var me = this; return me.visible; } /** * Sends a visibilityChanged notification */ protected notifyVisibilityChanged() { var me = this; me.fireEvent('visibilityChanged', me.visible); } // SIZE AND POSITIONING /** * Returns the bounds of this View based on the ViewBoundsInterface interface */ getBounds(el?: HTMLElement): ViewBoundsInterface { var me = this; el = el || me.getElement(); return Blend.Dom.getBounds(el); } /** * Sets the bounds of this View based on the ViewBoundsInterface interface */ setBounds(bounds: ViewBoundsInterface) { var me = this; me.setStyle(<StyleConfigiInterface>bounds); me.notifyBoundsChanged(); } /** * Sends boundsChanged notification */ notifyBoundsChanged() { var me = this; if (me.layout.isViewRendered()) { me.fireEvent('boundsChanged', me.getBounds()); } } // LAYOUT /** * sets style attributes on this View */ protected setStyle(styles: StyleConfigiInterface, el?: HTMLElement) { var me = this; el = el || me.el || me.getElement(); Blend.Dom.setStyle(el, styles); } /** * Finalizes a layout cycle within this View */ doneLayout() { this.sizeHash = this.getSizeHash(); this.isInALayoutContext = false; } /** * Checks if this View can be placed in a layout cycle */ protected canLayout() { return this.layoutEnabled && this.layout.isViewRendered() && this.visible; } /** * Temporary suspends the layout cycle */ suspendLayout() { this.layoutEnabled = false; } /** * Resumes the layout cycle */ resumeLayout() { this.layoutEnabled = true; } /** * Checks if the size of this View is different that sizeHash. * If so then this View should be placed in a layout cycle */ protected shouldLayout(): boolean { var me = this, cur = me.getSizeHash(); return (me.sizeHash !== cur); } /** * Creates and retrives the current size hash on this View */ private getSizeHash(): string { var me = this, cs = <ViewBoundsInterface>me.getBounds(); return [cs.height, cs.width].join('-'); } /** * Performs the actual layout peration on thie View */ protected layoutView() { this.layout.performLayout.apply(this.layout, arguments); } /** * Put this View in a parent layout context by passing true * or false otherwise */ placeInALayoutContext(state: boolean) { this.isInALayoutContext = state; } /** * Initiates a layout cycle on this View */ performLayout() { var me = this; if (me.canLayout()) { me.suspendLayout(); if (me.shouldLayout()) { me.layoutView.apply(me, arguments); } me.resumeLayout(); } } /** * Initiates a layout cycle based on an event. This function also checks * whether the view is currently part of an existing layout cycle. * If the component is part on a layout cycle then its native performLayout is * called, otherwise if it has a parent then the layout cycle will be deligated * from there. */ private handleLayoutTriggers(eventName: string) { var me = this; // only fire and event when the component is rendered and ready if (me.layoutTriggers.indexOf(eventName) !== -1 && me.canLayout()) { if (!me.isInALayoutContext && me.parent) { (<View>me.parent).invalidateLayout(); (<View>me.parent).performLayout(); } else { me.performLayout(); } } } /** * Makes sure the layout state is invalid so it can be placed in * the next layout cycle */ invalidateLayout(performLayout?: boolean) { var me = this; me.sizeHash = null; if (performLayout === true) { me.performLayout(); } } // INTERNAL EVENTS /** * Internal notification to initiate a layout cycle. This method * is used when the View has to replayout but no external event * should be fired */ protected redoLayout() { this.fireEvent('redo-layoyt'); } protected fireEvent(eventName: string, ...args: any[]) { /** * Override of the fireEvent function to trigger * performLayout on registered events. */ var me = this; if (me.layout.isViewRendered() === true && me.canFireEvents()) { me.handleLayoutTriggers(eventName); if (eventName !== 'redo-layout') { super.fireEvent.apply(me, arguments); } } } /** * Disables the event and notification on this View */ protected dispableEvents() { this.eventsEnabled = false; } /** * Enables the event and notification on this view */ protected enableEvents() { this.eventsEnabled = true; } /** * Checks if the events are enabled */ protected canFireEvents() { return this.eventsEnabled; } /** *Helps configuring the thsi View before the rendering cycle is complete */ protected finalizeRender() { var me = this, cssClass = [] .concat(Blend.wrapInArray(me.cssClass)) .concat(Blend.wrapInArray(me.borderCssClass)) .concat(Blend.wrapInArray(me.initialConfig.cssClass)); me.setVisible(me.initialConfig.visible); me.setCssClass(cssClass); me.setBounds({ width: me.initialConfig.width, height: me.initialConfig.height, top: me.initialConfig.top, left: me.initialConfig.left, }); } /** * Retrives the HTMLElement for this View */ getElement(): HTMLElement { var me = this; if (!me.layout.isViewRendered()) { me.el = me.layout.render(); me.dispableEvents(); me.finalizeRender(); me.enableEvents(); } return me.el; } } }
2a2a816dee863fc99a62ae3a9224b2ee8b61e380
TypeScript
nachoscocco/demo-typescript
/11)tipo-retorno-func.ts
3.15625
3
(()=>{ const sumar = ( s1: number, s2: number): number =>s1 + s2; const nombre = ():string => 'Hola Nacho'; const obtenerSalario = ():Promise<string> =>{ return new Promise ((resolve,reject)=>{ resolve('Nacho'); reject('scocco'); }); } obtenerSalario() .then( a => console.log(a.toUpperCase())); })();
e1b0fb5f4b44db35f37487d935db9581338f02ee
TypeScript
isaacdomini/branches_front_end_private
/app/objects/sigmaNode/sigmaNodeHelpers.ts
2.875
3
import { decibels, percentage_as_decimal, seconds, timestamp } from '../interfaces'; import {calculateRecall} from '../../forgettingCurve'; export function calculatePercentOpacity( { lastReviewTime, lastEstimatedStrength, now }: { lastReviewTime: timestamp, lastEstimatedStrength: decibels, now: timestamp }) { const timeSinceLastRecall: seconds = (now - lastReviewTime) / 1000 const estimatedCurrentRecall: percentage_as_decimal = calculateRecall({ S: lastEstimatedStrength, t: timeSinceLastRecall }) const MAX_OPACITY = 1 const MIN_OPACITY = .4 // make sure color is never invisible or too hard to see const opacity = MIN_OPACITY + (estimatedCurrentRecall) * (MAX_OPACITY - MIN_OPACITY) return opacity } /** * * @source https://stackoverflow.com/questions/1573053/javascript-function-to-convert-color-names-to-hex-codes */ export function colorToRGBA(color) { // Returns the color as an array of [r, g, b, a] -- all range from 0 - 255 // color must be a valid canvas fillStyle. This will cover most anything // you'd want to use. // Examples: // colorToRGBA('red') # [255, 0, 0, 255] // colorToRGBA('#f00') # [255, 0, 0, 255] let cvs, ctx; cvs = document.createElement('canvas'); cvs.height = 1; cvs.width = 1; ctx = cvs.getContext('2d'); ctx.fillStyle = color; ctx.fillRect(0, 0, 1, 1); return ctx.getImageData(0, 0, 1, 1).data; }
e3b842ab64d490030dfae0039263de17601fd03d
TypeScript
FF3300-studio/hackustica-pattern-generator-a
/src/ts-old-2/tiles/wave.ts
3.0625
3
import paper from "paper"; import { interpolate_points } from "../geometry/interpolation"; import { Line, line_from_p_a } from "../geometry/line"; export function curve_squaring_handles( p0: paper.Point, p1: paper.Point, a0: number, a1: number, s: number ): Array<paper.Point> { // We need to calculate the intersection point between the two handles // So we can apply the squaring // Lines const l0: Line = line_from_p_a(p0, a0); const l1: Line = line_from_p_a(p1, a1); // Getting the intersection const pI = l0.intersect(l1); // Getting the handles const p0h: paper.Point = interpolate_points(p0, pI, s); const p1h: paper.Point = interpolate_points(p1, pI, s); return [p0h, p1h]; } export function wave_v_half_base( p1: paper.Point, a: number, s: number, t: number ): paper.Path { try { if (p1.quadrant != 1) throw "The point must be positive!"; // P0 is the origin const p0 = new paper.Point(0, 0); // We have to extend points according to thickness // So we define some translation vector const t0 = new paper.Point(t / 2, 0); const t1 = new paper.Point(t / 2.1, 0).rotate( a - 90, new paper.Point(0, 0) ); // Points on the inner side const p0_i = p0.add(t0); const p1_i = p1.add(t1); // Getting the inner handles const [p0_ih, p1_ih] = curve_squaring_handles(p0_i, p1_i, 90, a, s); // The angle between the line that connects p0_i–p1_i // and any internal handle should be > 0 if (p1_i.subtract(p0_i).angle > p0_ih.subtract(p0_i).angle) { throw new Error("The flesso angle should be smaller!"); } // Points on the outer side const p0_o = p0.subtract(t0); const p1_o = p1.subtract(t1); // Getting outer handles const [p0_oh, p1_oh] = curve_squaring_handles(p0_o, p1_o, 90, a, s); // Drawing const path = new paper.Path(); path.moveTo(p0_i); path.cubicCurveTo(p0_ih, p1_ih, p1_i); path.lineTo(p1_o); path.cubicCurveTo(p1_oh, p0_oh, p0_o); path.closePath(); return path; } catch (error) { throw new Error(error); } } export function wave_v_half( p0: paper.Point, p1: paper.Point, a: number, s: number, t: number ): paper.Path { // We calculate the vector between p0 and p1 const v = p1.subtract(p0); // And we make it absolute const v_abs = v.abs(); // We call the base shape function const path = wave_v_half_base(v_abs, a, s, t); // We flip it accordingly to signs path.scale(Math.sign(v.x), Math.sign(v.y), new paper.Point(0, 0)); // And then we translate it to the origin path.translate(p0); return path; } export function wave_v( p0: paper.Point, w: number, h: number, a: number, s: number, t: number ): paper.Path { // Calculating the halfway anchor const p1 = p0.add(new paper.Point(w, h / 2)); // Calculating the flesso point const pI = interpolate_points(p0, p1, 0.5); // Getting the two halves const half_0 = wave_v_half(p0, pI, a, s, t); const half_1 = wave_v_half(p1, pI, a, s, t); // Merging them const wave_top = half_0.unite(half_1); // Copying it and flipping it const wave_bot = <paper.Path>wave_top.clone(); wave_bot.scale(1, -1, p1); return <paper.Path>wave_top.unite(wave_bot); } export function tile_wave_v( o: paper.Point, w: number, h: number, d: number, t: number = 0.25, a: number = 0, s: number = 0.56 ): paper.Path { // Calculating starting point const p = new paper.Point(o.x + w / 2, o.y); // Calculating thickness const tck = (t * w) / 2; // Check angle return wave_v(p, (d * w) / 4, h, a, s, tck); }
46ec45c813a5d360fac8355cb46aec7b2f02efe0
TypeScript
caotsinghua/rnnote
/app/utils/request.ts
2.546875
3
// import Storage from './storage' import qs from 'qs' import Toast from 'react-native-root-toast' const defaultHeaders = { 'Content-Type': 'application/json; charset=UTF-8' } const statusMessageMap = { 400: '请求错误', 401: '未授权,请登录', 403: '拒绝访问', 404: '请求地址出错', 408: '请求超时', 413: '上传文件过大!', 500: '服务器内部错误', 501: '服务未实现', 502: '网关错误', 503: '服务不可用', 504: '网关超时', 505: 'HTTP版本不受支持' } class Request { baseUrl: string constructor({ baseUrl = '' }) { this.baseUrl = baseUrl } request( { url, method = 'get', params, data, headers = defaultHeaders, ...otherOptions }: { url: string data?: any method?: string params?: any headers?: any }, qsStringifyOptions = {} // qs.stringify的配置 ) { let requestUrl = `${this.baseUrl}/${url}` const query = qs.stringify(params, qsStringifyOptions) if (requestUrl.indexOf('?') > -1) { requestUrl = `${requestUrl}&${query}` } else { requestUrl = `${requestUrl}?${query}` } return fetch(requestUrl, { method, body: data, // post时使用 headers, ...otherOptions }) .then(res => { return this.handleResponse(res) // 处理response }) .catch(e => { return this.handleError(e) }) } handleResponse(response: Response) { return this.checkStatus(response).then(res => { return res.json() }) } handleError(error: any) { if (error.message === 'Network request failed') { Toast.show('网络离线,请联网后重试.', { duration: Toast.durations.LONG }) } else if (error.response && error.message) { Toast.show(error.message, { duration: Toast.durations.LONG }) } } checkStatus(response: Response): Promise<Response> { return new Promise((resolve, reject) => { if (response.status >= 200 && response.status < 300) { resolve(response) } else { let message = (statusMessageMap as any)[response.status] || response.statusText reject({ response, message }) } }) } } export default Request
df19b6c0843ffe41eb4a5560ddbb5f7d7f1ef110
TypeScript
geriley/cooper-pantry
/apps/api/src/app/entities/address.entity.ts
2.53125
3
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class Address { @PrimaryGeneratedColumn() public id: number; @Column() public address1: string; @Column({ nullable: true }) public address2: string; @Column() public city: string; @Column() public state: string; @Column() public zipcode: string; }
7b4ae54bdf8d0a531bffbc7e7d921bb7cfc80ed3
TypeScript
ldh2016/test
/testExtends/src/Animal.ts
3.1875
3
/* * 动物类; */ class Animal { /**动物名字*/ public name: string; constructor() { } /**动物外形(每个动物外形不一样的 所以要在子类重写)*/ public setSkin(): void { } /**动物跑的方法*/ public run(): void { } }
83863826661f521c9489af7ee017db5784643056
TypeScript
markostj/angular-todos
/src/app/modules/todos/store/todo.reducer.ts
2.671875
3
import { createReducer, on } from '@ngrx/store'; import { addTodo, deleteTodo, updateCompletion, updateTodo, } from './todo.action'; import { Todo } from '../models/todo'; export interface State { todos: Todo[]; } export const initialState: State = { todos: [], }; export const todosReducer = createReducer( initialState, on(addTodo, (state, actions) => { return { ...state, todos: [...state.todos, actions] }; }), on(deleteTodo, (state, actions) => { return { ...state, todos: state.todos.filter((todo) => todo.id !== actions.id), }; }), on(updateCompletion, (state, actions) => { return { ...state, todos: state.todos.map((todo) => todo.id === actions.id ? { ...todo, completed: !todo.completed } : todo ), }; }), on(updateTodo, (state, actions) => { return { ...state, todos: state.todos.map((todo) => todo.id === actions.id ? { ...todo, name: actions.name, date: actions.date, completed: actions.completed, } : todo ), }; }) );
46a1eee2940cc5e180db35b7988c1dea58c19ba1
TypeScript
jeuvreyl/factorio-calc
/src/app/calc/shared/assembling-machine.model.ts
2.609375
3
interface AssemblingMachineObject { name: string; iconUrl: string; craftingSpeed: number; ingredientCount: number; craftingCategories: Array<string>; recipe: string; } export type AssemblingMachine = Readonly<AssemblingMachineObject>;
4a27b22b752d4297502717dbdacc752d834e560b
TypeScript
Bhaikko/recipe-angular-app
/src/app/shared/ingredient.model.ts
2.6875
3
export class Ingredient { // A shortcut for defining constructor along with its memebers constructor (public name: string, public amount: number) {} }
cd70474cecfaadadec57ab1c329a844c962992b8
TypeScript
SamA21/TM470-20B-SA
/TM470/ClientApp/src/app/venues/components/create-venue.ts
2.546875
3
import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import $ from 'jquery'; import 'bootstrap'; @Component({ selector: 'create-venue', templateUrl: './create-venue.html' }) export class CreateVenueComponent { public venue: VenueViewModel; public ErrorMessageShow: boolean; private _http: HttpClient; private _baseUrl: string; constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) { this._http = http; this._baseUrl = baseUrl; this.venue = <VenueViewModel>{}; this.ErrorMessageShow = false; } public CreateVenue() { $('#CreateVenueForm').modal(); } public SubmitVenue() { this.ErrorMessageShow = false; this.venue.name = $("#VenueName").val(); this.venue.location = $("#VenueLocation").val(); var capacity = $("#VenueCapacity").val(); if (parseInt(capacity) != NaN) { this.venue.capacity = parseInt(capacity); var url = this._baseUrl + 'venues' + '/SubmitNewVenue'; this._http.post<VenueResult>(url, { Name: this.venue.name, Location: this.venue.location, Capacity: this.venue.capacity }) .subscribe(result => { if (result.message == "Created new Venue") { window.location.reload(); } else { this.ErrorMessageShow = true; } }, error => console.error(error)); } else { this.ErrorMessageShow = true; } } } interface VenueViewModel { name: string; location: string; capacity: number; } interface VenueResult { message: string; }
f82059796b31db295c246864520b04e2b8570692
TypeScript
baahrens/react-md
/packages/transition/src/useTransition.ts
3
3
import { Dispatch, RefCallback, useEffect, useReducer, useRef } from "react"; import { useEnsuredRef } from "@react-md/utils"; import { ENTER, ENTERED, ENTERING, EXIT, EXITED, EXITING, TransitionAction, TransitionStage, UNMOUNT, } from "./constants"; import { getNextStage } from "./getNextStage"; import { getTimeout } from "./getTimeout"; import { getTimeoutDuration } from "./getTimeoutDuration"; import { TransitionOptions } from "./types"; export interface TransitionState { /** * The current stage for the transition. This probably won't be used too much * unless you want to apply custom classnames based on the stage. */ stage: TransitionStage; /** * Boolean if the component should be rendered in the DOM. This will always be * `true` if the `temporary` option is omitted or `false`. Otherwise, it will * be `true` during the transitions and entered. */ rendered: boolean; /** * Boolean if the transition is in the initial mounting/appearing stage while * entering. This will be `false` if the `appear` option is `false` and * automatically set to `false` after the first transition if `appear` was * `true`. */ appearing: boolean; } export interface TransitionReturnValue<E extends HTMLElement> extends TransitionState { /** * A ref that must be passed to a DOM node for the transition to work. This * _technically_ should not need to be passed to a DOM node for non-css * transitions or transitions that do not require access to a DOM node, but it * it seems like too much work to make it conditional for those types for * transitions. */ ref: RefCallback<E>; /** * A dispatch function that cna update the transition state manually. This * should really not be used too much unless your transition is for appear * only transitions. For those cases, you can watch for a value change and * just trigger the ENTER transition again: * * ```ts * const prevThing = useRef(thing); * if (thing !== prevThing.current) { * prevThing.current = thing; * dispatch(ENTER); * } * ``` * * Note: This **should be dispatched during the render** to get the correct * timing. */ dispatch: Dispatch<TransitionAction>; } /** * * @internal */ const reducer = ( state: TransitionState, action: TransitionAction ): TransitionState => { switch (action) { case ENTER: case ENTERING: case EXIT: case EXITING: case EXITED: return { ...state, rendered: true, stage: action }; case ENTERED: return { rendered: true, stage: action, appearing: false }; case UNMOUNT: return { stage: EXITED, rendered: false, appearing: false }; default: return state; } }; /** * * @internal */ const INITIAL_STATE: TransitionState = { appearing: false, rendered: true, stage: ENTERED, }; /** * * @internal */ const getInitialState = ( transitionIn: boolean, temporary: boolean, appear: boolean ): (() => TransitionState) => () => { return { rendered: !temporary || transitionIn, appearing: appear && transitionIn, stage: transitionIn && !appear ? ENTERED : EXITED, }; }; /** * This is heavily inspired by the `Transition` component from * `react-transition-group` since it's really just a hook version of it. * * This hook allows you to transition between an enter and exit state with * defined timeouts, but you'll most likely be looking for the * `useCSSTransition` instead. * * @param options - All the options used for the transition. * @returns An object describing the current transition stage and props that * should be passed to a component. */ export function useTransition<E extends HTMLElement = HTMLDivElement>({ appear = false, repaint = false, temporary = false, transitionIn, timeout: propTimeout, onEnter, onEntering, onEntered, onExit, onExiting, onExited, ref: propRef, }: TransitionOptions<E>): TransitionReturnValue<E> { const [{ stage, rendered, appearing }, dispatch] = useReducer( reducer, INITIAL_STATE, getInitialState(transitionIn, temporary, appear) ); // need to store in mutable ref since these are mostly going to be arrow // functions and shouldn't cause the transitions to change const handlers = useRef({ onEnter, onEntering, onEntered, onExit, onExiting, onExited, }); useEffect(() => { handlers.current = { onEnter, onEntering, onEntered, onExit, onExiting, onExited, }; }); const timeout = getTimeout(propTimeout, appear); const [nodeRef, refHandler] = useEnsuredRef(propRef); const disableEnterExitTransition = useRef(!appear || !transitionIn); // this effect handles the transition from: // - EXITED -> ENTER // - ENTERED -> EXIT // - EXITED -> ENTERED (when enter timeout is 0) // - ENTERED -> EXITED (when exit timeout is 0) // // all the dependencies are ignored except for `transitionIn` since the // other values changing would actually cause more bugs and this effect // really doesn't care if they changed. useEffect(() => { // should never trigger a transition on mount unless both the `appear` and // `transitionIn` are enabled for the appear transition if (disableEnterExitTransition.current) { disableEnterExitTransition.current = false; return; } let duration = 0; if (transitionIn) { duration = appearing ? timeout.appear : timeout.enter; } else { duration = timeout.exit; } if (duration > 0) { dispatch(transitionIn ? ENTER : EXIT); } else { dispatch(transitionIn ? ENTERED : EXITED); } // see comment above about why it's only `transitionIn` // eslint-disable-next-line react-hooks/exhaustive-deps }, [transitionIn]); const isFirstRender = useRef(true); // this effect handles the transitions for: // - ENTER -> ENTERING // - ENTERING -> ENTERED // - EXIT -> EXITING // - EXITING -> EXIT useEffect(() => { // need to skip the effects on first render since it should only be called // after a transition change if (isFirstRender.current) { isFirstRender.current = false; return; } const node = nodeRef.current; if (node) { if (repaint && stage !== EXITED && stage !== ENTERED) { // force repaint for CSS transitions // eslint-disable-next-line no-unused-expressions node.scrollTop; } const { onEnter, onEntering, onEntered, onExit, onExiting, onExited, } = handlers.current; switch (stage) { case ENTER: if (onEnter) { onEnter(node, appearing); } break; case ENTERING: if (onEntering) { onEntering(node, appearing); } break; case ENTERED: if (onEntered) { onEntered(node, appearing); } break; case EXIT: if (onExit) { onExit(node); } break; case EXITING: if (onExiting) { onExiting(node); } break; case EXITED: if (onExited) { onExited(node); } break; // no default } } const nextStage = getNextStage(stage); if (stage === nextStage) { if (stage === EXITED && temporary) { dispatch(UNMOUNT); } return; } const duration = getTimeoutDuration( stage, timeout.appear, timeout.enter, timeout.exit, appearing ); if (duration <= 0) { dispatch(nextStage); return; } const dispatchTimeout = window.setTimeout(() => { dispatch(nextStage); }, duration); return () => { window.clearTimeout(dispatchTimeout); }; }, [ nodeRef, appearing, repaint, stage, temporary, timeout.appear, timeout.enter, timeout.exit, ]); return { ref: refHandler, stage, rendered, appearing, dispatch, }; }
afd935a598c5afa68b655e843bbab8239987ff96
TypeScript
project-koku/koku-ui
/src/store/priceList/selectors.ts
2.6875
3
import type { RootState } from 'store/rootReducer'; import { stateKey } from './reducer'; export const getRateTierTimeRange = (unit: string) => { const sep = unit.split('-'); if (sep.length === 2) { return { unit: sep[0], range: sep[1] }; } return { unit: null, period: null }; }; export const rateFlatter = rate => { return rate.rates .map(rt => { const time_range = getRateTierTimeRange(rt.metric.label_measurement_unit); return rt.tiered_rates.map((tier, ix) => { return { source_uuids: rate.sources.map(provider => provider.uuid), display: `${rt.metric.label_metric.toLowerCase()} ${rt.metric.label_measurement.toLowerCase()} rate`, metric_type: rt.metric.name, index: ix, value: tier.value, value_unit: tier.unit, range_value: [tier.usage.usage_start, tier.usage.usage_end], range_unit: time_range.unit, period: time_range.range, }; }); }) .map(r => r[0]); }; export const priceList = (state: RootState) => state[stateKey]; export const cachedRates = (state: RootState, providerUuid: string) => { if (priceList(state).rates && priceList(state).rates.get(providerUuid)) { return priceList(state).rates.get(providerUuid); } return null; }; export const rates = (state: RootState, providerUuid: string) => { const cachedData = cachedRates(state, providerUuid); if (cachedData) { return cachedData.data; } return []; }; export const ratesPerProvider = (state: RootState, providerUuid: string) => rates(state, providerUuid) && rates(state, providerUuid) .map(rateFlatter) .reduce((acc, rateArray) => { return [...acc, ...rateArray]; }, []) .reduce((acc, rate) => { let next = { ...acc }; rate.source_uuids.forEach(uuid => { const prev = acc[uuid] || []; next = { ...next, [uuid]: [...prev, rate], }; }); return next; }, {}); export const status = (state: RootState, providerUuid: string) => { return priceList(state).status.get(providerUuid); }; export const error = (state: RootState, providerUuid: string) => priceList(state).error.get(providerUuid);
60df72f0e88f84c881e3db7a02f612a9882151e3
TypeScript
vickenstein/express-association
/src/controller/ApplicationError.ts
2.65625
3
import * as ExtendableError from 'es6-error' // @ts-ignore: ExtendableError miss match imported interface export class ApplicationError extends ExtendableError { _log: string message: string stack: any ['constructor']: typeof ApplicationError static status: number constructor(message: any = 'There was an error', log?: any) { super(message) this._log = log } get type() { return this.constructor.name } get status() { return this.constructor.status || 500 } get log() { return this._log || this.message } }
b9fdb7db2750af9c3efca4fb7500c377dbe15bb9
TypeScript
future4code/Pedro-Sekine
/5-modulo/17-bloco/LabECommerce/src/endpoints/createProduct.ts
2.828125
3
import { connection } from "../connection"; import { Request, Response } from "express"; import { v4 as generateID } from "uuid"; const errors = { MISSING_DATA_BODY: { status: 400, message: "Body of the request must contain name, price and imageURL.", }, PRICE_NAN: { status: 400, message: "Price must be a number.", }, }; export const createProduct = async (req: Request, res: Response) => { try { const { name, price, imageURL } = req.body; if (!name || !price || !imageURL) { throw new Error(errors.MISSING_DATA_BODY.message); } if (isNaN(price)) { throw new Error(errors.PRICE_NAN.message); } await connection("labecommerce_products") .insert({ id: generateID(), name, price: Number(price), image_url: imageURL }) res.status(201).send("Product created successfully") } catch (err: any) { switch (err.message) { case errors.MISSING_DATA_BODY.message: res .status(errors.MISSING_DATA_BODY.status) .send(errors.MISSING_DATA_BODY.message); break; case errors.PRICE_NAN.message: res.status(errors.PRICE_NAN.status).send(errors.PRICE_NAN.message); break; } } };
13fb9b52e7d8acc8777b22a0dc4fddba871d5821
TypeScript
Jebiel/mobile_computing_project
/models/AutocompleteResult.ts
2.53125
3
export interface AutocompleteResult { type: string; geocoding: AutocompleteResultGeocoding; intentions: any[]; features: Feature[]; } export interface Feature { type: string; geometry: Geometry; properties: Properties; distance: number; } export interface Geometry { coordinates: number[]; type: string; } export interface Properties { geocoding: AddressClass; } export interface AddressClass { type: Type; label: string; name: string; postcode: null | string; city: any; // Test this at a later point (City) id: string; citycode: string; administrativeRegions: AdministrativeRegion[]; poiTypes?: PoiType[]; properties?: Property[]; address?: AddressClass; countryCodes: any[]; // Test this at a later point (CountryCode[]) street?: string; housenumber?: string; } export interface AdministrativeRegion { id: any; // Test this at a later point (ID) insee: string; level: number; label: any; // Test this at a later point name: any; // Test this at a later point (AdministrativeRegionName) zipCodes: any[]; coord: Coord; bbox: number[]; zoneType: ZoneType; parentID: any | null; // Test this at a later point codes: Code[]; } export interface Code { name: any; // Test this at a later point value: string; } export interface Coord { lon: number; lat: number; } export enum ZoneType { City = "city", Country = "country", State = "state", } export interface PoiType { id: string; name: string; } export interface Property { key: string; value: string; } export enum Type { House = "house", Poi = "poi", Street = "street", } export interface AutocompleteResultGeocoding { version: string; query: string; }
6c34cc3b5f7cca25ba7bf655c141eda19e4fa856
TypeScript
Quang-Nhan/JSXPath
/ts/index.spec.ts
2.90625
3
import { runPath, runPaths } from './index'; const getTestDescription = (result) => { return result.description ? `${result.path}: ${result.description}` : result.path; } describe('Misc Tests' , () => { let json; describe('Array of mixed values', () => { beforeEach(() => { json =[1 , "2", {o: 3}, [{a: 4.1}, {b: 5.2}, {a: 6.6}]]; }); it('', () => { runPaths([ { path: '/*[2]', then: (result) => { expect(result.value).toEqual(['2']); } }, { path: '/*/o', then: (result) => { expect(result.value).toEqual([3]); } }, { path: '/*[4]', description: 'from root, get the fourth positioned value', then: (result) => { expect(result.value).toEqual([[{a: 4.1}, {b: 5.2}, {a: 6.6}]]); } }, { path: '/*[4]/*', description: 'get all the node values within the array', then: (result) => { expect(result.value).toEqual([{a: 4.1}, {b: 5.2}, {a: 6.6}]); } }, { path: '/*[4]/*[a]', description: 'filter and display a nodes', then: (result) => { expect(result.value).toEqual([{a: 4.1}, {a: 6.6}]); } }, { path: '/*[4]/*[a]/a', description: 'filter and display a node values', then: (result) => { expect(result.value).toEqual([4.1, 6.6]); } } ], {json}); }); }); });
ec3223e6afa34ff1e278ae81426de0edbff6fcf3
TypeScript
cyjo9603/chalkak
/front/src/reducers/user/updateUserInfo.ts
2.75
3
export const UPDATE_USER_INFO_REQUEST = 'UPDATE_USER_INFO_REQUEST' as const; export const UPDATE_USER_INFO_SUCCESS = 'UPDATE_USER_INFO_SUCCESS' as const; export const UPDATE_USER_INFO_FAILURE = 'UPDATE_USER_INFO_FAILURE' as const; export interface UpdateInfo { familyName?: string; firstName?: string; birth?: string; phone?: string; mail?: string; profilePhoto?: string; } export interface UpdateUserInfoRequest { type: typeof UPDATE_USER_INFO_REQUEST; data: UpdateInfo; } export interface UpdateUserInfoSuccess { type: typeof UPDATE_USER_INFO_SUCCESS; data: UpdateInfo; } export interface UpdateUserInfoFailure { type: typeof UPDATE_USER_INFO_FAILURE; error: string; } export const updateUserInfoRequest = (data: UpdateInfo): UpdateUserInfoRequest => ({ type: UPDATE_USER_INFO_REQUEST, data, }); export const updateUserInfoSuccess = (data: UpdateInfo): UpdateUserInfoSuccess => ({ type: UPDATE_USER_INFO_SUCCESS, data, }); export const updateUserInfoFailure = (error: string): UpdateUserInfoFailure => ({ type: UPDATE_USER_INFO_FAILURE, error, }); export type UpdateUserInfo = UpdateUserInfoRequest | UpdateUserInfoSuccess | UpdateUserInfoFailure;
0c44d8024e7e3b1f092aba91bbc897eb0aff44e9
TypeScript
cometkim/re-typescript
/ts_inspiration/___to_fix.d.ts
4.0625
4
interface Dictionary<T> { [key: string]: T; } export let keys: keyof Dictionary<number>; // string | number export let value: Dictionary<number>["foo"]; // number ////////////////////////////////////////////////////////// type TypeName<T> = T extends string ? "string" : T extends number ? "number" : T extends boolean ? "boolean" : T extends undefined ? "undefined" : T extends Function ? "function" : "object"; type T0 = TypeName<string>; // "string" type T1 = TypeName<"a">; // "string" type T2 = TypeName<true>; // "boolean" type T3 = TypeName<() => void>; // "function" type T4 = TypeName<string[]>; // "object" ////////////////////////////////////////////////////////// interface A { x: string; y: number; z: boolean; } type Exclude<T, U> = T extends U ? never : T; type stripped = Exclude<keyof A, "y">; export enum StringEnum { A = "A", B = "B", } export enum NumberEnum { A, B, } ////////////////////////////////////////////////////////// type StrictNumericEnumParam< Enum extends number, Param extends Enum > = true extends ({ [key: number]: false } & { [P in Enum]: true })[Enum] ? true extends ({ [key: number]: false } & { [P in Enum]: true })[Param] ? Param : never : Enum; export enum Foo { A, B, C, } export enum Bar { D, E, F, } // typically would be written as function doFoo(value: Foo): void declare function doFoo<Value extends Foo>( value: StrictNumericEnumParam<Foo, Value> ): void; declare const foo: Foo; declare const bar: Bar; declare const n: number; type x = "xxx" extends string ? true : false;
aa32abe71fdb279f3ab478288ba2a19ef31eeee1
TypeScript
hachi-eiji/sandbox-todo-app
/mock-api/src/tasks/tasks.service.ts
2.71875
3
import { Injectable } from '@nestjs/common'; import { Task } from './task'; @Injectable() export class TasksService { findAll(): Task[] { const result = []; const date = new Date(2020, 0, 1); for (let i = 0; i < 9; i++) { result.push({ id: i * 100, title: `タイトル${i}`, description: `めっちゃ長い説明なんだけど...そうだね説明${i}`, due_date: `${date.getFullYear()}-0${date.getMonth() + 1}-0${date.getDate()}T00:00`, }); } result.push({ id: 10, title: 'タイトル10', description: '説明10', due_date: null, }); return result; } create() { return { status: '201', message: 'ok' }; } update() { return { status: 200, message: 'ok', }; } delete() { return { status: 200, }; } }
a87412962e96275c2c2174034e74fd6b065b5bda
TypeScript
nguyer/aws-sdk-js-v3
/clients/node/client-codedeploy-node/types/_InstanceInfo.ts
2.921875
3
import { _Tag, _UnmarshalledTag } from "./_Tag"; /** * <p>Information about an on-premises instance.</p> */ export interface _InstanceInfo { /** * <p>The name of the on-premises instance.</p> */ instanceName?: string; /** * <p>The ARN of the IAM session associated with the on-premises instance.</p> */ iamSessionArn?: string; /** * <p>The IAM user ARN associated with the on-premises instance.</p> */ iamUserArn?: string; /** * <p>The ARN of the on-premises instance.</p> */ instanceArn?: string; /** * <p>The time at which the on-premises instance was registered.</p> */ registerTime?: Date | string | number; /** * <p>If the on-premises instance was deregistered, the time at which the on-premises instance was deregistered.</p> */ deregisterTime?: Date | string | number; /** * <p>The tags currently associated with the on-premises instance.</p> */ tags?: Array<_Tag> | Iterable<_Tag>; } export interface _UnmarshalledInstanceInfo extends _InstanceInfo { /** * <p>The time at which the on-premises instance was registered.</p> */ registerTime?: Date; /** * <p>If the on-premises instance was deregistered, the time at which the on-premises instance was deregistered.</p> */ deregisterTime?: Date; /** * <p>The tags currently associated with the on-premises instance.</p> */ tags?: Array<_UnmarshalledTag>; }
8f5760f0d826548dcf8c9265bdd67ed6f929ddf1
TypeScript
ZedTT/ReStyle
/ReStyle-Backend/src/routes/tradeRequestRoutes.ts
2.59375
3
import { Express } from "express"; import { getIncomingTradeRequestsForUser, updateTradeRequestStatus } from '../controllers/tradeControllers'; const tradeRequestRoutes = (app: Express) => { /** * Routes for trade request inbox page. */ app.route('/api/traderequests') // To get all the incoming pending requests where a currently logged-in user is a notified user. .get((request, response) => { getIncomingTradeRequestsForUser(response, request.query.uid); }) // To change a status of a specific trade request. .post((request, response) => { const tradeRequestId = request.body.tradeRequestId; const status = request.body.status; updateTradeRequestStatus(response, tradeRequestId, status) }) } export default tradeRequestRoutes;
65208de5a65712213738c3ac6c384c282b37bcb7
TypeScript
kristianmandrup/typescript-ast-processor
/packages/node-matcher/src/occurrence.ts
3.046875
3
import { createCountingASTNodeTraverser } from '@tecla5/qast-traverser' import { isNonEmptyStr, isEmpty } from './_util' import { BaseNodeTester } from './base' export interface INodeOccurrenceTester { countInTree(query: any): number countOccurrence(options: any): number } export function createNodeOccurrenceTester(node: any, options: any = {}) { return new NodeOccurrenceTester(node, options) } /** * Counts occurences of specific types (or categories) of nodes * Within an AST sub-structure */ export class NodeOccurrenceTester extends BaseNodeTester { factories: any constructor(node: any, options: any = {}) { super(node, options) this.factories = options.factories } /** * * @param nodeType */ findFirst(nodeType: any) { return this.createNodeTraverser(this.options).findFirst(nodeType) } /** * Create a Node traverser for additional information gathering in subtrees, * such as counting specific nodes * @param options */ createNodeTraverser(options: any = {}) { const createNodeTraverser = options.createNodeTraverser || createCountingASTNodeTraverser return createNodeTraverser(options) } /** * Count occurences in sub tree(s) under this node * Call ASTNodeTraverser with traverseQuery to control which nodes to exclude/include in visit count * * TODO: Needs improvement/fix * * query: * - nodeTypes: * - toCount * - toExclude * * @param traverseQuery */ countInTree(query: any, type: string = 'visited'): number { const opts = { ...this.options, query, node: this.node, } const counter = this.counter(opts) return counter[type] || 0 } /** * Visit all nodes in AST sub-tree * @param opts */ visited(opts = {}) { const nodeTraverser = this.createNodeTraverser(opts) nodeTraverser.visit() return nodeTraverser } /** * Get the traverse counter map after having visited all nodes in AST sub-tree * @param opts */ counter(opts = {}) { return this.visited(opts).counter || {} } /** * Counts occurences * By default excludes any declaration from consideration unless includeAll is set * Calls countInTree * @param options */ countOccurrence(options: any = {}): number { let { nodeTypes } = options nodeTypes = nodeTypes || {} if (!options.includeAll) { // default categories to exclude nodeTypes.exclude = nodeTypes.exclude || ['declaration'] } if (isEmpty(nodeTypes)) { this.error('Warning: empty nodeTypes - nothing to count') return 0 } return this.countInTree({ nodeTypes, }) } /** * * @param options */ // protected createExpressionTester(options: any = {}) { return this.factories.details.createTester('expression', { ...options, node: this.node, }) } // protected /** * Count occurences of a particular token * @param token * @param options */ countOccurenceOf(token: string, options: any = {}): number { return this.countOccurrence({ nodeTypes: { // function that given a node determines if it should be counted or not toCount: this.createTokenTester(token, options), }, }) } /** * Create a token tester * @param token * @param options */ createTokenTester(token: string, options: any = {}) { return this.createTokenTesterFun(token, { ...options, exclude: ['loop'], // exclude any nested loops }) } // protected /** * Create an expression tester function * @param token * @param options */ createTokenTesterFun(token: string, options: any = {}) { if (!isNonEmptyStr(token)) { this.error('Invalid or missing token', { token, }) } return (node: any) => { const exprTester = this.createExpressionTester({ ...options, node }) return exprTester.is(token, node) } } }
9c2312afc5fc592945cd99808ce64d233219d9c0
TypeScript
alvesitalo/e-commerce
/src/app/api.service.ts
2.53125
3
import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { Banner } from 'src/models/banner'; import { Category } from 'src/models/category'; import { Course } from 'src/models/course'; const apiUrl = 'https://api.decroly.com.br'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: HttpClient) {} private handleError(error: HttpErrorResponse): any { console.error( `Back-end returned code ${error.status}, ` + `body was: ${error.message}` ); return throwError( 'Something bad happened. Please try again later.' ); } getBanner(id: string): Observable<any> { const url = `${apiUrl}/ecommerce/banner/${id}`; return this.http.get<Banner>(url).pipe( catchError(this.handleError) ); } getCategories(id: string): Observable<any> { const url = `${apiUrl}/categories/${id}`; return this.http.get<Category[]>(url).pipe( catchError(this.handleError) ); } getCourses(id: string): Observable<any> { const url = `${apiUrl}/ecommerce/courses/all?id=${id}`; return this.http.get<Course[]>(url).pipe( catchError(this.handleError) ); } }
55b5a14bb921b891bf5589acddb861b04510d9b2
TypeScript
FawwazMayda/LearnWeb
/tsc-start/hello.ts
3.328125
3
const msg: String = "CountryBalls" function toCapitalCase(word: String) { return word[0].toUpperCase() + word.slice(1).toLowerCase() } console.log(`Len: ${msg.length}`) for(let i=0;i<msg.length;i++) { console.log(`${i} => ${msg[i]}`) } console.log(msg.slice(0,10)) console.log(msg.slice(4,6)) console.log(`Uppercase: ${msg.toUpperCase()}`) console.log(`Locale Lowercase: ${msg.toLocaleLowerCase()}`) console.log(`Capital Case: ${toCapitalCase(msg)}`)
f59b2241b2693f318f524991f15ad0f3b400c369
TypeScript
sonuk-dev/Game-page
/src/app/game/snake/snake.component.ts
2.625
3
import { Component, OnInit } from '@angular/core'; import { Router } from "@angular/router"; import { ScoreService } from "../score.service"; @Component({ selector: 'app-snake', templateUrl: './snake.component.html', styleUrls: ['./snake.component.css', '../start/start.component.scss'] }) export class SnakeComponent implements OnInit { constructor(private router: Router, private scoreService: ScoreService) { } board_border = 'black'; board_background = "white"; snake_col = 'lightblue'; snake_border = 'darkblue'; // Snake and Food size elementSize = 20; snake = [ { x: 200, y: 200 }, { x: 190, y: 200 }, { x: 180, y: 200 }, { x: 170, y: 200 }, { x: 160, y: 200 } ] get snakeSpeed() { return this.currentScore > 160 ? 100 : 270 - this.currentScore; } get game_over() { return this.scoreService.game_over; } set game_over(value) { this.scoreService.game_over = value; } get currentScore() { return this.scoreService.currentScore; } set currentScore(value) { this.scoreService.currentScore = value; } // True if changing direction directionChanged = false; // Horizontal velocity food_x; food_y; dx = this.elementSize; // Vertical velocity dy = 0; snakeboard = document.createElement('canvas'); // Return a two dimensional drawing context snakeboard_ctx = this.snakeboard.getContext("2d"); ngOnInit(): void { this.snakeboard.width = 500; this.snakeboard.height = 500; document.querySelector('#snakeboard').appendChild(this.snakeboard) document.addEventListener("keydown", (event) => { this.change_direction(event) }); // Start game // main function called repeatedly to keep the game running this.main(); this.gen_food(); } main() { this.has_game_ended() if (this.game_over) return; this.directionChanged = false; setTimeout(() => { this.clear_board(); this.drawFood(); this.move_snake(); this.drawSnake(); // Repeat this.main(); }, this.snakeSpeed) } // draw a border around the canvas clear_board() { // Select the colour to fill the drawing this.snakeboard_ctx.fillStyle = this.board_background; // Select the colour for the border of the canvas this.snakeboard_ctx.strokeStyle = this.board_border; // Draw a "filled" rectangle to cover the entire canvas this.snakeboard_ctx.fillRect(0, 0, this.snakeboard.width, this.snakeboard.height); // Draw a "border" around the entire canvas this.snakeboard_ctx.strokeRect(0, 0, this.snakeboard.width, this.snakeboard.height); } // Draw the snake on the canvas drawSnake() { // Draw each part this.snake.forEach((snakePart) => { this.drawSnakePart(snakePart) }); } drawFood() { this.snakeboard_ctx.fillStyle = 'lightgreen'; this.snakeboard_ctx.strokeStyle = 'darkgreen'; this.snakeboard_ctx.fillRect(this.food_x, this.food_y, this.elementSize, this.elementSize); this.snakeboard_ctx.strokeRect(this.food_x, this.food_y, this.elementSize, this.elementSize); } // Draw one snake part drawSnakePart(snakePart) { // Set the colour of the snake part this.snakeboard_ctx.fillStyle = this.snake_col; // Set the border colour of the snake part this.snakeboard_ctx.strokeStyle = this.snake_border; // Draw a "filled" rectangle to represent the snake part at the coordinates // the part is located this.snakeboard_ctx.fillRect(snakePart.x, snakePart.y, this.elementSize, this.elementSize); // Draw a border around the snake part this.snakeboard_ctx.strokeRect(snakePart.x, snakePart.y, this.elementSize, this.elementSize); } has_game_ended() { for (let i = 4; i < this.snake.length; i++) { if (this.snake[i].x == this.snake[0].x && this.snake[i].y == this.snake[0].y) return true } const hitLeftWall = this.snake[0].x < 0; const hitRightWall = this.snake[0].x > this.snakeboard.width - this.elementSize; const hitToptWall = this.snake[0].y < 0; const hitBottomWall = this.snake[0].y > this.snakeboard.height - this.elementSize; if (hitLeftWall || hitRightWall || hitToptWall || hitBottomWall) { this.game_over = true; this.scoreService.addGame(this.currentScore); let user = JSON.parse(localStorage.getItem('currentUser')); if (this.currentScore > user.bestScore) { this.scoreService.changeBestScore(this.currentScore).subscribe( (res: any) => { localStorage.setItem('currentUser', JSON.stringify(res.user)); localStorage.setItem('token', res.token); this.router.navigate(['/game/game-over']) } ); } else this.router.navigate(['/game/game-over']) } } random_food(min, max) { return Math.round((Math.random() * (max - min) + min) / this.elementSize) * this.elementSize; } gen_food() { // Generate a random number the food x-coordinate this.food_x = this.random_food(0, this.snakeboard.width - this.elementSize); // Generate a random number for the food y-coordinate this.food_y = this.random_food(0, this.snakeboard.height - this.elementSize); // if the new food location is where the snake currently is, generate a new food location this.snake.forEach((part) => { const has_eaten = part.x == this.food_x && part.y == this.food_y; if (has_eaten) this.gen_food(); }); } change_direction(event) { const LEFT_KEY = 37; const RIGHT_KEY = 39; const UP_KEY = 38; const DOWN_KEY = 40; // Prevent the snake from reversing if (this.directionChanged) return; this.directionChanged = true; const keyPressed = event.keyCode; const goingUp = this.dy == -this.elementSize; const goingDown = this.dy == this.elementSize; const goingRight = this.dx == this.elementSize; const goingLeft = this.dx == -this.elementSize; switch (true) { case keyPressed == LEFT_KEY && !goingRight: this.dx = -this.elementSize; this.dy = 0; break; case keyPressed == UP_KEY && !goingDown: this.dx = 0; this.dy = -this.elementSize; break; case keyPressed == RIGHT_KEY && !goingLeft: this.dx = this.elementSize; this.dy = 0; break; case keyPressed == DOWN_KEY && !goingUp: this.dx = 0; this.dy = this.elementSize; break; } } move_snake() { // Create the new Snake's head const head = { x: this.snake[0].x + this.dx, y: this.snake[0].y + this.dy }; // Add the new head to the beginning of snake body this.snake.unshift(head); const has_eaten_food = this.snake[0].x == this.food_x && this.snake[0].y == this.food_y; if (has_eaten_food) { // Increase score this.currentScore += 10; // Display score on screen document.getElementById('score').innerHTML = String(this.currentScore); // Generate new food location this.gen_food(); } else { // Remove the last part of snake body this.snake.pop(); } } }
9f69f0188b7d543e7d906d5f473f106b6b487ef5
TypeScript
ericbiewener/utlz
/src/index.ts
3.046875
3
import execa from 'execa' import fs from 'fs' import path from 'path' import { spawnSync, SpawnSyncOptionsWithStringEncoding } from 'child_process' export function sleep<T = void>(ms = 0, value?: T): Promise<T> { return new Promise((resolve) => setTimeout(() => resolve(value), ms)) } export function isFile(filepath: string) { try { return fs.statSync(filepath).isFile() } catch (e) { if (e.code !== 'ENOENT') throw e // File might exist, but something else went wrong (e.g. permissions error) return false } } export type ReadDirSyncResult = { name: string; itemPath: string; isFile: boolean } export function readDirSync(dir: string): ReadDirSyncResult[] { const items = [] for (const name of fs.readdirSync(dir)) { if (name === '.DS_Store') continue const itemPath = path.join(dir, name) items.push({ name, itemPath, isFile: isFile(itemPath) }) } return items } export function defaultSpawnSync( cmd: string, args: string[], options?: SpawnSyncOptionsWithStringEncoding, ) { const { error, stderr, stdout } = spawnSync(cmd, args, options) if (error) throw error const stderrStr = stderr.toString() if (stderrStr) throw new Error(stderrStr) return stdout.toString() } export function removeFileExt(filepath: string, extensions?: string[]) { const ext = path.extname(filepath) if (!ext) return filepath return !extensions || extensions.includes(ext.slice(1)) ? filepath.slice(0, -ext.length) : filepath } export function findFileForExtensions(filepath: string, extensions: string[]) { const filepathRoot = removeFileExt(filepath) for (const ext of extensions) { const newPath = `${filepathRoot}.${ext}` if (isFile(newPath)) return newPath } } export function runCmd(cmd: string, args: string[], options?: execa.SyncOptions<null>) { try { const { stdout } = execa.sync(cmd, args.filter(Boolean), { stdio: 'inherit', ...options, }) return stdout } catch (e) { // Catch the error so that we don't have to see the JS stack trace. The executed command will // have had its own output. process.exit(1) } } export const createDir = (dirpath: string, options?: fs.MakeDirectoryOptions) => { try { fs.mkdirSync(dirpath, { recursive: true, ...options }) } catch (e) { if (e.code !== 'EEXIST') throw e return false } return true } export const writeFileIfNew = (filepath: string, data = '') => { if (isFile(filepath)) return false createDir(path.dirname(filepath)) fs.writeFileSync(filepath, data) return true } class ErrorWithData<D> extends Error { name = 'ErrorWithData' data: D | undefined constructor(message: string, data?: D) { super(message) this.data = data } } /** * Capture stdout & stderr in variables, while also allowing it to flow through to the parent * process's stdout (e.g. a terminal window). * * Also provides some sensible error handling. Will throw if there is any stderr. */ export const exe = async (cmd: string, args: string[], options?: execa.SyncOptions<null>) => { const child = execa(cmd, args.filter(Boolean), { ...options, stdio: 'pipe', }) // Catch the error and exit the process. This is an irrecoverable crash. child.on('error', (e) => { console.error(`CRASH: ${e.message}`) process.exit(1) }) // Let the ouput flow through to the main process's stdout child.stdout.pipe(process.stdout) child.stderr.pipe(process.stderr) let stdout = '' let stderr = '' child.stdout.on('data', (buffer) => { stdout += buffer.toString() }) child.stderr.on('data', (buffer) => { stderr += buffer.toString() }) // Wait for both stdout and stderr to close await Promise.all([ new Promise((res) => child.stdout.on('close', res)), new Promise((res) => child.stderr.on('close', res)), ]) if (stderr) throw new ErrorWithData('stderr has data', { stdout, stderr }) return stdout }
cf094a86f88eb96a1ac01ee15fdf135897b15172
TypeScript
evan-lin9/mini-snabbdom
/src/mini-snabbdom/patch.ts
3.1875
3
import createElement from './createElement' import { vnode, VNode } from './vnode' import { isDef } from '../utils'; function isEle(pet: Element | VNode): pet is Element { return (pet as Element).tagName !== undefined; } function addVnodes(parentNode: Node, vnodes: VNode[]) { // console.log(parentNode) for(let i = 0; i < vnodes.length; i++) { // 依次创建 dom 并插入 console.log(vnodes[i]) const childDom = createElement(vnodes[i]); parentNode.insertBefore(childDom, null) // parentNode.insertBefore(childDom) } } function diff (oldVnode: VNode, newVnode: VNode) { if (oldVnode === newVnode) return const elm = newVnode.elm = oldVnode.elm if (isDef(newVnode.text)) { if (newVnode.text === oldVnode.text) return if (isDef(oldVnode.children)) { console.log('移除oldCh') // 这里我并没有执行 removeVnodes 函数,猜测跟下面一段代码有关? // 果然如此!因为执行新增文本操作,会直接覆盖掉原来的子节点 // mdn 证实了我的推测 https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent // Setting textContent on a node removes all of the node's children // and replaces them with a single text node with the given string value. } elm.textContent = newVnode.text } else { if (isDef(oldVnode.children) && isDef(newVnode.children)) { if (oldVnode.children === newVnode.children) return; console.log('updateChildren') } else if (isDef(newVnode.children)) { if (isDef(oldVnode.text)) elm.textContent = ''; // 准备实现这个方法 addVnodes(elm, newVnode.children as VNode[]) } else if (isDef(oldVnode.children)) { console.log('removeVnodes') } if (isDef(oldVnode.text)) elm.textContent = '' } } export function patch(oldVnode: Element | VNode, newVnode: VNode) { // 判断第一个参数是否为 Element 类型 if (isEle(oldVnode)) { // 创建一个 vnode oldVnode = vnode(oldVnode.tagName.toLowerCase(), {}, [], undefined, oldVnode); } // 判断是否为统一节点 if (oldVnode.key === newVnode.key && oldVnode.sel === newVnode.sel) { // 同一个节点,则开始 diffs 算法 diff(oldVnode, newVnode) } else { const dom = createElement(newVnode) // 先插入新的节点后再删除旧节点 if (oldVnode.elm !== undefined && dom) { oldVnode.elm.parentNode.insertBefore(dom, oldVnode.elm) } // 删除老的 dom oldVnode.elm.parentNode.removeChild(oldVnode.elm) } }
c725776592c74aca7f8a9e8c91bb00efa57449be
TypeScript
SAP/fundamental-ngx
/libs/cdk/src/lib/utils/directives/auto-complete/auto-complete.directive.ts
2.890625
3
import { Directive, ElementRef, EventEmitter, HostListener, Input, Output } from '@angular/core'; import { BACKSPACE, CONTROL, DELETE, ENTER, ESCAPE, LEFT_ARROW, RIGHT_ARROW } from '@angular/cdk/keycodes'; import { KeyUtil } from '../../functions/key-util'; export interface AutoCompleteEvent { term: string; forceClose: boolean; } @Directive({ selector: '[fdkAutoComplete]', standalone: true }) export class AutoCompleteDirective { /** Values that will fill missing text in the input. */ @Input() options: any[]; /** * Input text, that is taken from ngModel of formControl, * there has to be difference between native input value and model value */ @Input() inputText: string; /** Whether the auto complete directive should be enabled */ @Input() enable = true; /** Display function. Accepts an object of the same type as the * items passed to dropdownValues as argument, and outputs a string. * An arrow function can be used to access the *this* keyword in the calling component. * See search input examples for details. */ @Input() displayFn = this._defaultDisplay; /** Event thrown, when the auto ahead text is accepted */ @Output() // eslint-disable-next-line @angular-eslint/no-output-on-prefix readonly onComplete: EventEmitter<AutoCompleteEvent> = new EventEmitter<AutoCompleteEvent>(); /** @hidden */ private readonly _completeKeys: number[] = [ENTER]; /** @hidden */ private readonly _fillKeys: number[] = [LEFT_ARROW, RIGHT_ARROW]; /** @hidden */ private readonly _stopKeys: number[] = [BACKSPACE, DELETE, ESCAPE]; /** @hidden */ private oldValue: string; /** @hidden */ private lastKeyUpEvent: KeyboardEvent; /** @hidden */ constructor(private _elementRef: ElementRef) {} /** @hidden */ @HostListener('keyup', ['$event']) handleKeyboardEvent(event: KeyboardEvent): void { if (this.enable) { if (KeyUtil.isKeyCode(event, this._stopKeys)) { this._elementRef.nativeElement.value = this.inputText; } else if (KeyUtil.isKeyCode(event, this._completeKeys)) { this._sendCompleteEvent(true); this._moveIndicatorToLastCharacter(); } else if (KeyUtil.isKeyCode(event, this._fillKeys)) { this._sendCompleteEvent(false); } else if (!this._isControlKey(event) && this.inputText) { /** Prevention from triggering typeahead, when having crtl/cmd + keys */ if (!this._triggerTypeAhead()) { return; } this.oldValue = this.inputText; const item = this.options.find((option) => this.displayFn(option).toLocaleLowerCase().startsWith(this.inputText.toLocaleLowerCase()) ); if (item) { this._typeahead(this.displayFn(item)); } } } this.lastKeyUpEvent = event; } /** @hidden */ private _typeahead(displayedValue: string): void { this._elementRef.nativeElement.value = displayedValue; const selectionStartIndex = this.inputText.length; this._elementRef.nativeElement.setSelectionRange(selectionStartIndex, displayedValue.length); } /** @hidden */ private _isControlKey(event: KeyboardEvent): boolean { return KeyUtil.isKeyCode(event, CONTROL) || event.ctrlKey; } /** @hidden */ private _defaultDisplay(value: any): string { return value; } /** @hidden */ private _triggerTypeAhead(): boolean { if ( this.lastKeyUpEvent && KeyUtil.isKeyCode(this.lastKeyUpEvent, CONTROL) && this.inputText === this.oldValue ) { return false; } else { return true; } } /** @hidden */ private _sendCompleteEvent(forceClose: boolean): void { this.onComplete.emit({ term: this._elementRef.nativeElement.value, forceClose }); } /** @hidden */ private _moveIndicatorToLastCharacter(): void { const inputTextLength = this.inputText?.length ?? 0; this._elementRef.nativeElement.setSelectionRange(inputTextLength, inputTextLength); } }
9dfabcfb0d67efc673e417bc676e0cb0e7c1374e
TypeScript
gizak/batch
/lib/helpers.ts
2.515625
3
export function newObjProxy<T>(obj: any, shadow: T): T { obj = obj || {} const handler = { get(target, prop, receiver) { if (prop in obj && obj[prop] !== undefined) { return Reflect.get(obj, prop) } return Reflect.get(target, prop, receiver) } } return new Proxy<T>(shadow, handler) }
3ef7f286a8929bcc759efdcb9c92fb3b949d1040
TypeScript
edgardleal/backup
/src/presenter/cli/command/show.ts
2.671875
3
/** * show.ts * Copyright (C) 2021 * * @author Edgard Leal <edgard.leal@gmail.com> * @module show.ts */ import BackupReader from '../../../db/backup-reader'; import DBFactory from '../../../db/db-factory'; import Out from '../Out'; import Since from '../since'; import { formatSize } from '../size'; import Command from './command'; const Chart = require('cli-chart'); /** * Show details for a backup * @author edgardleal@gmail.com * @since 24.03.21 */ export default class Show implements Command { private reader: BackupReader // eslint-disable-next-line no-useless-constructor constructor() { this.reader = new DBFactory().getBackupReader(); } async run(...args: string[]): Promise<void> { Out.info('\n\n\n'); const marging = ' '; const backup = await this.reader.read(args[0]); if (!backup) { Out.t('db.not_found', { name: args[0] }); // eslint-disable-line return; } const chart = new Chart({ xlabel: 'days', ylabel: 'size', direction: 'y', width: 40, height: 10, lmargin: 5, step: 2, }); const dataProvider = { getData: () => Promise.resolve(backup), }; const lastBackup = await new Since(dataProvider).render(); Out.info('%sName : %s', marging, backup.name); // eslint-disable-line Out.info('%sFreq : %d day(s)', marging, backup.frequency || 1); // eslint-disable-line Out.info('%sLast : %s', marging, lastBackup); // eslint-disable-line Out.info('%sSize : %s\n', marging, formatSize((backup.currenteExecution || { size: 0 }).size)); // eslint-disable-line const executions = (backup!.executions || []); let i = Math.max(0, executions.length - 20); for (; i < executions.length; i += 1) { const execution = backup!.executions![i]; if (execution.size) { chart.addBar(execution.size || 0); } } chart.draw(); } }
e9c2f4c14aa35a3150bb0fe9af14890326946e6a
TypeScript
chrishumboldt/rocket-utility
/src/utility/transform/transform.utility.spec.ts
2.640625
3
/** * @author Chris Humboldt */ import { RocketTransform } from './transform.utility'; describe('Rocket Transform Utility:', () => { // Tests. it('Should transform bytes into a readable string.', () => { expect(RocketTransform.bytes({ bytes: 2000 })).toEqual('2 KB'); expect(RocketTransform.bytes({ bytes: 30000 })).toEqual('30 KB'); expect(RocketTransform.bytes({ bytes: 4000000 })).toEqual('4 MB'); expect(RocketTransform.bytes({ bytes: 8000000000 })).toEqual('8 GB'); expect(RocketTransform.bytes({ bytes: 1600000000000 })).toEqual('1.6 TB'); expect(RocketTransform.bytes({ bytes: 3200000000000000 })).toEqual( '3.2 PB' ); expect(RocketTransform.bytes({ bytes: 6440000000000000000 })).toEqual( '6.44 EB' ); expect(RocketTransform.bytes({ bytes: 88700000000000000000000 })).toEqual( '88.7 ZB' ); expect( RocketTransform.bytes({ bytes: 46200000000000000000000000 }) ).toEqual('46.2 YB'); }); });
8222a3f2e7c54cc3f6549a45fdfa6bdff143bb41
TypeScript
six2020/six-react
/02-typescript-2/src/10.ts
3.3125
3
export {} interface List{ readonly id: number; name: string; age?: number } interface Result{ data: List[] } function render(result: Result){ result.data.forEach((value)=>{ console.log('value.id ====>>>>', value.id); console.log('value.name ====>>>>', value.name); if(value.age) console.log('value.age ====>>>>', value.age); // value.id ++ }) } let result = { data: [ {id: 1, name: 'A'}, {id: 2, name: 'B'}, ] } render(result)
9a7e01acadd7ac5e0c62eadbcdc7f39e6b6004de
TypeScript
robinsound/vscode-go-impl-methods
/src/interfaces-stubs-generator.ts
2.59375
3
import * as cp from 'child_process'; import { dirname } from 'path'; import * as vscode from 'vscode'; import { Receiver } from './receiver'; export class InterfaceStubsGenerator { pattern: RegExp; constructor(private editor: vscode.TextEditor | undefined) { this.pattern = /^\/\/\s*([a-zA-Z_][a-zA-Z0-9_]*)\s+(\*?(?:[a-zA-Z_][a-zA-Z0-9]*\.)?[a-zA-Z_][a-zA-Z0-9_]*)$/; } findMatches(line: string): RegExpMatchArray | null { return line.match(this.pattern); } receiver(): Receiver | undefined { let line = this.editor?.document.lineAt(this.editor.selection.active.line); let matches = this.findMatches(line?.text.trim() as string); if (!matches) { return undefined; } return { name: matches[1], type_: matches[2], range: line?.range }; } parse(): Receiver | undefined { const receiver = this.receiver(); if (!receiver) { vscode.window.showWarningMessage(`Receiver is not in the correct format. Please, comment the line and use the following format for receiver: "f *File", "m MyType", "c CustomType"`); return; } return receiver; } implement(interface_: string, receiver: Receiver, callback?: (stubs: string) => void): void { vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: "Generating stub methods..." }, (progress, token) => { return new Promise((resolve) => { const impl = cp.exec(`impl "${receiver?.name} ${receiver?.type_}" ${interface_}`, { cwd: dirname((this.editor as vscode.TextEditor).document.fileName) }, (error, stdout, stderr) => { if (error) { vscode.window.showInformationMessage(stderr); return resolve(true); } const position = this.editor?.selection.active; const previousPosition = position?.with(position.line, 0); this.editor?.edit(editBuilder => { editBuilder.replace(receiver?.range as vscode.Range, stdout); const newPosition = this.editor?.selection.active; const newSelection = new vscode.Selection(previousPosition as vscode.Position, newPosition as vscode.Position); (this.editor as vscode.TextEditor).selection = newSelection; if (callback) { callback(stdout); } }); resolve(true); }); }); }); } }
9b12b0136967fec7ddc77660b9f5af48aed62b5e
TypeScript
carlgrimsborn/StoreApp
/src/reducers/userReducer.ts
2.859375
3
import {User} from '../Types'; const initUser: User = { id: 0, surname: '', lastname: '', email: '', password: '', items: [], }; const UserReducer = (user: User = initUser, action: any) => { if (action.type === 'SET_USER') { const newUser = action.user; return { ...user, ...newUser, }; } if (action.type === 'CLEAN_USER') { return { ...user, ...initUser, }; } return user; }; export default UserReducer;
b230147ab9c196f767614a47dbb7300431cb5236
TypeScript
k3nNyJP/atcoder
/abc240/c/Main.ts
3.234375
3
function searchCombination(items: number[], target: number): boolean { if (target === 0 || items.indexOf(target) !== -1) { return true; } else if (items.every((item) => item > target)) { return false; } const searched = []; for (let i = 0; i < items.length; i++) { const item = items[i]; if (searched[item]) { continue; } searched[item] = true; if ( searchCombination( [ ...items.slice(0, i).filter((value) => value <= target - item), ...items.slice(i + 1).filter((value) => value <= target - item), ], target - item ) ) { return true; } } return false; } function Main(input: string[]) { const firstLine = input[0].split(" ").map((value) => parseInt(value, 10)); const N = firstLine[0]; const X = firstLine[1]; let shortest = 0; const diffs = []; for (let i = 1; i <= N; i++) { const jump = input[i].split(" ").map((value) => parseInt(value, 10)); shortest += jump[0]; const diff = jump[1] - jump[0]; diffs.splice( diffs.findIndex((value) => value > diff), 0, diff ); } if (shortest > X) { console.log("No"); return; } const shortage = X - shortest; console.log( searchCombination( diffs.slice( 0, diffs.findIndex((value) => value > shortage) ), shortage ) ? "Yes" : "No" ); } //*この行以降は編集しないでください(標準入出力から一度に読み込み、Mainを呼び出します) Main(require("fs").readFileSync("/dev/stdin", "utf8").split("\n"));
7cb23fe1c39dd632f2787ffe9e2268cd7fadd3ad
TypeScript
aicacia/flash-cards
/src/lib/state/decks.ts
2.640625
3
import { debounce } from "@aicacia/debounce"; import Automerge from "automerge"; import { createStore } from "./store"; export interface IDeck { name: string; createdAt: string; updatedAt: string; } export const deckStore = createStore("decks", { table: new Automerge.Table<IDeck>(), }); export function createDeck(name: string) { let id: string | undefined; deckStore.update((state) => { const now = new Date().toJSON(); id = state.table.add({ name, createdAt: now, updatedAt: now, }); }, `Create Deck ${name}`); return id; } export function updateDeck(id: string, deck: Partial<IDeck>) { deckStore.update((state) => { const row = state.table.byId(id); if (deck.name) { row.name = deck.name; } row.updatedAt = new Date().toJSON(); }, `Update Deck ${id}`); } export const updateDeckDebounced = debounce(updateDeck, 1000); export function deleteDeck(id: string) { cardStore.update((state) => { for (const row of state.table.rows.filter((row) => row.deckId === id)) { state.table.remove(row.id); } }, `Delete Deck ${id}`); deckStore.update((state) => { state.table.remove(id); }, `Delete Deck ${id}`); } import { cardStore } from "./cards";
0cc46c909db27adfc258b7033c73afb66c5a53c0
TypeScript
gg1122/vscode-tabster
/src/modules/tabster-hot/utils.ts
2.59375
3
import { HOT_SET_LABEL_1 } from "./consts"; import { THotLabel } from "./models"; export function isHotLabel(key: THotLabel | string): boolean { for (let i = 0; i < 10; ++i) { if (key === `${HOT_SET_LABEL_1.slice(0, -1)}${i}`) { return true; } } return false; } export function getLabelSortOrder(key: THotLabel) { return Number(key.slice(-1)); }
c0dc83652ad339021a9851acd4cac5bf741c91b1
TypeScript
RaulALR/weather-app
/src/app/shared/utils.ts
2.515625
3
import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Observable } from 'rxjs'; import { MatIconRegistry } from '@angular/material'; import { DomSanitizer } from '@angular/platform-browser'; @Injectable() export class Utils { public days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; constructor( private domSanitizer: DomSanitizer, private matIconRegistry: MatIconRegistry ) { } // Register external icons into app public getIcons(iconsArray: Array<string>) { iconsArray.forEach((item) => { const name = item.split('.'); this.matIconRegistry.addSvgIcon( name[0], this.domSanitizer.bypassSecurityTrustResourceUrl(`../assets/icons/${item}.svg`) ); }); } // Get day of the param public getDateDay(dataTxt: string) { const date = new Date(dataTxt); return this.days[date.getDay()]; } // Get hour of the param public getDateHour(dataTxt: string) { const date = new Date(dataTxt); return date.getHours(); } // Get positive or negative symbol public getTempSymbol(num) { switch (Math.sign(num)) { case 1: return '+'; case -1: return '-'; break; default: return ''; } } // Get actual date public getDate() { return new Date(); } }
ee4de68c99aeb54acef718f28ca25c3af267d120
TypeScript
pokt-network/pocket-js
/src/rpc/models/application.ts
3.25
3
import { Hex } from "../.." import { StakingStatus } from "./staking-status" /** * * * @class Application */ export class Application { /** * * Creates a Application object using a JSON string * @param {String} json - JSON string. * @returns {Application} - Application object. * @memberof Application */ public static fromJSON(json: string): Application { try { const jsonObject = JSON.parse(json) const status = StakingStatus.getStatus(jsonObject.status) return new Application( jsonObject.address, jsonObject.public_key, jsonObject.jailed, status, jsonObject.chains, BigInt(jsonObject.staked_tokens), BigInt(jsonObject.max_relays), jsonObject.unstaking_time ) } catch (error) { throw error } } public readonly address: string public readonly publicKey: string public readonly jailed: boolean public readonly status: StakingStatus public readonly chains: string[] public readonly stakedTokens: BigInt public readonly maxRelays: BigInt public readonly unstakingCompletionTime: string | undefined /** * Creates a Application. * @constructor * @param {string} address - The hex address of the application * @param {string} publicKey - The hex consensus public key of the application. * @param {boolean} jailed - Has the application been jailed from staked status? * @param {StakingStatus} status - Application staking status * @param {string[]} chains - An array of blockchains * @param {BigInt} stakedTokens - How many staked tokens * @param {BigInt} maxRelays - Max amount of relays. * @param {string} unstakingCompletionTime - If unstaking, min time for the application to complete unstaking */ constructor( address: string, publicKey: string, jailed: boolean, status: StakingStatus, chains: string[] = [], stakedTokens: BigInt, maxRelays: BigInt, unstakingCompletionTime: string = "" ) { this.address = address this.publicKey = publicKey this.jailed = jailed this.status = status this.chains = chains this.stakedTokens = stakedTokens this.maxRelays = maxRelays this.unstakingCompletionTime = unstakingCompletionTime if (!this.isValid()) { throw new TypeError("Invalid Application properties.") } } /** * * Creates a JSON object with the Application properties * @returns {JSON} - JSON Object. * @memberof Application */ public toJSON() { return { address: this.address, chains: this.chains, public_key: this.publicKey, jailed: this.jailed, max_relays: Number(this.maxRelays.toString()), status: this.status, staked_tokens: Number(this.stakedTokens.toString()), unstaking_time: this.unstakingCompletionTime } } /** * * Verify if all properties are valid * @returns {boolean} - True or false. * @memberof Application */ public isValid() { let validAddress = true let validPubKey = true if (this.address) { validAddress = Hex.validateAddress(this.address) } if (this.publicKey) { validPubKey = Hex.validatePublicKey(this.publicKey) } return validAddress && this.chains.length > 0 && validPubKey && this.jailed !== undefined && Number(this.maxRelays.toString()) >= 0 && this.status !== undefined && Number(this.stakedTokens.toString()) >= 0 } }
ccadeb954c8cd813a56a6206730471128b407b66
TypeScript
pranavkaushik9/react-typescript-grpahql-apollo-mobx-express-sample
/web/src/shared/domain/trade.ts
2.84375
3
import { observable } from "mobx"; type TradeSide = 'BUY' | 'SELL'; type TradeStatus = 'OPEN' | 'NOMINATED'; export class Trade { @observable id: string; @observable side: TradeSide; @observable status: TradeStatus; @observable price: number; @observable quantity: number; @observable counterPartyId: string; @observable counterPartyName: string @observable commodityId: string; @observable locationId: string; @observable date?: string; constructor( id: string = '', side: TradeSide = 'BUY', status: TradeStatus = 'OPEN', price: number = 0, quantity: number = 0, counterPartyId: string, counterPartyName: string, commodityId: string, locationId: string, date: string ) { this.id = id; this.side = side; this.status = status; this.price = price; this.quantity = quantity; this.counterPartyId = counterPartyId; this.counterPartyName = counterPartyName; this.commodityId = commodityId; this.locationId = locationId; this.date = date; } }
ee8893732ca76723076cb626f1da62968f71cf35
TypeScript
DefinitelyTyped/DefinitelyTyped
/types/gulp-sort/index.d.ts
2.734375
3
// Type definitions for gulp-sort 2.0 // Project: https://github.com/pgilad/gulp-sort // Definitions by: Joe Skeen <https://github.com/joeskeen> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> /** Sort files in stream by path or any custom sort comparator */ import gulpUtil = require('gulp-util'); interface IOptions { /** * A function to compare two files. * Returns: * -1 if file1 should be before file2, * 0 if file1 is equivalent to file2, and * 1 if file1 should be after file2 */ comparator?: IComparatorFunction | undefined; /** Whether to sort in ascending order, default is true */ asc?: boolean | undefined; /** Whether to use a custom sort function. */ customSortFn?: (files: gulpUtil.File[], comparator?: IComparatorFunction) => gulpUtil.File[]; } interface IComparatorFunction { /** * A function to compare two files. * Returns: * -1 if file1 should be before file2, * 0 if file1 is equivalent to file2, and * 1 if file1 should be after file2 */ (file1: gulpUtil.File, file2: gulpUtil.File): number; } /** Sort files in stream by path or any custom sort comparator */ declare function gulpSort(): NodeJS.ReadWriteStream; declare function gulpSort(comparator: IComparatorFunction): NodeJS.ReadWriteStream; declare function gulpSort(options: IOptions): NodeJS.ReadWriteStream; declare namespace gulpSort {} export = gulpSort;
1a4704112ca0dc8e97b4c97af454669b2e788499
TypeScript
maddalax/Logicful
/frontend/app/src/util/Cache.ts
2.71875
3
const cache: { [key: string]: any } = {}; export function cacheSet(key: string, value: any) { cache[key] = value; } export function cacheGet(key: string) { return cache[key]; } export function cacheClear(key: string) { delete cache[key]; }
0e4254a65808c94bdb6dc298e972721361b3bc42
TypeScript
xRahman/Kosmud
/Src/Shared/Physics/VehiclePhysics.ts
2.75
3
/* Part of Kosmud */ // Augment global namespace with number-related functions and constants. import "../../Shared/Utils/Number"; import { ClassFactory } from "../../Shared/Class/ClassFactory"; import { Attributes } from "../../Shared/Class/Attributes"; import { Angle } from "../../Shared/Utils/Angle"; // import { ZeroToOne } from "../../Shared/Utils/ZeroToOne"; import { PositiveNumber } from "../../Shared/Utils/PositiveNumber"; import { NonnegativeNumber } from "../../Shared/Utils/NonnegativeNumber"; import { ZeroTo2Pi } from "../../Shared/Utils/ZeroTo2Pi"; import { Vector } from "../../Shared/Physics/Vector"; // import { PhysicsBody } from "../../Shared/Physics/PhysicsBody"; import { PhysicsWorld } from "../../Shared/Physics/PhysicsWorld"; import { Engine } from "../../Shared/Engine/Engine"; // import { Zone } from "../../Shared/Game/Zone"; // import { Vehicle } from "../../Shared/Game/Vehicle"; import { Physics } from "../../Shared/Physics/Physics"; // import { ShapeAsset } from "../../Shared/Asset/ShapeAsset"; // import { Serializable } from "../../Shared/Class/Serializable"; import { EntityPhysics } from "../../Shared/Physics/EntityPhysics"; // import { Vehicle } from "../../Shared/Game/Vehicle"; export class VehiclePhysics extends EntityPhysics { protected static version = 0; // These are constants. They only change if you install a new engine // into the vehicle or something like that. public readonly MAX_SPEED = new PositiveNumber(3); public readonly FORWARD_THRUST = new PositiveNumber(1); public readonly BACKWARD_THRUST = new PositiveNumber(0.5); public readonly STRAFE_THRUST = new PositiveNumber(0.2); public readonly MAX_ANGULAR_VELOCITY = new PositiveNumber(Math.PI / 2); public readonly ANGULAR_THRUST = new PositiveNumber(1); /// Přesunuto do předka. // public readonly DENSITY = new PositiveNumber(1); // public readonly FRICTION = new ZeroToOne(0.5); // // 0 - almost no bouncing, 1 - maximum bouncing. // public readonly RESTITUTION = new ZeroToOne(1); // These variables reflect buffs and debuffs that change // current thrust, maximum speed or maximum angular velocity. public readonly thrustMultiplier = new NonnegativeNumber(1); protected static thrustMultiplier: Attributes = { saved: false }; public readonly speedMultiplier = new NonnegativeNumber(1); protected static speedMultiplier: Attributes = { saved: false }; public readonly angularVelocityMultiplier = new NonnegativeNumber(1); protected static angularVelocityMultiplier: Attributes = { saved: false }; /// Přesunuto do předka. // /// TODO: Až budu chtít PhysicsBody savovat, tak musím tohle pořešit. // /// Property 'initialPosition' se totiž používá jen při vkládání // /// do physics worldu - getPosition() potom vytahuje pozici s physicsBody. // /// Možná to bude chtít custom savování/loadování, protože při savu // /// je potřeba nejdřív vytáhnout aktuální pozici z this.body a pak až ji // /// savnout. A při loadu se pak zas musí body vytvořit. // public readonly initialPosition = { x: 0, y: 0 }; // public readonly initialRotation = new ZeroTo2Pi(0); // These variables are updated in steering forces computation // and are sent to the client to be drawn in debug mode. public readonly desiredVelocity = new Vector(); protected static desiredVelocity: Attributes = { saved: false }; public readonly steeringForce = new Vector(); protected static steeringForce: Attributes = { saved: false }; // (This variable is not sent to the client, only torqueRatio is sent). public torque = 0; protected static torque: Attributes = { saved: false }; /// Přesunuto do předka. // private shapeAsset: ShapeAsset | "Not set" = "Not set"; /// Přesunuto do předka. // private physicsBody: PhysicsBody | "Not in physics world" = // "Not in physics world"; // protected static physicsBody: Attributes = { saved: false }; // These variables are updated in steering forces computation and are // sent to the client where they are used for displaying ship thrusters. private forwardThrustRatio = 0; protected static forwardThrustRatio: Attributes = { saved: false }; private leftwardThrustRatio = 0; protected static leftwardThrustRatio: Attributes = { saved: false }; private torqueRatio = 0; protected static torqueRatio: Attributes = { saved: false }; private readonly waypoint = { position: new Vector(), // Keep direction separately because when we reach the waypoint, target // vector will have zero length and thus an undefined direction. direction: new ZeroTo2Pi(0) }; /// Přesunuto do předka. // private vehicle: Vehicle | "Not set" = "Not set"; // --------------- Public accessors ------------------- /// Přesunuto do předka. // // ! Throws exception on error. // public setVehicle(vehicle: Vehicle) // { // if (this.hasOwnProperty("vehicle") && this.vehicle !== "Not set") // { // throw Error(`Failed to set reference to ${vehicle.debugId}` // + ` to it's physics because there already is a reference` // + ` to vehicle ${this.vehicle.debugId} there`); // } // this.vehicle = vehicle; // } /// Přesunuto do předka. // // ! Throws exception on error. // public getVehicle() // { // if (this.vehicle === "Not set") // { // throw Error(`Missing reference to a respective vehicle in` // + ` vehicle physics. Make sure the reference is set in vehicle's` // + ` onInstantiation() method`); // } // return this.vehicle; // } public get currentMaxSpeed() { return this.MAX_SPEED.valueOf() * this.speedMultiplier.valueOf(); } public get currentForwardThrust() { return this.FORWARD_THRUST.valueOf() * this.thrustMultiplier.valueOf(); } public get currentBackwardThrust() { return this.BACKWARD_THRUST.valueOf() * this.thrustMultiplier.valueOf(); } public get currentStrafeThrust() { return this.STRAFE_THRUST.valueOf() * this.thrustMultiplier.valueOf(); } public get currentMaxAngularVelocity() { return this.MAX_ANGULAR_VELOCITY.valueOf() * this.angularVelocityMultiplier.valueOf(); } public get currentAngularThrust() { return this.ANGULAR_THRUST.valueOf() * this.thrustMultiplier.valueOf(); } /// Přesunuto do předka. // // ! Throws exception on error. // public get inertiaValue() // { // // ! Throws exception on error. // return this.getPhysicsBody().getInertia().valueOf(); // } /// Přesunuto do předka. // // ! Throws exception on error. // public get massValue() // { // // ! Throws exception on error. // return this.getPhysicsBody().getMass().valueOf(); // } /// Přesunuto do předka. // // ! Throws exception on error. // public setShapeAsset(asset: ShapeAsset) // { // if (this.hasOwnProperty("shapeAsset") && this.shapeAsset !== "Not set") // // ! Throws exception on error. // this.getVehicle().removeAsset(this.shapeAsset); // // ! Throws exception on error. // this.shapeAsset = this.getVehicle().addAsset(asset); // } /// Přesunuto do předka. // // ! Throws exception on error. // public getShapeAsset() // { // if (this.shapeAsset === "Not set") // { // throw new Error(`${this.getVehicle().debugId} doesn't have shape asset`); // } // return this.shapeAsset; // } // ---------------- Public methods -------------------- /// Přesunuto do předka. // // ! Throws exception on error. // public getPosition() { return this.getPhysicsBody().getPosition(); } /// Přesunuto do předka. // // ! Throws exception on error. // public setPosition(position: { x: number; y: number }) // { // // ! Throws exception on error. // this.getPhysicsBody().setPosition(position); // } /// Přesunuto do předka. // // ! Throws exception on error. // public getX() { return this.getPhysicsBody().getX(); } // // ! Throws exception on error. // public getY() { return this.getPhysicsBody().getY(); } // // ! Throws exception on error. // public getRotation() { return this.getPhysicsBody().getRotation(); } public getDesiredVelocity() { return this.desiredVelocity; } public getSteeringForce() { return this.steeringForce; } // ! Throws exception on error. public getVelocity() { return this.getPhysicsBody().getVelocity(); } // ! Throws exception on error. public setVelocity(velocity: Vector) { // ! Throws exception on error. this.getPhysicsBody().setVelocity(velocity); } // ! Throws exception on error. public getAngularVelocity() { return this.getPhysicsBody().getAngularVelocity(); } public getForwardThrustRatio() { return this.forwardThrustRatio; } public getLeftwardThrustRatio() { return this.leftwardThrustRatio; } public getTorqueRatio() { return this.torqueRatio; } public getWaypointPosition() { return this.waypoint.position; } public getWaypointDirection() { return this.waypoint.direction.valueOf(); } // ! Throws exception on error. public updateWaypointDirection() { // ! Throws exception on error. const shipPosition = this.getPosition(); const waypointPosition = this.getWaypointPosition(); if (!shipPosition.equals(waypointPosition)) { const targetVector = Vector.v1MinusV2 ( waypointPosition, shipPosition ); this.waypoint.direction.set(targetVector.getRotation()); } } // ! Throws exception on error. public setWaypoint(position: { x: number; y: number }) { this.waypoint.position.set(position); // ! Throws exception on error. this.updateWaypointDirection(); } /// Přesunuto do předka. // // ! Throws exception on error. // public getShape() // { // // ! Throws exception on error. // return this.getPhysicsBody().getShape(); // } /// Přesunuto do předka. // // ! Throws exception on error. // public addToPhysicsWorld(physicsWorld: PhysicsWorld, zone: Zone) // { // // ! Throws exception on error. // const physicsShape = this.getShapeAsset().getShape(); // this.physicsBody = physicsWorld.createPhysicsBody // ( // this.getVehicle(), this, physicsShape // ); // /// Nothing needs to be initialized for now. I'll leave it here // /// for possible future use. // // // ! Throws exception on error. // // this.init(); // // ! Throws exception on error. // // Set waypoint to the new position so the vehicle doesn't // // go back to where it was. // this.setWaypoint(this.getPhysicsBody().getPosition()); // } // ! Throws exception on error. // ~ Overrides EntityPhysics.addToPhysicsWorld(). public addToPhysicsWorld(physicsWorld: PhysicsWorld) { super.addToPhysicsWorld(physicsWorld); // ! Throws exception on error. // Set waypoint to the new position so the vehicle doesn't // go back to where it was. this.setWaypoint(this.getPhysicsBody().getPosition()); } // ! Throws exception on error. public steer() { // ! Throws exception on error. this.arrive(); // this.seek(); // ! Throws exception on error. this.getPhysicsBody().applyForce(this.steeringForce); // ! Throws exception on error. this.getPhysicsBody().applyTorque(this.torque); } // ! Throws exception on error. // This is only used on the client in debug drawing mode. public computeBrakingDistance() { // ! Throws exception on error. const targetVector = this.computeTargetVector(); const fullBrakingThrust = this.computeBrakingThrust(targetVector); return computeBrakingDistance ( this.massValue, this.currentMaxSpeed, // ! Throws exception on error. fullBrakingThrust ); } // --------------- Protected methods ------------------ // // ! Throws exception on error. // protected seek() // { // // ! Throws exception on error. // const currentVelocity = this.getVelocity(); // // ! Throws exception on error. // // Rotation in Box2D can be negative or even greater than 2π. // // We need to fix that so we can correcly subtract angles. // const currentRotation = Angle.normalize(this.getRotation()); // // ! Throws exception on error. // const currentPosition = this.getPosition(); // const desiredPosition = this.waypoint; // // 1. 'desired velocity' = 'desired position' - 'current position'. // const desiredVelocity = Vector.v1MinusV2 // ( // desiredPosition, currentPosition // ); // // 2. Scale 'desired velocity' to maximum speed. // desiredVelocity.setLength(this.MAX_SPEED); // const desiredSteeringForce = Vector.v1MinusV2 // ( // desiredVelocity, // currentVelocity // ); // this.computeLinearForces // ( // desiredSteeringForce, // desiredVelocity, // currentVelocity, // currentRotation // ); // const desiredRotation = desiredVelocity.getRotation(); // const angularDistance = this.desiredRotation - currentRotation; // /// TODO (zatím natvrdo): // const angularPhase = "Accelerating"; // this.computeAngularForces // ( // currentRotation, // desiredRotation, // angularDistance, // angularPhase // ); // } // ! Throws exception on error. protected arrive() { this.torque = this.computeArriveTorque(); this.steeringForce.set(this.computeArriveSteeringForce()); } // ---------------- Private methods ------------------- /// Přesunuto do předka. // // ! Throws exception on error. // private getPhysicsBody() // { // if (this.physicsBody === "Not in physics world") // { // throw Error(`Vehicle ${this.getVehicle().debugId} is not in` // + ` physics world yet and doesn't have a physics body`); // } // return this.physicsBody; // } // --- Init --- /// Nothing needs to be initialized for now. I'll leave it here /// for possible future use. // ! Throws exception on error. // private init() // { // } // --- Arrive Torque --- private computeArriveTorque() { // ! Throws exception on error. const currentAngularVelocity = this.getAngularVelocity(); // ! Throws exception on error. // (There is a hard angular velocity limit in Box2d.) this.validateAngularVelocity(currentAngularVelocity); // ! Throws exception on error. const inertia = this.inertiaValue; // ! Throws exception on error. const angularVelocityChange = this.computeAngularVelocityChange(inertia, currentAngularVelocity); const torque = this.computeTorqueToChangeAngularVelocity ( angularVelocityChange, inertia ); this.updateTorqueRatio(torque); return torque; } // ! Throws exception on error. private computeAngularVelocityChange ( inertia: number, currentAngularVelocity: number ) { // ! Throws exception on error. const angularDistance = this.computeAngularDistance(); const desiredAngularVelocity = // ! Throws exception on error. this.computeDesiredAngularVelocity(angularDistance, inertia); return desiredAngularVelocity - currentAngularVelocity; } // ! Throws exception on error. private computeAngularDistance() { // ! Throws exception on error. const desiredRotation = this.getWaypointDirection(); // ! Throws exception on error. const currentRotation = this.getRotation().valueOf(); return Angle.minusPiToPi(desiredRotation - currentRotation); } // ! Throws exception on error. private computeDesiredAngularVelocity ( angularDistance: number, inertia: number ) { // Distance travelled by angular velocity achieved by one tick // of acceleration at full angular thrust (which is the same as // distance travelled in the last tick of decceleration). // d = F / (m * FPS * FPS * 2); const lastTickDistance = this.currentAngularThrust / (inertia * Engine.FPS * Engine.FPS * 2); // Prevent slow stopping by a lot of small iterations when we are // almost at the target. if (Math.abs(angularDistance) < lastTickDistance) return 0; let desiredAngularSpeed = Math.sqrt ( // We can't square root a negative number so we need to do it // on absolute value and reapply the direction later. Math.abs(angularDistance * this.currentAngularThrust * 2 / inertia) ); // In the previous step we have calculated angular velocity that we // would have to have at current position in order to stop exactly // at the target. But we are already at that point so we have to // subtract the change in angular velocity that will be added in // the next tick. desiredAngularSpeed -= this.currentAngularThrust / (inertia * Engine.FPS); desiredAngularSpeed = desiredAngularSpeed.atMost(this.currentMaxAngularVelocity); const desiredAngularVelocity = (angularDistance < 0) ? -desiredAngularSpeed : desiredAngularSpeed; // ! Throws exception on error. // (There is a hard angular velocity limit in Box2d.) return this.validateAngularVelocity(desiredAngularVelocity); } private computeTorqueToChangeAngularVelocity ( angularVelocityChange: number, inertia: number ) { // Compute angular thrust needed to reach desired angular velocity in // one tick (this handles the last tick when we need less than full // thrust to come to stop. In other cases we cap it to maximum thrust). const desiredAngularThrust = inertia * angularVelocityChange * Engine.FPS; return Number(desiredAngularThrust).clampTo ( -this.currentAngularThrust, this.currentAngularThrust ); } private updateTorqueRatio(torque: number) { const ratio = (this.currentAngularThrust !== 0) ? torque / this.currentAngularThrust : 0; this.torqueRatio = ratio * this.thrustMultiplier.valueOf(); } // --- Arrive Steering Force --- // ! Throws exception on error. private computeArriveSteeringForce() { // ! Throws exception on error. const currentVelocity = this.getVelocity(); const currentSpeed = currentVelocity.length(); // ! Throws exception on error. // (There is a hard speed limit in Box2d.) this.validateSpeed(currentSpeed); // ! Throws exception on error. const targetVector = this.computeTargetVector(); const distance = targetVector.length(); if (distance > 0) // ! Throws exception on error. this.updateWaypointDirection(); // ! Throws exception on error. const desiredSpeed = this.computeDesiredSpeed(distance, targetVector); this.desiredVelocity.set(targetVector).setLength(desiredSpeed); const velocityChange = this.computeVelocityChange(currentVelocity); // ! Throws exception on error. const thrust = this.computeSteeringThrust(velocityChange); return new Vector(velocityChange).setLength(thrust); } private computeVelocityChange(currentVelocity: Vector) { return Vector.v1MinusV2(this.desiredVelocity, currentVelocity); } // ! Throws exception on error. private computeSteeringThrust(velocityChange: Vector) { const thrustData = this.computeThrustData(velocityChange); const thrust = this.computeThrustValue ( velocityChange, thrustData.fullThrust ); this.updateThrustRatios(thrustData, thrust); return thrust; } // ! Throws exception on error. private computeThrustValue(velocityChange: Vector, fullThrust: number) { // ! Throws exception on error. const mass = this.massValue; const desiredSpeedChange = velocityChange.length(); // Compute thrust needed to reach desired speed in one tick // (this handles the last tick when we need less than full // thrust to come to stop. In other cases we cap it to full thrust). const desiredThrust = mass * desiredSpeedChange * Engine.FPS; return desiredThrust.atMost(fullThrust); } private computeThrustData(direction: Vector): ThrustData { const thrustAngle = this.angleToShip(direction); // Surprisingly, ratios of coordinates of a point on // an ellipse to respective radii of that ellipse // are calculated exactly the same way as on the circle // (it's because radia cancel themselves from the equations). const forwardThrustRatio = Math.cos(thrustAngle); const leftwardThrustRatio = Math.sin(thrustAngle); const fullThrust = this.computeThrustFromRatios ( forwardThrustRatio, leftwardThrustRatio ); return { forwardThrustRatio, leftwardThrustRatio, fullThrust }; } private computeThrustFromRatios ( forwardThrustRatio: number, leftwardThrustRatio: number ) { // The idea here is to compute thrust as a distance of a point on // ellipse with x radius equal to forward or backward maximum thrust // and y radius equal to strafe maximum thrust. // However, forward maximum thrust differs from backward maximum // thrust so it's not a single ellipse but half-an-ellipse in // forward direction and another half-an-ellipse in backward // direction. // (Also note that computing thrust as a point on ellipse technically // isn't correct, forces should actually just add up as vectors, but // I don't want ships to accelerate the fastest when going askew). if (forwardThrustRatio > 0) { return distanceFromOrigin ( forwardThrustRatio * this.currentForwardThrust, leftwardThrustRatio * this.currentStrafeThrust ); } else { return distanceFromOrigin ( forwardThrustRatio * this.currentBackwardThrust, leftwardThrustRatio * this.currentStrafeThrust ); } } private updateThrustRatios(thrustData: ThrustData, thrust: number) { let ratio = (thrustData.fullThrust !== 0) ? thrust / thrustData.fullThrust : 0; // Note that this will make thrusters even longer than 100% if // 'this.thrustMultiplier' is > 1. Exhaust sound volume will stay // at 100%, however, because sound volume can't go higher. ratio *= this.thrustMultiplier.valueOf(); this.forwardThrustRatio = thrustData.forwardThrustRatio * ratio; this.leftwardThrustRatio = thrustData.leftwardThrustRatio * ratio; } // ! Throws exception on error. private computeTargetVector() { return Vector.v1MinusV2 ( this.getWaypointPosition(), // ! Throws exception on error. this.getPosition() ); } private computeBrakingThrust(targetVector: Vector) { const thrustData = this.computeThrustData(Vector.negate(targetVector)); return this.computeThrustFromRatios ( thrustData.forwardThrustRatio, thrustData.leftwardThrustRatio ); } private angleToShip(direction: Vector) { const shipRotation = this.getRotation().valueOf(); const directionRotation = direction.getRotation(); return Angle.zeroTo2Pi(directionRotation - shipRotation); } // ! Throws exception on error. private computeDesiredSpeed(distance: number, targetVector: Vector): number { const fullBrakingThrust = this.computeBrakingThrust(targetVector); // Distance travelled by velocity achieved by one tick of // acceleration at fullBrakingThrust (which is the same as // distance travelled in the last tick of decceleration). // d = F / (m * FPS * FPS * 2); const lastTickDistance = fullBrakingThrust / (this.massValue * Engine.FPS * Engine.FPS * 2); // Prevent slow stopping by a lot of small iterations when we are // almost at the target. if (distance < lastTickDistance) return 0; let desiredSpeed = Math.sqrt ( distance * fullBrakingThrust * 2 / this.massValue ); // In the previous step we have calculated velocity that we would // have to have at current position in order to stop exactly at // the target. But we are already at that point so we have to subtract // the change in velocity that will be added in the next tick. desiredSpeed -= fullBrakingThrust / (this.massValue * Engine.FPS); desiredSpeed = desiredSpeed.atMost(this.currentMaxSpeed); // ! Throws exception on error. // (There is a hard speed limit in Box2d.) return this.validateSpeed(desiredSpeed); } // ! Throws exception on error. private validateSpeed(speed: number) { if (speed > Physics.MAXIMUM_POSSIBLE_SPEED) { throw Error(`Vehicle ${this.getEntity().debugId} attempts to reach` + ` speed '${speed}' which is greater than maximum speed allowed` + ` by Box2d physics engine (${Physics.MAXIMUM_POSSIBLE_SPEED}).` + ` There are three ways to handle this: 1 - set lower maximum` + ` speed for this vehicle, 2 - change coords transformation ratio in` + ` CoordsTransform so the same speed in pixels translates to lower` + ` speed in physics engine, 3 - increase engine FPS (that effectively` + ` increases maximum possible speed)`); } return speed; } // ! Throws exception on error. private validateAngularVelocity(angularVelocity: number) { if (angularVelocity > Physics.MAXIMUM_POSSIBLE_ANGULAR_VELOCITY) { throw Error(`Vehicle ${this.getEntity().debugId} attempts to reach` + ` angular velocity '${angularVelocity}' which is greater than` + ` maximum angular velocity allowed by Box2d physics engine` + ` (${Physics.MAXIMUM_POSSIBLE_ANGULAR_VELOCITY}). There are` + ` two ways to handle this: 1 - Make sure that maximum angular` + ` velocity for this vehicle doesn't exceed this limit, 2 - increase` + ` engine FPS (that effectively increases maximum possible angular` + ` velocity)`); } return angularVelocity; } } // ----------------- Auxiliary Functions --------------------- function computeBrakingDistance(m: number, v: number, F: number) { if (F === 0) return 0; return (m * v * v) / (F * 2); } function distanceFromOrigin(x: number, y: number) { return Math.sqrt(x * x + y * y); } // ------------------ Type declarations ---------------------- type ThrustData = { forwardThrustRatio: number; leftwardThrustRatio: number; fullThrust: number; }; ClassFactory.registerClassPrototype(VehiclePhysics);
217249deeb099031734972adfcafe2885770a45e
TypeScript
aceunlonely/Unknow
/main/base/base.ts
2.609375
3
class Body{ oid : string; } class BasicAttr { //strength str_base : number; str_max : number; str_bonus: number; str : number; //vitality vit_base : number; vit_max : number; vit_bonus:number; vit : number; //focus focus_base : number; focus_max : number; focus_bonus: number; focus: number; //agility agi_base : number; agi_max : number; agi_bonus:number; agi : number; //morale (士气) mo_base : number; mo_max : number; mo_bonus:number; mo : number; //strongD强度 strD_base : number; strD_max:number; strD_bonus:number; strD : number; //IQ iq_base:number; iq_max:number; iq_bonus:number; iq:number; //EQ eq_base:number; eq_max:number; eq_bonus:number; eq:number; } class HiddenAttr{ //基础属性成长值 str_g: number; vit_g:number; focus_g:number; agi_g:number; mo_g:number; std_g:number; iq_g:number; eq_g:number; //其他 // hp recover hpRec_base:number; hpRec_bonus:number; hpRec:number; // attack cost atkCo_base:number; atkCo_bonus:number; atkCo:number; // wrestle cost wsCo_base:number; wsCo_bonus:number; wsCo:number; //eva cost evaCo_base:number; evaCo_bonus:number; evaCo:number; //others // cost per month cost : number; // faith decrease per month faith_de: number; faith_de_count:number; // morale mo : number; //2 //suitability suit_sword: number; suit_shield:number; suit_claymore:number; suit_blade:number; suit_gun:number; suit_spear:number; suit_bow:number; suit_axe:number; suit_dagger:number; suit_staff:number; //weapon grow grow_base_init:number; // 初始 grow_base_bonus:number; // 附加 grow_base_bonus_level:number;//成长 grow_base:number; grow_sword:number; grow_shield:number; grow_claymore:number; grow_blade:number; grow_gun:number; grow_spear:number; grow_bow:number; grow_axe:number; grow_dagger:number; grow_staff:number; // battle talent battle_talent:number; } class BattleAttr{ hp_base:number; hp_bonus_m:number; hp_bonus_p:number; hp:number; mp_base:number; mp_bonus_m:number; mp_bonus_p:number; mp:number; atk_base:number; atk_bonus_m:number; atk_bonus_p:number; atk:number; mag_base:number; mag_bonus_m:number; mag_bonus_p:number; mag:number; def_base:number; def_bonus_m:number; def_bonus_p:number; def:number; //hit rate hr_base :number; hr_bonus_m:number; hr_bonus_p:number; hr:number; //cr 要害命中率 cr_base:number; cr_bonus_m:number; cr_bonus_p:number; cr:number; // evade eva_base:number; eva_bonus_m:number; eva_bonus_p:number; eva:number; } enum EnumQuntity { god,legend,ultima,famous,super,one,two,three,four,five,unknow,other} enum EquipType { weapon,shield,body,leg,head,special} enum EquipSubType{ sword} //装备特性 enum EquipSpecial {} export class Equip { name : string; subType : EquipSubType; quntity: EnumQuntity; cof: number; equipType: EquipType; at: number; at_shock:number; dura:number; //nai jiu special: EquipSpecial; parry: number; //ge dang def : number; //hit rate plus hr_bonus_p:number; //c rate plus cr_bonus_p:number; //eva rate plus; eva_bonus_p:number; //eva c rate plus; ceva_bonus_p:number; // shanghai xiu zheng hcor hCor:number; // c xiu zheng chCor; chCor:number; // str_bonus:number; vit_bonus:number; focus_bonus:number; agi_bonus:number; mo_bonus:number; strD_bonus:number; iq_bonus:number; eq_bonus:number; hp_bonus:number; mp_bonus:number; atk_bonus:number; def_bonus:number; hr_bonus:number; cr_bonus:number; eva_bonus:number; ceva_bonus:number; } // equip cap enum EquipType { weapon,shield,body,leg,head,special} class EquipCap{ l_hand : Equip; r_hand : Equip; head : Equip; body: Equip; leg: Equip; } export class HumenBeing extends Body { name : string; hunterName : string; hunterLevel: number; basicWage : number; summery : string; get wage() : number{ return 12;} //基础属性 basicAttr: BasicAttr; hiddenAttr: HiddenAttr; battleAttr : BattleAttr; equip:EquipCap; }
31c3cb32e2592e465691574ef134a40cf840c598
TypeScript
crusaider/hass-node-scripting-host
/src/rx-operators/newState.ts
2.703125
3
import { HassEntityBase } from 'home-assistant-js-websocket'; import { OperatorFunction } from 'rxjs'; import { pluck } from 'rxjs/operators'; import { StateChangedEvent } from './../StateChangedEvent'; /** * Plucks the new state from a emitted {@link StateChangedEvent}. * * @template T Type of the entity that has changed state. * @returns The new state from the {@link StateChangedEvent}. */ export function newState<T extends HassEntityBase>(): OperatorFunction< StateChangedEvent<T>, T > { return (input$) => input$.pipe(pluck<StateChangedEvent<T>, T>('data', 'new_state')); }
6dfe08ff26dfe26e0270b010c027a3f771f9b806
TypeScript
HXWfromDJTU/leetcode-daily
/141.环形链表.ts
4.0625
4
/** * @param {ListNode} head * @return {boolean} */ var hasCycle = function(head) { // 边界条件 if (!head || !head.next) return false const startTime = new Date().getTime() const gap = 500 let hasTail = false // 使用一个固定时间进行循环,让链表找自己的尾巴 while(new Date().getTime() - startTime < 500) { if (!head.next) { hasTail = true } else { head.next = head.next.next } } // 返回能不能找到的结果 return !hasTail }; // 解法2 使用set来存储访问过的节点 /** * @param {ListNode} head * @return {boolean} */ const hasCycle2 = function(head) { // 边界条件处理 if (!head || !head.next) return false const visitedSet = new Set() while (head.next) { // 若set中出现重复的节点,则说明有环 if (visitedSet.has(head.next)) { return true } else { // 若没有 // 存起来当前节点 visitedSet.add(head.next) // 向后移动 head.next = head.next.next } } return false }; // 方法3 快慢指针法 const hasCycle3 = function(head) { // 边界条件处理 if (!head || !head.next) return false let fast = head.next; let slow = head; // 保证 fast 与 slow 所指向都是有值的,并且要保证 fast.next.next 也要可以找到 while (fast && fast.next && slow) { if (fast === slow) { return true } else { // 慢指针走一步,快指针走两步 slow = slow.next fast = fast.next.next } } return false };
037a3f61f6ca54150d105103f96c1f676b8fcde0
TypeScript
scarlos723/inventario-angular
/src/app/services/cliente.service.ts
2.6875
3
import { Injectable } from '@angular/core'; import { Cliente } from '../interfaces/cliente'; @Injectable({ providedIn: 'root' }) export class ClienteService { clientes: Cliente[]; constructor() { let client1 : Cliente = { id : 1, cedula : 1061481512, nombres : 'Camilo Andres', apellidos :'Salgado Hernandez', telefono : 3135554444 }; let client2 : Cliente = { id : 2, cedula : 10415381512, nombres : 'Maria Antonia', apellidos :'Perez Prieto', telefono : 3135577744 }; let client3 : Cliente = { id : 3, cedula : 1061482512, nombres : 'Waldo Jose', apellidos :'Malavida Galindez', telefono : 3135444111 }; let client4 : Cliente = { id : 4, cedula : 10611475512, nombres : 'Pedro', apellidos :'Rengifo Hernandez', telefono : 3137754444 }; this.clientes = [client1,client2,client3,client4]; } // metodos que se pueden llamar desde los components getCliente(){ return this.clientes } getClienteById(id:any){ //por algun motivo me toca especificar el id de tipo any return this.clientes.find(item => item.id == id); //verifica cada item en clientes y comprueva el id } crearCliente(datos:any){ let idAux = this.clientes.length +1; let clienAux:Cliente={ id : idAux, cedula : datos.cedula, nombres : datos.nombreClient, apellidos : datos.apellidoClient, telefono : datos.telefono } return clienAux; } }