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
3c6a28c58a8c611713287911b101dbc6c6d6d565
TypeScript
hollyoops/algorithm
/src/reverseLinkedList.test.ts
4.125
4
/** * * Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL */ interface INode { value: number next?: INode } class NodeList { private first?: INode private tail?: INode get head() { return this.first } addNode(value: number) { const newNode = { value, } if (!this.tail) { this.first = newNode this.tail = this.first } else { this.tail.next = newNode this.tail = newNode } return this } reverse() { let cur = this.first this.tail = this.first let pre: INode | undefined = undefined while (cur) { const next = cur.next cur.next = pre pre = cur cur = next } this.first = pre } listValues() { const list: number[] = [] let cur = this.first while (cur) { list.push(cur.value) cur = cur.next } return list } } test('should reverse the link list', () => { const list = new NodeList() ;[1, 2, 3, 4, 5].forEach(element => { list.addNode(element) }) list.reverse() expect(list.listValues()).toEqual([5, 4, 3, 2, 1]) })
6a6fa5032c89bac1d30b85d7a923c96d16ee345d
TypeScript
Type-Any/WTT
/src/utils/hooks/useMutation.ts
2.765625
3
import {useCallback, useState} from 'react'; export const useMutation = <Req = any, Res = any>( fetcher: (endpoint: string, req?: Req) => Promise<Res>, revalidateFn?: () => void, ): [ excute: (endpoint: string, req: Req) => Promise<Res | undefined>, loading: boolean, error: string | null, ] => { const [loading, setLoading] = useState<boolean>(false); const [error, setError] = useState<string | null>(null); const excute = async (endpoint: string, req: Req) => { try { setError(null); setLoading(true); const response = await fetcher(endpoint, req); revalidateFn?.(); return response; } catch (error: any) { const message = error?.message || 'Unexpected Error'; setError(message); } finally { setLoading(false); } }; return [excute, loading, error]; };
223f3abea2a49a8a64b106889e6585a371fd0fa1
TypeScript
mytlogos/enterprise-lister
/packages/scraper/src/tools.ts
2.890625
3
import { TocEpisode, TocPart, TocContent } from "./externals/types"; /** * Returns true if the value is a TocEpisode. * * @param tocContent value to check */ export function isTocEpisode(tocContent: TocContent): tocContent is TocEpisode { return "url" in tocContent; } /** * Returns true if the value is a TocPart. * * @param tocContent value to check */ export function isTocPart(tocContent: TocContent): tocContent is TocPart { return "episodes" in tocContent; }
71213542501dc3c698488d57f8fd13538469e88e
TypeScript
ryanvanrooyen/csscrape
/Source/httpClient.ts
2.890625
3
import * as urls from 'url'; import { ILogger, NullLogger } from './logging'; import { IHttpTransport, HttpTransport} from './httpTransport'; export interface IHttpClient { get(url: string): Promise<IHttpResponse>; } export interface IHttpResponse { url: string, data: string } export class HttpClient implements IHttpClient { constructor(private log: ILogger = new NullLogger(), private transport: IHttpTransport = new HttpTransport()) { } get(url: string) { try { return this.internalGet(url); } catch (err) { return Promise.reject<IHttpResponse>(err); } } private internalGet(url: string): Promise<IHttpResponse> { if (!url || !url.length) throw 'No url specified to http get.'; if (url.indexOf('://') === -1) url = 'http://' + url; var parsedUrl = this.parseUrl(url); var options = this.getHttpOptions('GET', parsedUrl); return this.transport.transfer(parsedUrl, options).then(resp => { var newResp = this.checkStatusCodes(url, resp.statusCode, resp.headers); if (newResp) return newResp; return { url: url, data: resp.data }; }); } private parseUrl(url: string) { var parsedUrl = urls.parse(url); if (!parsedUrl.protocol || !parsedUrl.protocol.length) { parsedUrl.protocol = 'http:'; } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') { throw `Invalid url protocol to http get request: ${parsedUrl.protocol}`; } return parsedUrl; } private getHttpOptions(method: string, url: urls.Url) { return { method: method, hostname: url.host, port: null, path: url.path, headers: { accept: '*/*', "cache-control": "no-cache", "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36' } }; } // Can return a new response to be returned from the client. private checkStatusCodes(url: string, statusCode: number, headers: {}): Promise<IHttpResponse> { if (this.isInRange(statusCode, 200)) return null; var location: string = (<any>headers).location; var redirectCodes = [300, 301, 307, 410]; if (this.isValue(statusCode, redirectCodes) && location) { var newUrl = urls.resolve(url, location); if (newUrl !== url) { this.log.warn(`Received ${statusCode} from ${url}`); this.log.warn(`Going to new url ${newUrl}`); return this.get(newUrl); } } if (!this.isInRange(statusCode, 200)) { this.log.error(`Received status code ${statusCode} for url ${url} with headers:`); this.log.error(headers); throw `Received status code ${statusCode} for url ${url}`; } return null; } private isInRange(value: number, numb: number) { return value >= numb && value < (numb + 100); } private isValue(value: number, numbs: number[]) { return numbs.some(n => value === n); } }
dc8422866e76ecab7e09fb4961cdbb79fae05104
TypeScript
leandrogr/chat-api
/src/users/dto/create-user.dto.ts
2.65625
3
import { IsEmail, IsNotEmpty, Matches } from 'class-validator'; import { RegExHelper } from 'src/helpers/regex.helper'; import { MessagesHelper } from 'src/helpers/messages.helper'; export class CreateUserDto { @IsNotEmpty() name: string; @IsNotEmpty() @IsEmail() email: string; @IsNotEmpty() @Matches(RegExHelper.password, { message: MessagesHelper.PASSWORD_VALID, }) password: string; }
e0b183c3db776f36aa793279c399f0d91f21f1f1
TypeScript
haniot/timeseries
/test/unit/models/user.model.spec.ts
2.84375
3
import { assert } from 'chai' import { User } from '../../../src/application/domain/model/user' describe('Models: User', () => { const userJSON: any = { id: '5a62be07d6f33400146c9b61', type: 'patient' } describe('fromJSON()', () => { context('when the json is correct', () => { it('should return a user model', () => { const result = new User().fromJSON(userJSON) assert.propertyVal(result, 'id', userJSON.id) assert.propertyVal(result, 'type', userJSON.type) }) }) context('when the json is empty', () => { it('should return a user model with undefined parameters', () => { const result = new User().fromJSON({}) assert.propertyVal(result, 'id', undefined) assert.propertyVal(result, 'type', undefined) }) }) context('when the json is undefined', () => { it('should return a user model with undefined parameters', () => { const result = new User().fromJSON(undefined) assert.propertyVal(result, 'id', undefined) assert.propertyVal(result, 'type', undefined) }) }) context('when the json is a string', () => { it('should transform the string in json and return User model', () => { const result = new User().fromJSON(JSON.stringify(userJSON)) assert.propertyVal(result, 'id', userJSON.id) assert.propertyVal(result, 'type', userJSON.type) }) }) }) })
7a15e47c2de09840bc97b379480e9d10d1f633e3
TypeScript
JoshuaSkootsky/svelte-ts-electron-forge
/packages/utils/src/fibonacci.ts
3.625
4
export function fibonacci(n: number): number { if (n < 0) { throw new Error('Can\'t compute the fibonacci number of a negative index') } if (n < 2) { return 1 } return fibonacci(n - 1) + fibonacci(n - 2) }
0893eb8f59a6d6d0a8ea53cfc75ff4c7b3032794
TypeScript
zengming00/node-gd-bmp
/src/demo/test.ts
2.53125
3
import * as http from 'http'; import { BMP24 } from '../BMP24'; // gd-bmp import * as font from '../font'; /* 用PCtoLCD2002取字模 行列式扫描,正向取模(高位在前) */ const cnfonts: font.IFont = { // 自定义字模 w: 16, h: 16, fonts: '中国', data: [ [0x01, 0x01, 0x01, 0x01, 0x3F, 0x21, 0x21, 0x21, 0x21, 0x21, 0x3F, 0x21, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x08, 0x08, 0x08, 0x08, 0x08, 0xF8, 0x08, 0x00, 0x00, 0x00, 0x00], /* "中",0 */ [0x00, 0x7F, 0x40, 0x40, 0x5F, 0x41, 0x41, 0x4F, 0x41, 0x41, 0x41, 0x5F, 0x40, 0x40, 0x7F, 0x40, 0x00, 0xFC, 0x04, 0x04, 0xF4, 0x04, 0x04, 0xE4, 0x04, 0x44, 0x24, 0xF4, 0x04, 0x04, 0xFC, 0x04] /* "国",1 */ ], }; // 测试字库 function makeImg2() { const img = new BMP24(300, 140); img.drawString('helloworld', 20, 10, BMP24.font8x16, 0xff0000); img.drawString('helloworld', 20, 25, BMP24.font12x24, 0x00ff00); img.drawString('helloworld', 20, 50, BMP24.font16x32, 0x0000ff); img.drawString('中国', 20, 85, cnfonts, 0xffffff); return img; } function rand(min: number, max: number) { return ~~(Math.random() * (max - min) + min); } // 制造验证码图片 function makeCapcha() { const img = new BMP24(100, 40); img.drawRect(0, 0, img.w, img.h, rand(0, 0xffffff)); img.fillRect(1, 1, img.w - 2, img.h - 2, 0xffffff); img.drawCircle(rand(0, 100), rand(0, 40), rand(10, 40), rand(0, 0xffffff)); img.fillRect(rand(0, 100), rand(0, 40), rand(10, 35), rand(10, 35), rand(0, 0xffffff)); img.drawLine(rand(0, 100), rand(0, 40), rand(0, 100), rand(0, 40), rand(0, 0xffffff)); // 画曲线 const w = img.w / 2; const h = img.h; const color = rand(0, 0xffffff); const y1 = rand(-5, 5); const w2 = rand(10, 15); const h3 = rand(4, 6); const bl = rand(1, 5); for (let i = -w; i < w; i += 0.1) { const yy = Math.floor(h / h3 * Math.sin(i / w2) + h / 2 + y1); const xx = Math.floor(i + w); for (let j = 0; j < bl; j++) { img.drawPoint(xx, yy + j, color); } } const p = 'ABCDEFGHKMNPQRSTUVWXYZ3456789'; let str = ''; for (let a = 0; a < 5; a++) { str += p.charAt(Math.random() * p.length | 0); } const fonts = [BMP24.font8x16, BMP24.font12x24, BMP24.font16x32]; // eslint-disable-next-line one-var let x = 15, y = 8; for (const ch of str) { const f = fonts[Math.random() * fonts.length | 0]; y = 8 + rand(-10, 10); img.drawChar(ch, x, y, f, rand(0, 0xffffff)); x += f.w + rand(2, 8); } return img; } // 测试生成验证码的效率 const start = Date.now(); let n = 0; while ((Date.now() - start) < 1000) { makeCapcha(); // makeImg2(); n++; } console.log(`1秒钟生成:${n}`); http.createServer((req, res) => { switch (req.url) { case '/favicon.ico': res.end(); break; case '/img2': { console.time('makeImg2'); const img = makeImg2(); console.timeEnd('makeImg2'); res.setHeader('Content-Type', 'image/bmp'); res.end(img.getFileData()); break; } case '/data': { const img = makeImg2(); const dataUrl = img.getDataUrl(); res.setHeader('Content-Type', 'text/html'); res.end(`<img src="${dataUrl}"/>`); break; } case '/': default: { console.time('makeCapcha'); const img = makeCapcha(); console.timeEnd('makeCapcha'); res.setHeader('Content-Type', 'image/bmp'); res.end(img.getFileData()); } } }).listen(3000); console.log('localhost:3000');
e3c8916f97ed0ffff726b0680b0cb833df2c2db0
TypeScript
terzeron/Angular2Test
/typescript_test/test07.ts
3.421875
3
class MyCar { _numTier: number; _carName: string; constructor(carName: string, numTier: number) { this._carName = carName; this._numTier = numTier; } getCarName(): String { return this._carName; } numTier() { return this._numTier; } } let myCar: MyCar = new MyCar("tiara", 1); console.log(myCar.getCarName());
3f0d1ea27c432bf3447ad41f1a7a6115afcbaea6
TypeScript
truenas/webui
/src/app/interfaces/keychain-credential.interface.ts
2.625
3
import { KeychainCredentialType } from 'app/enums/keychain-credential-type.enum'; import { SshCredentials } from 'app/interfaces/ssh-credentials.interface'; export type KeychainCredential = | KeychainSshKeyPair | KeychainSshCredentials; export interface KeychainSshKeyPair { attributes: SshKeyPair; id: number; name: string; type: KeychainCredentialType.SshKeyPair; } export interface SshKeyPair { private_key: string; public_key: string; } export interface KeychainSshCredentials { attributes: SshCredentials; id: number; name: string; type: KeychainCredentialType.SshCredentials; } export type KeychainCredentialCreate = Omit<KeychainCredential, 'id'>; export type KeychainCredentialUpdate = Omit<KeychainCredential, 'id' | 'type'>;
932e96852ab0155dca6577758d30922d70ec9c75
TypeScript
adham-ta/RepoBot
/test/integration/webhook.test.ts
2.578125
3
import Stream from "stream"; import request from "supertest"; import pino from "pino"; import { Probot } from "../../src"; import * as data from "../fixtures/webhook/push.json"; describe("webhooks", () => { let probot: Probot; let output: any; const streamLogsToOutput = new Stream.Writable({ objectMode: true }); streamLogsToOutput._write = (object, encoding, done) => { output.push(JSON.parse(object)); done(); }; beforeEach(() => { output = []; probot = new Probot({ appId: 1, privateKey: "bexo🥪", secret: "secret", log: pino(streamLogsToOutput), }); }); test("it works when all headers are properly passed onto the event", async () => { const dataString = JSON.stringify(data); await request(probot.server) .post("/") .send(dataString) .set("x-github-event", "push") .set("x-hub-signature", probot.webhooks.sign(dataString)) .set("x-github-delivery", "3sw4d5f6g7h8") .expect(200); }); test("shows a friendly error when x-hub-signature is missing", async () => { await request(probot.server) .post("/") .send(data) .set("x-github-event", "push") // Note: 'x-hub-signature' is missing .set("x-github-delivery", "3sw4d5f6g7h8") .expect(400); expect(output[0]).toEqual( expect.objectContaining({ msg: "Go to https://github.com/settings/apps/YOUR_APP and verify that the Webhook secret matches the value of the WEBHOOK_SECRET environment variable.", }) ); }); test("logs webhook error exactly once", async () => { await request(probot.server) .post("/") .send(data) .set("x-github-event", "push") // Note: 'x-hub-signature' is missing .set("x-github-delivery", "3sw4d5f6g7h8") .expect(400); const errorLogs = output.filter((output: any) => output.level === 50); expect(errorLogs.length).toEqual(1); }); });
9c3dbb6ff73b6aa7cad93db3d0d62eed9e1beedb
TypeScript
KairuRengu/OpenORPG
/OpenORPG.TypeScriptClient/Game/States/GameplayState.ts
2.6875
3
 module OpenORPG { // The gameplay state manages export class GameplayState extends Phaser.State { private zone: Zone = null; private currenTrack: Phaser.Sound; private ChatManager: ChatManager; private inventoryWindow: InventoryWindow; private characterWindow: CharacterWindow; // Keep track of character info private playerInfo: PlayerInfo = new PlayerInfo(); constructor() { super(); // Init this.ChatManager = new ChatManager(); this.inventoryWindow = new InventoryWindow(); this.characterWindow = new CharacterWindow(this.playerInfo); // Do some basic key bindings $(document).on('keypress', (event: JQueryEventObject) => { if (document.activeElement) { var x: any = document.activeElement; var id = x.id; if (event.which == 13) { if (id == "chatmessage") { console.log('focus game'); $("#canvasholder").focus(); } else { console.log('focus chat'); $("#chatmessage").focus(); } } } }); } preload() { SpriteManager.loadSpriteImages(this.game); // Load up everything else var loader = this.game.load; loader.tilemap("map_1", "assets/Maps/1.json", null, Phaser.Tilemap.TILED_JSON); loader.tilemap("map_2", "assets/Maps/2.json", null, Phaser.Tilemap.TILED_JSON); loader.image("tilesheet", "assets/Maps/tilesheet_16.png"); // Load all our audio loader.audio("audio_music_town", [DirectoryHelper.getMusicPath() + "town.ogg"]); loader.audio("audio_effect_hit", [DirectoryHelper.getAudioEffectPath() + "hit1.ogg"]); } render() { if (this.zone != null) this.zone.render(); } create() { // Start our physics systems this.game.physics.startSystem(Phaser.Physics.ARCADE); var network = NetworkManager.getInstance(); network.registerPacket(OpCode.SMSG_ZONE_CHANGED, (packet: any) => { if (this.zone != null) this.zone.clearZone(); // Stop current music and all sound effects this.game.sound.stopAll(); // Load new audio track in this.currenTrack = this.game.add.audio("audio_music_town", 0.5, true, true); this.currenTrack.play(); this.zone = new Zone(this.game, packet.zoneId); for (var entityKey in packet.entities) { var entity = packet.entities[entityKey]; // Create your objects here var worldEntity: Entity = this.zone.addNetworkEntityToZone(entity); // Do camera following here if (worldEntity.id == packet.heroId) { this.game.camera.follow(worldEntity); this.zone.movementSystem.attachEntity(worldEntity); // Init character info for (var key in entity.characterStats.stats) { var statObject = entity.characterStats.stats[key]; this.playerInfo.characterStats[statObject.statType] = { currentValue: statObject.currentValue, maximumValue: statObject.maximumValue }; } this.playerInfo.name = worldEntity.name; this.characterWindow.renderStats(); } } }); // Register for stat changes network.registerPacket(OpCode.SMSG_STAT_CHANGE, (packet: any) => { // Update these, fire callback this.playerInfo.characterStats[packet.stat].currentValue = packet.currentValue; this.playerInfo.characterStats[packet.stat].maximumValue = packet.maximumValue; // Trigger callback this.playerInfo.onCharacterStatChange(); }); } update() { if (this.zone != null) this.zone.update(); } } }
cc7b3d0b911b0ffcb1264b36b072d63c6380783d
TypeScript
usagihana/ducktools
/src/createEventBus.ts
2.8125
3
export function createEventBus(debug = false){ const subscribers = {} // channel => array[callback()] function on(channel, func){ let out = func if(debug){ out = function(rest){ func(rest) console.log(' %cEVENT - '+channel,'color:orange;',JSON.stringify(rest)) } } subscribers[channel] = subscribers[channel] || [] subscribers[channel].push(out) return true } function emit(channel, payload){ if(!subscribers[channel]) return console.warn('No Subscribers for '+channel) subscribers[channel].forEach( f => f(payload) ) } function clear(channel){ subscribers[channel] = null subscribers[channel] = [] } const exports = { on, emit, clear } return exports }
d2d21c6c1f6154e3539c21fa99a53d465e384e7b
TypeScript
felipeVoid/a-club
/src/app/pipes/file-icon.pipe.ts
2.515625
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'fileIcon' }) export class FileIconPipe implements PipeTransform { transform(type: any): string { try { switch(type.trim().toLowerCase()) { case 'jpg': case 'jpeg': case 'png': case 'svg': case 'ico': case 'gif': case 'tiff': return 'photo_library'; case 'mp4': case 'avi': case '3gp': case 'mov': return 'video_library'; case 'pdf': return 'picture_as_pdf'; case 'mp3': case 'flac': return 'library_music'; default: return 'library_books'; } } catch (e) { return 'library_books'; } } }
e357ca9526f97154234e47fcdccc75f564b06a4e
TypeScript
MagusM/food-chooser-server
/src/repositories/postgres.ts
2.59375
3
import { ICheckboxFoodOption, IUser } from '../entities/interfaces' import postgresConnection from './dbConfig'; const { Pool } = require('pg'); const pool = new Pool(postgresConnection); export async function getAllFoods() { return pool.query('SELECT * FROM foods') } export async function addNewFood(foodName: string) { pool.query('INSERT INTO Foods(FOOD_NAME, FOOD_CATEGORY) VALUES($1, $2)', [foodName, 'אוכל']) } export async function addUser(user: IUser) { await pool.query(`UPDATE Users SET FIRST_NAME=$1, LAST_NAME=$2, BIRTH_DATE=$3, ID_NUMBER=$4, PHONE_NAMBER=$5, LAST_UPDATED=NOW() WHERE EMAIL=$6;`, [user.FIRST_NAME, user.LAST_NAME, user.BIRTH_DATE, user.ID_NUMBER, user.PHONE_NAMBER, user.EMAIL]); await pool.query(`INSERT INTO Users (EMAIL, FIRST_NAME, LAST_NAME, BIRTH_DATE, ID_NUMBER, PHONE_NAMBER, CREATED_AT, LAST_UPDATED) SELECT $1, $2, $3, $4, $5, $6, NOW(), NOW() WHERE NOT EXISTS (SELECT 1 FROM Users WHERE EMAIL=$7);`, [user.EMAIL, user.FIRST_NAME, user.LAST_NAME, user.BIRTH_DATE, user.ID_NUMBER, user.PHONE_NAMBER, user.EMAIL]); } export async function userLoggeddIn(user: IUser) { await pool.query(`UPDATE Users SET LAST_LOGGED_IN=NOW() WHERE EMAIL=$1;`,[user.EMAIL]); await pool.query(`INSERT INTO Users (EMAIL, CREATED_AT, LAST_LOGGED_IN) SELECT $1,NOW(), NOW() WHERE NOT EXISTS (SELECT 1 FROM Users WHERE EMAIL=$2);`, [user.EMAIL, user.EMAIL]); } export async function deselectUsersFood(email: string) { await pool.query(`UPDATE Users_Food SET SELECT_ACTIVE=$1, LAST_UPDATED=NOW() WHERE EMAIL=$2 AND SELECT_ACTIVE=$3;`,[false, email, true]); } export async function addUserFood(foodOption: ICheckboxFoodOption, email: string) { await pool.query(`UPDATE Users_Food SET SELECT_ACTIVE=$1, LAST_UPDATED=NOW() WHERE EMAIL=$2 And FOOD_ID=$3;`,[true, email, foodOption.food_id]); await pool.query(`INSERT INTO Users_Food (EMAIL, FOOD_ID, SELECT_ACTIVE, LAST_UPDATED) SELECT $1, $2, $3, NOW() WHERE NOT EXISTS (SELECT 1 FROM Users_Food WHERE EMAIL=$4 AND FOOD_ID=$5);`, [email, foodOption.food_id, true, email, foodOption.food_id]); }
9b22b72134b42cc468e856c7399fb6110193ccc6
TypeScript
AlexMunoz/preact-devtools
/src/view/components/profiler/flamegraph/transform/patchTree.ts
2.875
3
import { ID, Tree } from "../../../../store/types"; import { mapChildren, adjustNodesToRight, deepClone } from "./util"; export function patchTree(old: Tree, next: Tree, rootId: ID): Tree { const out: Tree = new Map(old); const oldRoot = old.get(rootId); const root = next.get(rootId)!; if (next.size === 0) { return old; } // Fast path if tree is new if (!oldRoot) { const offset = root.startTime; next.forEach(node => { out.set(node.id, { ...deepClone(node), treeStartTime: node.startTime - offset, treeEndTime: node.endTime - offset, }); }); return out; } const deltaStart = oldRoot.treeStartTime - root.startTime; const deltaEnd = oldRoot.treeStartTime + (root.endTime - root.startTime) - oldRoot.treeEndTime; // Move new tree to old tree position. out.set(root.id, { ...deepClone(root), treeStartTime: oldRoot.treeStartTime, treeEndTime: oldRoot.treeStartTime + (root.endTime - root.startTime), }); // Move children of newly committed sub-tree mapChildren(next, root.id, child => { out.set(child.id, { ...deepClone(child), // TODO: Check for stale children treeStartTime: child.startTime + deltaStart, treeEndTime: child.endTime + deltaStart, }); }); // Enlarge parents and move children adjustNodesToRight(out, root.id, deltaEnd); return out; }
37a167a51de8fbb1ef3f006be8d6c2d3f48169e4
TypeScript
ExcelDurant/helpme_nest_backend
/src/auth/auth.service.ts
2.546875
3
import { Injectable } from '@nestjs/common'; import { UsersService } from '../users/users.service'; import { JwtService } from '@nestjs/jwt'; import { User } from '../users/schemas/user.schema'; import * as bcrypt from 'bcrypt'; @Injectable() export class AuthService { constructor( private usersService: UsersService, private jwtService: JwtService ) { } async validateUser(email: string, pass: string): Promise<any> { const user = await this.usersService.findOne(email); const isMatch = await bcrypt.compare(pass, user.password); if (user && isMatch) { const { password, ...result } = user; return result; } return null; } async login(user: any) { const payload = { email: user.email, sub: user._id }; const { password, ...result } = user; return { access_token: this.jwtService.sign(payload), payload: payload, user:result }; } async signup(user: User) { const saltOrRounds = 10; const hashedPass = await bcrypt.hash(user.password, saltOrRounds); user.password = hashedPass; const createdUser = await this.usersService.createUser(user); const { password, ...result } = createdUser; const { _id, email } = createdUser; const payload = { sub: _id, email: email }; let signedUser = result._doc; delete signedUser.password; return { access_token: this.jwtService.sign(payload), user: signedUser as User } } }
8686d1baf5940ee0c8afbd7657e5b9e0f597af12
TypeScript
thisissoon-fm/frontend
/src/app/player/store/reducers/current.reducer.ts
2.734375
3
import * as fromCurrent from '../actions/current.action'; import { QueueItem } from '../../../api'; export interface CurrentState { loaded: boolean; loading: boolean; current: QueueItem; } export const initialState: CurrentState = { loaded: false, loading: false, current: null }; const newState = (state, newData) => { return Object.assign({}, state, newData); }; export function currentReducer( state = initialState, action: fromCurrent.CurrentAction ): CurrentState { switch (action.type) { case fromCurrent.LOAD_CURRENT: { return newState(state, { loaded: false, loading: true }); } case fromCurrent.LOAD_CURRENT_SUCCESS: { const current = (<fromCurrent.LoadCurrentSuccess>action).payload; return { loaded: true, loading: false, current }; } case fromCurrent.LOAD_CURRENT_FAIL: { return newState(state, { loaded: false, loading: false }); } case fromCurrent.REMOVE_CURRENT_SUCCESS: { return newState(state, { loaded: false, loading: false, current: null }); } case fromCurrent.ADD_PAUSE_SUCCESS: { return newState(state, { current: newState(state.current, { paused: true }) }); } case fromCurrent.REMOVE_PAUSE_SUCCESS: { return newState(state, { current: newState(state.current, { paused: false }) }); } case fromCurrent.TIMER_INCREMENT: { const player = state.current.player; player.elapsed_seconds++; player.elapsed_time += 1000; player.elapsed_percentage = player.elapsed_time / state.current.track.duration; return newState(state, { current: newState(state.current, { player }) }); } } return state; } export const getCurrentLoaded = (state: CurrentState) => state.loaded; export const getCurrentLoading = (state: CurrentState) => state.loading; export const getCurrent = (state: CurrentState) => state.current;
06cfbccd2c55924e2d368dcdaa7af97b1e2f5f89
TypeScript
ULL-ESIT-INF-DSI-2021/ull-esit-inf-dsi-20-21-prct08-filesystem-notes-app-Nitro1000
/tests/note.spec.ts
2.765625
3
import 'mocha'; import {expect} from 'chai'; import {Note} from '../src/note'; describe('Test Note', () => { const testNota = new Note('Test Nota', 'Nota prueba', 'Blue'); it('La nota es una intancia de la clase Note', () => { expect(testNota).to.be.instanceOf(Note); }); it('El titulo de la nota es Test Nota', () => { expect(testNota.getTitle()).to.be.eql('Test Nota'); }); it('El contenido de la nota es Nota prueba', () => { expect(testNota.getBody()).to.be.eql('Nota prueba'); }); it('El color de la nota es Blue', () => { expect(testNota.getColor()).to.be.eql('Blue'); }); });
22de62d64378502aebde14b8b47b8ae621c43ef0
TypeScript
evilive3000/umbrella
/examples/mandelbrot/src/gradient.ts
2.6875
3
import { TAU } from "@thi.ng/math/api"; import { clamp01 } from "@thi.ng/math/interval"; import { comp } from "@thi.ng/transducers/func/comp"; import { normRange } from "@thi.ng/transducers/iter/norm-range"; import { tuples } from "@thi.ng/transducers/iter/tuples"; import { push } from "@thi.ng/transducers/rfn/push"; import { transduce } from "@thi.ng/transducers/transduce"; import { map } from "@thi.ng/transducers/xform/map"; // see http://dev.thi.ng/gradients/ const cosColor = (dc: number[], amp: number[], fmod: number[], phase: number[], t: number) => transduce( map<number[], number>( ([a, b, c, d]) => clamp01(a + b * Math.cos(TAU * (c * t + d))) ), push(), tuples(dc, amp, fmod, phase) ); export const cosineGradient = (n: number, spec: number[][]) => { const [dc, amp, fmod, phase] = spec; return transduce( comp( map((t: number) => cosColor(dc, amp, fmod, phase, t)), map(([r, g, b]) => (b * 255) << 16 | (g * 255) << 8 | (r * 255) | 0xff000000) ), push(), normRange(n - 1) ); };
025a57bfa82b6a99dcbe310a6a52f6c10193e745
TypeScript
Zeng95/facile-translation-cli
/client/src/utils.ts
2.734375
3
export const truncate = (query: string) => { const len = query.length; if (len <= 20) { return query; } return query.substring(0, 10) + len + query.substring(len - 10, len); };
b41bca4f20468add15af293a97fc1183c0ab80b2
TypeScript
lanemt/definitelytyped.github.io
/types/overload-protection/overload-protection-tests.ts
2.59375
3
import op = require('overload-protection'); const config1: op.ProtectionConfig = { production: true, clientRetrySecs: 2, sampleInterval: 1, maxEventLoopDelay: 40, maxHeapUsedBytes: 25, maxRssBytes: 321, errorPropagationMode: true, logging: console.log, logStatsOnReq: false, }; const config2: op.ProtectionConfig = { logging: false, }; const config3: op.ProtectionConfig = { logging: 'warn', }; const instance = op('koa'); console.log(instance); console.log(instance({ foo: 'bar' }, () => 'Hello')); console.log(instance.overload); console.log(instance.eventLoopOverload); console.log(instance.heapUsedOverload); console.log(instance.rssOverload); console.log(instance.eventLoopDelay); console.log(instance.maxEventLoopDelay); console.log(instance.maxHeapUsedBytes); console.log(instance.maxRssBytes); const instance2 = op('express', config1); console.log(instance2({ foo: 'bar' }, { hello: 'world' }, () => 'World')); op('http', config2); op('restify', config3);
01cc4be5e1fb08b4d20874c9b42dd7f57aed40f6
TypeScript
d-o-n-u-t-s/note-editor
/src/utils/TimeCalculator.ts
3.078125
3
import { Fraction, IFraction } from "../math"; import { Measure } from "../objects/Measure"; import { OtherObject } from "../objects/OtherObject"; class BPMChangeData { private readonly unitTime: number; private readonly time: number; private stopTime: number; public readonly bpm: number; public readonly measurePosition: number; /** * コンストラクタ * @param current 現在のBPM拍子変更情報 * @param prev 直前のBPM拍子変更情報 * @param stops 停止情報 */ constructor( current: BpmChangeAndBeat, prev: BPMChangeData, stops: OtherObject[] ) { this.measurePosition = current.measurePosition; this.unitTime = (240 / current.bpm) * Fraction.to01(current.beat); this.time = prev ? prev.getTime(this.measurePosition) : 0; this.bpm = current.bpm; this.stopTime = 0; // 停止時間を計算する // TODO: stops全てを見ないように最適化できそう for (const stop of stops) { const measurePosition = stop.getMeasurePosition(); // 直前のBPM変更と現在のBPM変更の間に配置されている停止命令を探す if ( (prev ? prev.measurePosition : 0) <= measurePosition && this.measurePosition > measurePosition ) { const bpm = prev.bpm; // NOTE: 停止時間は192分音符を基準にする this.stopTime += (240 / bpm) * ((1 / 192) * stop.value); } } } /** * 小節位置の再生時間を取得する * @param measurePosition 小節位置 */ public getTime(measurePosition: number) { return ( this.time + this.stopTime + (measurePosition - this.measurePosition) * this.unitTime ); } } /** * BPM 変更命令 + 拍子 */ type BpmChangeAndBeat = { beat: IFraction; bpm: number; measurePosition: number; }; export class TimeCalculator { data: BPMChangeData[] = []; constructor(data: OtherObject[], measures: Measure[]) { // BPM 変更命令に拍子情報を追加 let bpmChanges = data .filter((object) => object.isBPM()) .map((bpmChange) => ({ beat: measures[bpmChange.measureIndex].beat, bpm: bpmChange.value, measurePosition: bpmChange.getMeasurePosition(), })); // 拍子変更対応 let index = 0; for (let i = 0; i < measures.length; i++) { // 直前の BPM 変更を取得 while ( index + 1 < bpmChanges.length && bpmChanges[index + 1].measurePosition <= i ) index++; const prev = bpmChanges[index]; // 拍子が変わっているか if (Fraction.equal(prev.beat, measures[i].beat)) continue; // 小節の頭なら上書き if (prev.measurePosition == i) { prev.beat = measures[i].beat; continue; } // それ以外は追加 bpmChanges.splice(index + 1, 0, { beat: measures[i].beat, bpm: prev.bpm, measurePosition: i, }); } // 同じ位置にBPM拍子変更命令が配置されないようにマップで管理する const bpmChangeMap = new Map<number, BpmChangeAndBeat>(); for (const bpmChange of bpmChanges) { bpmChangeMap.set(bpmChange.measurePosition, bpmChange); } // 一時停止の位置にBPM拍子変更命令がなければ複製して配置する const stops = data.filter((object) => object.isStop()); for (const stop of stops) { if (!bpmChangeMap.has(stop.getMeasurePosition())) { // 一時停止命令の直前にある BPM 変更命令を探す const prevKey = Math.max( ...[...bpmChangeMap.keys()].filter( (measurePosition) => measurePosition <= stop.getMeasurePosition() ) ); const prevBpmAndBeat = bpmChangeMap.get(prevKey)!; bpmChangeMap.set(stop.getMeasurePosition(), { beat: measures[stop.measureIndex].beat, bpm: prevBpmAndBeat.bpm, measurePosition: stop.getMeasurePosition(), }); } } bpmChanges = [...bpmChangeMap.values()].sort( (a, b) => a.measurePosition - b.measurePosition ); for (let i = 0; i < bpmChanges.length; i++) { this.data.push(new BPMChangeData(bpmChanges[i], this.data[i - 1], stops)); } } /** * 小節位置の再生時間を取得する * @param measurePosition 小節位置 */ getTime(measurePosition: number) { for (let i = this.data.length - 1; ; i--) { if (this.data[i].measurePosition <= measurePosition) { return this.data[i].getTime(measurePosition); } } } /** * 小節位置のBPMを取得する * @param measurePosition 小節位置 */ getBpm(measurePosition: number) { for (let i = this.data.length - 1; ; i--) { if (this.data[i].measurePosition <= measurePosition) { return this.data[i].bpm; } } } }
d18ef532e3c02b6f88f5324b72f814b1b3176d25
TypeScript
mdimai666/vue-quasar-typescript-example
/src/controllers/JobsController.ts
2.71875
3
import { QController, IQBackend_ListRequestParam, ISResponseList } from './QController' import JobItem from 'src/models/JobItem' export interface IRequestJobsListFilter { m_spam?: bool m_link?: bool deleted?: bool dt_actual?: bool } function JobsKindToFilter(kind: EJobsKind): IRequestJobsListFilter { if (kind == EJobsKind.spam) { return { deleted: false, m_spam: true, } } else if (kind == EJobsKind.linked) { return { m_link: true } } else if (kind == EJobsKind.deleted) { return { m_spam: false, deleted: true, } } else if (kind == EJobsKind.all) { return {} } else { // actual return { m_spam: false, deleted: false, dt_actual: true } } // if (filter_mode == 'spam') return `m_spam=true&m_link=&deleted=false` // else if (filter_mode == 'linked') return `m_spam=&m_link=true&deleted=` // else if (filter_mode == 'deleted') // return `m_spam=false&m_link=&deleted=true` // else if (filter_mode == 'all') return `m_spam=&m_link=&deleted=` // // if(filter_mode == 'actual') // else return `m_spam=false&m_link=&deleted=false&dt_actual=true` } export class JobsController extends QController<JobItem> { controller: string = 'jobs' constructor() { super() } async list2(_param: IQBackend_ListRequestParam, _kind: EJobsKind | IRequestJobsListFilter): Promise<ISResponseList<JobItem> | undefined> { let kind: IRequestJobsListFilter if (<any>_kind in EJobsKind) { kind = JobsKindToFilter(_kind as any) } else { kind = _kind as any } let param = Object.assign(_param, kind) return await super.list(param) } } export default JobsController export enum EJobsKind { actual, all, spam, linked, deleted }
ed40c707f5f8e7400530880fa416bcfc190e58eb
TypeScript
CWSpear/discord.ts
/examples/command/discords/simple commands.ts
2.9375
3
import { Discord, SimpleCommand, SimpleCommandMessage, SimpleCommandOption, } from "../../../src/index.js"; import { GuildMember, Role, User } from "discord.js"; @Discord() export abstract class commandTest { @SimpleCommand("race") race(command: SimpleCommandMessage): void { command.message.reply( `command prefix: \`\`${command.prefix}\`\`\ncommand name: \`\`${ command.name }\`\`\nargument string: \`\`${ !command.argString.length ? " " : command.argString }\`\`` + `\nRelated Commands: \`\`${ !command.getRelatedCommands().length ? "none" : command .getRelatedCommands() .map((cmd) => cmd.name) .join(", ") }\`\`` ); } @SimpleCommand("race car", { description: "simple command example" }) car( @SimpleCommandOption("user", { type: "USER" }) user: User, @SimpleCommandOption("role", { description: "mention the role you wish to grant", type: "ROLE", }) role: Role, command: SimpleCommandMessage ): void { !user ? command.sendUsageSyntax() : command.message.reply( `command prefix: \`\`${command.prefix}\`\`\ncommand name: \`\`${command.name}\`\`\nargument string: \`\`${command.argString}\`\`` ); } @SimpleCommand("race bike") bike(command: SimpleCommandMessage): void { command.message.reply( `command prefix: \`\`${command.prefix}\`\`\ncommand name: \`\`${command.name}\`\`\nargument string: \`\`${command.argString}\`\`` ); } @SimpleCommand("testx") testx( @SimpleCommandOption("user", { type: "USER" }) user: GuildMember | User, command: SimpleCommandMessage ): void { command.message.reply(`${user}`); } }
ba464413a97c59a49b28a20212772c7e33e94f1a
TypeScript
cameronmarlow/microcovid
/src/data/FormatPrecision.ts
3.21875
3
const SIGFIGS = 1 /** * Format points for display - fixed point with a set precision. * This is necessary because float.toPrecision will use exponential notation for large or small numbers. */ export function fixedPointPrecision(val: number | null): string { if (!val) { return '0' } const orderOfMagnitude = Math.floor(Math.log10(val)) const orderOfMangitudeToDisplay = orderOfMagnitude - SIGFIGS + 1 const decimalsToDisplay = orderOfMangitudeToDisplay > 0 ? 0 : -orderOfMangitudeToDisplay const roundedValue = Number.parseFloat(val.toPrecision(SIGFIGS)) const withoutCommas = roundedValue.toFixed(decimalsToDisplay) if (withoutCommas.indexOf('.') !== -1 || withoutCommas.length <= 3) { return withoutCommas } // This is a super clumsy way to do this, but it's late and it worrrks let withCommas = '' const firstChunkLen = withoutCommas.length % 3 if (firstChunkLen !== 0) { withCommas = withoutCommas.slice(0, firstChunkLen) + ',' } for (let i = firstChunkLen; i < withoutCommas.length; i += 3) { withCommas += withoutCommas.slice(i, i + 3) if (i + 3 < withoutCommas.length) { withCommas += ',' } } return withCommas } /** * Converts |val| to a percentage (including '%') with SIGFIGS sigfigs. * @param val */ export function fixedPointPrecisionPercent(val: number | null): string { if (!val) { return '0%' } return fixedPointPrecision(val * 100) + '%' }
e69fef8d60addb966f3aa30f53cbca418814c8a3
TypeScript
QingqiShi/fier-client
/src/hooks/useFirebaseAuth.ts
2.703125
3
import { auth } from 'firebase/app'; import user from 'stores/user'; import useFirebaseError from 'hooks/useFirebaseError'; function useFirebaseAuth() { const [userState, userActions] = user.useStore(); const handleError = useFirebaseError(); function signUp({ email, password, name, }: { email: string; password: string; name: string; }) { return handleError(async () => { const userCred = await auth().createUserWithEmailAndPassword( email, password ); if (userCred.user) { await userCred.user.updateProfile({ displayName: name, }); userActions.updateUser(name); } return userCred; }); } function signIn({ email, password }: { email: string; password: string }) { return handleError(async () => { const userCred = await auth().signInWithEmailAndPassword(email, password); return userCred; }); } function signOut() { return handleError(() => auth().signOut()); } function updateName(name: string) { const user = auth().currentUser; if (!user) return; const currentName = user.displayName; return handleError( async () => { userActions.updateUser(name); await user.updateProfile({ displayName: name }); }, () => { userActions.updateUser(currentName || ''); } ); } function updateEmail(email: string, currentPassword: string) { return handleError(async () => { const user = auth().currentUser; if (!user || !user.email) return; const cred = auth.EmailAuthProvider.credential( user.email, currentPassword ); await user.reauthenticateWithCredential(cred); await user.updateEmail(email); }); } function updatePassword(password: string, currentPassword: string) { return handleError(async () => { const user = auth().currentUser; if (!user || !user.email) return; const cred = auth.EmailAuthProvider.credential( user.email, currentPassword ); await user.reauthenticateWithCredential(cred); await user.updatePassword(password); }); } return { user: userState, signIn, signUp, signOut, updateName, updateEmail, updatePassword, }; } export default useFirebaseAuth;
9439456c1ccaddad04efefba1f5e2f4e22df5ccf
TypeScript
mjeson/IntroToTypeScript
/ExternalModules/Program.ts
2.609375
3
import answers = require("./ExternalAnswers"); class Program { public static Main() { let answer = new answers.ExternalAnswers.TheAnswer(); console.log(answer.state()); } } Program.Main();
b1b90402b8d0957c358a8845916082c6add7b4cf
TypeScript
miikey/mento-fi
/src/utils/addresses.ts
3.03125
3
import { getAddress, isAddress } from '@ethersproject/address' import { logger } from 'src/utils/logger' export function isValidAddress(address: string) { // Need to catch because ethers' isAddress throws in some cases (bad checksum) try { const isValid = address && isAddress(address) return !!isValid } catch (error) { logger.warn('Invalid address', error, address) return false } } export function validateAddress(address: string, context: string) { if (!address || !isAddress(address)) { const errorMsg = `Invalid addresses for ${context}: ${address}` logger.error(errorMsg) throw new Error(errorMsg) } } export function normalizeAddress(address: string) { validateAddress(address, 'normalize') return getAddress(address) } export function shortenAddress(address: string, elipsis?: boolean, capitalize?: boolean) { validateAddress(address, 'shorten') const shortened = normalizeAddress(address).substr(0, 8) + (elipsis ? '...' : '') return capitalize ? capitalizeAddress(shortened) : shortened } export function capitalizeAddress(address: string) { return '0x' + address.substring(2).toUpperCase() } export function areAddressesEqual(a1: string, a2: string) { validateAddress(a1, 'compare') validateAddress(a2, 'compare') return getAddress(a1) === getAddress(a2) } export function trimLeading0x(input: string) { return input.startsWith('0x') ? input.substring(2) : input } export function ensureLeading0x(input: string) { return input.startsWith('0x') ? input : `0x${input}` }
9bfc59cb985dbb62ad49d55798b846b13d9a3920
TypeScript
milg15/noya
/packages/noya-utils/src/__tests__/getIncrementedName.test.ts
2.921875
3
import { getIncrementedName } from '../index'; test('empty Space', () => { expect(getIncrementedName('', [''])).toEqual(' 2'); }); test('one word', () => { expect(getIncrementedName('A', ['A'])).toEqual('A 2'); }); test('one digit number', () => { expect(getIncrementedName('A 5', ['A 5'])).toEqual('A 6'); }); test('two digit number', () => { expect(getIncrementedName('A 15', ['A 15'])).toEqual('A 16'); }); test('invalid number at the end', () => { expect(getIncrementedName('A2', ['A2'])).toEqual('A2 2'); }); test('bigger number in array', () => { expect(getIncrementedName('A', ['A', 'A 3'])).toEqual('A 4'); });
b4156323a82f5a23a5d8dc89c9150fccf220c4a7
TypeScript
ttn1129/VueTypescriptSample
/src/models/MyOption/Prefecture.ts
2.671875
3
import MyOptionInterface from "./MyOptionInterface"; export default class Prefecture implements MyOptionInterface { id: number; name: string; constructor(p__id: number, p__name: string) { this.id = p__id; this.name = p__name; } }
3784f5de4be92097931e1238c64665697c2bf9da
TypeScript
Tibo-lg/iLiving
/app/js/controllers/timedUsageCtrl.ts
2.53125
3
/// <reference path='../_all.ts' /> module iLiving.controllers{ export interface TimedUsageScope{ timeserie: TimeSerie; height: number; width: number; setResolution: Function; resolutionClass: Function; $parent: iLivingScope; } export class TimedUsageCtrl{ private scope: TimedUsageScope; private curResolution: string; private oneHour: TimeSerie; private oneDay: TimeSerie; private threeDay: TimeSerie; public constructor( $scope :TimedUsageScope){ this.scope = $scope; this.oneHour = { 'date': ["10:00:00", "11:00:00","12:00:00","13:00:00","14:00:00","15:00:00","16:00:00","17:00:00","18:00:00","19:00:00"], 'values': { 'Kitchen': [10, 23, 9, 45, 5, 9, 4, 13, 6, 0], 'Living Room': [13, 18, 6, 45, 6, 9, 2, 21, 2, 11], 'Bedroom 1': [8, 26, 9, 10, 5, 12, 4, 13, 6, 0], 'Bedroom 2': [8, 26, 9, 10, 5, 12, 4, 13, 6, 0], 'Bedroom 3': [8, 26, 9, 10, 5, 12, 4, 13, 6, 50] } }; this.oneDay = { 'date': ["10:00:00", "11:00:00","12:00:00","13:00:00","14:00:00","15:00:00","16:00:00","17:00:00","18:00:00","19:00:00"], 'values': { 'Kitchen': [10, 23, 9, 45, 5, 9, 4, 13, 6, 0], 'Living Room': [13, 21, 6, 45, 10, 9, 2, 21, 2, 11], 'Bedroom 1': [8, 26, 9, 10, 3, 12, 2, 13, 6, 0], 'Bedroom 2': [8, 26, 7, 13, 5, 16, 4, 13, 4, 0], 'Bedroom 3': [8, 26, 9, 10, 5, 12, 4, 13, 6, 50] } }; this.threeDay = { 'date': ["10:00:00", "11:00:00","12:00:00","13:00:00","14:00:00","15:00:00","16:00:00","17:00:00","18:00:00","19:00:00"], 'values': { 'Kitchen': [10, 23, 9, 45, 5, 9, 4, 13, 6, 0], 'Living Room': [13, 21, 6, 45, 10, 9, 2, 21, 2, 11], 'Bedroom 1': [8, 26, 9, 10, 3, 12, 6, 13, 6, 0], 'Bedroom 2': [8, 3, 7, 7, 5, 16, 4, 13, 4, 0], 'Bedroom 3': [8, 26, 9, 10, 5, 12, 4, 28, 6, 50] } }; this.scope.height = $scope.$parent.height; this.scope.width = $scope.$parent.width; this.scope.resolutionClass = (resolution)=>{return this.resolutionClass(resolution);}; this.scope.setResolution = (resolution)=>{ return this.setResolution(resolution);}; this.scope.timeserie = this.oneHour; this.curResolution = "1h"; } public resolutionClass(resolution: string) { return resolution === this.curResolution ? 'active' : ''; } public setResolution(resolution: string) { if( resolution === "1h"){ this.scope.timeserie = this.oneHour; } else if( resolution == "1d" ){ this.scope.timeserie = this.oneDay; } else if( resolution == "3d" ){ this.scope.timeserie = this.threeDay; } else{ return; } this.curResolution = resolution; } } } iLiving.registerController('TimedUsageCtrl', ['$scope']);
2774cb7e6bbae620a79c65e527ffb8944ab607d9
TypeScript
prashu18400/angular-ivy-p1ze6f
/src/app/app.component.ts
2.5625
3
import { Component, VERSION } from '@angular/core'; import {Hero} from './hero'; @Component({ selector: 'my-app', template : ` <h1>My name is Prashanth</h1> <p>The hero's birthday is {{ birthday | date }}</p>`, templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Angular ' + VERSION.major; title = 'Tour of Heroes'; prducts = ['Shirt','Trousers','Watches']; heroos=[ new Hero(1,"Superman"), new Hero(1,"Batman") ] birthday = new Date(2000,3,18); toggle = true; get format(){return this.toggle?'shortDate':'fullDate';} toggleFormat(){this.toggle = !this.toggle;} }
6ba68f3851a59177792ef2c49dcab559887b9c59
TypeScript
howardyan93/NgNode
/ng2ts/rpc/serialization.ts
2.8125
3
import * as cgi from '../cgi/cgi'; import * as path from 'path'; import * as pathreducer from 'pathreducer'; /** * You must provide a Module Name for the this Serializable decorator. It uses the Module Name to deserialize the object. * @param moduleName */ export function Serializable (moduleName: string) { return (target: any) => { // save a reference to the original constructor var original: Function = target; // a utility function to generate instances of a class function construct(constructor: Function, args: any[]) { var c: any = function () { return constructor.apply(this, args); } c.prototype = constructor.prototype; let instance: { [id: string]: string } = new c(); instance['@Serializable.ModuleName'] = moduleName; instance['@Serializable.TypeName'] = original.name; return instance; } // the new constructor behaviour var f: any = function (...args:any[]) { console.log("New: " + original.name + " : Serializable"); return construct(original, args); } // copy prototype so intanceof operator still works f.prototype = original.prototype; // return new constructor (will override original) return f; } } // References is the dictionary that hold all loaded library; var References: { [id: string]: { [id: string]: ObjectConstructor } } = {}; var __moduleRoot: string; /** * This path is determined by path.dirname(require.main.filename). If you want to changed the default value, set a new value to it after require/import. */ export var __relativeRoot: string = path.dirname(require.main.filename); export function Deserialize(jsonObject: any): any { if (typeof jsonObject != 'object') return jsonObject; if (Array.isArray(jsonObject)) { console.log('Deserialize Array: ', JSON.stringify(jsonObject)); for (let i = 0; i < (<any[]>jsonObject).length; i++) { (<any[]>jsonObject).push(Deserialize((<any[]>jsonObject)[i])); } } if (jsonObject['@Serializable.ModuleName'] && jsonObject['@Serializable.TypeName']) { console.log('Deserialize Object: ', JSON.stringify(jsonObject)); let moduleName:string = jsonObject['@Serializable.ModuleName']; let typeName:string = jsonObject['@Serializable.TypeName']; //load module to References if (moduleName.charAt(0) == '.') { //this is a relative file; // if the module was not loaded, load it from the module file; if (!References[moduleName]) { let $file = pathreducer.reduce(__relativeRoot + '\/' + moduleName + '.js'); console.log('Deserialize->Load Type Def from: ', $file); References[moduleName] = cgi.DynamicRequire(pathreducer.filename($file), pathreducer.pathname($file)); } } else { //this is a module } //how to obtain the module and type from it? let obj = new References[moduleName][typeName](); for (let key in jsonObject) { if (key != '$$hashKey') obj[key] = jsonObject[key]; } return obj; } return jsonObject; }
c6b021c4013050b587f83c7c2611a9e25ea08d78
TypeScript
agg23/mercury-parser
/src/extractors/custom/news.ycombinator.com/index.ts
2.578125
3
import { Comment } from 'extractors/types'; const findCommentParent = (comments: Comment[], indentLevel: number) => { const stack: Array<{ comment: Comment; depth: number }> = comments.map( comment => ({ comment, depth: 0 }) ); while (stack.length > 0) { const { comment, depth } = stack.pop()!; if (depth === indentLevel - 1) { return comment; } if (comment.children) { stack.push( ...comment.children.map(c => ({ comment: c, depth: depth + 1 })) ); } } return undefined; }; export const NewsYcombinatorComExtractor = { domain: 'news.ycombinator.com', title: { selectors: [['#pagespace', 'title']], }, author: { selectors: ['.fatitem .hnuser'], }, date_published: { selectors: [['.fatitem .age', 'title']], }, dek: { selectors: [], }, lead_image_url: { selectors: [], }, content: { selectors: [['.fatitem tr:nth-of-type(4) td:nth-of-type(2)']], // Is there anything in the content you selected that needs transformed // before it's consumable content? E.g., unusual lazy loaded images transforms: {}, // Is there anything that is in the result that shouldn't be? // The clean selectors will remove anything that matches from // the result clean: ['.athing', '.subtext'], }, comment: { topLevel: { selectors: [['.comment-tree .comtr tr']], }, childLevel: { // selectors: [['.ind', 'indent']], insertTransform: ( $: cheerio.Root, node: cheerio.Element, newComment: Comment, comments: Comment[] ) => { const indentNode = $('.ind', node).first(); if (!indentNode) { return; } const indentLevel = parseInt(indentNode.attr('indent') ?? '0', 10); if (indentLevel === 0) { // Top level comment comments.push(newComment); return; } // Not top level comment. Traverse tree to find where it goes const parent = findCommentParent(comments, indentLevel); if (!parent) { console.error( 'Could not find parent for comment. Appending as a top level comment' ); comments.push(newComment); return; } (parent.children ??= []).push(newComment); }, }, author: { selectors: [['.hnuser']], }, date: { selectors: [['.age', 'title']], }, text: { selectors: [['.comment .commtext']], clean: ['.reply'], }, }, };
efb81f5c5b6170c91925dc48aa4ecfade75742ce
TypeScript
SMasiu/GraphJS
/src/labels/value-label.ts
3.296875
3
import { Label } from './label' export class ValueLabel extends Label { values: number[] identifier: 'value' = 'value' constructor( public start: number, public end: number, public step: number, { reverse }: { reverse?: boolean } = {} ) { super() this.reverse = reverse || false this.values = this.toLabel() } toLabel(): number[] { const { start, end, step } = this let v: number[] = [] if ((end - start) % step !== 0) { throw new Error('Steps count is not type of Int') } if ((start > 0 && end > 0) || (start < 0 && end < 0)) { throw new Error('Invalid range') } this.underZero = 0 if (start < end) { this.min = start this.max = end for (let i = start; i <= end; i += step) { if (i < 0) { this.underZero++ } v.push(i) } } else { this.min = end this.max = start this.reversedValues = true for (let i = start; i >= end; i -= step) { if (i < 0) { this.underZero++ } v.push(i) } } let index = v.findIndex((x) => x === 0) if (index === -1) { throw new Error('Grid should contain 0') } if (this.reverse) { v = v.reverse() } return v } }
4f8b0759c1c0b9444816eb774e12648331b2a72d
TypeScript
Diogny/adt
/test/graph-directed-create.ts
2.65625
3
import { Edge, WeightedEdge } from "../src/lib/Graph"; import { DirectedEdgeAnalizer, DirectedComponentAnalizer } from "../src/lib/Graph-Directed-Analizers"; import { fromJSON } from "../src/lib/Graph-Utils"; import { dfsAnalysis } from "../src/lib/Graph-Search"; //independent run // node --require ts-node/register --trace-uncaught test/graph-directed-create.ts //or //in this case it's itself in Run Task as "Graph create" //remember to change the name in launch.json const g = fromJSON({ name: "DiGraph", directed: true, weighted: false, nodes: 13, edges: [ { from: 0, to: 5 }, { from: 0, to: 1 }, { from: 0, to: 6 }, { from: 2, to: 0 }, { from: 2, to: 3 }, { from: 3, to: 2 }, { from: 3, to: 5 }, { from: 4, to: 3 }, { from: 4, to: 11 }, { from: 4, to: 2 }, { from: 5, to: 4 }, { from: 6, to: 4 }, { from: 6, to: 9 }, { from: 7, to: 6 }, { from: 7, to: 8 }, { from: 8, to: 7 }, { from: 8, to: 9 }, { from: 9, to: 10 }, { from: 9, to: 11 }, { from: 10, to: 12 }, { from: 11, to: 12 }, { from: 12, to: 9 }, ] }); console.log('name: ', g.name); console.log('nodes: ', g.size); console.log('g.directed: ', g.directed); console.log('g.edgeCount: ', g.edgeCount()); console.log('Edges'); g.nodeList().forEach(n => { console.log((g.nodeEdges(n.id) as Edge[]).map(e => { return `(${e.v}>${e.w}${g.weighted ? ` @${(e as WeightedEdge).weight}` : ''})` }).join(' ')) }); let start = 0, analizers = [ new DirectedEdgeAnalizer(true, true, true), new DirectedComponentAnalizer(), ]; dfsAnalysis(g, start, analizers);
72b8b80d0e9422577a903d325c2c0cb39d7226a8
TypeScript
mipli/cabalites
/src/EffectsHandler.ts
3.1875
3
import * as Core from './core'; export interface TintEffect { position: Core.Vector2, color: Core.Color } export class EffectsHandler { private static instance: EffectsHandler; private tints: TintEffect[][]; private count: number; get hasEffects(): boolean { return this.count > 0; } public static getInstance() { if (!this.instance) { this.instance = new EffectsHandler(); } return this.instance; } private constructor() { this.tints = Core.Utils.buildMatrix<TintEffect>(100, 100, null); this.count = 0; } public getTileTint(position: Core.Vector2) { return this.tints[position.x][position.y]; } public addTileTint(position: Core.Vector2, color: Core.Color) { this.count++; this.tints[position.x][position.y] = { position: position, color: color }; } public removeTileTint(position: Core.Vector2, color?: Core.Color) { this.count = Math.max(this.count - 1, 0); this.tints[position.x][position.y] = null; } }
d52c4b12fd628430fe6f4361448f10da4eb3394d
TypeScript
cpmsys/vuex-typesafe-class
/test/inheritance.spec.ts
2.6875
3
import "jest"; import Vue from "vue"; import Vuex from "vuex"; interface IAmbient { $test: { test(): any }; } import { createModule, MutationKeys, Mutation, StateMap, StateFactory, useStore } from "../src/index"; Vue.config.productionTip = false; Vue.config.devtools = false; describe("Builder", () => { Vue.use(Vuex); it("State", () => { const m = createModule( class Root extends class BaseStore { test = 123; } {} ); const store = new Vuex.Store(m); expect(store.state.test).toEqual(123); }); it("Getter", () => { const m = createModule( class Root extends class { test = 123; get testGetter() { return "test getter " + this.test; } } {} ); const store = new Vuex.Store(m); expect(store.getters.testGetter).toEqual("test getter 123"); }); it("Mutation (Generator, ES6+)", () => { class Root extends class { test: number = 123; *testSetter(value: number): any { this.test = value; } } {} const m = createModule(Root); const store = new Vuex.Store(m); store.commit("testSetter", 456); expect(store.state.test).toEqual(456); }); it("Mutation (Decorator)", () => { class Root { public test: number = 123; @Mutation testSetter(v: number) { this.test = v; } } const m = createModule(class extends Root {}); const store = new Vuex.Store(m); store.commit("testSetter", 456); expect(store.state.test).toEqual(456); }); it("Mutation (Setter)", () => { class Root { public test: number = 123; set testSetter(v: number) { this.test = v; } } const m = createModule(class extends Root {}); const store = new Vuex.Store(m); store.commit("testSetter", 456); expect(store.state.test).toEqual(456); }); it("Action", async () => { const m = createModule( class Root extends class { test = 123; async testAction({ test }: { test: number }) { return "test action " + this.test + ":" + test; } } {} ); const store = new Vuex.Store(m); await expect(store.dispatch("testAction", { test: 456 })).resolves.toEqual( "test action 123:456" ); }); it("Action with commit", async () => { const m = createModule( class Root extends class { test = 123; set testSetter(v: number) { this.test = v; } async testAction({ test }: { test: number }) { this.testSetter = 456; return "test action " + this.test + ":" + test; } } {} ); const store = new Vuex.Store(m); await expect(store.dispatch("testAction", { test: 123 })).resolves.toEqual( "test action 456:123" ); }); it("Action with commit", async () => { class Base { test = 123; set testSetter(v: number) { this.test = v; } async parentTest({ test }: { test: number }) { this.testSetter = 456; return "test action " + this.test + ":" + test; } } const m = createModule( class Root extends Base { async testAction({ test }: { test: number }) { return "parent " + (await super.parentTest({ test })); } } ); const store = new Vuex.Store(m); await expect(store.dispatch("testAction", { test: 123 })).resolves.toEqual( "parent test action 456:123" ); }); it("Nested", () => { class Base { a = 123; set aSetter(v: number) { this.a = v; } get aGetter() { return "Getter " + this.a; } async aAction({ test }: { test: number }) { this.aSetter = 456; } } class AceOfBase extends Base { b = 123; set bSetter(v: number) { this.b = v; } get bGetter() { return "Getter " + this.b; } async bAction({ test }: { test: number }) { this.bSetter = 456; } } const m = createModule( class Root extends AceOfBase { c = 123; set cSetter(v: number) { this.c = v; } get cGetter() { return "Getter " + this.c; } async cAction({ test }: { test: number }) { this.cSetter = 456; } } ); const store = new Vuex.Store(m); expect(Object.keys(m.state())).toEqual(["a", "b", "c"]); expect(Object.keys(m.mutations)).toEqual(["aSetter", "bSetter", "cSetter"]); expect(Object.keys(m.getters)).toEqual(["aGetter", "bGetter", "cGetter"]); expect(Object.keys(m.actions)).toEqual(["aAction", "bAction", "cAction"]); }); });
ec24cdf3b6e2e0d0fe24bb05871fced54cef6b8a
TypeScript
concord-consortium/hurricane-model
/src/math-utils.test.ts
2.65625
3
import { latLngPlusVector } from "./math-utils"; import { distanceTo } from "geolocation-utils"; test("latLngPlusVector", () => { const initialPos = {lat: 0, lng: 0}; let newPos = {lat: 0, lng: 20}; const dist1 = distanceTo(initialPos, newPos); let newPosCalculated = latLngPlusVector(initialPos, {u: dist1, v: 0}); expect(newPosCalculated.lat).toEqual(newPos.lat); expect(newPosCalculated.lng).toBeCloseTo(newPos.lng); newPos = {lat: -20, lng: 0}; const dist2 = distanceTo(initialPos, newPos); newPosCalculated = latLngPlusVector(initialPos, {u: 0, v: -dist2}); expect(newPosCalculated.lat).toBeCloseTo(newPos.lat); expect(newPosCalculated.lng).toEqual(newPos.lng); newPos = {lat: -20, lng: 20}; newPosCalculated = latLngPlusVector(initialPos, {u: dist1, v: -dist2}); expect(newPosCalculated.lat).toBeCloseTo(newPos.lat); expect(newPosCalculated.lng).toBeCloseTo(newPos.lng); });
274b1b146dad9887aa26f1d81e0530d02a703ade
TypeScript
Mirdoriss/Mirdocsify.github.io
/题题对战/代码/实时服务器/mgobexs/pushHandler.ts
2.546875
3
import { mgobexsInterface } from "./mgobexsInterface"; import { AnsGameData, Player, GameState } from "./msgHandler"; import { Que } from "./Question"; import { calcScore } from "./Util"; export const ANS_TIME = 16500; export const ANS_COUNT = 5; export const ANS_FULL = 200; export interface SerPushMsg { cmd: SER_PUSH_CMD, err: string, gameState: GameState, } export enum SER_PUSH_CMD { CURRENT = 1, GAME_STEP = 2, ERR = 3, } // 新游戏 function newGame({ gameData, SDK, room }: mgobexsInterface.ActionArgs<null>) { let gData = gameData as AnsGameData; gData.gameState.curQueId = -1; gData.gameState.que = null; // 重置总分 gData.gameState.playerGroup.forEach(group => group.forEach(player => { player.sumScore = 0; player.ans = -1; })); newRound(arguments[0]); } // 当前游戏状态 function curGame({ gameData, SDK, room }: mgobexsInterface.ActionArgs<null>, pushCmd: SER_PUSH_CMD, playerIdList: string[] = []) { let gData = gameData as AnsGameData; playerIdList = playerIdList.filter(id => !!id); if (gData.gameState.curQueId >= 0 && gData.gameState.time >= 0) { // 剩余时间 gData.gameState.time = ANS_TIME - (Date.now() - gData.startRoundTime); } const gameState = { ...gData.gameState }; SDK.sendData({ playerIdList, data: { cmd: pushCmd, err: "", gameState } }); } // 新一局 function newRound({ gameData, SDK, room }: mgobexsInterface.ActionArgs<null>) { let gData = gameData as AnsGameData; gData.gameState.curQueId++; gData.gameState.que = gData.ques[gData.gameState.curQueId]; gData.gameState.time = ANS_TIME; gData.startRoundTime = Date.now(); // 重置当前分数 gData.gameState.playerGroup.forEach(group => group.forEach(player => { player.score = -1; player.ans = -1; })); curGame(arguments[0], SER_PUSH_CMD.GAME_STEP); // 计时结束 gData.roundTimer = setTimeout(() => { endRound(arguments[0]); }, ANS_TIME); } // 结束一局 function endRound({ gameData, SDK, room }: mgobexsInterface.ActionArgs<null>) { let gData = gameData as AnsGameData; gData.gameState.time = -100; curGame(arguments[0], SER_PUSH_CMD.GAME_STEP); // 2秒后结束游戏 if (!gData.gameState.finish && gData.gameState.curQueId >= ANS_COUNT - 1) { return setTimeout(() => endGame(arguments[0]), 2000); } // 2秒后新一局 return setTimeout(() => newRound(arguments[0]), 2000); } // 结束游戏 async function endGame({ gameData, SDK, room }: mgobexsInterface.ActionArgs<null>) { let gData = gameData as AnsGameData; gData.gameState.curQueId = 100000; gData.gameState.finish = true; curGame(arguments[0], SER_PUSH_CMD.GAME_STEP); } // 检查提交的答案 function checkSubmit({ gameData, SDK, room }: mgobexsInterface.ActionArgs<null>, playerId: string, ans: number) { let gData = gameData as AnsGameData; // 超过时间 if (gData.gameState.time <= 0) { return curGame(arguments[0], SER_PUSH_CMD.GAME_STEP);; } // 超过题目数量 if (gData.gameState.curQueId >= ANS_COUNT) { return curGame(arguments[0], SER_PUSH_CMD.GAME_STEP); } let player: Player = null; let que: Que = gData.gameState.que; gData.gameState.playerGroup.forEach(group => group.forEach(p => p.playerId === playerId && (player = p))); // 异常 if (!player || player.score > 0 || player.ans >= 0 || !que) { return curGame(arguments[0], SER_PUSH_CMD.GAME_STEP); } player.ans = ans; if (que.ans !== ans) { // 答错 player.score = 0; } else { // 答对 let scale = 1; if (gData.gameState.curQueId === ANS_COUNT - 1) { scale = 2; } let score = calcScore(ANS_FULL * scale, Date.now() - gData.startRoundTime); player.score = score; player.sumScore += score; } // 全部提交就结束一局 if (isAllSubmit(arguments[0])) { clearTimeout(gData.roundTimer); return endRound(arguments[0]); } return curGame(arguments[0], SER_PUSH_CMD.GAME_STEP); } function isAllSubmit({ gameData, SDK, room }: mgobexsInterface.ActionArgs<null>): boolean { let gData = gameData as AnsGameData; let res = true; gData.gameState.playerGroup.forEach(group => group.forEach(p => p.ans < 0 && (res = false))); return res; } export { newGame, curGame, newRound, endRound, endGame, checkSubmit };
085130ca3df8e87cb9d7af79cd766bda34a3480e
TypeScript
ghoullier/zetapush
/packages/common/src/utils/files.ts
2.6875
3
import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; export const mkdirs = (file: string) => { let dirs = []; for (let dir of path.parse(file).dir.split(path.sep)) { dirs.push(dir); let dirPath = dirs.join(path.sep); if (dirPath) { fs.existsSync(dirPath) || fs.mkdirSync(dirPath); } } }; export const getZetaFilePath = (...relativePath: string[]) => { const p = path.normalize(path.resolve(os.homedir(), '.zeta', ...relativePath)); mkdirs(p); return p; }; export const mkdir = (root: string) => new Promise((resolve, reject) => { fs.mkdir(root, (failure) => { if (failure) { return reject(failure); } resolve(root); }); });
a2be23bcefb47e2d5620d7689ff5521cc11fa146
TypeScript
7Power/taleweaver
/packages/core/lib/key/utils/getKeySignatureFromKeyboardEvent.ts
2.6875
3
import Key from '../Key'; import * as keys from '../keys'; import KeySignature from '../KeySignature'; import ModifierKey from '../ModifierKey'; import { AltKey, CtrlKey, MetaKey, ShiftKey } from '../modifierKeys'; const KEY_STRING_TO_KEY_MAP: { [key: string]: Key } = { 'a': keys.AKey, 'b': keys.BKey, 'c': keys.CKey, 'd': keys.DKey, 'e': keys.EKey, 'f': keys.FKey, 'g': keys.GKey, 'h': keys.HKey, 'i': keys.IKey, 'j': keys.JKey, 'k': keys.KKey, 'l': keys.LKey, 'm': keys.MKey, 'n': keys.NKey, 'o': keys.OKey, 'p': keys.PKey, 'q': keys.QKey, 'r': keys.RKey, 's': keys.SKey, 't': keys.TKey, 'u': keys.UKey, 'v': keys.VKey, 'w': keys.WKey, 'x': keys.XKey, 'y': keys.YKey, 'z': keys.ZKey, 'A': keys.AKey, 'B': keys.BKey, 'C': keys.CKey, 'D': keys.DKey, 'E': keys.EKey, 'F': keys.FKey, 'G': keys.GKey, 'H': keys.HKey, 'I': keys.IKey, 'J': keys.JKey, 'K': keys.KKey, 'L': keys.LKey, 'M': keys.MKey, 'N': keys.NKey, 'O': keys.OKey, 'P': keys.PKey, 'Q': keys.QKey, 'R': keys.RKey, 'S': keys.SKey, 'T': keys.TKey, 'U': keys.UKey, 'V': keys.VKey, 'W': keys.WKey, 'X': keys.XKey, 'Y': keys.YKey, 'Z': keys.ZKey, 'Num1': keys.Num1Key, 'Num2': keys.Num2Key, 'Num3': keys.Num3Key, 'Num4': keys.Num4Key, 'Num5': keys.Num5Key, 'Num6': keys.Num6Key, 'Num7': keys.Num7Key, 'Num8': keys.Num8Key, 'Num9': keys.Num9Key, 'Num0': keys.Num0Key, 'Dash': keys.DashKey, 'Equal': keys.EqualKey, 'Space': keys.SpaceKey, 'ArrowLeft': keys.ArrowLeftKey, 'ArrowRight': keys.ArrowRightKey, 'ArrowUp': keys.ArrowUpKey, 'ArrowDown': keys.ArrowDownKey, 'Backspace': keys.BackspaceKey, 'Delete': keys.DeleteKey, 'Enter': keys.EnterKey, }; function getKeyFromKeyString(keyString: string): Key | null { if (!(keyString in KEY_STRING_TO_KEY_MAP)) { return null; } return KEY_STRING_TO_KEY_MAP[keyString]; } export default function getKeySignatureFromKeyboardEvent(event: KeyboardEvent): KeySignature | null { const modifierKeys: ModifierKey[] = []; if (event.altKey) { modifierKeys.push(AltKey); } if (event.ctrlKey) { modifierKeys.push(CtrlKey); } if (event.metaKey) { modifierKeys.push(MetaKey); } if (event.shiftKey) { modifierKeys.push(ShiftKey); } const key = getKeyFromKeyString(event.key); if (!key) { return null; } return new KeySignature(key, modifierKeys); }
2f5d9007dbfff95f18479913b34a1e7f1ad5c93d
TypeScript
getabetterpic/fly-my-rockets
/apps/fly-my-rockets/src/app/rockets/functions/rocket-photo-ref.spec.ts
2.59375
3
import { rocketPhotoRef, ThumbnailSizes } from './rocket-photo-ref'; describe('rocketPhotoRef', () => { let originalRef; beforeEach(() => { originalRef = 'asdf1234/images/rockets/IMG_1234.jpg'; }); describe('when getting the small ref', () => { it('returns the correct string', () => { const ref = rocketPhotoRef(originalRef, ThumbnailSizes.Small); expect(ref).toEqual( 'asdf1234/images/rockets/thumbnails/IMG_1234_50x50.jpg' ); }); }); describe('when getting the medium ref', () => { it('returns the correct string', () => { const ref = rocketPhotoRef(originalRef, ThumbnailSizes.Medium); expect(ref).toEqual( 'asdf1234/images/rockets/thumbnails/IMG_1234_400x600.jpg' ); }); }); describe('when getting the original ref', () => { it('returns the correct string', () => { const thumbnailRef = rocketPhotoRef(originalRef, ThumbnailSizes.Medium); expect(rocketPhotoRef(thumbnailRef, ThumbnailSizes.Original)).toEqual( originalRef ); }); }); });
f29c0a91c855ad90f67b536f913fea82d6bfd412
TypeScript
r00t-101-LoL/replikit
/packages/commands/src/composition.ts
2.53125
3
import { command, CommandBuilder, MiddlewareLike, NormalizeType, TextParameterOptions } from "@replikit/commands"; import { CommandContext, ParameterOptions, Command as CommandInfo, DefaultOptions, CommandResultAsync, Parameters, RestParameterOptions } from "@replikit/commands/typings"; import { assert, CompositionFactory, createCompositionInfo } from "@replikit/core"; import { Constructor } from "@replikit/core/typings"; import { MessageContext } from "@replikit/router"; export const commandComposer = new CompositionFactory<CommandBuilder, CommandContext>(); export function createParameterAccessor<T>( field: string ): (context: CommandContext<Parameters>) => NormalizeType<T> { return context => context.params[field] as NormalizeType<T>; } export function required<T>(type: Constructor<T>, options?: ParameterOptions<T>): NormalizeType<T> { return commandComposer.compose((builder, field) => { builder.required(field, type, options); return { get: createParameterAccessor(field) }; }); } export function text(options: TextParameterOptions & { splitLines: true }): string[]; export function text(options?: TextParameterOptions): string; export function text(options?: TextParameterOptions): unknown { return commandComposer.compose((builder, field) => { builder.text(field, options); return { get: createParameterAccessor(field) }; }); } export function rest<T>( type: Constructor<T>, options?: RestParameterOptions<T> ): NormalizeType<T>[] { return commandComposer.compose((builder, field) => { builder.rest(field, type, options); return { get: createParameterAccessor<T[]>(field) }; }); } export function optional<T>( type: Constructor<T>, options?: ParameterOptions<T> & Required<DefaultOptions<T>> ): NormalizeType<T>; export function optional<T>( type: Constructor<T>, options?: ParameterOptions<T> ): NormalizeType<T> | undefined; export function optional<T>( type: Constructor<T>, options?: ParameterOptions<T> ): NormalizeType<T> | undefined { return commandComposer.compose((builder, field) => { builder.optional(field, type, options); return { get: createParameterAccessor<T>(field) }; }); } export type CommandLike = Constructor<Command> | Constructor<CommandContainer> | CommandInfo; export function resolveCommand(commandLike: CommandLike): CommandInfo { if (typeof commandLike !== "function") { return commandLike; } const commandBuilder = command(undefined!); const compositionInfo = createCompositionInfo(commandLike, commandBuilder); const result = commandBuilder.build(); result.name = compositionInfo.fields.name; assert(result.name, "Command name is required"); result.compositionInfo = compositionInfo; result.aliases = compositionInfo.fields.aliases; if (compositionInfo.prototype instanceof CommandContainer) { const fields = compositionInfo.fields as CommandContainer; const commands = fields.commands; assert(commands, "Command array is required"); result.commands = commands.map(resolveCommand); for (const command of result.commands) { command.parent = result; } result.default = fields.default; return result; } interface CommandPrototype { execute(): CommandResultAsync; } commandBuilder.use(...(compositionInfo.fields as Command).middleware); // eslint-disable-next-line @typescript-eslint/unbound-method commandBuilder.handler((compositionInfo.prototype as CommandPrototype).execute); return result; } abstract class CommandBase extends MessageContext { abstract name: string; aliases: string[] = []; } export abstract class Command extends CommandBase { abstract execute(): CommandResultAsync; middleware: MiddlewareLike[] = []; } export abstract class CommandContainer extends CommandBase { abstract commands: CommandLike[]; default?: string; } // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface Command extends CommandContext {}
7a1c109b901abe3480adfcdb464bb24da7d3a9b1
TypeScript
brynbellomy/fibonacci-trap
/logic-x.d.ts
2.875
3
declare class Event { channel:number; send (): void; sendAfterMilliseconds (ms:number): void; sendAtBeat (beat:number): void; sendAfterBeats (beats:number): void; trace(): void; } declare class Note extends Event { pitch:number; velocity:number; articulationID:number; inStartFrame:number; isRealtime:boolean; } declare class NoteOn extends Note { constructor(event?:Event); } declare class NoteOff extends Note { constructor(event?:Event); } declare function GetParameter(name:string): number; declare function Trace(str:string): void; declare function GetTimingInfo(): ITimingInfo; interface ITimingInfo { /** `true` if the host transport is playing. */ playing: boolean; /** `true”`means the host transport is cycling. */ cycling:boolean; /** Indicates the beat position at the start of the process block. */ blockStartBeat: number; /** A floating point number indicates the beat position at the end of the process block. */ blockEndBeat:number; /** A floating point number indicates the length of the process block in beats. */ blockLength:number; /** A floating point number indicates the host tempo. */ tempo:number; /** An integer number indicates the host meter numerator. */ meterNumerator:number; /** An integer number indicates the host meter denominator. */ meterDenominator:number; /** A floating point number indicates the beat position at the start of the cycle range. */ leftCycleBeat:number; /** A floating point number indicates the beat position at the end of the cycle range. */ rightCycleBeat:number; } declare var MIDI: { _noteNames: string[], _ccNames: string[], noteNumber: (name:string) => number, noteName: (noteNumber:number) => string, ccName: (ccNum:number) => string, allNotesOff: VoidFunction, normalizeStatus: (value:number) => number, normalizeChannel: (value:number) => number, normalizeData: (value:number) => number, }; interface VoidFunction { (); } interface IPrintable { toString(): string; }
03c69cf9fc925bba8d6183077e113d961108b780
TypeScript
zimejin/SlagalicaGame
/apps/slagalica-api/src/app/game/multiplayer/state/slagalica.ts
3.03125
3
import { ArraySchema } from '@colyseus/schema'; import { SlagalicaGame } from '@slagalica-api/game/shared'; import { WordModel } from '@slagalica-api/models'; import { GameWinner } from '@slagalica/data'; import { Schema, type } from 'colyseus.js'; class SlagalicaPlayer extends Schema { @type('string') word: string; @type('string') error: string; @type('number') points: number = 0; } export class SlagalicaGameState extends Schema { @type(['string']) letters = new ArraySchema<string>(); @type(SlagalicaPlayer) red: SlagalicaPlayer = new SlagalicaPlayer(); @type(SlagalicaPlayer) blue: SlagalicaPlayer = new SlagalicaPlayer(); @type('string') winner: GameWinner; constructor() { super(); } async initGame() { this.letters = new ArraySchema(...SlagalicaGame.getLetters()); } async calculateWinner() { const blueWord = this.blue.word; const redWord = this.red.word; const invalidWord = 'Word is invalid.'; let foundBlue, foundRed; if (blueWord && SlagalicaGame.validateWord(this.letters, blueWord)) { foundBlue = await WordModel.findOne({ word: blueWord }); } if (redWord && SlagalicaGame.validateWord(this.letters, redWord)) { foundRed = await WordModel.findOne({ word: redWord }); } /** * if Both have correct words */ if (foundBlue && foundRed) { const blueLength = blueWord.length; const redLength = redWord.length; /** * Check who has longer word */ if (blueLength > redLength) this.winner = GameWinner.Blue; else if (blueLength < redLength) this.winner = GameWinner.Red; else this.winner = GameWinner.Both; this.blue.points = SlagalicaGame.calculatePoints(blueWord); this.red.points = SlagalicaGame.calculatePoints(redWord); /** * If only blue has correct word */ } else if (foundBlue) { this.red.error = invalidWord; this.winner = GameWinner.Blue; this.blue.points = SlagalicaGame.calculatePoints(blueWord); /** * If only red has correct word */ } else if (foundRed) { this.blue.error = invalidWord; this.winner = GameWinner.Red; this.red.points = SlagalicaGame.calculatePoints(redWord); /** * If both have invalid words */ } else { this.red.error = invalidWord; this.blue.error = invalidWord; this.winner = GameWinner.None; } } }
28bc89895f2c14ef8c9c597e040e9a73f5818858
TypeScript
saptam007/Hunger-Truck
/src/main.ts
2.625
3
import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.log(err)); //sample code for javascript examples //demo for call function var obj={num:2}; var addToThis= function(a,b,c){ return this.num+a+b+c; } console.log("bind demo:"+ addToThis.call(obj,2,3,4)); //demo for apply function var numbers= [2,3,4]; console.log("apply demo :"+addToThis.apply(obj,numbers)); //demo for bind function var bound=addToThis.bind(obj); console.log(bound(2,3,4));
19c75cff3fb212ebe551d96556eb241a9c8fbe46
TypeScript
Everpoint/sGis
/source/layers/FeatureLayer.ts
3.078125
3
import {Layer, LayerConstructorParams} from "./Layer"; import {error} from "../utils/utils"; import {Feature} from "../features/Feature"; import {Bbox} from "../Bbox"; import {sGisEvent} from "../EventHandler"; import {Render} from "../renders/Render"; import {StaticImageRender} from "../renders/StaticImageRender"; export interface FeatureLayerConstructorParams extends LayerConstructorParams { features?: Feature[] } /** * New features are added to the feature layer * @event FeaturesAddEvent */ export class FeaturesAddEvent extends sGisEvent { static type: string = 'featuresAdd'; /** * Array of features that were added */ readonly features: Feature[]; constructor(features: Feature[]) { super(FeaturesAddEvent.type); this.features = features; } } /** * Some features were removed from the feature layer * @event FeaturesRemoveEvent */ export class FeaturesRemoveEvent extends sGisEvent { static type: string = 'featuresRemove'; /** * Array of features that were removed */ readonly features: Feature[]; constructor(features: Feature[]) { super(FeaturesRemoveEvent.type); this.features = features; } } /** * A layer that contains arbitrary set of features. * @alias sGis.FeatureLayer */ export class FeatureLayer extends Layer { private _features: Feature[]; /** * @param __namedParameters - properties to be set to the corresponding fields. * @param extensions - [JS ONLY]additional properties to be copied to the created instance. */ constructor({delayedUpdate = true, features = [], ...layerParams}: FeatureLayerConstructorParams = {}, extensions?: Object) { super({delayedUpdate, ...layerParams}, extensions); this._features = features; } getRenders(bbox: Bbox, resolution: number): Render[] { let renders = []; this.getFeatures(bbox, resolution).forEach(feature => { renders = renders.concat(feature.render(resolution, bbox.crs)); renders.forEach(render => { if (render instanceof StaticImageRender) { render.onLoad = () => { this.redraw(); } } }); }); return renders; } getFeatures(bbox: Bbox, resolution: number): Feature[] { if (!this.checkVisibility(resolution)) return []; return this._features.filter(feature => feature.crs.canProjectTo(bbox.crs) && (feature.persistOnMap || feature.bbox.intersects(bbox))) } /** * Adds a feature or an array of features to the layer. * @param features - features to add. * @throws if one of the features is already in the layer. * @fires FeaturesAddEvent */ add(features: Feature | Feature[]): void { const toAdd = Array.isArray(features) ? features : [features]; if (toAdd.length === 0) return; toAdd.forEach(f => { if (this._features.indexOf(f) !== -1) error(new Error(`Feature ${f} is already in the layer`)); }); this._features = this._features.concat(toAdd); this.fire(new FeaturesAddEvent(toAdd)); this.redraw(); } /** * Removes a feature or an array of features from the layer. * @param features - feature or features to be removed. * @throws if the one of the features is not in the layer. * @fires [[FeaturesRemoveEvent]] */ remove(features: Feature | Feature[]): void { const toRemove = Array.isArray(features) ? features : [features]; if (toRemove.length === 0) return; toRemove.forEach(f => { let index = this._features.indexOf(f); if (index === -1) error(new Error(`Feature ${f} is not in the layer`)); this._features.splice(index, 1); }); this.fire(new FeaturesRemoveEvent(toRemove)); this.redraw(); } /** * Returns true if the given feature is in the layer. * @param feature */ has(feature: Feature): boolean { return this._features.indexOf(feature) !== -1; } /** * Moves the given feature to the top of the layer (end of the list). If the feature is not in the layer, the command is ignored. * @param feature */ moveToTop(feature: Feature): void { let index = this._features.indexOf(feature); if (index !== -1) { this._features.splice(index, 1); this._features.push(feature); this.redraw(); } } /** * List of features in the layer. If assigned, it removes all features and add new ones, firing all the respective events. * @fires [[FeaturesAddEvent]] * @fires [[FeaturesRemoveEvent]] */ get features(): Feature[] { return this._features; } set features(features: Feature[]) { const currFeatures = this._features; this._features = []; this.fire(new FeaturesRemoveEvent(currFeatures)); this.add(features); this.redraw(); } }
c5a95ddb6a34bb5bd68dc80b88c7cea6799aa552
TypeScript
standardnotes/auth
/src/Domain/User/User.spec.ts
2.53125
3
import { User } from './User' describe('User', () => { const createUser = () => new User() it('should indicate if support sessions', () => { const user = createUser() user.version = '004' expect(user.supportsSessions()).toBeTruthy() }) it('should indicate if does not support sessions', () => { const user = createUser() user.version = '003' expect(user.supportsSessions()).toBeFalsy() }) it('should indicate if the user is potentially a vault account', () => { const user = createUser() user.email = 'a75a31ce95365904ef0e0a8e6cefc1f5e99adfef81bbdb6d4499eeb10ae0ff67' expect(user.isPotentiallyAVaultAccount()).toBeTruthy() }) it('should indicate if the user is not a vault account', () => { const user = createUser() user.email = 'test@test.te' expect(user.isPotentiallyAVaultAccount()).toBeFalsy() }) })
05425b23d3beee32d1a788548ce0f175024329eb
TypeScript
codepink/typescript
/notes/2C-typeguard-typeof.ts
3.375
3
// - `typeof로 number, string, boolean, symbol 타입을 찾을 때 타입 가드가 됨 // - 원시 타입에만 사용 가능 function getLast(value: number | string | any[]) { if (typeof value === 'number') { return value % 10; // return value[value.length - 1]; // ERROR } if (typeof value === 'string') { return value.charAt(value.length - 1); // return value % 10; // ERROR } return value[value.length - 1]; } export {};
cc93b185c3927c2d566d6436fcd9a87384177bb6
TypeScript
toadius2/Wedding-APP-API-PROJECT
/src/error/notserializeableerror.ts
2.9375
3
import BasicError from "./baseerror" /** * This error class indicates a NotSerializeableError */ export default class NotSerializeableError extends BasicError { type: string; status: number; /** * Constructs a new NotSerializeableError * @param message - The error message */ constructor() { super("Not NotSerializeable Message given"); Object.setPrototypeOf(this, NotSerializeableError.prototype); this.type = 'NotSerializeableError'; this.status = 400; } }
ffd68e06f39043fb0cdf55ee1dc4ef203ec9fcd5
TypeScript
marcjmiller/dafcbts
/frontend/src/models/CbtModel.ts
2.53125
3
export class CbtModel { public id: number; public name: string; public description: string; public webAddress: string; public cbtSource: string; constructor(id: number, name: string, description: string, webAddress: string, cbtSource: string) { this.id = id; this.name = name; this.description = description; this.webAddress = webAddress; this.cbtSource = cbtSource; } }
30a6cff312662fe200568205c84516f63ee2d94a
TypeScript
ORCID/orcid-angular
/src/app/shared/pipes/record-holder-roles/record-holder-roles.pipe.spec.ts
2.75
3
import { RecordHolderRolesPipe } from './record-holder-roles.pipe' import { Contributor } from '../../../types' describe('RecordHolderContributionPipe', () => { let pipe: RecordHolderRolesPipe beforeEach(() => { pipe = new RecordHolderRolesPipe() }) it('create an instance', () => { expect(pipe).toBeTruthy() }) it('should return roles of contribution holder if exist', () => { const contributors = getContributor() expect(pipe.transform(contributors, null, '0000-0000-0000-000X')).toBe( 'Conceptualization, Project administration' ) expect(pipe.transform(contributors, null, '0000-0000-0000-000Z')).toBe(null) }) }) function getContributor(): Contributor[] { return [ { creditName: 'Test Name', contributorOrcid: { path: '0000-0000-0000-000X', uri: 'https://dev.orcid.org/0000-0000-0000-000X', }, rolesAndSequences: [ { contributorRole: 'conceptualization', contributorSequence: null, }, { contributorRole: 'project administration', contributorSequence: null, }, ], } as Contributor, ] }
701555aa5190eb08149e7b0b5e22067a313ac3d3
TypeScript
dmitrolov/dmt2
/src/app/types/adventure/mechanics.ts
3.078125
3
import { Multilanguage } from "../General"; // Категории размеров interface CreatureSizes { value: string; title: Multilanguage; area: number; } export const creatureSize: CreatureSizes[] = [ { value: 'tiny', title: { en: 'Tiny', ru: 'Крошечный' }, area: 2.5 // 2,5 × 2,5 фута или меньше }, { value: 'small', title: { en: 'Small', ru: 'Маленький', }, area: 5, }, { value: 'medium', title: { en: 'Medium', ru: 'Средний', }, area: 5, }, { value: 'large', title: { en: 'Large', ru: 'Большой', }, area: 10, }, { value: 'huge', title: { en: 'Huge', ru: 'Огромный', }, area: 15, }, { value: 'gargantuan', title: { en: 'Gargantuan', ru: 'Громадный', }, area: 20, // 20 × 20 футов или больше }, ]; export interface Damage { type: string; count: number; dice: number; range: number; } interface GameLanguages { value: string; title: Multilanguage; } export const gameLanguages = [ { value: 'common', title: { eng: 'Common', ru: 'Общий', } }, { value: 'gnomish', title: { eng: 'Gnomish', ru: 'Гномий', } }, ];
da8b3d76209311e261c18345ded8b3f85769e2ea
TypeScript
cq-pandora/projects
/services/bot/src/util/functions/chancesRoll.ts
2.953125
3
import random from './random'; import { RollChances } from '../../common-types'; export default function chancesRoll(chances: RollChances): string { let sum = 0; for (const weight of Object.values(chances)) { sum += weight; } const roll = random(0, sum - 1); let shift = 0; for (const [form, weight] of Object.entries(chances)) { if (shift <= roll && roll < shift + weight) { return form; } shift += chances[form]; } return ''; }
09795ad9e01f922046f28d50fe487f2601259109
TypeScript
orzngo/ghost
/src/entities/layers/LayerManager.ts
2.765625
3
import {Layer} from "./Layer"; export class LayerManager { baseLayer:Layer; managedLayers:Layer[] = []; constructor(public scene:g.Scene, public base:Appendable = scene) { this.baseLayer = new Layer(scene, "LayerManagerBase"); this.base.append(this.baseLayer); } add(name:string, parent:Appendable = this.baseLayer): Layer { const layer = new Layer(this.scene, name); parent.append(layer); return layer; } append(layer:Layer, parent:Appendable = this.baseLayer):void { parent.append(layer); } } export type Appendable = g.Scene | g.E | Layer;
6f3f7d6bd35f8435ae539b15400a847c68fbaacc
TypeScript
Kalashin1/sabiman-backend
/data/validators/validator.ts
2.609375
3
// validating email const isEmail = function (val: string){ return new RegExp(/^[\w]+(\.[\w]+)*@([\w]+\.)+[a-z]{2,7}$/).test(val) } // // validating passwords const isPassword = function(val: string){ return new RegExp(/([a-z]?[A-Z]+[a-z]+[0-9]+)/).test(val) } export { isEmail, isPassword }
4e1b678f974d4b72bfefa5fb25c5b7c196ae22d6
TypeScript
jimjsong/node-red-contrib-differences
/src/differences-node.ts
2.59375
3
/* ========================================================================= Copyright 2020 T-Mobile USA, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. See the LICENSE file for additional language around the disclaimer of warranties. Trademark Disclaimer: Neither the name of "T-Mobile, USA" nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. ================================ */ import { Red, Node, NodeProperties } from "node-red"; import { complement, intersection, union } from "./diff"; export default function differencesNode(RED: Red) { function DifferencesNode(config: NodeProperties & { [key: string]: any }) { RED.nodes.createNode(this, config); const node = this as Node; // const context = this.context(); // Left input this.leftInput = config.leftInput || "left"; this.leftInputType = config.leftInputType || "msg"; // Right input this.rightInput = config.rightInput || "right"; this.rightInputType = config.rightInputType || "msg"; // Function this.func = config.func || "-"; // Output this.output = config.output || "payload"; node.on("input", function (msg: any, send: { (msg: any): void }) { const leftInputValue = RED.util.evaluateNodeProperty( this.leftInput, // "payload", "widgets", "gadgets", etc. this.leftInputType, // "msg", "flow", "global" node, msg ); const rightInputValue = RED.util.evaluateNodeProperty( this.rightInput, // "payload", "widgets", "gadgets", etc. this.rightInputType, // "msg", "flow", "global" node, msg ); switch (this.func) { case "-": msg[this.output] = complement(leftInputValue, rightInputValue); break; case "⋂": msg[this.output] = intersection(leftInputValue, rightInputValue); break; case "⋃": msg[this.output] = union(leftInputValue, rightInputValue); break; default: throw new Error(`Unknown function selection: ${this.func}`); } send(msg); }); } RED.nodes.registerType("differences", DifferencesNode); } module.exports = differencesNode;
136c81120b96a2c9fcd33e16143f81ea2f8b0370
TypeScript
PlatinBae/plugins
/packages/api/src/lib/structures/api/ApiRequest.ts
2.734375
3
import { IncomingMessage } from 'http'; import type { AuthData } from '../http/Auth'; export class ApiRequest extends IncomingMessage { /** * The query parameters. */ public query: Record<string, string | string[]> = {}; /** * The URI parameters. */ public params: Record<string, string> = {}; /** * The body that was sent by the user. */ public body?: unknown; /** * The authorization information. This field indicates three possible values: * * - `undefined`: The authorization middleware has not been executed yet. * - `null`: The user is not authorized. * - `AuthData`: The user is authorized. */ public auth?: AuthData | null; }
afe6eb91edd0433502fddaefa68eafcbeeef963a
TypeScript
kedrzu/vuvu
/src/formz/model.ts
2.65625
3
import Vue from 'vue'; import * as jsep from 'jsep'; const jsepParse = require('jsep'); interface ModelBase { $errors?: ModelErrors; } export interface ModelError { key: string; message: string; } export interface ModelErrors { [key: string]: string[]; } export function hasErrors<T extends object>(model: T) { let errorsAll = model && (model as ModelBase).$errors; return errorsAll && Object.keys(errorsAll).length > 0; } export function getErrorsForProp<T extends object>(model: T, prop: string): string[] { let errorsAll = model && (model as ModelBase).$errors; let errorsForKey = prop != null && errorsAll && errorsAll[prop.toString()]; return errorsForKey || []; } export function getErrors(model: object) { return (model as ModelBase).$errors || Vue.set(model, '$errors', {}); } export function clearErrorsForProp<T extends object>(model: T, prop: string): void { let errorsAll = model && (model as ModelBase).$errors; if (errorsAll) { Vue.delete(errorsAll, prop); } } export function clearAllErrors<T extends object | object[]>(model: T): void { if (!model) { return; } if (Array.isArray(model)) { for (let item of model) { clearAllErrors(item); } } else if (model instanceof Object) { (model as ModelBase).$errors = null; for (let prop of Object.keys(model)) { let value = model[prop]; clearAllErrors(value); } } } export function setErrors<T extends object>(model: T, errors: ModelError[]): void { clearAllErrors(model); if (errors && errors.length) { for (let error of errors) { let expression = jsepParse(error.key); addErrorForExpression(model, expression, error.message); } } } function addErrorForExpression<T extends object>(model: T, expr: jsep.Expression, message: string) { if (!expr) { return; } switch (expr.type) { case 'MemberExpression': { let memberExpr = expr as jsep.MemberExpression; let childModel = findChildModel(model, memberExpr.object); switch (memberExpr.property.type) { case 'Identifier': { let propertyExpr = memberExpr.property as jsep.Identifier; addErrorForKey(childModel, propertyExpr.name, message); return; } case 'Literal': { let literalExpr = memberExpr.property as jsep.Literal; addErrorForKey(childModel, literalExpr.value.toString(), message); return; } } } case 'Identifier': { let identifier = expr as jsep.Identifier; let child = model[identifier.name]; if (child instanceof Object) { addErrorForKey(child, '', message); } else { addErrorForKey(model, identifier.name, message); } return; } } } function addErrorForKey<T extends ModelBase>(model: T, key: string, message: string) { let errors = getErrors(model); let forKey = errors[key] || Vue.set(errors, key, []); forKey.push(message); } function findChildModel<T extends ModelBase>(model: T, expr: jsep.Expression): ModelBase { if (!expr) { return null; } switch (expr.type) { case 'Identifier': { let identifier = expr as jsep.Identifier; let childModel = model[identifier.name]; if (!childModel) { childModel = {}; Vue.set(model, identifier.name, childModel); } return childModel; } case 'MemberExpression': { let memberExpr = expr as jsep.MemberExpression; let childModel = findChildModel(model, memberExpr.object); return findChildModel(childModel, memberExpr.property); } } }
7c0eb4b06861bf8cf5a93e0a3355c328fae5fce2
TypeScript
kapturoff/secret-santa-vk
/src/helpers/requestHandlers/roomCreated.ts
2.828125
3
import { ClientInfo, MessageResponse, Room } from 'interfaces' import Markup from 'node-vk-bot-api/lib/markup' export default function roomCreatedHandler(clientInfo: ClientInfo, room: Room): MessageResponse { return { text: `Поздравляю, ты только что создал комнату для проведения "Тайного Санты" 👀 Вот название комнаты: "${room.name}", а вот её код: ${room.code} Чтобы к ней присоединились твои друзья, они должны запустить бота, нажать на кнопку "Присоединиться к комнате", а затем отправить в диалог с ботом следующий код: ${room.code} А всё, что теперь требуется от тебя — разослать друзьям код от этой комнаты, а затем, когда все соберутся, начать розыгрыш, нажав на кнопку под этим сообщением или отправив в беседу с ботом эту команду: /startRoom:${room.code} Ну а в следующем сообщении ты можешь отправить список своих пожеланий для подарков 😅 Этот список увидит только твой личный Тайный Санта. Если ты не хочешь его заполнять или хочешь, чтобы твой Тайный Санта придумал что тебе дарить самостоятельно — не беда: ты можешь пропустить этот этап и оставить поле полностью пустым, написав мне "Пропустить". Подумай хорошенько, ведь другой возможности добавить список пожеланий у тебя не будет 😭 P.S.: Не забудь дать разрешение боту на написание сообщений, иначе он не сможет написать тебе когда игра начнётся и ты не узнаешь имя своего получателя!`, buttons: Markup.keyboard([ Markup.button({ color: 'primary', action: { type: 'text', label: 'Начать!', payload: JSON.stringify({ command: 'startRoom:' + room.code }), }, }), ]).inline(), } as MessageResponse }
055e2a3f41033e99d7b7272204e038fbaa888c3b
TypeScript
sanjevShakya/react-redux-typescript-boilerplate
/src/reducers/data/items/ids.ts
2.765625
3
import * as ItemActions from "../../../actions/data/items"; import * as ItemProps from "./types"; const { FETCH_ITEMS_FULFILLLED, FETCH_ITEMS_REJECTED, SAVE_ITEMS_FULFILLLED } = ItemActions.ACTIONS; const DEFAULT_STATE: ItemProps.IDsProps = []; export default (state = DEFAULT_STATE, action: ItemProps.ActionTypes) => { switch (action.type) { case FETCH_ITEMS_FULFILLLED: { return action.payload.result; } case FETCH_ITEMS_REJECTED: { return DEFAULT_STATE; } case SAVE_ITEMS_FULFILLLED: { if (state.indexOf(action.payload.result) === -1) state.unshift(action.payload.result); return state; } } return state; };
b0860a3bc10414cbef75157b6775dae6be26627e
TypeScript
djudorange/apihive
/packages/apihive/src/components/ErrorResponse/index.ts
2.640625
3
import Base from '../Base'; import { Component } from '..'; import Text from '../Text'; declare global { namespace JSX { interface IntrinsicElements { ERRORRESPONSE: any; //React.PropsWithChildren<Props>; } } } interface ErrorResponseProps { status: number; name: string; appCode?: number; } export default class ErrorResponse extends Base { props: ErrorResponseProps; name: string; context: any; message: string = 'Error'; constructor(props: ErrorResponseProps) { super(); this.props = props; this.name = props.name; } appendChild(child: Component) { if (child instanceof Text) { this.message = child.props.text; } } render() { return { app_code: this.props.appCode, message: this.message, ...this.context }; } setContext(context: any) { this.context = context; } getStatus() { return this.props.status; } }
ff331482528a73af5131d73c368ff6b5c5fe5dc6
TypeScript
mocoolka/mocoolka-function
/src/create.ts
3.078125
3
import setName from './setName'; /** * Create a Function with those param * @param name * @param params * @param functionBody * @return {Function} */ const create = (name:string, params, functionBody:string):Function=> { let temp = new Function(params, functionBody); setName(temp, name); return temp; }; export default create;
ed6d1cb24f2a1ec4d45ad94646b27ae89acae3c3
TypeScript
IanPSRocha/2019.1-PretEvent
/front-end/pret-event/src/app/models/event.ts
2.65625
3
export class Event { id: number; title: string; date: string; place: string; points: number; description: string; // tslint:disable-next-line: variable-name url_image: string; // tslint:disable-next-line: variable-name reward_id: number; creator_id: number; constructor(title: string, date: string, place: string, time: string, points: number, description: string, rewardId: number, creatorId: number, photoUrl?: string) { this.title = title; this.date = date + "T" + time; this.place = place; this.points = points; this.description = description; this.url_image = photoUrl || ''; this.reward_id = rewardId; this.creator_id = creatorId; } }
443fd7095d577c7277b4ae926d7d0c801dea06cd
TypeScript
mmaterowski/raft
/raft-frontend/src/app/servers/circle.ts
2.5625
3
export class Circle { constructor( public x: number, public y: number, public r: number, public color: string, public text: string ) {} }
f7af9757844425008986673a975d78100ae3f2e0
TypeScript
SomtoUgeh/sw-client
/src/components/roots/redux/reducer.ts
2.84375
3
import { ResourceState } from 'models/common'; import { FETCH_ROOT, FETCH_ROOT_FAILURE, FETCH_ROOT_SUCCESS, FetchRootActionType, } from './type'; export interface RootsCompleteInterface { roots: Record<string, unknown>; error: string; status: ResourceState; } const INITIAL_STATE: RootsCompleteInterface = { roots: {}, status: 'IDLE', error: '', }; const rootReducer = ( state = INITIAL_STATE, action: FetchRootActionType, ): RootsCompleteInterface => { switch (action.type) { case FETCH_ROOT: return { ...state, status: 'LOADING', }; case FETCH_ROOT_SUCCESS: return { ...state, status: 'SUCCESS', roots: action.payload, }; case FETCH_ROOT_FAILURE: return { ...state, status: 'FAILURE', error: action.payload, }; default: return state; } }; export default rootReducer;
41385451bffdee7dde5b27e5c39155f27bab43a3
TypeScript
helospark/helospark-site
/helospark-core-ui/src/app/common/authentication-store/authentication-store.service.ts
2.578125
3
import { Token } from './token'; import { AuthenticationTokens } from './authentication-tokens'; import { Injectable, OnInit } from '@angular/core'; @Injectable() export class AuthenticationStoreService { private thresholdTime:number = 1000; private tokenKey:string = "Authentication-tokens"; private authenticationTokens:AuthenticationTokens; constructor() { var result = localStorage.getItem(this.tokenKey); if (result) { try { this.authenticationTokens = JSON.parse(result); } catch (e) { console.log("Cannot parse json " + e); } } } getToken():string { if (this.authenticationTokens && this.isTokenValid(this.authenticationTokens.authenticationToken)) { return this.authenticationTokens.authenticationToken.token; } else { return null; } } setTokens(tokens:AuthenticationTokens) { console.log("Tokens changed"); this.updateToken(tokens); } getRefreshToken():string { if (this.authenticationTokens && this.isTokenValid(this.authenticationTokens.refreshToken)) { return this.authenticationTokens.refreshToken.token; } else { return null; } } updateToken(tokens:AuthenticationTokens) { this.authenticationTokens = tokens; localStorage.setItem(this.tokenKey, JSON.stringify(this.authenticationTokens)); } clearToken() { this.authenticationTokens = null; localStorage.removeItem(this.tokenKey); } isTokenRefreshRequired():boolean { return this.authenticationTokens != null && this.authenticationTokens.authenticationToken.expiresAt - Date.now() < this.thresholdTime && this.authenticationTokens.refreshToken.expiresAt - Date.now() > this.thresholdTime; } isReloginRequired():boolean { return this.authenticationTokens != null && this.authenticationTokens.refreshToken.expiresAt - Date.now() < this.thresholdTime; } isLoggedIn():boolean { return this.authenticationTokens != null && !this.isReloginRequired(); } isLoggedOut():boolean { return !this.isLoggedIn(); } isAdmin():boolean { return this.isLoggedIn() && this.authenticationTokens.admin; } private isTokenValid(token:Token):boolean { var millisecondsTillExpiry:number = token.expiresAt - Date.now(); return millisecondsTillExpiry > this.thresholdTime; } }
d75ca162ba39af97164095f061afb851caea873f
TypeScript
oracle/nosql-node-sdk
/src/types/param.d.ts
2.703125
3
/*- * Copyright (c) 2018, 2023 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl/ */ import type { CapacityMode } from "./constants"; import type { PutOpt, DeleteOpt } from "./opt"; import type { SyncPolicy, ReplicaAckPolicy } from "./durability"; import type { AnyRow, KeyField, RowKey, FieldValue } from "./data"; import type { getAuthorization } from "./auth/config"; import type { OpaqueType } from "./type_utils"; /** * Cloud service only. * Note: this type is only relevant when using the driver with the Cloud * Service or Cloud Simulator. It is not relevant when using the driver * with on-premise NoSQL Database (see {@link ServiceType.KVSTORE}), in which * case it is ignored in the operations mentioned below and is not returned as * part of {@link TableResult }. * <p> * A TableLimits object is used during table creation to specify the * throughput and capacity to be consumed by the table. It is also used * in an operation to change the limits of an existing table. These * operations are performed by {@link NoSQLClient#tableDDL} and * {@link NoSQLClient#setTableLimits} methods. The values provided are * enforced by the system and used for billing purposes. * <p> * Throughput limits are defined in terms of read units and write units. A * read unit represents 1 eventually consistent read per second for data up to * 1 KB in size. A read that is absolutely consistent is double that, * consuming 2 read units for a read of up to 1 KB in size. This means that if * an application is to use {@link Consistency.ABSOLUTE} it may need to * specify additional read units when creating a table. A write unit * represents 1 write per second of data up to 1 KB in size. * <p> * In addition to throughput, table capacity must be specified to indicate * the maximum amount of storage, in gigabytes, allowed for the table. * <p> * In {@link CapacityMode.PROVISIONED} mode (the default), all 3 values must * be specified whenever using this object. There are no defaults and no * mechanism to indicate "no change." * <p> * In {@link CapacityMode.ON_DEMAND} mode, only the storageGB parameter must * be specified. */ export interface TableLimits { /** * The desired throughput of read operation in terms of read units, as a * positive integer. A read unit represents 1 eventually consistent read * per second for data up to 1 KB in size. A read that is absolutely * consistent is double that, consuming 2 read units for a read of up to * 1 KB in size. * @see {@link Consistency} */ readUnits?: number; /** * The desired throughput of write operation in terms of write units, as a * positive integer. A write unit represents 1 write per second of data up * to 1 KB in size. */ writeUnits?: number; /** * The maximum storage to be consumed by the table, in gigabytes, as * positive integer. */ storageGB?: number; /** * Capacity mode of the table, {@link CapacityMode.PROVISIONED} or * {@link CapacityMode.ON_DEMAND}. * @defaultValue {@link CapacityMode.PROVISIONED} */ mode?: CapacityMode; } /** * RowVersion is an opaque type that represents the version of a row in the * database. The driver uses Node.js Buffer to store the version. The * version is returned by successful {@link NoSQLClient#get} operation * and can be used by {@link NoSQLClient#put}, * {@link NoSQLClient#putIfVersion }, {@link NoSQLClient#delete} and * {@link NoSQLClient#deleteIfVersion } methods to conditionally perform those * operations to ensure an atomic read-modify-write cycle. This is an opaque * object from an application perspective. Use of {@link RowVersion} in this * way adds cost to operations so it should be done only if necessary. */ export type RowVersion = OpaqueType<Buffer, "RowVersion">; /** * An opaque type that represents continuation key for * {@link NoSQLClient#deleteRange}. It is used to perform an operation across * multiple calls to this method (such as in a loop until continuation * key becomes null). This is an opaque type from application perspective * and only values from previous results should be used. */ export type MultiDeleteContinuationKey = OpaqueType<Buffer, "MultiDeleteContinuationKey">; /** * An opaque type that represents continuation key for * {@link NoSQLClient#query}. It is used to perform an operation across * multiple calls to this method (such as in a loop until continuation * key becomes null). This is an opaque type from application perspective * and only values from previous results should be used. */ export type QueryContinuationKey = OpaqueType<Buffer, "QueryContinuationKey">; /** * Note: On-Prem only. * <p> * Durability specifies the master and replica sync and ack policies to be * used for a write operation. * @see {@link SyncPolicy} * @see {@link ReplicaAckPolicy} */ export interface Durability { /** * The sync policy to use on the master node. */ masterSync: SyncPolicy; /** * The sync policy to use on a replica. */ replicaSync: SyncPolicy; /** * The replica acknowledgement policy * to be used. */ replicaAck: ReplicaAckPolicy; } /** * Used to specify time to live (TTL) for rows provided to * {@link NoSQLClient#put} and other put methods, such as * {@link NoSQLClient#putIfAbsent}, {@link NoSQLClient#putIfPresent} and * {@link NoSQLClient#putIfVersion}. * <p> * TTL is restricted to durations of days and hours, with day being * 24 hours. Note that you may only specify only one of * {@link days} or {@link hours} fields, not both. * You may specify TTL as object such as <em>\{ days: numDays \}</em> or * <em>\{ hours: numHours \}</em>, or if you are using duration of days * you can specify TTL as just a number indicating number of days, so using * e.g. <em>opt.ttl = 5;</em> is also allowed. * <p> * Sometimes you may may need to indicate explicitly that the record doesn't * expire. This is needed when you perform put operation on existing record * and want to remove its expiration. You may indicate no expiration * by setting days or hours of to Infinity (or just set TTL itself to * Infinity), or use constant {@link TTLUtil.DO_NOT_EXPIRE}. * <p> * The record expiration time is determined as follows: * <p> * Records expire on day or hour boundaries, depending on which 'days' or * 'hours' field is used. At the time of the write operation, the TTL * parameter is used to compute the record's expiration time by first * converting it from days (or hours) to milliseconds, and then adding it * to the current system time. If the resulting expiration time is not evenly * divisible by the number of milliseconds in one day (or hour), it is * rounded up to the nearest day (or hour). The day and hour boundaries (the * day boundary is at midnight) are considered in UTC time zone. * <p> * The minimum TTL that can be specified is 1 hour. Because of the rounding * behavior described above, the actual record duration will be longer than * specified in the TTL (because of rounding up). * <p> * Also note that using duration of days are recommended as it will result in * the least amount of storage overhead compared to duration of hours. * <p> * {@link TTLUtil } class provides functions to create and manage TTL * instances and convert between TTL and record expiration time. * @see {@link TTLUtil} */ export interface TimeToLive { /** * Duration in days as positive integer or Infinity. Exclusive with * {@link TimeToLive#hours}. */ days?: number; /** * Duration in hours as positive integer or Infinity. Exclusive with * {@link TimeToLive#days}. */ hours?: number; } /** * FieldRange defines a range of values to be used in a * {@link NoSQLClient#deleteRange } operation, as specified in * <em>opt.fieldRange</em> for that operation. * <p> * FieldRange is used as the least significant component in a partially * specified key value in order to create a value range for an operation that * returns multiple rows or keys. The data types supported by FieldRange are * limited to the atomic types which are valid for primary keys. * <p> * The <i>least significant component</i> of a key is the first component of * the key that is not fully specified. For example, if the primary key for a * table is defined as the tuple &lt;a, b, c&gt; a FieldRange can be specified * for <em>a</em> if the primary key supplied is empty. A FieldRange can be * specified for <em>b</em> if the primary key supplied to the operation * has a concrete value for <em>a</em> but not for <em>b</em> or <em>c</em>. * </p> * <p> * This object is used to scope a {@link NoSQLClient#deleteRange} operation. * The fieldName specified must name a field in a table's primary key. * The values used must be of the same type and that type must match * the type of the field specified. * </p> * <p> * You may specify the {@link FieldValue} for lower bound, upper bound or * both. Each bound may be either inclusive, meaning the range starts with * (for lower bound) or ends with (for upper bound) with this value, or * exclusive, meaning the range starts after (for lower bound) or ends before * (for upper bound) the value. Properties {@link startWith} and * {@link endWith} specify inclusive bounds and properties {@link startAfter} * and {@link endBefore} specify exclusive bounds. Note that for each end of * the range you may specify either inclusive or exclusive bound, but not * both. * <p> * Validation of this object is performed when it is used in an operation. * Validation includes verifying that the field is in the required key and, * in the case of a composite key, that the field is in the proper order * relative to the key used in the operation. */ export interface FieldRange { /** * Field name for the range. */ fieldName: string; /** * Field value for the lower bound of the range, inclusive. May be * undefined if no lower bound is enforced. May not be used together with * {@link startAfter}. */ startWith?: KeyField; /** * Field value for the lower bound of the range, exclusive. May be * undefined if no lower bound is enforced. May not be used together with * {@link startWith}. */ startAfter?: KeyField; /** * Field value for the upper bound of the range, inclusive. May be * undefined if no upper bound is enforced. May not be used together with * {@link endBefore}. */ endWith?: KeyField; /** * {@link KeyField} value for the upper bound of the range, exclusive. May * be undefined if no upper bound is enforced. May not be used together * with {@link endWith}. */ endBefore?: KeyField; } /** * Represents one of <em>put</em> or <em>delete</em> sub operations in the * <em>operations</em> array argument provided to * {@link NoSQLClient#writeMany} method. It contains row for put operation * (as <em>put</em> key) or primary key for delete operation (as * <em>delete</em> key) and may contain additional properties representing * options for this sub operation. These options are the same as used for * {@link NoSQLClient#put} and {@link NoSQLClient#delete} and they override * options specified in <em>opt</em> parameter of * {@link NoSQLClient#writeMany} * for this sub operation. Exceptions to this are <em>timeout</em>, * <em>compartment</em> and <em>durability</em> which cannot be specified per * sub-operation, but only for the whole {@link NoSQLClient#writeMany} * operation. * <p> * If issuing operations for multiple tables, you must also specify * {@link WriteOperation#tableName} for each operation. See * {@link NoSQLClient#writeMany } for more details. * <p> * Note that in a more simple case where operations are for a single table and * are either all <em>put</em> or all <em>delete</em> and you don't need to * set per-operation options, you may prefer to use * {@link NoSQLClient#putMany} or {@link NoSQLClient#deleteMany} methods and * avoid using this type. * @typeParam TRow Type of table row instance. Must include primary key * fields. Defaults to {@link AnyRow}. */ export interface WriteOperation<TRow = AnyRow> { /** * Table name for the operation. Only needed when issuing operations for * multiple tables. This property is mutually exclusive with * <em>tableName</em> parameter to {@link NoSQLClient#writeMany}. */ tableName?: string; /** * Row for <em>put</em> operation, designates this operation as * <em>put</em>. One and only one of {@link put} or {@link delete} * properties must be set. */ put?: TRow; /** * Primary key for <em>delete</em> operation, designates this operation as * <em>delete</em>. One and only one of {@link put} or {@link delete} * properties must be set. * @see {@link RowKey} */ delete?: RowKey<TRow>; /** * If true, and if this operation fails, it will cause the entire * {@link NoSQLClient#writeMany} operation to abort. */ abortOnFail?: boolean; /** * Same as {@link PutOpt#ifAbsent}, valid only for <em>put</em> operation. */ ifAbsent?: boolean; /** * Same as {@link PutOpt#ifPresent}, valid only for <em>put</em> * operation. */ ifPresent?: boolean; /** * Same as {@link PutOpt#matchVersion} for <em>put</em> operation or * {@link DeleteOpt#matchVersion} for <em>delete</em> operation. */ matchVersion?: RowVersion; /** * Same as {@link PutOpt#ttl}, valid only for <em>put</em> operation. */ ttl?: TimeToLive | number; /** * Same as {@link PutOpt#updateTTLToDefault}, only valid for <em>put</em> * operation. */ updateTTLToDefault?: boolean; /** * Same as {@link PutOpt#exactMatch}, valid only for <em>put</em> * operation. */ exactMatch?: boolean; /** * Same as {@link PutOpt#returnExisting} for <em>put</em> operation or * {@link DeleteOpt#returnExisting} for <em>delete</em> operation. */ returnExisting?: boolean; /** * Same as {@link PutOpt#identityCacheSize}, valid only for <em>put</em> * operation. */ identityCacheSize?: number; } /** * Represents information about invocation of a method on {@link NoSQLClient} * instance. Contains the method that was called and its parameters including * the options <em>opt</em> parameter. Operation object may be used in the * following ways: * <ul> * <li>It is available as {@link NoSQLError#operation} property allowing the * error code to examine the operation that caused the error.</li> * <li>It is available as parameter to {@link NoSQLClient} events * allowing to customize the behavior of event hanlders depending on what * operation has caused the event.</li> * <li>It is available as parameter to methods of {@link RetryHandler}. * If the application is using custom retry handler, it can customize the * retry logic based on what operation has caused the retryable error.</li> * <li>It is available as parameter to * {@link getAuthorization} method of authorization * provider. If the application is using custom authorization mechanism, it * can customize its behavior based on what operation requires authorization. * </li> * </ul> * <p> Note that the {@link Operation#opt} property also extends * {@link Config} object with which {@link NoSQLClient} instance was created, * so in addition to properties in <em>opt</em> argument you may use * {@link Operation#opt} to access all additional properties of * {@link Config}. * <p> * Besides the properties described below, the remaining properties of * {@link Operation} object represent parameters passed to the * {@link NoSQLClient} method and are named as such. The values of these * properties are the values passed as corresponding parameters of the method. * E.g. if the method takes parameter <em>tableName</em> with value 'Employee' * then the {@link Operation} object will have property * <em>tableName: 'Employee'</em>. */ export interface Operation { /** * The API represented by the operation, which is the * instance method of {@link NoSQLClient} class. */ readonly api: Function; /** * <em>opt</em> parameter that is passed to {@link NoSQLClient} methods. * Extends {@link Config}. */ readonly opt?: object; /** * Parameters passed to {@link NoSQLClient} method. */ [name: string]: any; } /** * Cloud Service only. Represents table entity tag (ETag). * <p> * Table ETag is an opaque value that represents the current * version of the table itself and can be used in table modification * operations such as {@link NoSQLClient#tableDDL}, * {@link NoSQLClient#setTableLimits} and {@link NoSQLClient#setTableTags} to * only perform them if the ETag for the table has not changed. This is an * optimistic concurrency control mechanism allowing an application to ensure * that no unexpected modifications have been made to the table. * <p> * The value of the ETag passed to the table modification operations must be * the value {@link TableResult#etag} returned in the previous * {@link TableResult}. If set for on-premises service, the ETag is silently * ignored. */ export type TableETag = OpaqueType<string, "TableETag">; /** * Cloud Service only. Represents defined tags for a table. * <p> * See chapter <em>Tagging Overview</em> in Oracle Cloud Infrastructure * documentation. Defined tags represent metadata managed by an administrator. * Users can apply these tags to a table by identifying the tag and supplying * its value. * <p> * Each defined tag belongs to a namespace, where a namespace serves as a * container for tag keys. Defined tags are represented by a nested two-level * plain JavaScript object, with top-level keys representing tag namespaces * and the value of each key being an object containing tag keys and values * for a particular namespace. All tag values must be strings. * <p> * Defined tags are used only in these cases: table creation operations * executed by {@link NoSQLClient#tableDDL} with <em>CREATE TABLE</em> SQL * statement and table tag modification operations executed by * {@link NoSQLClient#setTableTags}. They are not used for other table DDL * operations. If set for an on-premises service, they are silently ignored. */ export interface DefinedTags { [namespace: string]: { [key: string]: string; } } /** * Cloud Service only. Represents free-form tags for a table. * <p> * See chapter <em>Tagging Overview</em> in Oracle Cloud Infrastructure * documentation. Free-form tags represent an unmanaged metadata created and * applied by the user. Free-form tags do not use namespaces. Free-form tags * are represented by a plain JavaScript object containing tag keys and * values. All tag values must be strings. * <p> * Free-form tags are used only in these cases: table creation operations * executed by {@link NoSQLClient#tableDDL} with <em>CREATE TABLE</em> SQL * statement and table tag modification operations executed by * {@link NoSQLClient#setTableTags}. They are not used for other table DDL * operations. If set for an on-premises service, they are silently ignored. */ export interface FreeFormTags { [key: string]: string; }
3e66de513cd176f04b189f2ef02cd99cba984cbf
TypeScript
nklincoln/persona-maps
/src/app/common/persona.spec.ts
2.9375
3
import { Aspect } from './aspect'; import { PersonaAspect } from './persona-aspect'; import { Persona } from './persona'; import * as sinon from 'sinon'; import * as chai from 'chai'; let should = chai.should(); describe('Persona', () => { let myAspect0: Aspect; let myAspect1: Aspect; let myAspect2: Aspect; let myAspect3: Aspect; let personaAspect0: PersonaAspect; let personaAspect1: PersonaAspect; let personaAspect2: PersonaAspect; let personaAspect3: PersonaAspect; let persona: Persona; beforeEach(() => { myAspect0 = new Aspect('myAspect0', 5); myAspect1 = new Aspect('myAspect1', 3); myAspect2 = new Aspect('myAspect2', 5); myAspect3 = new Aspect('myAspect3', 5); personaAspect0 = new PersonaAspect(myAspect0, 1); personaAspect1 = new PersonaAspect(myAspect1, 2); personaAspect2 = new PersonaAspect(myAspect2, 3); personaAspect3 = new PersonaAspect(myAspect3, 7); persona = new Persona('bob'); }) it('should be able to set and get the persona name', function () { persona.getName().should.equal('bob'); persona.setName('sally'); persona.getName().should.equal('sally'); }); it('should be able to add and get a single persona aspect', function () { persona.addPersonaAspect(personaAspect0); persona.getPersonaAspect(myAspect0).should.deep.equal(personaAspect0); }); it('should throw if trying to get a single persona aspect that does not exist', function () { try { persona.getPersonaAspect(myAspect0).should.deep.equal(personaAspect0); fail('should have errored with missing aspect'); } catch (error) { error.toString().should.equal('Error: No PersonaAspect containing Aspect with name [myAspect0].'); } }); it('should be able to add and get a multiple aspects', function () { let array = [personaAspect0, personaAspect1, personaAspect2, personaAspect3]; persona.addPersonaAspects(array); persona.getPersonaAspects().should.deep.equal(array); }); it('should be able to inform if contains aspect', function () { let array = [personaAspect0, personaAspect1, personaAspect2, personaAspect3]; persona.addPersonaAspects(array); persona.hasPersonaAspect(myAspect1).should.be.true; }); it('should be able to inform if does not contain aspect', function () { let array = [personaAspect1, personaAspect2, personaAspect3]; persona.addPersonaAspects(array); persona.hasPersonaAspect(myAspect0).should.be.false; }); it('should be able to remove a single aspect', function () { let array = [personaAspect0, personaAspect1, personaAspect2, personaAspect3]; let expectedAfter = [personaAspect0, personaAspect1, personaAspect3]; persona.addPersonaAspects(array); persona.getPersonaAspects().should.deep.equal(array); // remove an item and check persona.removePersonaAspect(myAspect2); persona.getPersonaAspects().should.deep.equal(expectedAfter); }); it('should throw if trying to remove an aspect that doesnt exist', function () { try { persona.removePersonaAspect(myAspect0); fail('should have errored with missing aspect'); } catch (error) { error.toString().should.equal('Error: No PersonaAspect containing Aspect with name [myAspect0].'); } }); it('should be able to update a persona aspect weighting', function () { let array = [personaAspect0, personaAspect1, personaAspect2, personaAspect3]; persona.addPersonaAspects(array); persona.getPersonaAspect(myAspect0).getWeighting().should.be.equal(1); // update and check persona.updatePersonaAspectWeighting(myAspect0, 9); persona.getPersonaAspect(myAspect0).getWeighting().should.be.equal(9); }); it('should throw if trying to update an aspect that doesnt exist', function () { try { persona.updatePersonaAspectWeighting(myAspect0, 7); fail('should have errored with missing aspect'); } catch (error) { error.toString().should.equal('Error: No PersonaAspect containing Aspect with name [myAspect0].'); } }); it('should be able to return scheme data', function () { let array = [personaAspect0, personaAspect1]; persona.addPersonaAspects(array); let expectedScheme = {domain: ['#7CFC00', '#FFFF00']}; persona.getScheme().should.deep.equal(expectedScheme); }); it('should be able to return persona aspect data', function () { let array = [personaAspect0, personaAspect1]; persona.addPersonaAspects(array); let expectedData = [{name: 'myAspect0', value: 1}, {name: 'myAspect1', value: 2}]; persona.getData().should.deep.equal(expectedData); }); });
827ea9589f967634f6bfe2861b727b4d51a15103
TypeScript
Quramy/copl-ts
/src/structure/traverser.ts
3
3
export interface Tree<Kind extends string = string> { readonly kind: Kind; } export type Select<T extends Tree, Kind extends T["kind"]> = T & { kind: Kind }; export type TraverserCallbackFn<T extends Tree, Context, Result, Kind extends T["kind"]> = ( node: Select<T, Kind>, ctx: Context, next: (node: T, ctx: Context) => Result, ) => Result; export type TraverserCallbackFnMap<T extends Tree, Context, Result> = { [Kind in T["kind"] as Uncapitalize<Kind>]: TraverserCallbackFn<T, Context, Result, Kind>; }; export function createTreeTraverser<T extends Tree, Context, Result>( nodeFunctions: TraverserCallbackFnMap<T, Context, Result>, ): (node: T, ctx: Context) => Result { const fn = (node: T, ctx: Context): Result => { const k = node.kind; const key = k[0].toLowerCase() + k.slice(1); const callback = (nodeFunctions as any)[key]; if (typeof callback !== "function") throw new Error("invalid kind"); return callback(node, ctx, fn); }; return fn; }
72350dd2a97af19f228b6dcbd62f90c22b35b73a
TypeScript
naddeoa/systemconf
/src/lib/systemconf-parser-git.ts
2.828125
3
import * as command from "../lib/command"; import * as parseTypes from "../config/parse-types"; import * as parseUtils from "../lib/parse-utils"; function installFn(parseResult: parseTypes.ParseResult): string { return `git clone ${parseResult.tokens[0]} ${parseResult.tokens[1]}`; } function uninstallFn(parseResult: parseTypes.ParseResult): string { return `rm -rf ${parseResult.tokens[1]}`; } function isInstalledFn(parseResult: parseTypes.ParseResult): string { return `test -d ${parseResult.tokens[1]}`; } /** * Mapper that enables git lines in systemconf config files. They look like * * git oh-my-zsh: https://github.com/robbyrussell/oh-my-zsh.git ~/foobarfoov * * @param parseResults The parse results for git lines. */ function mapper(parseResults: parseTypes.ParseResult[]): parseTypes.ProcessedParseResults { const errors: parseTypes.ProcessingError[] = []; parseResults.reduce( (acc, result) => { if(result.tokens.length !== 2){ acc.push({ for:result, message: `Wrong args supplied to a git config line for ${result.name}. Each line should have included two args. Got ${result.rest}` }); } return acc; }, errors); const validParses = parseResults.filter(result => result.tokens.length === 2); const partitionedResults = parseUtils.partitionByName(validParses); const commandSchemas = Object.keys(partitionedResults).map(name => { const groupedParseResults = partitionedResults[name]; return parseUtils.parseResultsToCommandSchema(name, groupedParseResults, { installFn, uninstallFn, isInstalledFn }); }); return { commandSchemas, errors, parseResults } } const systemConfModule: parseTypes.SystemConfModule = { mapper, format: "git" } export default systemConfModule;
e3e8bbc9ceb19deefdff1364a394a580935cf542
TypeScript
subzerodeluxe/distanceBox_prototypes
/src/components/countdown/countdown.ts
2.8125
3
import { Component, Input } from '@angular/core'; import { AlertController } from "ionic-angular"; // interface import { ICountdown } from "../i-countdown/i-countdown"; @Component({ selector: 'countdown', templateUrl: 'countdown.html' }) export class CountdownComponent { @Input() timeInSeconds: number; public countdown: ICountdown; constructor(public alertCtrl: AlertController) {} ngOnInit() { this.initTimer(); } hasFinished() { return this.countdown.hasFinished; } initTimer() { if(!this.timeInSeconds) { this.timeInSeconds = 0; } this.countdown = <ICountdown>{ seconds: this.timeInSeconds, runTimer: false, hasStarted: false, hasFinished: false, secondsRemaining: this.timeInSeconds }; this.countdown.displayTime = this.getSecondsAsDigitalClock(this.countdown.secondsRemaining); this.countdown.displayDate = this.formatDate(this.countdown.secondsRemaining); this.countdown.daysLeft = this.getDaysLeft(this.countdown.secondsRemaining); } startTimer() { this.countdown.hasStarted = true; this.countdown.runTimer = true; this.timerTick(); } pauseTimer() { this.countdown.runTimer = false; } resumeTimer() { this.startTimer(); } timerTick() { setTimeout(() => { if (!this.countdown.runTimer) { return; } this.countdown.secondsRemaining--; this.countdown.displayTime = this.getSecondsAsDigitalClock(this.countdown.secondsRemaining); if (this.countdown.secondsRemaining > 0) { this.timerTick(); } else { this.countdown.hasFinished = true; // show Alert let alert = this.alertCtrl.create({ title: 'Time \'\s up!', buttons: ['OK'] }) alert.present(); } }, 1000); } getSecondsAsDigitalClock(inputSeconds: number) { var sec_num = parseInt(inputSeconds.toString(), 10); // don't forget the second param var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); var hoursString = ''; var minutesString = ''; var secondsString = ''; hoursString = (hours < 10) ? "0" + hours : hours.toString(); minutesString = (minutes < 10) ? "0" + minutes : minutes.toString(); secondsString = (seconds < 10) ? "0" + seconds : seconds.toString(); return hoursString + ':' + minutesString + ':' + secondsString; } getDaysLeft(inputSeconds: number) { // REVERSE THE MAGIC: SET CURRENT DATE AND SECONDS var currentDate = new Date(); var newHours = currentDate.setHours(2); var newMinutes = currentDate.setMinutes(0); var newSeconds = currentDate.setSeconds(0); var currentSeconds = currentDate.getTime() / 1000; // CALCULATE FINAL SECONDS var final = inputSeconds + currentSeconds; var deadline = new Date(final *1000); // THE MAGIC var msPerDay = 24 * 60 * 60 * 1000; var timeLeft = (deadline.getTime() - currentDate.getTime()); var e_daysLeft = timeLeft / msPerDay; var daysLeft = Math.floor(e_daysLeft); console.log("Days left: " + daysLeft); return daysLeft.toString() + " " + " Days left"; } formatDate(inputSeconds: number) { console.log("Deze seconden komen binnen: " + inputSeconds); var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var dayNames = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ]; // REVERSE THE MAGIC: SET CURRENT DATE AND SECONDS var currentDate = new Date(); var newHours = currentDate.setHours(2); var newMinutes = currentDate.setMinutes(0); var newSeconds = currentDate.setSeconds(0); var currentSeconds = currentDate.getTime() / 1000; // CALCULATE FINAL SECONDS var final = inputSeconds + currentSeconds; var newDate = new Date(final *1000); console.log("Final seconds " + final); var day = newDate.getDate(); var dayIndex = newDate.getDay(); var monthIndex = newDate.getMonth(); var year = newDate.getFullYear(); return dayNames[dayIndex] + ' ' + day + ' ' + monthNames[monthIndex] + ' ' + year; } }
a237cb8ae2bd2260fc8715d528dd1120ad4ef156
TypeScript
huridocs/uwazi
/app/api/authorization.v2/services/AuthorizationService.ts
2.796875
3
import { User } from 'api/users.v2/model/User'; import { PermissionsDataSource } from '../contracts/PermissionsDataSource'; import { UnauthorizedError } from '../errors/UnauthorizedError'; import { EntityPermissions } from '../model/EntityPermissions'; import { Relationship } from 'api/relationships.v2/model/Relationship'; type AccessLevels = 'read' | 'write'; export class AuthorizationService { private authenticatedUser?: User; private permissionsDS: PermissionsDataSource; constructor(permissionsDS: PermissionsDataSource, authenticatedUser?: User) { this.permissionsDS = permissionsDS; this.authenticatedUser = authenticatedUser; } private isPrivileged() { return this.authenticatedUser && this.authenticatedUser.isPrivileged(); } private getRelatedPermissionsSets(sharedIds: string[]) { return this.permissionsDS.getByEntities(sharedIds); } async filterEntities(level: AccessLevels, sharedIds: string[]): Promise<string[]> { if (this.isPrivileged()) { return sharedIds; } const allEntitiesPermissions = await this.getRelatedPermissionsSets(sharedIds).all(); let filteredEntitiesPermissions: EntityPermissions[] = []; if (this.authenticatedUser) { const user = this.authenticatedUser; filteredEntitiesPermissions = allEntitiesPermissions.filter(entityPermissions => entityPermissions.allowsUserTo(user, level) ); } else { filteredEntitiesPermissions = level === 'read' ? allEntitiesPermissions.filter(entityPermissions => entityPermissions.allowsPublicReads() ) : []; } return filteredEntitiesPermissions.map(entityPermissions => entityPermissions.entity); } async filterRelationships(relationships: Relationship[], accessLevel: AccessLevels) { const involvedSharedIds: Set<string> = Relationship.getSharedIds(relationships); const allowedSharedIds = new Set( await this.filterEntities(accessLevel, [...involvedSharedIds]) ); const allowedRelationships = relationships.filter( relationship => allowedSharedIds.has(relationship.from.entity) && allowedSharedIds.has(relationship.to.entity) ); return allowedRelationships; } async isAuthorized(level: AccessLevels, sharedIds: string[]) { if (this.isPrivileged()) { return true; } const allEntitiesPermissions = this.getRelatedPermissionsSets(sharedIds); if (this.authenticatedUser) { const user = this.authenticatedUser; return allEntitiesPermissions.every(entityPermissions => entityPermissions.allowsUserTo(user, level) ); } return ( level === 'read' && allEntitiesPermissions.every(entityPermissions => entityPermissions.allowsPublicReads()) ); } async validateAccess(level: AccessLevels, sharedIds: string[]) { if (!(await this.isAuthorized(level, sharedIds))) { throw new UnauthorizedError('Not authorized'); } } } export type { AccessLevels };
f89ddd30955405930249c43cdc62e69a6d4479ee
TypeScript
ZhidkovGV/smart-chess
/src/helpers/BoardModel.ts
3.3125
3
import { Bishop, Figure, figureColor, FigureConstructor, King, Knight, Pawn, Queen, Rook } from "./Figures"; import { xor } from "./xor"; interface TeamConfig { pawnsRow: number; bigGuysRow: number; color: figureColor; } const blackConfig: TeamConfig = { pawnsRow: 1, bigGuysRow: 0, color: 'black' } const whiteConfig: TeamConfig = { pawnsRow: 6, bigGuysRow: 7, color: 'white' } const figuresPositionMap = new Map<number, FigureConstructor>([ [0, Rook], [1, Knight], [2, Bishop], [3, Queen], [4, King], [5, Bishop], [6, Knight], [7, Rook] ]) export interface Position { x: number; y: number; }; export type boardModel = Cell[][]; export class Cell { public color: figureColor public figure: Figure | null; constructor(color: figureColor, figure: Figure | null) { this.color = color; this.figure = figure; } } export class GameBoardModel { private _boardModel: boardModel constructor(boardModel?: boardModel) { this._boardModel = boardModel ? boardModel : this._dropFigures(this._initBoard()); } get currentBoard(): boardModel { return this._boardModel; } private _dropFigures(board: boardModel): boardModel { const teamsConfig = [whiteConfig, blackConfig]; teamsConfig.forEach(teamConfig => { board[teamConfig.pawnsRow].forEach(cell => cell.figure = new Pawn(teamConfig.color)); board[teamConfig.bigGuysRow].forEach((cell, index) => { const figureClass = figuresPositionMap.get(index) cell.figure = new figureClass!(teamConfig.color) as Figure; }) }) return board; } private _initBoard(): boardModel { let colorToggle = false; const emptyBoard = Array.from({ length: 8 }, () => { colorToggle = !colorToggle; return Array.from({ length: 8 }, (_, i) => { const color = xor(colorToggle, !!(i % 2)) ? 'black' : 'white'; const cell = new Cell(color, null); return cell; }) }); return emptyBoard; } }
426d89acdb37a68b36ee42d3023f412b5cba5210
TypeScript
antonyjim/osm
/packages/core/src/lib/log.ts
2.6875
3
/** * /lib/log.ts * Provide core logging features to the site */ // Node Modules // NPM Modules import { debug as rawDebug } from 'debug' // Local Modules import { Querynator, simpleQuery } from './queries' // Constants and global variables class Log { private tableName: string private requiresContext?: boolean private primaryKey?: string private message: string constructor( message: string, context?: { table: string; primaryKey: string } ) { if (context && !context.primaryKey && context.table) { console.error( 'When a log table is supplied, a primary key must also be supplied' ) } else if (!message) { console.error( new TypeError('Any logging requires a message to be supplied') ) } else if (context && context.table && context.primaryKey) { console.log(`Context of %o supplied`, context) context.table.endsWith('_log') ? (this.tableName = context.table) : (this.tableName = context.table + '_log') this.primaryKey = context.primaryKey this.requiresContext = true this.message = message } else if (!message && !context) { console.error('Any logging requires a message to be supplied') } else { this.tableName = 'sys_log' this.requiresContext = false this.message = message } } protected createQ({ query, params }) { try { simpleQuery(query, params) } catch (e) { console.error('CRITICAL LOGGING ERROR ' + e.message) } } public info(objectId?: string) { const params: Array<string | Date> = [this.tableName] let log = '' let query = '' if (this.requiresContext) { if (!objectId) { console.error( new TypeError( `Logging to ${this.tableName} requires a primary key of ${this.primaryKey}` ) ) } query = 'INSERT INTO ?? (log_time, log_user, log_message, log_severity) VALUES (?, ?, ?, 5)' params.push(new Date()) params.push(this.primaryKey) params.push(objectId) } else { query = 'INSERT INTO ?? (log_message, log_severity) VALUES (?, 5)' } if (this.message && typeof this.message !== 'string') { log = JSON.stringify(this.message) } else if (typeof this.message === 'string') { log = this.message } else { console.error('Cannot log without a message') } console.log( 'INFO ' + new Date().toISOString().replace('T', ' ') + ': ' + log ) params.push(log) this.createQ({ query, params }) return 0 } public error(severity: number = 3, objectId?: string) { if (!this.message) return null console.error( 'ERROR(' + severity + ') ' + new Date().toISOString().replace('T', ' ') + ': ' + this.message ) let log = '' let query = '' const params: any[] = [this.tableName] if (this.requiresContext) { if (!objectId) { console.error( new TypeError( `Logging errors to ${this.tableName} requires a primary key of ${this.primaryKey}` ) ) } query = 'INSERT INTO ?? (log_time, log_user, log_message, log_severity) VALUES (?, ?, ?, 5)' params.push(new Date()) params.push(this.primaryKey) params.push(objectId) } else { query = 'INSERT INTO ?? (log_message) VALUES (?)' } if (this.message && typeof this.message !== 'string') { log = JSON.stringify(this.message) } else if (this.message && typeof this.message === 'string') { log = this.message } else { console.error('Cannot log without a message') } params.push(log) params.push(severity) this.createQ({ query, params }) } public async get(timeframe: Date[], reqId?: string) { let query: string = '' let params = [] if (timeframe.length === 2) { if (reqId && this.requiresContext) { query = 'SELECT * FROM ?? WHERE log_time BETWEEN ? AND ? AND ?? = ? ORDER BY log_time DESC' params = [ this.tableName, timeframe[0], timeframe[1], this.primaryKey, reqId ] } else if (!this.requiresContext) { query = 'SELECT * FROM ?? WHERE log_time BETWEEN ? AND ? ORDER BY log_time DESC' params = [this.tableName, timeframe[0], timeframe[1]] } else { console.error( new Error( 'Context is required to retrieve logs from ' + this.tableName ) ) } } else { if (reqId && this.requiresContext) { query = 'SELECT * FROM ?? WHERE ?? = ? ORDER BY log_time DESC LIMIT 20' params = [this.tableName, this.primaryKey, reqId] } else if (!this.requiresContext) { query = 'SELECT * FROM ?? ORDER BY log_time DESC' params = [this.tableName] } else { console.error( new Error( 'Context is required to retrieve logs from ' + this.tableName ) ) } } return await new Querynator().createQ({ query, params }, 'CALL') } } function RequestLog(method: string, uri: string) { const params: string[] = [ 'sys_log_request', 'request_uri', uri, 'request_method', method ] const query: string = 'INSERT INTO ?? SET ?? = ?, ?? = ?' simpleQuery(query, params).catch((err) => { console.error(err) }) } function debug(name: string): debug.Debugger { const debugFunc = rawDebug(name) debugFunc.log = console.log.bind(console) return debugFunc } export { Log, RequestLog, debug }
8b00790b9a89aa7ee9aa4868223eba247cb5c942
TypeScript
GobilINC/mirror-graph
/src/graphql/resolvers/CdpResolver.ts
2.5625
3
import { In, MoreThan, Raw } from 'typeorm' import { Resolver, Query, Arg } from 'type-graphql' import { Service } from 'typedi' import { Cdp } from 'graphql/schema' import { CdpService } from 'services' @Service() @Resolver((of) => Cdp) export class CdpResolver { constructor(private readonly cdpService: CdpService) {} @Query((returns) => [Cdp], { description: 'Get cdps' }) async cdps( @Arg('maxRatio') maxRatio: number, @Arg('tokens', (type) => [String], { nullable: true }) tokens?: string[], @Arg('address', (type) => [String], { nullable: true }) address?: string[], ): Promise<Cdp[]> { const addressCondition = address ? { address: In(address) } : {} const tokensCondition = tokens ? { token: In(tokens) } : {} if (Array.isArray(address) && address.length > 50) { throw new Error('too many addresses') } if (Array.isArray(tokens) && tokens.length > 50) { throw new Error('too many tokens') } return this.cdpService.getAll({ where: { collateralRatio: Raw((alias) => `${alias} < ${maxRatio}`), mintAmount: MoreThan(0), ...addressCondition, ...tokensCondition, }, order: { collateralRatio: 'ASC' }, take: 100 }) } @Query((returns) => [Cdp], { description: 'Get liquidation target cdps' }) async liquidations(): Promise<Cdp[]> { return this.cdpService.getAll({ where: { collateralRatio: Raw((alias) => `${alias} < min_collateral_ratio`) }, order: { mintValue: 'DESC' }, take: 100 }) } }
e68f1312129d9fd1e1c0d14c829fdb0385880fb1
TypeScript
Mrowa96/account
/src/modules/StoredAccountData/StoredAccountData.ts
2.953125
3
const ACCOUNT_DATA_KEY = 'accountData'; export function store(email: string): void { localStorage.setItem( ACCOUNT_DATA_KEY, btoa( JSON.stringify({ email, }), ), ); } export function get(): { email: string } | undefined { const storedData = localStorage.getItem(ACCOUNT_DATA_KEY); if (storedData) { try { const decodedData = JSON.parse(atob(storedData)) as { email: string; }; return { email: decodedData.email, }; } catch (error) { console.error(error); } } return undefined; } export function clear(): void { localStorage.removeItem(ACCOUNT_DATA_KEY); }
43cd9d917a01cf46fabccf15a8e408817540eb7b
TypeScript
MiracleUFO/squares
/src/squares/squares.service.ts
2.75
3
import { Injectable } from '@nestjs/common'; @Injectable() export class SquaresService { getSquare(number: number) { const square = number * number; return square; } getSquareRoot(number: number) { const squareRoot = Math.sqrt(number); return squareRoot; } }
ab81e401ba261398c374b8846f22b85d393fee71
TypeScript
stochi00/WebEng07_Gr11
/UEB2/lab2/app/components/control.boolean.component.ts
2.703125
3
import {Component, Input} from '@angular/core'; import {ControlUnit} from "../model/controlUnit"; import {DatePipe} from "@angular/common"; @Component({ moduleId: module.id, selector: 'control-boolean', templateUrl: '../views/controlboolean.html' }) export class ControlBoolean { @Input() controlunit: ControlUnit; log: LogEntry[] = []; chartLabels: string[] = ['An', 'Aus']; charData: number[] = [0, 0]; chartType: string = 'doughnut'; setValue(value: boolean) { this.log.push(new LogEntry((this.controlunit.current ? "An" : "Aus"), (value ? "An" : "Aus"))); this.controlunit.current = (value ? 1 : 0); if (value) this.charData[0]++; else this.charData[1]++; this.charData = this.charData.slice(); } logToString(): string { var history: string = ""; for (var i = 0; i < this.log.length; i++) { var element = this.log[i]; history += element + "\n"; } return history; } } class LogEntry { datepipe: DatePipe; datetime: Date; oldvalue: any; newvalue: any; public constructor(oldvalue: any, newvalue: any) { this.datepipe = new DatePipe('DE-de'); this.datetime = new Date(); this.oldvalue = oldvalue; this.newvalue = newvalue; } toString(): string { return this.datepipe.transform(this.datetime, "dd.MM.yyyy hh:mm:ss") + " " + " " + this.oldvalue + " -> " + this.newvalue; } }
859149dad82d3ddee3561f9957c33657934684fe
TypeScript
fabricjs/fabric.js
/src/gradient/parser/misc.ts
2.546875
3
import type { GradientType, GradientUnits } from '../typedefs'; export function parseType(el: SVGGradientElement): GradientType { return el.nodeName === 'linearGradient' || el.nodeName === 'LINEARGRADIENT' ? 'linear' : 'radial'; } export function parseGradientUnits(el: SVGGradientElement): GradientUnits { return el.getAttribute('gradientUnits') === 'userSpaceOnUse' ? 'pixels' : 'percentage'; }
475c6cdb3234baf52b106f57df717d3b90ddd816
TypeScript
ruisunon/machinat
/packages/auth/src/types.ts
2.625
3
import type { IncomingMessage, ServerResponse, IncomingHttpHeaders, } from 'http'; import type { MachinatUser, MachinatChannel } from '@machinat/core'; import type { RoutingInfo } from '@machinat/http'; import type AuthError from './error'; type TokenBase = { iat: number; exp: number; }; export type AuthPayload<Data> = { platform: string; data: Data; refreshTill?: number; scope: { domain?: string; path: string }; }; export type AuthTokenPayload<Data> = TokenBase & AuthPayload<Data>; export type StatePayload<State> = { platform: string; state: State; }; export type StateTokenPayload<State> = TokenBase & StatePayload<State>; export type ErrorMessage = { code: number; reason: string }; export type ErrorPayload = { platform: string; error: ErrorMessage; scope: { domain?: string; path: string }; }; export type ErrorTokenPayload = TokenBase & ErrorPayload; export type AuthContextBase = { loginAt: Date; expireAt: Date; }; export type AuthContext< User extends MachinatUser, Channel extends MachinatChannel > = { platform: string; user: User; channel: Channel; } & AuthContextBase; export type AnyAuthContext = AuthContext<MachinatUser, MachinatChannel>; export type ContextSupplement<Context extends AnyAuthContext> = Omit< Context, 'platform' | 'loginAt' | 'expireAt' >; type ErrorResult = { success: false; code: number; reason: string; }; export type VerifyResult<Data> = { success: true; data: Data } | ErrorResult; export type ContextResult<Context extends AnyAuthContext> = | { success: true; contextSupplment: ContextSupplement<Context> } | ErrorResult; export type IssueAuthOptions = { refreshTill?: number; signatureOnly?: boolean; }; export type RedirectOptions = { assertInternal?: boolean; }; export interface ResponseHelper { /** Get content of state cookie from request, return null if absent. */ getState<State>(): Promise<null | State>; /** Issue state cookie to response, return the signed JWT string. */ issueState<State>(state: State): Promise<string>; /** Get content of auth cookie from request, return null if absent. */ getAuth<Data>(): Promise<null | Data>; /** Issue state cookie to response, return the signed token. */ issueAuth<Data>(authData: Data, options?: IssueAuthOptions): Promise<string>; /** Get content of error cookie from request, return null if absent. */ getError(): Promise<null | ErrorMessage>; /** Issue error cookie to response, return the signed JWT string. */ issueError(code: number, message: string): Promise<string>; /** * Redirect resonse with 302 status. If a relative or empty URL is given, the * redirectUrl option of {@link AuthContoller} is taken as the base for * resolving the final target. */ redirect(url?: string, options?: RedirectOptions): boolean; } export interface ServerAuthorizer< Credential, Data, Context extends AnyAuthContext > { platform: string; /** * Handle requests required in the auth flow, for the most of time, it's used * for redirecting user-agent from/to other identity provider (IdP). Any * request match route "<auth_server_entry>/{platform}/*" would be delegated * to this method, and it's responsible to close the the server response. */ delegateAuthRequest( req: IncomingMessage, res: ServerResponse, responseHelper: ResponseHelper, routingInfo: RoutingInfo ): Promise<void>; /** * Called when sign requests from client side are received, controller would * sign in the user by issuing a token to client and signing a signature * wihtin cookie if it resolve success. */ verifyCredential(credential: Credential): Promise<VerifyResult<Data>>; /** * Called when refresh requests from client side are received, controller * would refresh token and signature if it resolve success. */ verifyRefreshment(data: Data): Promise<VerifyResult<Data>>; /** * Called before the authorization finish, you can make some simple non-async * final checks. Return the auth context supplement if success. */ checkAuthContext(data: Data): ContextResult<Context>; } export type AnyServerAuthorizer = ServerAuthorizer< unknown, unknown, AnyAuthContext >; export type AuthorizerCredentialResult<Credential> = | { success: true; credential: Credential } | ErrorResult; export interface ClientAuthorizer< Credential, Data, Context extends AnyAuthContext > { platform: string; /** * Initiate necessary libary like IdP SDK to start authentication works, this * method is expected to be called before the view of app start rendering and * would only be called once. */ init( authEntry: string, errorFromServer: null | AuthError, dataFromServer: null | Data ): Promise<void>; /** * Start work flow from client side and resolve the auth data which would be * then verified and signed at server side. If the auth flow reuqire * redirecting user-agent, just set the location and pend resolving. */ fetchCredential( entry: string ): Promise<AuthorizerCredentialResult<Credential>>; /** * Called before the authorization finish, you can make some simple non-async * final checks. Return the auth context supplement if success. */ checkAuthContext(data: Data): ContextResult<Context>; } export type AnyClientAuthorizer = ClientAuthorizer< unknown, unknown, AnyAuthContext >; export type SignRequestBody<Credential> = { platform: string; credential: Credential; }; export type RefreshRequestBody = { token: string; }; export type VerifyRequestBody = { token: string; }; export type AuthApiResponseBody = { platform: string; token: string; }; export type AuthApiErrorBody = { platform: undefined | string; error: ErrorMessage; }; export type AuthConfigs = { secret: string; redirectUrl: string; apiPath?: string; tokenAge?: number; authCookieAge?: number; dataCookieAge?: number; refreshPeriod?: number; cookieDomain?: string; cookiePath?: string; sameSite?: 'strict' | 'lax' | 'none'; secure?: boolean; }; export type WithHeaders = { headers: IncomingHttpHeaders; }; export type ContextOfAuthorizer< Authorizer extends AnyServerAuthorizer | AnyClientAuthorizer > = Authorizer extends ServerAuthorizer<unknown, unknown, infer Context> ? Context : Authorizer extends ClientAuthorizer<unknown, unknown, infer Context> ? Context : never; type UserOfContext<Context extends AnyAuthContext> = Context extends AuthContext<infer User, any> ? User : never; export type UserOfAuthorizer< Authorizer extends AnyServerAuthorizer | AnyClientAuthorizer > = UserOfContext<ContextOfAuthorizer<Authorizer>>;
fa04aa92298b927d263ca6f55f0e0f61ba9966a6
TypeScript
nmarsden/fireworks
/src/app/tile-hints.ts
3.015625
3
import { ArrayUtils } from './array-utils'; export class TileHints { includedColours: string[] = []; excludedColours: string[] = []; includedNumbers: number[] = []; excludedNumbers: number[] = []; isSame(tileHints: TileHints): boolean { return ArrayUtils.compareArrays(this.includedColours, tileHints.includedColours) && ArrayUtils.compareArrays(this.excludedColours, tileHints.excludedColours) && ArrayUtils.compareArrays(this.includedNumbers, tileHints.includedNumbers) && ArrayUtils.compareArrays(this.excludedNumbers, tileHints.excludedNumbers); } }
6aac7acef46cafd6b18b46efb823ea854a97d035
TypeScript
nicolasxu/learn_ts
/004.object-key-type.ts
3.4375
3
// example 1 let stuff: {[key: string]: string} = {} stuff['a'] = 'hellow' // note: in ES6, key can be a variable in object, just use [] oprator /* e.g.: var obj = { [var1]: 'hello world' // var1 is variable } obj[var1] to access the val of this variable key */ // example 2 export interface IFeatureResult { [key: string]: number }
81553c304a49e2188e8e3b6f90a6c2064ae59456
TypeScript
kashyaprahul94/smart-home
/Mobile/src/common/networking/models/response.ts
2.6875
3
import { HttpHeaders as Headers } from "@angular/common/http"; export class Response { private _ok: boolean; private _status: number; private _statusText: string; private _data: any; private _headers: Headers; constructor ( ok: boolean = false, status: number = -1, statusText: string = "", headers: Headers = null, data: any = null ) { this._ok = ok; this._status = status; this._statusText = statusText; this._headers = headers; this._data = data; } public isOkay (): boolean { return this._ok } public setOkay ( status: boolean ): Response { this._ok = status; return this; } public status (): number { return this._status } public setStatus ( status: number ): Response { this._status = status; return this; } public statusText (): string { return this._statusText } public setStatusText ( statusText: string ): Response { this._statusText = statusText; return this; } public headers (): Headers { return this._headers } public setHeaders ( headers: Headers ): Response { this._headers = headers; return this; } public data (): any { return this._data; } public setData ( data: any ): Response { this._data = data; return this; } }
fe3e7f4021aeef7daa6ec281c5e76043301e516a
TypeScript
Gui-dev/gallery-repo
/src/services/photo.ts
2.765625
3
import { deleteObject, getDownloadURL, listAll, ref, uploadBytes } from 'firebase/storage' import { v4 as uuid } from 'uuid' import { firebaseStorage } from './firebase' type PhotoProps = { name: string url: string } export const getAllPhotos = async (): Promise<PhotoProps[]> => { const list: PhotoProps[] = [] const imagesFolder = ref(firebaseStorage, 'images') const listPhoto = await listAll(imagesFolder) for (const i in listPhoto.items) { const photoUrl = await getDownloadURL(listPhoto.items[i]) list.push({ name: listPhoto.items[i].name, url: photoUrl }) } return list } export const insertPhoto = async (file: File): Promise<PhotoProps> => { if (['image/jpeg', 'image/jpg', 'image/png'].includes(file.type)) { const imageName = uuid() const newFile = ref(firebaseStorage, `images/${imageName}`) const upload = await uploadBytes(newFile, file) const photoUrl = await getDownloadURL(upload.ref) return { name: upload.ref.name, url: photoUrl } } else { throw new Error('Tipo de arquivo não permitido') } } export const removePhoto = async (photoName: string) => { const photo = ref(firebaseStorage, `images/${photoName}`) await deleteObject(photo) }
f6069b26eab22a4ddb4e88a086af6081ac08afc2
TypeScript
Somrlik/mad-cows
/src/utils/shutdown.ts
2.609375
3
import logger from './logger'; const BLOCKING_HANDLER_TIMEOUT = 10000; type ImmediateShutdownCallback = (() => (number | void)); type BlockingShutdownCallback = (() => Promise<any>); export let immediateShutdownCallbacks: Set<ImmediateShutdownCallback> = new Set(); export let blockingShutdownHandlers: Set<BlockingShutdownCallback> = new Set(); // process.once('exit', callImmediateHandlers); process.once('SIGHUP', callImmediateHandlers); process.once('SIGINT', callImmediateHandlers); process.once('SIGBREAK', callImmediateHandlers); function callImmediateHandlers() { logger.warn('[KILL] Caught immediate exit event! Exiting now!'); immediateShutdownCallbacks.forEach((callback: ImmediateShutdownCallback) => { callback(); }); process.exit(127); } process.once('SIGTERM', callBlockingHandlers); async function callBlockingHandlers() { const promises: BlockingShutdownCallback[] = []; blockingShutdownHandlers.forEach((callback: BlockingShutdownCallback) => { promises.push(async () => { const callbackPromise = callback(); setTimeout(() => { logger.error(`[SIGTERM] A handler reached the ${BLOCKING_HANDLER_TIMEOUT}ms limit!`); Promise.reject(callbackPromise); }, BLOCKING_HANDLER_TIMEOUT); return callbackPromise; }); }); return await Promise.all(promises) .catch((reason) => { logger.info('[SIGTERM] Failed to resolve all exit handlers!', reason); }).finally(() => { logger.info('[SIGTERM] Terminating...'); process.exit(1); }); }
08ffd653636e1988be86b04e8ae024c794519270
TypeScript
antomarsi/malditos-goblins-discordjs
/Goblin/index.ts
3.078125
3
import { getRandomOcupacao, IOcupacao } from './Ocupacao'; import { getRandomColoracao, IColoracao } from './Coloracao'; import { getRandomCaracteristica, ICaracteristica } from './Caracteristica'; import { randomInt } from '../utils/math'; export default class Goblin { public ocupacao: IOcupacao; public coloracao: IColoracao; public caracteristica: ICaracteristica; public nome: string; constructor(name?:string ) { this.nome = name || this.generateName(); this.ocupacao = getRandomOcupacao(); this.coloracao = getRandomColoracao(); this.caracteristica = getRandomCaracteristica(); } public static generateGoblin(name?: string) { const goblin = new Goblin(); return goblin; } public generateName(): string { let prefix = ['Sp', 'Cr', 'Bu', 'Ut', 'An', 'Om']; let sufix = ['or', 'ut', 'ar', 'an', 'an', 'ec']; return prefix[randomInt(0, prefix.length - 1)] + sufix[randomInt(0, sufix.length - 1)]; } get combate(): number { return this.ocupacao.combate + this.coloracao.combate; } get conhecimento(): number { return this.ocupacao.conhecimento + this.coloracao.conhecimento; } get habilidade(): number { return this.ocupacao.habilidade + this.coloracao.habilidade; } get sorte(): number { return this.ocupacao.sorte + this.coloracao.sorte; } get cor(): number { return parseInt(this.coloracao.cor.replace("#", ""), 16) } }
090ba97ab3aab83c27a2989c4ee53e5c53b70999
TypeScript
mndrake/doodle-classifier
/frontend/src/store/layout/actions.ts
2.765625
3
import {Action, Dispatch} from "redux"; import {action} from "typesafe-actions"; import {PayloadAction} from "typesafe-actions/dist/types"; import axios from "axios"; import Round from "../../models/Round"; export type TimerAction = | PayloadAction<'TIMER_START', number> | Action<'TIMER_TICK'> | Action<'TIMER_STOP'> export type NewGameAction = | Action<'NEW_GAME_REQUEST'> | PayloadAction<'NEW_GAME_SUCCESS', {rounds: Round[]}> | PayloadAction<'NEW_GAME_FAILURE', {error: string}> export type LayoutAction = | TimerAction | NewGameAction // action creators export const startTimer = (timeInSeconds: number):TimerAction => action('TIMER_START', timeInSeconds); export const stopTimer = ():TimerAction => action('TIMER_STOP'); // action creators export function newGame(totalRounds: number) { return (dispatch: Dispatch<NewGameAction>) => { dispatch(action('NEW_GAME_REQUEST')); return axios.get('/api/sample-words/' + String(totalRounds)) .then(res => { const rounds = res.data.map((word:string, i:number):Round => ( {id: i+1, word: word.replace(/_/g,' '), prediction: '...', strokes: []})); dispatch(action('NEW_GAME_SUCCESS', {rounds})); }) .catch((err: Error) => { dispatch(action('NEW_GAME_FAILURE',{ error: err.message})); }); }; }
256056df7f1802322a2761c09250438d5277d17a
TypeScript
green-fox-academy/heshrian
/foundation w1-5/week-02/day-03/drawing/18 envelopestar/envelopestar.ts
2.65625
3
'use strict'; const canvas = document.querySelector('.main-canvas') as HTMLCanvasElement; const ctx = canvas.getContext('2d') as CanvasRenderingContext2D; export = {} // DO NOT TOUCH THE CODE ABOVE THIS LINE // Fill the canvas with a checkerboard pattern. let length: number = 600 / 2; ctx.beginPath(); ctx.moveTo(length + 20, length); // ctx.lineTo(length,20); // ctx.stroke(); for (let i2: number = 20; i2 < length; i2 += 20) { ctx.strokeStyle = "green"; ctx.lineTo(length, i2); ctx.stroke(); ctx.moveTo(length + i2, length); } ctx.moveTo(length + 20, length); for (let i: number = 20; i < length; i += 20) { ctx.lineTo(length, 2 * length - i); ctx.stroke(); ctx.moveTo(length + i, length); } ctx.moveTo(length - 20, length); for (let i3: number = 20; i3 < length; i3 += 20) { ctx.lineTo(length,i3); ctx.stroke(); ctx.moveTo(length - i3, length); } ctx.moveTo(length-20,length); for (let i4: number = 20; i4 < length; i4 += 20) { ctx.lineTo(length, 2 * length - i4); ctx.stroke(); ctx.moveTo(length - i4, length); } ctx.moveTo(300,20); ctx.lineTo(300,580); ctx.stroke();
800b239a7b2c37ab0d3da42c119d0534b52805c0
TypeScript
wesib/generic
/src/shares/shareable.ts
2.890625
3
import { AfterEvent, AfterEvent__symbol, afterValue, EventKeeper, trackValueBy, ValueTracker, } from '@proc7ts/fun-events'; import { noop, valueProvider, valueRecipe } from '@proc7ts/primitives'; import { ComponentContext } from '@wesib/wesib'; import { SharerAware } from './sharer-aware'; const Shareable$Internals__symbol = /*#__PURE__*/ Symbol('Shareable.internals'); /** * Abstract implementation of value shareable by component. * * Shareable instance contains a {@link body} that become usable only when bound to sharer component. * * @typeParam TBody - Shareable body type. * @typeParam TSharer - Sharer component type. */ export class Shareable<TBody = unknown, TSharer extends object = any> implements EventKeeper<[TBody]>, SharerAware { /** * Converts shareable body or its provider to provider that always returns an `AfterEvent` keeper of shareable body. * * @typeParam TBody - Shareable body type. * @typeParam TSharer - Sharer component type. * @param body - Either shareable body, or its provider. * * @returns Shareable body provider. */ static provider<TBody = unknown, TSharer extends object = any>( body: TBody | Shareable.Provider<TBody, TSharer>, ): (this: void, sharer: ComponentContext<TSharer>) => AfterEvent<[TBody]> { const provider = valueRecipe(body); return context => afterValue(provider(context)); } /** * @internal */ private [Shareable$Internals__symbol]: Shareable$Internals<TBody, TSharer>; /** * Constructs shareable instance. * * @param body - Either shareable body, or its provider. */ constructor(body: TBody | Shareable.Provider<TBody, TSharer>) { this[Shareable$Internals__symbol] = new Shareable$Internals(this, body); } /** * Sharer component context. * * Accessing it throws an exception until bound to sharer. */ get sharer(): ComponentContext<TSharer> { return this[Shareable$Internals__symbol].sharer(); } /** * An `AfterEvent` keeper of shareable body. * * An `[AfterEvent__symbol]` method always returns this value. */ get read(): AfterEvent<[TBody]> { return this[Shareable$Internals__symbol].get().read; } /** * Informs this shareable instance on its sharer component. * * @param sharer - Sharer component context. */ sharedBy(sharer: ComponentContext<TSharer>): void { this[Shareable$Internals__symbol].sharedBy(sharer); } [AfterEvent__symbol](): AfterEvent<[TBody]> { return this.read; } /** * Shareable body. * * Accessing is throws an exception until bound to sharer. */ get body(): TBody { return this[Shareable$Internals__symbol].get().it; } } export namespace Shareable { /** * Shareable provider signature. * * Provides shareable body rather the shareable instance itself. * * @typeParam TBody - Shareable body type. * @typeParam TSharer - Sharer component type. */ export type Provider<TBody = unknown, TSharer extends object = any> = /** * @param sharer - Sharer component context. * * @returns Either shareable body instance, or an `AfterEvent` keeper reporting one. */ (this: void, sharer: ComponentContext<TSharer>) => TBody | AfterEvent<[TBody]>; } class Shareable$Internals<TBody, TSharer extends object> { private readonly _get: (this: void, sharer: ComponentContext<TSharer>) => AfterEvent<[TBody]>; constructor( private readonly _source: Shareable<TBody, TSharer>, body: TBody | Shareable.Provider<TBody, TSharer>, ) { this._get = Shareable.provider(body); } sharer(): ComponentContext<TSharer> { this._notBound(); } get(): ValueTracker<TBody> { this._notBound(); } sharedBy(sharer: ComponentContext<TSharer>): void { this.sharedBy = noop; this.sharer = valueProvider(sharer); this.get = () => { const tracker = trackValueBy(this._get(sharer)); this.get = valueProvider(tracker); return tracker; }; } private _notBound(): never { throw new TypeError(`${String(this._source)} is not properly shared yet`); } }
0f19fe234336fc7f64fbf9ca015fbcfa96cfcc5d
TypeScript
Vittorg3/Fortune-Cookie
/src/domain/entities/phrase.entitie.ts
2.84375
3
export const phrasesContent: string[] = [ 'Motivação é a arte de fazer as pessoas fazerem o que você quer que elas façam porque elas o querem fazer.', 'Toda ação humana, quer se torne positiva ou negativa, precisa depender de motivação.', 'No meio da dificuldade encontra-se a oportunidade.', 'Lute. Acredite. Conquiste. Perca. Deseje. Espere. Alcance. Invada. Caia. Seja tudo o quiser ser, mas, acima de tudo, seja você sempre.', 'Eu faço da dificuldade a minha motivação. A volta por cima vem na continuação.', 'Tudo o que um sonho precisa para ser realizado é alguém que acredite que ele possa ser realizado.', 'Vida trará coisas boas se tiveres paciência.', 'Não compense na ira o que lhe falta na razão.', 'Siga os bons e aprenda com eles.', 'Aquele que se importa com o sentimento dos outros, não é um tolo.', 'O riso é a menor distância entre duas pessoas.', 'Faça pequenas coisas agora e maiores coisas lhe serão confiadas cada dia.', 'Sua visão se tornará clara apenas quando você puder olhar dentro de seu coração.', 'Todas as coisas são difíceis antes de se tornarem fáceis.' ]; export class Phrase { private phrases: string[]; constructor (phrasesContentInjection?: string[]) { this.phrases = phrasesContentInjection || phrasesContent; } execute() { const numberDrawn = Math.floor(Math.random() * this.phrases.length); return this.phrases[numberDrawn]; } };
ef9357c0ac5473707db7bcce0b91dd37a7aa1037
TypeScript
green-fox-academy/Adamman48
/week-03/day-02/copy-file.ts
3.296875
3
'use strict'; export{}; // Write a function that copies the contents of a file into another // It should take the filenames as parameters // It should return a boolean that shows if the copy was successful const fs = require('fs'); let copyFrom: string = 'content-to-copy.txt'; let copyTo: string = 'copied-content.txt'; function copyContent(from: string, to: string) { try { let content: string = fs.readFileSync(from, 'utf-8'); fs.writeFileSync(to, content); console.log('The copy was successful: ' + true) } catch { console.log('The copy was successful: ' + false); } } copyContent(copyFrom, copyTo);
2568eca11328e002eff3101c78e0170bb3995908
TypeScript
jarthursantos/multicast
/packages/shared/web-components/ScheduleCalendar/types.ts
2.546875
3
import { Dispatch, SetStateAction } from 'react' export interface IScheduleCalendarProps { selectedDate: Date setSelectedDate: Dispatch<SetStateAction<Date>> daysWithSchedules: IDayWithSchedule[] } export interface IDayWithSchedule { date: Date state: 'normal' | 'priority' | 'request' }
eb4987bfed820a844ca6fe5acfe09a01ef0f3c14
TypeScript
DreamLarva/js-ts-Algorithms
/算法/排序算法/quickSort.ts
3.890625
4
import { swap } from "./util"; import insertionSort from "./insertionSort"; /** * 快速排序 * 它是一种分而治之的算法,通过递归的方式将数据依次分解为包含较小元素和较大元素的不同子序列。 * 该算法不断重复这个步骤直到所有数据都是有序的。 * 这个算法首先要在列表中选择一个元素作为基准值(pivot)。 * 数据排序围绕基准值进行,将列表中小于基准值的元素移到数组的底部,将大于基准值的元素移到数组的顶部。 * */ export function qSort(list: number[]): number[] { if (list.length === 0) { return []; } const lesser: number[] = []; const greater: number[] = []; const pivot = list[0]; // 从第一个元素开始 因为第一个值为基准值 如果只剩基准值(递归的最末则不会进这个循环) for (let i = 1; i < list.length; i++) { if (list[i] < pivot) { lesser.push(list[i]); } else { greater.push(list[i]); } } // console.log(qSort(lesser).concat(pivot, qSort(greater))); return qSort(lesser).concat(pivot, qSort(greater)); } /** * 快速排序有很大的优化空间 * 1.取的基准值越接近 数组所有元素的中位数 排序的成熟越少(三数取中) * 2.快速排序并不稳定 在分割的数组的元素的个数小于10的情况下可以采用插入排序(稳定) 来减少排序的次数 * 3.对于递归可已使用尾调优化(es6) * */ // 三数取中(median-of-three) // 选取第一个元素 最后一个元素 和中间的元素 选择其中 的中位数 作为基准值 export function qSort1(list: number[]): number[] { if (list.length === 0) { return []; } const lesser: number[] = []; const greater: number[] = []; medianOfThree(list); const pivot = list[0]; // 从第一个元素开始 因为第一个值为基准值 如果只剩基准值(递归的最末则不会进这个循环) for (let i = 1; i < list.length; i++) { if (list[i] < pivot) { lesser.push(list[i]); } else { greater.push(list[i]); } } // console.log(qSort(lesser).concat(pivot, qSort(greater))); return qSort1(lesser).concat(pivot, qSort1(greater)); } // 三数取中 export function medianOfThree(arr: number[]) { const high = arr.length - 1, low = 0, mid = (low + (high - low)) >> 1; // ts 又立功了 // 使用三数取中法选择枢轴 if (arr[0] > arr[high]) { // 目标: arr[mid] <= arr[high] swap(arr, mid, high); } if (arr[low] > arr[high]) { // 目标: arr[low] <= arr[high] swap(arr, low, high); } if (arr[mid] > arr[low]) { // 目标: arr[low] >= arr[mid] swap(arr, mid, low); } } // 当待排序的数组的长度<=10 就是用插入排序 export function qSort2(list: number[]): number[] { if (list.length === 0) { return []; } const lesser: number[] = []; const greater: number[] = []; medianOfThree(list); const pivot = list[0]; if (list.length <= 10) { return insertionSort(list); } // 从第一个元素开始 因为第一个值为基准值 如果只剩基准值(递归的最末则不会进这个循环) for (let i = 1; i < list.length; i++) { if (list[i] < pivot) { lesser.push(list[i]); } else { greater.push(list[i]); } } // console.log(qSort(lesser).concat(pivot, qSort(greater))); return qSort2(lesser).concat(pivot, qSort2(greater)); } // 聚集相同元素 就是在划分的时候在分出一个与基准值相同的值的数组(对于有大量相同的元素的数组 提升很大) export function qSort3(list: number[]): number[] { if (list.length === 0) { return []; } const lesser: number[] = []; const greater: number[] = []; medianOfThree(list); const pivot = [list[0]]; if (list.length <= 10) { return insertionSort(list); } // 从第一个元素开始 因为第一个值为基准值 如果只剩基准值(递归的最末则不会进这个循环) for (let i = 1; i < list.length; i++) { if (list[i] === pivot[0]) { pivot.push(list[i]); } else if (list[i] < pivot[0]) { lesser.push(list[i]); } else { greater.push(list[i]); } } // console.log(qSort(lesser).concat(pivot, qSort(greater))); return qSort3(lesser).concat(pivot, qSort3(greater)); }
9aeee7bce0152fcf6a5f0407f8a332994c3d42ef
TypeScript
MalakronikMausi/WebValueCharts
/client/resources/modules/app/services/AuthGuard.service.ts
2.640625
3
/* * @Author: aaronpmishkin * @Date: 2016-08-05 16:07:21 * @Last Modified by: aaronpmishkin * @Last Modified time: 2016-08-30 18:51:30 */ // Import Angular Classes: import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; // Import Application Classes: import { CurrentUserService } from './CurrentUser.service'; /* AuthGuardService is an Angular service that is used to manage user access to all front-end routes depending on a user's authentication status. It allows authenticated users (either temporary or permanent) to navigate to any route in the application, but will redirect all users that are not logged in to the '/register' route no matter what route they attempt to navigate to. This is how the application implements a login wall. The AuthGuardService is used by registering the class in the canActivate array of a route's definition. See app.routes.ts for an example of this. Then, when a user attempts to navigate to that route, the router calls the canActivate inside AuthGuardService. Navigation is permitted if this methods returns true, and blocked if false. Note that false simply prevents navigation; it does not redirect the user to '/navigate'. */ @Injectable() export class AuthGuardService implements CanActivate { // ======================================================================================== // Constructor // ======================================================================================== /* @returns {void} @description Used for Angular's dependency injection ONLY. It should not be used to do any initialization of the class. This constructor will be called automatically when Angular constructs an instance of this class prior to dependency injection. */ constructor( private router: Router, private currentUserService: CurrentUserService) { } // ======================================================================================== // Methods // ======================================================================================== /* @returns {boolean} - Whether navigation to the activated route will be permitted or not. @description Used by the Angular router to determine whether a the current user will be permitted to navigate to the newly activated route. This method should NEVER be called manually. Leave routing, and calling of the canActivate, canDeactivate, etc. classes to the Angular 2 router. */ canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { // Does the current user have a username? The username will ALWAYS be defined if they are logged in as a permanent or temporary user. if (this.currentUserService.getUsername() !== undefined && this.currentUserService.getUsername() !== null && this.currentUserService.getUsername() !== '') { return true; // Allow the user to navigate to the activated route. } else { this.router.navigate(['/register']); // Redirect the user to register, which is the only route they are allowed to view if they are not authenticated. return false; // Prevent the current navigation. } } }
6853f148caf88cd330df8aae30e1a032d0ed171c
TypeScript
MohamedAliHabib/poc-express-graphql
/src/tests/integration/middleware/auth.test.ts
2.640625
3
import request from 'supertest'; import User from '../../../db/models/UserModel'; import server from '../../../app'; import mongoose from 'mongoose'; import TestUtils from '../../testUtils'; const users = [ new User({ name: 'user1', email: 'user1@testing.com', password: 'Test1234!', age: 25, phone: '+1 4801849392', isAdmin: true, }), new User({ name: 'user2', email: 'user2@testing.com', password: 'Test1234!', age: 30, phone: '+1 4801849377', isAdmin: false, }), ]; describe('Middleware', () => { afterEach(async () => { await User.deleteMany({}); }); describe('requiresAuth', () => { let token: string; const exec = async () => { return await request(server).post('/graphql').send({ query: `mutation { addGenre(name: "${'genre1'}") {id name} }`, }).set('Authorization', 'Bearer ' + token); }; beforeEach(() => { token = new User().generateAuthToken(); }); it('should return an error if no token is provided', async () => { const res = await request(server).post('/graphql').send({ query: `mutation { addGenre(name: "${'genre1'}") {id name} }`, }); const message = res.body.errors.map((err: Error) => err.message) .join(', '); expect(message).toContain('Requires authentication'); }); it('should return an error if token has an expected (malformed) structure', async () => { token = 'a'; const res = await exec(); const message = res.body.errors.map( (err: Error) => err.message).join(', '); expect(message).toContain('Token is malformed'); }); it('should return an error if token is expired', async () => { token = TestUtils.generateTestAccessToken(new User(), '10ms'); await TestUtils.delay(20); const res = await exec(); const message = res.body.errors.map( (err: Error) => err.message).join(', '); expect(message).toContain('Token has expired'); }, ); it('should return an error if token is invalid', async () => { // alter any thing in the token token = token.slice(0, -1); const res = await exec(); const message = res.body.errors.map( (err: Error) => err.message).join(', '); expect(message).toContain('Invalid token'); }, ); it('should return data if token is valid', async () => { const res = await exec(); expect(res.body.data.addGenre).toHaveProperty('id'); expect(res.body.data.addGenre).toHaveProperty('name', 'genre1'); }); }); describe('requiresAdmin', () => { let token: string; const exec = async () => { return await request(server).post('/graphql').send({ query: '{users {id name}}', }).set('Authorization', 'Bearer ' + token); }; beforeEach(async () => { const payload = { _id: new mongoose.Types.ObjectId().toHexString(), isAdmin: true, }; const user = new User(payload); token = user.generateAuthToken(); await User.collection.insertMany(users); }); it('should return an error if token is invalid', async () => { token = token.slice(0, -1); const res = await exec(); const message = res.body.errors.map( (err: Error) => err.message).join(', '); expect(message).toContain('Invalid token'); }, ); it('should return an error if user is not an admin', async () => { token = new User().generateAuthToken(); const res = await exec(); const message = res.body.errors.map( (err: Error) => err.message).join(', '); expect(message).toContain('Action Denied'); }); it('should return data if user is an admin', async () => { const res = await exec(); expect(res.body.data.users.length).toBe(2); expect(res.body.data.users[0]).toHaveProperty('id'); expect(res.body.data.users[0]).toHaveProperty('name', users[0].name); }); }); });
bb711a147faf92351a86c100999bcee48da404c5
TypeScript
opticdev/optic
/projects/optic/src/utils/id.ts
2.546875
3
export const getEndpointId = (endpoint: { method: string; path: string; }): string => { return `${endpoint.method.toUpperCase()} ${endpoint.path.toLowerCase()}`; };
f53746a8aef424785adb74bb5a5a3cfff1f78132
TypeScript
maxcodefaster/superlogin-next
/src/sessionAdapters/MemoryAdapter.ts
2.875
3
import { SessionAdapter } from '../types/adapters'; export class MemoryAdapter implements SessionAdapter { #keys: Record<string, string>; #expires: Record<string, number>; constructor(config?: any) { this.#keys = {}; this.#expires = {}; console.log('Memory Adapter loaded'); } storeKey(key: string, life: number, data: string) { const now = Date.now(); this.#keys[key] = data; this.#expires[key] = now + life; this.removeExpired(); return Promise.resolve(); } getKey(key: string) { const now = Date.now(); if (this.#keys[key] && this.#expires[key] > now) { return Promise.resolve(this.#keys[key]); } else { return Promise.resolve(false); } } deleteKeys(keys: string[]) { if (!(keys instanceof Array)) { keys = [keys]; } keys.forEach(key => { delete this.#keys[key]; delete this.#expires[key]; }); this.removeExpired(); return Promise.resolve(keys.length); } quit() { return Promise.resolve(); } private removeExpired() { const now = Date.now(); Object.keys(this.#expires).forEach(key => { if (this.#expires[key] < now) { delete this.#keys[key]; delete this.#expires[key]; } }); } }