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 |
|---|---|---|---|---|---|---|
c1e0a1ebb4aba16824ab4c8719af563d2a182d15 | TypeScript | mithunbalyada/react-to-do | /src/types.d.ts | 2.796875 | 3 | export type TodoType = {
text: string,
completed: boolean,
}
export type CompleteTodoType = (todo:TodoType) => void;
export type AddTodo = (todo:string) => void
export type TodoStatType = {
todo:number;
done:number;
} |
9be0c5b2b6aa3ecdc774b4efa7c75dd4dd497f92 | TypeScript | anakorn/tlr-party-builder | /src/models/character.ts | 2.59375 | 3 | import { combineMaterialRequirementLists } from './material-requirement';
import { Character, Upgrade } from '../types/types';
import { findActiveUpgrade, completeUpgradeFromUpgradesList } from './upgrade';
export const getActiveUpgrades = function(character: Character) {
return character.upgradeGroups
.map(findActiveUpgrade)
.filter((x): x is Upgrade => !!x)
.map((upgrade: Upgrade) => upgrade.materialRequirements)
.reduce(combineMaterialRequirementLists, []);
}
export const completeActiveUpgrade = function(
upgradeGroupIndex: number,
character: Character
): Character {
return ({
...character,
upgradeGroups: [
...character.upgradeGroups.slice(0, upgradeGroupIndex),
completeUpgradeFromUpgradesList(character.upgradeGroups[upgradeGroupIndex]),
...character.upgradeGroups.slice(upgradeGroupIndex + 1, character.upgradeGroups.length)
]
})
} |
db348c043f9e5fc4b99734cd45c4ded2ad4dfdd5 | TypeScript | connor-hitchcock/Leftovers-The-Ecommerce-Food-Web-App | /frontend/tests/unit/business-profile.spec.ts | 2.53125 | 3 | import Vue from 'vue';
import Vuetify from 'vuetify';
import {createLocalVue, mount, Wrapper, RouterLinkStub} from '@vue/test-utils';
import BusinessProfile from '@/components/BusinessProfile/index.vue';
import VueRouter from "vue-router";
import convertAddressToReadableText from '@/components/utils/Methods/convertJsonAddressToReadableText';
Vue.use(Vuetify);
describe('index.vue', () => {
let wrapper: Wrapper<any>;
let vuetify: Vuetify;
let date = new Date();
/**
* Set up to test the routing and whether the business profile page shows what is required
*/
beforeEach(() => {
const localVue = createLocalVue();
const router = new VueRouter();
localVue.use(VueRouter);
vuetify = new Vuetify();
wrapper = mount(BusinessProfile, {
//creates a stand in(mocking) for the routerlink
stubs: {
RouterLink: RouterLinkStub
},
router,
localVue,
vuetify,
//Sets up each test case with some values to ensure the business profile page works as intended
data() {
return {
business: {
name: "Some Business Name",
address: {
"country": "Some Country",
"streetName": "Some Street Name",
"streetNumber": "1",
"city": "Some City",
"district": "Some District",
"postcode": "1234",
"region": "Some Region"
},
businessType: "Some Business Type",
description: "Some Description",
created: date,
administrators: [
{
id: 1,
firstName: "Some First Name",
lastName: "Some Last Name"
},
{
id: 2,
firstName: "Another First Name",
lastName: "Another Last Name"
}
]
},
readableAddress: "1 Some Street Name",
};
}
});
});
it("Must contain the business name", () => {
expect(wrapper.text()).toContain('Some Business Name');
});
it("Must contain the business street address", () => {
expect(wrapper.text()).toContain('1 Some Street Name');
});
it("Must contain the business type", () => {
expect(wrapper.text()).toContain('Some Business Type');
});
it("Must contain the business description", () => {
expect(wrapper.text()).toContain('Some Description');
});
it("Must contain the business created date", () => {
expect(wrapper.text()).toContain(`${("0" + date.getDate()).slice(-2)} ` +
`${date.toLocaleString('default', {month: 'short'})} ${date.getFullYear()} (0 months ago)`);
});
it("Must contain the business administrator first name and last name", () => {
expect(wrapper.text()).toContain('Some First Name Some Last Name');
});
it("Can contain multiple business administrators", () => {
expect(wrapper.text()).toContain('Another First Name Another Last Name');
});
it("Router link must lead to the proper endpoint with the admin id", () => {
expect(wrapper.findAllComponents(RouterLinkStub).at(0).props().to).toBe('/profile/1');
});
it("Router link can have multiple endpoints with different admin id", () => {
expect(wrapper.findAllComponents(RouterLinkStub).at(1).props().to).toBe('/profile/2');
});
}); |
047321e62a5dba5bb49fe46c0c608b9dac0e31f5 | TypeScript | cuarti/tslint-test | /demo/interface.ts | 2.671875 | 3 |
interface Editable {}
interface Styled {
className?: string;
}
interface Button extends Styled {}
interface Project {
name: string;
}
interface Builder<T> {
build(): T;
}
interface ProjectBuilder extends Builder<Project> {}
|
c911a4e42473406e8cfc9b1ab3d25751d40b67a4 | TypeScript | tinnguyenhuuletrong/near-learn-kyc-on-chain | /contract/assembly/index.ts | 2.53125 | 3 | import { context, Context, logging, storage } from "near-sdk-as";
import { KYCCandidate, KYCContract } from "./model";
let contract: KYCContract;
/*********/
/* Main */
/*********/
export function initContract(
bizName: string,
bizBlockpassClientId: string
): KYCContract {
/// Initializes the contract with the given NEAR foundation account ID.
assert(!storage.hasKey("init"), "Already initialized");
contract = new KYCContract(bizName, bizBlockpassClientId);
storage.set("init", true);
contract.addOperatorPubKey(context.senderPublicKey);
storage.set("_ins", contract);
return contract;
}
/***********/
/* Read */
/***********/
export function getKycStatus(accId: string = context.sender): KYCCandidate {
_isInit();
const ins = contract.getCandidateByAccId(accId) as KYCCandidate;
return ins;
}
export function hasCandidate(accId: string): boolean {
_isInit();
return contract.hasCandidate(accId);
}
@nearBindgen
export class InfoReturnObj {
owner: string;
bizName: string;
bizBlockpassClientId: string;
}
export function info(): InfoReturnObj {
_isInit();
const owner = contract.owner;
const bizName = contract.bizName;
const bizBlockpassClientId = contract.bizBlockpassClientId;
const res = new InfoReturnObj();
res.owner = owner;
res.bizName = bizName;
res.bizBlockpassClientId = bizBlockpassClientId;
return res;
}
/***********/
/* Write */
/***********/
export function addCandidate(): string {
_isInit();
const candidate = contract.addCandidate();
return candidate.refId;
}
export function updateCandidateStatus(refId: string, status: string): boolean {
_isInit();
contract.updateCandidateStatus(refId, status);
return true;
}
export function addOperator(pubKey: string): void {
_isInit();
contract.addOperatorPubKey(pubKey);
}
export function removeOperator(pubKey: string): void {
_isInit();
contract.removeOperatorPubKey(pubKey);
}
export function listOperator(): string[] {
_isInit();
return contract.listOperatorPubKey();
}
/************/
/* Internal */
/************/
function _isInit(): void {
assert(
storage.hasKey("init") && storage.getSome<bool>("init") == true,
"The contract should be initialized before usage."
);
contract = storage.getSome<KYCContract>("_ins");
}
|
07bd8cc81098ac5ba30e2d0edaaf508654f431f9 | TypeScript | art-grig/Reinforced.Lattice | /Reinforced.Lattice.Script/Scripts/Reinforced.Lattice/DateService.d.ts | 2.96875 | 3 | declare module PowerTables {
/**
* API responsible for dates operations
*/
class DateService {
constructor(datepickerOptions: IDatepickerOptions);
private _datepickerOptions;
private ensureDpo();
/**
* Determines is passed object valid Date object
* @param date
* @returns {}
*/
isValidDate(date: Date): boolean;
/**
* Converts jsDate object to server's understandable format
*
* @param date Date object
* @returns {string} Date in ISO 8601 format
*/
serialize(date?: Date): any;
/**
* Parses ISO date string to regular Date object
*
* @param dateString Date string containing date in ISO 8601
* @returns {}
*/
parse(dateString: string): Date;
/**
* Retrieves Date object from 3rd party datepicker exposed by HTML element
*
* @param element HTML element containing datepicker componen
* @returns {Date} Date object or null
*/
getDateFromDatePicker(element: HTMLElement): Date;
/**
* Creates datepicker object of HTML element using configured function
*
* @param element HTML element that should be converted to datepicker
*/
createDatePicker(element: HTMLElement, isNullableDate?: boolean): void;
/**
* Creates datepicker object of HTML element using configured function
*
* @param element HTML element that should be converted to datepicker
*/
destroyDatePicker(element: HTMLElement): void;
/**
* Passes Date object to datepicker element
*
* @param element HTML element containing datepicker componen
* @param date Date object to supply to datepicker or null
*/
putDateToDatePicker(element: HTMLElement, date: Date): void;
}
}
|
8a9a13225b024e83450913d153e414572a16e309 | TypeScript | ayumitanaka13/react-w4d2 | /Exercises/exercise5.ts | 3.9375 | 4 | // ⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇⏇
// Exercise 5 – Classes
// ⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈⏈
// Objectives:
// • Create classes with typed properties and methods
// • Add access modifiers to class members
const Exercise5 = () => {
// ======== Exercise 5.1 ========
// Goals:
// • Add explicit parameter type to the greet method
// • Add explicit return type to the greet method
class MC {
greet(event:string = 'party') {
return `Welcome to the ${event}`
}
}
const mc = new MC()
console.log('[Exercise 5.1]', mc.greet('show'))
// ======== Exercise 5.2 ========
// Goals:
// • Add explicit parameter types to constructor
// • Add typed parameters for storing values
class Person {
constructor(public name:string, public age:number) {
}
}
const jane = new Person('Jane', 31)
console.log('[Exercise 5.2]', `The new person's name is ${jane.name}.`)
// ======== Exercise 5.3 ========
// Goals:
// • Explicitly make the title and salary properties publicly available
// • Reduce class to three lines of code while maintaining functionality
class Employee {
constructor(public title: string, public salary: number) {
}
}
// class Contractor extends Employee {
// constructor(title: string, salary: number, public time: number) {
// super(title, salary)
// }
// }
const employee = new Employee('Engineer', 100000)
// const contractor = new Contractor('Software Engineer', 10000, 30)
console.log(
'[Exercise 5.3]',
`The new employee's title is ${employee.title} and they earn $ ${employee.salary}.`
)
}
Exercise5()
|
2589f126d296535618816bd20e57e975654da116 | TypeScript | tayduivn/TrueFail | /SRC/front-end/src/core/models/http.model.ts | 2.734375 | 3 | export class ResultModel<T> {
public data: T;
public result: number;
public errorMessage: string;
public constructor(init?: Partial<ResultModel<T>>) {
Object.assign(this, init);
}
}
|
774e42b27f612037f1e2e405e738f71582b74961 | TypeScript | FelipeOSilva/DenunciaApp | /src/providers/sqlite-helper/sqlite-helper.service.ts | 2.625 | 3 | import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
@Injectable()
export class SqliteHelperService {
private db: SQLiteObject;
constructor(
public platform: Platform,
public sqlite: SQLite
) { }
//Função para a criação do Banco de dados
private createDatabase(dbName?: string): Promise<SQLiteObject | void> {
return this.sqlite.create({
name: dbName || 'DenunciaApp.db',
location: 'default'
})
.then((db: SQLiteObject) => {
this.db = db;
return this.db;
})
.catch((error: Error) => console.log('Erro ao criar ou abrir DB', error));
}
//Função para "pegar" o banco de dados, existente ou criando um novo
getDb(dbName?: string, newOpen?: boolean): Promise<SQLiteObject | void> {
if (newOpen) return this.createDatabase(dbName);
return (this.db) ? Promise.resolve(this.db) : this.createDatabase(dbName);
}
//Função para retornar todos os dados de uma tabela, podendo ser definada a ordem
getAll(table: string, order?: string, orderBy?: string) {
return this.getDb()
.then((db: SQLiteObject) => {
return this.db.executeSql(`SELECT * FROM ${table} ORDER BY ${order || 'id'} ${orderBy || 'DESC'}`, {})
.then(resultSet => {
let list = []
for (let i = 0; i < resultSet.rows.length; i++) {
list.push(resultSet.rows.item(i));
console.log('resultSET', resultSet.rows.item(i));
}
console.log('resultSET FULL', resultSet.rows);
return list;
}).catch((e) => console.error('Erro no GETALL', e));
}).catch((e) => console.error('', e));
}
//Função para verificar se existe algum valor em uma tabela.
onCount(table) {
return this.db.executeSql(`SELECT COUNT(*) as qtd FROM ${table}`, {});
}
//Função para inserir dados em uma tabela.
onInsert(table, arrayValues) {
let values = '';
for (let i = 0; i < arrayValues.length; i++) {
(i === (arrayValues.length - 1)) ? values += '?'
: values += '?, ';
}
console.log(`INSERT INTO ${table} VALUES (${values})`, arrayValues)
return this.db.executeSql(`INSERT INTO ${table} VALUES (${values})`, arrayValues);
}
}
|
8ac8da292a81c3b9a21e09a5f1dabf4b706b0dae | TypeScript | willsnake/SalesLoft-Challenge | /pages/api/salesloft.ts | 2.53125 | 3 | import type { NextApiRequest, NextApiResponse } from 'next'
import Api from '../../helpers/api'
// Interfaces
import { ApiResponse } from '../../interfaces'
export const config = {
api: {
externalResolver: true,
},
}
/**
* This endpoint was implemented to communicate with the SalesLoft API, in the future it can implement cache for the requests
* this will improve performance
* @typeParam NextApiRequest
* @typeParam NextApiResponse<ApiResponse>
* @returns NextApiResponse<ApiResponse>
*/
export default async (
req: NextApiRequest,
res: NextApiResponse<ApiResponse>
) => {
const { page = 1, perPage = 10 } = req.query
const api = new Api({
apiBaseUrl: process.env.SALESLOFT_API_URL,
apiKey: process.env.SALESLOFT_API_KEY,
})
try {
const result = await api.getPeople({
include_paging_counts: true,
per_page: Number(perPage),
page: Number(page),
})
return res.status(200).json(result)
} catch (err) {
throw new Error(err)
}
}
|
c4a60533e0b59ac2760a43098d197cc793fb0c3c | TypeScript | wudi0431/mcare-app | /src/app/shared/services/repair-shared.service.ts | 2.5625 | 3 | /**
* 单例模式使用
* 用来记录多个步骤之间的数据共享操作
*/
import { Injectable } from '@angular/core';
@Injectable()
export class RepairSharedService {
private _session = {};
constructor() { }
set(key: string, value: any) {
this._session[key] = value;
}
get(key: string) {
return this._session[key];
}
has(key: string) {
if (this.get(key)) return true;
return false;
}
remove(key: string) {
this._session[key] = null;
}
}
|
b249b548c2f0b09c1f195df194ca09ab87f818ab | TypeScript | GuoYuFu123/typescript-learn | /typescript高级/src/3-3方法的装饰器.ts | 4.125 | 4 |
// 普通函数, target对应的是类的prototype
// 静态方法, target对应的是类的构造函数
// descriptor类似于definePrototype一样
function getNameDecorator(target: any, key: string, descriptor: PropertyDescriptor) {
console.log(target, key, descriptor)
// descriptor.writable = false;
descriptor.value = function() {
return 'guoguo decorator';
};
}
class Test3 {
private name: string;
constructor(name: string){
this.name = name
}
@getNameDecorator
getName() {
return this.name;
}
}
const test3 = new Test3('dell');
// test3.getName = () => {
// return '123';
// };
console.log(test3.getName());
/**
* eg:装饰器组合,执行顺序
*
* 官方:这种是普通函数,接受参数的,显示普通函数执行,返回装饰器函数,因为装饰器函数是从下往上执行的,所以就是后面的顺序
* 1、由上至下依次对装饰器表达式求值。
* 2、求值的结果会被当作函数,由下至上依次调用。
*/
function f() {
console.log("f(): evaluated");
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("f(): called");
}
}
function g() {
console.log("g(): evaluated");
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("g(): called");
}
}
class C {
@f()
@g()
method() {}
}
/**
f(): evaluated
g(): evaluated
g(): called
f(): called
*/
|
c2712c6f684b8cfcb64b3ee8c211d20d2202a43a | TypeScript | ssube/noicejs | /src/error/ContainerNotBoundError.ts | 2.734375 | 3 | import { BaseError } from './BaseError.js';
/**
* Error indicating that this container is not bound yet and not ready to be used.
*
* @public
*/
export class ContainerNotBoundError extends BaseError {
constructor(msg = 'container is not bound', ...nested: Array<Error>) {
super(msg, ...nested);
}
}
|
307f8ff5a9c5f5455329e06991197a1b8cf628ed | TypeScript | andeemarks/2048 | /test/board.test.ts | 3.078125 | 3 | import Board from "../src/board";
describe("Board", () => {
const board = new Board();
it("guards attempts to access out-of-bound rows", () => {
expect(() => {
board.rowAtPosition(-1);
}).toThrowError();
expect(() => {
board.rowAtPosition(board.height());
}).toThrowError();
});
it("knows when it is full", () => {
expect(board.isFull()).toBeFalsy();
expect(new Board([[0]]).isFull()).toBeFalsy();
expect(new Board([[2]]).isFull()).toBeTruthy();
});
it("knows when the player has won", () => {
expect(board.isComplete()).toBeFalsy();
expect(
new Board([
[2, 4],
[1024, 512],
]).isComplete()
).toBeFalsy();
expect(
new Board([
[2, 2, 2],
[4, 0, 2048],
[64, 32, 4],
]).isComplete()
).toBeTruthy();
expect(new Board([[2048]]).isComplete()).toBeTruthy();
});
});
|
7da9e9c628367055cf934f9f4925619a0f845a52 | TypeScript | mDinardo08/dissertation | /UltimateTicTacToe/ClientApp/src/app/services/api/api.service.tests.spec.ts | 2.8125 | 3 | import { ApiService } from "./api.service";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
describe("Api Service", () => {
let service: ApiService;
beforeEach(() => {
service = new ApiService(null);
});
it("Will return the Url value from the config", () => {
const url = service.getURL();
expect(url).toBe("./api/");
});
it("Will call get on the Http client", () => {
const mockHttp = jasmine.createSpyObj("HttpClient", ["get"]);
service = new ApiService(mockHttp);
spyOn(service, "getURL").and.returnValue("mockUrl");
service.get("/some endpoint");
expect(mockHttp.get).toHaveBeenCalledWith("mockUrl/some endpoint");
});
it("Will return the object returned from the http client", () => {
const mockHttp = jasmine.createSpyObj("HttpClient", ["get"]);
const observable = new Observable<string>();
mockHttp.get.and.returnValue(observable);
service = new ApiService(mockHttp);
const result = service.get<string>("end");
expect(result).toBe(observable);
});
it("Will return an object with a httpOptions field", () => {
const result = service.getOptions();
expect(result.headers).toBeDefined();
});
it("Will have a httpHeaders object in the httpOptions field", () => {
const result = service.getOptions();
expect(result.headers instanceof HttpHeaders).toBe(true);
});
it("Will set content type to application json", () => {
const result = service.getOptions();
const options = <HttpHeaders>result.headers;
expect(options.get("Content-Type")).toBe("application/json");
});
it("Will call to post at the correct URL", () => {
const mockHttp = jasmine.createSpyObj("HttpClient", ["post"]);
service = new ApiService(mockHttp);
spyOn(service, "getURL").and.returnValue("url");
spyOn(service, "getOptions").and.returnValue(null);
service.post("/endpoint", null);
expect(mockHttp.post).toHaveBeenCalledWith("url/endpoint", null, null);
});
it("Will call to post with the correct the http options", () => {
const mockHttp = jasmine.createSpyObj("HttpClient", ["post"]);
const options = {
value: {
"stuff": "thigs"
}
};
service = new ApiService(mockHttp);
spyOn(service, "getURL").and.returnValue("");
spyOn(service, "getOptions").and.returnValue(options);
service.post("", null);
expect(mockHttp.post).toHaveBeenCalledWith("", null, options);
});
it("Will call to post with correct data", () => {
const mockHttp = jasmine.createSpyObj("HttpClient", ["post"]);
service = new ApiService(mockHttp);
spyOn(service, "getURL").and.returnValue("");
spyOn(service, "getOptions").and.returnValue(null);
const data = {
value: {
"stuff": "thigs"
}
};
service.post("", data);
expect(mockHttp.post).toHaveBeenCalledWith("", data, null);
});
it("Will return whatever the HttpClient returns", () => {
const mockHttp = jasmine.createSpyObj("HttpClient", ["post"]);
const expected = new Observable<string>();
mockHttp.post.and.returnValue(expected);
service = new ApiService(mockHttp);
spyOn(service, "getURL").and.returnValue("");
spyOn(service, "getOptions").and.returnValue(null);
const actual = service.post("", null);
expect(actual).toBe(expected);
});
});
|
be574bdc9af662395e6daa71904f3c8b9b97be39 | TypeScript | Shrugsy/jet-cdk | /packages/jet/flight/index.ts | 2.75 | 3 | import {
BaseConfigWithUser,
BaseConfigWithUserAndCommandStage,
getUsernameFromIAM,
getUsernameFromOS,
loadConfig,
writePersonalConfig,
} from '../common/config';
import { Args } from './core/args';
import merge from 'deepmerge';
import cleanDeep from 'clean-deep';
import chalk from 'chalk';
import { listStages } from './commands/list-stages';
import { runDev } from './commands/dev';
import { runDeploy } from './commands/deploy';
import path from 'path';
/**
* Main entry point to jet run
* @param standalone Used as standalone cli, or as a library. Needed because I couldn't figure out clean exit
* @param args Options to run with
*/
export async function flight(standalone: boolean, args: Args) {
const config = await getMergedConfig(args);
//Normalise paths so they're not affected by projectpath
const configFilePath = args.config ? path.resolve(args.config) : args.config;
switch (args.command) {
case 'dev': {
if (checkDevStage(config, configFilePath)) {
await runDev(standalone, config, configFilePath);
}
break;
}
case 'deploy': {
if (checkDeployStage(config, configFilePath)) {
await runDeploy(config, configFilePath);
}
break;
}
case 'list-stages': {
const stages = listStages(
config.projectDir,
config.outDir,
configFilePath
);
console.info(
chalk.yellowBright(
chalk.bgBlack(chalk.bold('Stages detected from cdk:'))
)
);
stages.forEach((s) => {
console.info(s);
});
break;
}
}
}
/**
* Combine config with args into a final config, and verify the stage
* @param args
* @returns
*/
async function getMergedConfig(args: Args): Promise<BaseConfigWithUser> {
const baseConfig = loadConfig(args.projectDir, args.config);
let config: BaseConfigWithUser;
if (baseConfig.user) {
config = baseConfig as BaseConfigWithUser;
} else {
const username = (await getUsernameFromIAM()) ?? getUsernameFromOS();
writePersonalConfig(username, args.projectDir);
config = { ...baseConfig, user: username };
}
//The deep clean is important to make sure we dont overwrite values from the config with unset args
const argsConfig = cleanDeep(
{
//Resolve outdir to an absolute path if it exists, so it isnt affected by projectDir as cwd
outDir: args.outDir ? path.resolve(args.outDir) : undefined,
projectDir: args.projectDir,
dev: {
stage: args.stage,
stacks: args.stacks,
synthArgs: args.synthArgs,
deployArgs: args.deployArgs,
},
deploy: {
stage: args.stage,
stacks: args.stacks,
deployArgs: args.deployArgs,
},
},
{ undefinedValues: true }
);
const mergedConfig = merge<BaseConfigWithUser, typeof argsConfig>(
config,
argsConfig
);
//Substitute user back into our stages
return merge(mergedConfig, {
dev: {
stage: mergedConfig.dev.stage?.replace('{user}', mergedConfig.user),
},
deploy: {
stage: mergedConfig.deploy.stage?.replace('{user}', mergedConfig.user),
},
});
}
function checkDevStage(
config: BaseConfigWithUser,
configFilePath: string | undefined
): config is BaseConfigWithUserAndCommandStage<'dev'> {
return verifyStage(config, config.dev.stage, configFilePath);
}
function checkDeployStage(
config: BaseConfigWithUser,
configFilePath: string | undefined
): config is BaseConfigWithUserAndCommandStage<'deploy'> {
return verifyStage(config, config.deploy.stage, configFilePath);
}
/**
* Ensure that the stage that has been configured is actually available
* @param config loaded and merged configuration
* @param stage the specified stage
* @param configFilePath The path to the config file
* @returns
*/
function verifyStage(
config: BaseConfigWithUser,
stage: string | undefined,
configFilePath: string | undefined
): boolean {
const stages = listStages(config.projectDir, config.outDir, configFilePath);
let stageValid = true;
if (!stage) {
stageValid = false;
console.error(
chalk.redBright(
chalk.bgBlack('No stage has been provided, from config or argument.')
)
);
console.info('You may:');
console.info('- Add stage to your configuration file');
console.info('- Provide stage as an argument');
}
if (stage && !stages.includes(stage)) {
stageValid = false;
console.error(
chalk.redBright(chalk.bgBlack(`Stage ${stage} isn't valid for this app!`))
);
}
if (!stageValid) {
console.info(
chalk.yellowBright(chalk.bgBlack(chalk.bold('\nAvailable stages:')))
);
stages.forEach((s) => {
console.info(s);
});
} else {
console.info(
chalk.whiteBright(
chalk.bgBlack(
chalk.bold(`Jet taking off on stage: ${chalk.blueBright(stage)}`)
)
)
);
}
return stageValid;
}
|
29b629e1331276b19b30e038c4232b9ac8f0fb7d | TypeScript | yuth/amplify-cli | /packages/amplify-provider-awscloudformation/src/iterative-deployment/stack-progress-printer.ts | 2.5625 | 3 | import { StackEvent, StackEvents } from 'aws-sdk/clients/cloudformation';
import { IStackProgressPrinter } from './stack-event-monitor';
import columnify from 'columnify';
import chalk from 'chalk';
import ora, { Ora } from 'ora';
const CFN_SUCCESS_STATUS = ['UPDATE_COMPLETE', 'CREATE_COMPLETE', 'DELETE_COMPLETE', 'DELETE_SKIPPED'];
const CNF_ERROR_STATUS = ['CREATE_FAILED', 'DELETE_FAILED', 'UPDATE_FAILED'];
export class StackProgressPrinter implements IStackProgressPrinter {
private events: StackEvents = [];
private isRunning: boolean = true;
private spinner: Ora = ora('Deploying');
addActivity = (event: StackEvent) => {
this.events.push(event);
};
print = () => {
// CFN sorts the events by descending
this.events = this.events.reverse();
if (this.events.length > 0 && this.isRunning) {
console.log('\n');
const COLUMNS = ['ResourceStatus', 'LogicalResourceId', 'ResourceType', 'Timestamp', 'ResourceStatusReason'];
const e = this.events.map(ev => {
const res: Record<string, string> = {};
const { ResourceStatus: resourceStatus } = ev;
let colorFn = chalk.reset;
if (CNF_ERROR_STATUS.includes(resourceStatus!)) {
colorFn = chalk.red;
} else if (CFN_SUCCESS_STATUS.includes(resourceStatus!)) {
colorFn = chalk.green;
}
Object.entries(ev)
.filter(([name, value]) => COLUMNS.includes(name))
.forEach(([name, value]) => {
res[name] = colorFn(value);
});
return res;
});
console.log(
columnify(e, {
columns: COLUMNS,
showHeaders: false,
}),
);
this.events = [];
}
};
start = () => {
this.isRunning = true;
};
stop = () => {
this.spinner.stop();
};
}
|
75b8a2c034a4bc8d10480beee3e06b02a5fb54b4 | TypeScript | acf136/Angular | /src/app/shared/service/user.service.ts | 2.546875 | 3 | import { Injectable } from '@angular/core';
import { IUser } from '../interfaces';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UsersService {
// VERSION Using HttpClient returnig Observable<IUser[]>
private usersUrl = 'api/usersArray/'; // URL to web api
constructor( private http: HttpClient ) {}
/** GET users from the server
*
*/
getUsers(): Observable<IUser[]> {
return this.http.get<IUser[]>(this.usersUrl).pipe(
retry(2),
catchError( (error: HttpErrorResponse) => {
console.error(error);
return throwError(error);
} )
);
}
// CUD: operations
createUser(ps_name: string): Observable<IUser> {
const user = { name: ps_name , secondName: '', email: '', impagado: false};
return this.http.post<IUser>(this.usersUrl, user);
}
updateUser(p_id: number, p_user: IUser): Observable<any> {
return this.http.put(this.usersUrl + p_id, p_user);
}
deleteUser(p_id: number): Observable<any> {
return this.http.delete(this.usersUrl + p_id);
}
}
|
c838b53d34d0f38de0a5b7800d7d337078bf91e0 | TypeScript | mihaistoie/histria-js | /src/test/compositions/compositions-many.specs.ts | 2.515625 | 3 |
import * as assert from 'assert';
import * as path from 'path';
import { Transaction, loadRules, serializeInstance } from '../../index';
import { DbDriver, dbManager, DbManager, IStore, serialization } from 'histria-utils';
import { Order, OrderItem } from './model/compositions-model';
async function testCreate(): Promise<void> {
const transaction = new Transaction();
const order = await transaction.create<Order>(Order);
const item1 = await transaction.create<OrderItem>(OrderItem);
const item2 = await transaction.create<OrderItem>(OrderItem);
await order.items.add(item1);
const parent = await item1.order();
assert.equal(order, parent, '(1) Owner of orderItem1 is order');
assert.equal(item1.orderId, order.uuid, '(2) Owner of orderItem1 is order');
let children = await order.items.toArray();
assert.deepEqual(children.map(ii => ii.uuid), [item1.uuid], '(3) Owner of orderItem1 is order');
await item2.setOrder(order);
children = await order.items.toArray();
assert.equal(children.length, 2, '(1) Order has 2 items');
assert.deepEqual(children.map(ii => ii.uuid), [item1.uuid, item2.uuid], '(2) Order has 2 items');
await item1.setOrder(null);
children = await order.items.toArray();
assert.deepEqual(children.map(ii => ii.uuid), [item2.uuid], '(1) Order has 1 items');
await order.items.add(item1, 0);
children = await order.items.toArray();
assert.equal(children.length, 2, '(1) Order has 2 items');
assert.deepEqual(children.map(ii => ii.uuid), [item1.uuid, item2.uuid], '(2) Order has 2 items');
await order.items.remove(item2);
children = await order.items.toArray();
assert.equal(children.length, 1, '(4) Order has 1 items');
assert.deepEqual(children.map(ii => ii.uuid), [item1.uuid], '(5) Order has 1 items');
assert.equal(await item2.order(), null, '(6) Parent is null');
const data1 = transaction.saveToJson();
transaction.clear();
await transaction.loadFromJson(data1, false);
const data2 = transaction.saveToJson();
assert.deepEqual(data1, data2, 'Restore test in create');
transaction.destroy();
}
async function testLoad(): Promise<void> {
const transaction = new Transaction();
const order = await transaction.create<Order>(Order);
const item1 = await transaction.load<OrderItem>(OrderItem, { orderId: order.uuid });
const item2 = await transaction.load<OrderItem>(OrderItem, { orderId: order.uuid });
const children = await order.items.toArray();
assert.equal(children.length, 2, '(1) Order has 2 items');
assert.deepEqual(children.map(ii => ii.uuid).sort(), [item1.uuid, item2.uuid].sort(), '(2) Order has 2 items');
const order2 = await transaction.load<Order>(Order, { id: 101, items: [{ id: 1, amount: 0 }, { id: 2, amount: 0 }, { id: 3, amount: 0 }] });
const children2 = await order2.items.toArray();
assert.equal(children2.length, 3, 'Order has 3 items');
const oi2 = await transaction.findOne<OrderItem>(OrderItem, { id: 2 });
assert.equal(oi2.orderId, order2.id, 'item.orderId === order.id');
assert.equal(children2[1], oi2, 'order.items[1] == oi');
let i = 0;
order2.enumChildren(ec => {
i++;
}, true);
assert.equal(i, 3, 'Order has 3 children');
assert.equal(children2[0].loaded, true, '(1)Init rule called');
assert.equal(children2[1].loaded, true, '(2) Init rule called');
assert.equal(children2[2].loaded, true, '(3)Init rule called');
const data1 = transaction.saveToJson();
transaction.clear();
await transaction.loadFromJson(data1, false);
const data2 = transaction.saveToJson();
assert.deepEqual(data1, data2, 'Restore test in load');
transaction.destroy();
}
async function testRestore(): Promise<void> {
const transaction = new Transaction();
const order1 = await transaction.load<Order>(Order, { id: 101, totalAmount: 0, items: [{ id: 1, amount: 0 }, { id: 2, amount: 0 }, { id: 3, amount: 0 }] });
const children1 = await order1.items.toArray();
assert.equal(children1[1].loaded, true, '(1) Loaded = true Init rule called');
await children1[1].setLoaded(false);
assert.equal(children1[1].loaded, false, '(1) Loaded = false');
await children1[2].amount.setValue(10);
assert.equal(order1.totalAmount.value, 10, '(1) Rule called');
const saved = JSON.parse(JSON.stringify(order1.model()));
const transaction2 = new Transaction();
const order2 = await transaction.restore<Order>(Order, saved, false);
const children2 = await order2.items.toArray();
assert.equal(children2.length, 3, 'Order has 3 items');
assert.equal(children2[1].loaded, false, '(2) Loaded = false');
await children2[0].amount.setValue(10);
assert.equal(order2.totalAmount.value, 20, '(2) Rule called');
const data1 = transaction.saveToJson();
transaction.clear();
await transaction.loadFromJson(data1, false);
const data2 = transaction.saveToJson();
assert.deepEqual(data1, data2, 'Restore test in restore');
transaction.destroy();
}
async function testRules(): Promise<void> {
const transaction = new Transaction();
const order = await transaction.create<Order>(Order);
const item1 = await transaction.create<OrderItem>(OrderItem);
const item2 = await transaction.create<OrderItem>(OrderItem);
await order.items.add(item1);
await order.items.add(item2);
await item1.amount.setValue(10);
assert.equal(order.totalAmount.value, 10, 'Total amount = 10');
await item2.amount.setValue(10);
assert.equal(order.totalAmount.value, 20, 'Total amount = 20');
await item1.amount.setValue(5);
assert.equal(order.totalAmount.value, 15, 'Total amount = 15');
await order.items.remove(item2);
assert.equal(order.totalAmount.value, 5, 'Total amount = 5');
await item1.setOrder(null);
assert.equal(order.totalAmount.value, 0, 'Total amount = 0');
await order.items.set([item1, item2]);
assert.equal(order.totalAmount.value, 15, 'Total amount = 15');
order.$states.totalAmount.isDisabled = true;
const o = await serializeInstance(order, pattern1);
const excepted = {
id: order.id,
totalAmount: 15,
items: [
{ amount: 5, id: item1.id },
{ amount: 10, id: item2.id }
],
$states: {
totalAmount: {
isDisabled: true
}
}
};
assert.deepEqual(o, excepted, 'Serialization rules 1');
const data1 = transaction.saveToJson();
transaction.clear();
await transaction.loadFromJson(data1, false);
const data2 = transaction.saveToJson();
assert.deepEqual(data1, data2, 'Restore test in rules');
transaction.destroy();
}
async function testRemove(): Promise<void> {
let transaction = new Transaction();
let order = await transaction.create<Order>(Order);
let item1 = await transaction.create<OrderItem>(OrderItem);
let item2 = await transaction.create<OrderItem>(OrderItem);
await order.items.add(item1);
await order.items.add(item2);
await item2.remove();
const items = await order.items.toArray();
assert.equal(items.length, 1, 'Order has 1 item');
transaction.destroy();
transaction = new Transaction();
order = await transaction.create<Order>(Order);
item1 = await transaction.create<OrderItem>(OrderItem);
item2 = await transaction.create<OrderItem>(OrderItem);
const uuid = item1.id;
await order.items.add(item1);
await order.items.add(item2);
await order.remove();
const oi = await transaction.findOne<OrderItem>(OrderItem, { id: uuid });
assert.equal(oi, null, 'Order item removed');
transaction.destroy();
}
const pattern1 = {
properties: [
'totalAmount',
{
items: 'items',
$ref: '#/definitions/orderitem'
},
],
definitions: {
orderitem: {
properties: [
'amount'
]
}
}
};
describe('Relation One to many, Composition', () => {
before(() => {
serialization.check(pattern1);
const dm: DbManager = dbManager();
dm.registerNameSpace('compositions', 'memory', { compositionsInParent: true });
const store = dm.store('compositions');
store.initNameSpace('compositions', {
order: [
{
id: 1001,
totalAmount: 100,
items: [{
id: 2001,
amount: 50,
orderId: 1001,
loaded: true
},
{
id: 2002,
amount: 50,
orderId: 1001,
loaded: true
}
]
},
{
id: 1002,
totalAmount: 100,
items: [{
id: 2003,
amount: 50,
orderId: 1002,
loaded: true
},
{
id: 2004,
amount: 50,
orderId: 1002,
loaded: true
}
]
},
]
});
return loadRules(path.join(__dirname, 'model', 'rules'));
});
it('One to many composition - create', () => {
return testCreate();
});
it('One to many composition - load', () => {
return testLoad();
});
it('One to many composition - rules', () => {
return testRules();
});
it('One to one Many composition - restore', () => {
return testRestore();
});
it('One to one Many composition - remove', () => {
return testRemove();
});
});
|
f687ea1c25f591e0431d842fab5a0bfa17536c1b | TypeScript | TommyBi/EnProj | /ECP1.3U1S1/listen_repeat/src/view/MainView.ts | 2.53125 | 3 | namespace game {
export class MainView extends eui.Component {
public kCom0: game.DialogComponent;
public kCom1: game.DialogComponent;
public kCom2: game.DialogComponent;
public kCom3: game.DialogComponent;
public kCom4: game.DialogComponent;
public kCom5: game.DialogComponent;
public kCom6: game.DialogComponent;
public kCom7: game.DialogComponent;
public kComVideo: game.VideoComponent;
private mCurPlayIdx: number; // 当前正在播放的索引
constructor() {
super();
this.skinName = "MainViewSkin";
};
protected createChildren() {
super.createChildren();
for (let i = 0; i < 8; i++) {
// this[`kCom${i}`].addEventListener(mouse.MouseEvent.ROLL_OVER, this.onMoveOverCom, this);
// this[`kCom${i}`].addEventListener(mouse.MouseEvent.ROLL_OUT, this.onMoveOutCom, this);
this[`kCom${i}`].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouch, this);
this[`kCom${i}`].setData(i);
}
// mouse.enable(this.stage);
this.init();
}
private init(): void {
this.mCurPlayIdx = -1;
}
// /** 鼠标移到重放按钮 */
// private onMoveOverCom(e: egret.TouchEvent): void {
// this[`kCom${e.target.name}`].light();
// }
// /** 鼠标移出重放按钮 */
// private onMoveOutCom(e: egret.TouchEvent): void {
// if (Number(e.target.name) != this.mCurPlayIdx) {
// this[`kCom${e.target.name}`].normal();
// }
// }
private onTouch(e: egret.TouchEvent): void {
this.mCurPlayIdx = Number(e.target.name);
for (let i = 0; i < 8; i++) {
if (this.mCurPlayIdx == i) {
egret.log("选中:", e.target.name);
this[`kCom${i}`].light();
this.kComVideo.play(i);
} else {
this[`kCom${i}`].normal();
}
}
}
}
} |
569fb25a16954c1567783309af6f8a04a317eea9 | TypeScript | yume-chan/cloudmusic-vscode | /packages/client/src/unblock/kugou.ts | 2.78125 | 3 | /* import type { SongDetail, SongsItem, UnlockSongItem } from "../constant";
import axios from "axios";
import { createHash } from "crypto";
import { extname } from "path";
import filter from "./filter";
interface SearchResult {
data: {
lists: {
AlbumName: string;
SingerName: string;
SongName: string;
Suffix: string;
FileHash: string;
ExtName: string;
HQFileHash: string;
HQExtName: string;
SQFileHash: string;
SQExtName: string;
SuperFileHash: string;
SuperExtName: string;
}[];
};
}
// const format = MUSIC_QUALITY === 999000 ? 0 : MUSIC_QUALITY === 320000 ? 1 : 2;
async function search(keyword: string) {
keyword = encodeURIComponent(keyword);
try {
const {
data: {
data: { lists },
},
} = await axios.get<SearchResult>(
`http://songsearch.kugou.com/song_search_v2?keyword=${keyword}&page=1&pagesize=8&platform=WebFilter`
);
return lists.map(
({
AlbumName,
SingerName,
SongName,
FileHash,
// ExtName,
// HQFileHash,
// HQExtName,
// SQFileHash,
// SQExtName,
}) => ({
album: AlbumName,
artist: SingerName.split("、"),
dt: 0,
id: FileHash,
name: SongName,
// ...[
// { hash: SQFileHash, type: SQExtName },
// { hash: HQFileHash, type: HQExtName },
// { hash: FileHash, type: ExtName },
// ]
// .slice(format)
// .filter(({ hash }) => hash)[0],
})
);
} catch {}
return [];
}
async function songUrl({ id }: UnlockSongItem) {
try {
const {
data: { url },
} = await axios.get<{ url: string[] }>(
`http://trackercdn.kugou.com/i/v2/?key=${createHash("md5")
.update(`${id}kgcloudv2`)
.digest("hex")}&hash=${id}&pid=2&cmd=25&behavior=play`
);
return { url: url[0], type: extname(url[0]).split(".").pop(), md5: id };
} catch {}
return;
}
export default async function kugou(
song: SongsItem
): Promise<SongDetail | void> {
const list = await search(song.name);
const selected = filter(list, song);
return selected ? await songUrl(selected) : undefined;
}
*/
export default undefined;
|
256b70d1c2a8a9ba1004557610cc6141908ee568 | TypeScript | awschristou/aws-toolkit-vscode | /src/shared/logger.ts | 2.625 | 3 | /*!
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import * as os from 'os'
import * as path from 'path'
import * as vscode from 'vscode'
import * as nls from 'vscode-nls'
import * as winston from 'winston'
import * as Transport from 'winston-transport'
import { extensionSettingsPrefix } from './constants'
import { mkdir } from './filesystem'
import { fileExists } from './filesystemUtilities'
import { DefaultSettingsConfiguration, SettingsConfiguration } from './settingsConfiguration'
import { registerCommand } from './telemetry/telemetryUtils'
const localize = nls.loadMessageBundle()
const LOG_RELATIVE_PATH: string = path.join('Code', 'logs', 'aws_toolkit')
const DEFAULT_LOG_LEVEL: LogLevel = 'info'
const DEFAULT_LOG_NAME: string = `aws_toolkit_${makeDateString('filename')}.log`
const DEFAULT_OUTPUT_CHANNEL: vscode.OutputChannel = vscode.window.createOutputChannel('AWS Toolkit Logs')
let defaultLogger: Logger
export interface BasicLogger {
debug(...message: ErrorOrString[]): void
verbose(...message: ErrorOrString[]): void
info(...message: ErrorOrString[]): void
warn(...message: ErrorOrString[]): void
error(...message: ErrorOrString[]): void
}
export type LogLevel = keyof BasicLogger
export interface Logger extends BasicLogger {
logPath?: string
outputChannel?: vscode.OutputChannel
level: LogLevel
releaseLogger(): void
}
/**
* logPath is not required (as Winston will work without a file path defined) but will output errors to stderr.
*/
export interface LoggerParams {
outputChannel?: vscode.OutputChannel
logPath?: string
logLevel?: LogLevel
}
/**
* @param params: LoggerParams
* Creates the "default logger" (returnable here and through getLogger) using specified parameters or default values.
* Initializing again will create a new default logger
* --however, existing logger objects using the old default logger will be unaffected.
*/
export async function initialize(params?: LoggerParams): Promise<Logger> {
if (!params) {
const logPath = getDefaultLogPath()
const logFolder = path.dirname(logPath)
if (!(await fileExists(logFolder))) {
await mkdir(logFolder, { recursive: true })
}
defaultLogger = createLogger({
outputChannel: DEFAULT_OUTPUT_CHANNEL,
logPath
})
// only the default logger (with default params) gets a registered command
// check list of registered commands to see if aws.viewLogs has already been registered.
// if so, don't register again--this will cause an error visible to the user.
for (const command of await vscode.commands.getCommands(true)) {
if (command === 'aws.viewLogs') {
return defaultLogger
}
}
registerCommand({
command: 'aws.viewLogs',
callback: async () => await openLogFile()
})
} else {
defaultLogger = createLogger(params)
}
if (defaultLogger.outputChannel) {
defaultLogger.outputChannel.appendLine(
localize(
'AWS.log.fileLocation',
'Error logs for this session are permanently stored in {0}',
defaultLogger.logPath
)
)
}
return defaultLogger
}
/**
* Gets the default logger if it has been initialized with the initialize() function
*/
export function getLogger(): Logger {
if (defaultLogger) {
return defaultLogger
}
throw new Error('Default Logger not initialized. Call logger.initialize() first.')
}
/**
* @param params: LoggerParams--nothing is required, but a LogPath is highly recommended so Winston doesn't throw errors
*
* Outputs a logger object that isn't stored anywhere--it's up to the caller to keep track of this.
* No cleanup is REQUIRED, but if you wish to directly manipulate the log file while VSCode is still active,
* you need to call releaseLogger. This will end the ability to write to the logfile with this logger instance.
*/
export function createLogger(params: LoggerParams): Logger {
let level: LogLevel
if (params.logLevel) {
level = params.logLevel
} else {
const configuration: SettingsConfiguration = new DefaultSettingsConfiguration(extensionSettingsPrefix)
const setLevel = configuration.readSetting<string>('logLevel')
level = setLevel ? (setLevel as LogLevel) : DEFAULT_LOG_LEVEL
}
const transports: Transport[] = []
if (params.logPath) {
transports.push(new winston.transports.File({ filename: params.logPath }))
}
const newLogger: winston.Logger = winston.createLogger({
format: winston.format.combine(logFormat),
level,
transports
})
return {
logPath: params.logPath,
level,
outputChannel: params.outputChannel,
debug: (...message: ErrorOrString[]) =>
writeToLogs(generateWriteParams(newLogger, 'debug', message, params.outputChannel)),
verbose: (...message: ErrorOrString[]) =>
writeToLogs(generateWriteParams(newLogger, 'verbose', message, params.outputChannel)),
info: (...message: ErrorOrString[]) =>
writeToLogs(generateWriteParams(newLogger, 'info', message, params.outputChannel)),
warn: (...message: ErrorOrString[]) =>
writeToLogs(generateWriteParams(newLogger, 'warn', message, params.outputChannel)),
error: (...message: ErrorOrString[]) =>
writeToLogs(generateWriteParams(newLogger, 'error', message, params.outputChannel)),
releaseLogger: () => releaseLogger(newLogger)
}
}
function getDefaultLogPath(): string {
if (os.platform() === 'win32') {
return path.join(os.homedir(), 'AppData', 'Roaming', LOG_RELATIVE_PATH, DEFAULT_LOG_NAME)
} else if (os.platform() === 'darwin') {
return path.join(os.homedir(), 'Library', 'Application Support', LOG_RELATIVE_PATH, DEFAULT_LOG_NAME)
} else {
return path.join(os.homedir(), '.config', LOG_RELATIVE_PATH, DEFAULT_LOG_NAME)
}
}
async function openLogFile(): Promise<void> {
if (defaultLogger.logPath) {
await vscode.window.showTextDocument(vscode.Uri.file(path.normalize(defaultLogger.logPath)))
}
}
function releaseLogger(logger: winston.Logger): void {
logger.clear()
}
function formatMessage(level: LogLevel, message: ErrorOrString[]): string {
let final: string = `${makeDateString('logfile')} [${level.toUpperCase()}]:`
for (const chunk of message) {
if (chunk instanceof Error) {
final = `${final} ${chunk.stack}`
} else {
final = `${final} ${chunk}`
}
}
return final
}
function writeToLogs(params: WriteToLogParams): void {
const message = formatMessage(params.level, params.message)
params.logger.log(params.level, message)
if (params.outputChannel) {
writeToOutputChannel(
params.logger.levels[params.level],
params.logger.levels[params.logger.level],
message,
params.outputChannel
)
}
}
function writeToOutputChannel(
messageLevel: number,
logLevel: number,
message: string,
outputChannel: vscode.OutputChannel
): void {
// using default Winston log levels (mapped to numbers): https://github.com/winstonjs/winston#logging
if (messageLevel <= logLevel) {
outputChannel.appendLine(message)
}
}
// outputs a timestamp with the following formattings:
// type: 'filename' = YYYYMMDDThhmmss (note the 'T' prior to time, matches VS Code's log file name format)
// type: 'logFile' = YYYY-MM-DD HH:MM:SS
// Uses local timezone
function makeDateString(type: 'filename' | 'logfile'): string {
const d = new Date()
const isFilename: boolean = type === 'filename'
return (
`${d.getFullYear()}${isFilename ? '' : '-'}` +
// String.prototype.padStart() was introduced in ES7, but we target ES6.
`${padNumber(d.getMonth() + 1)}${isFilename ? '' : '-'}` +
`${padNumber(d.getDate())}${isFilename ? 'T' : ' '}` +
`${padNumber(d.getHours())}${isFilename ? '' : ':'}` +
`${padNumber(d.getMinutes())}${isFilename ? '' : ':'}` +
`${padNumber(d.getSeconds())}`
)
}
function padNumber(num: number): string {
return num < 10 ? '0' + num.toString() : num.toString()
}
function generateWriteParams(
logger: winston.Logger,
level: LogLevel,
message: ErrorOrString[],
outputChannel?: vscode.OutputChannel
): WriteToLogParams {
return { logger: logger, level: level, message: message, outputChannel: outputChannel }
}
interface WriteToLogParams {
logger: winston.Logger
level: LogLevel
message: ErrorOrString[]
outputChannel?: vscode.OutputChannel
}
export type ErrorOrString = Error | string // TODO: Consider renaming to Loggable & including number
// forces winston to output only pre-formatted message
const logFormat = winston.format.printf(({ message }) => {
return message
})
|
4b8aac6457a5ed4e5ba85f56a1f3b0870c36229d | TypeScript | evergreen-ci/spruce | /src/pages/spawn/spawnVolume/spawnVolumeTableActions/migrateVolumeReducer.ts | 2.734375 | 3 | import { FormState } from "components/Spawn/spawnHostModal";
export enum Page {
First,
Second,
}
interface State {
page: Page;
form: FormState;
}
export const initialState = { page: Page.First, form: {} };
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "goToNextPage":
return {
...state,
page: state.page === Page.First ? Page.Second : Page.First,
};
case "resetPage":
return { ...state, page: Page.First };
case "setForm":
return { ...state, form: action.payload };
case "resetForm":
return { ...state, form: {} };
default:
throw new Error(`Unknown reducer action ${action}`);
}
};
type Action =
| { type: "goToNextPage" }
| { type: "resetForm" }
| { type: "resetPage" }
| { type: "setForm"; payload: FormState };
|
a78ef3128a70150aff1dab0a784a6afbea7e15f6 | TypeScript | itmilos/fundamental-ngx | /libs/fn/src/lib/cdk/toast/classes/duration-dismissible/base-toast-duration-dismissible-ref.ts | 2.8125 | 3 | import { OverlayRef } from '@angular/cdk/overlay';
import { BaseToastRef } from '../base-toast-ref';
import { BaseToastDurationDismissibleContainerComponent } from './base-toast-duration-dismissible-container.component';
/** Maximum number of milliseconds that can be passed into setTimeout. */
const MAX_TIMEOUT = Math.pow(2, 31) - 1;
export abstract class BaseToastDurationDismissibleRef<T = any, P = any> extends BaseToastRef<T, P> {
/**
* Timeout ID for the duration setTimeout call. Used to clear the timeout if the toast is
* dismissed before the duration passes.
*/
protected durationTimeoutId!: ReturnType<typeof setTimeout>;
/** @hidden */
protected constructor(
public containerInstance: BaseToastDurationDismissibleContainerComponent<P>,
public overlayRef: OverlayRef
) {
super(containerInstance, overlayRef);
}
/** Dismisses the toast and clears the timeout. */
dismiss(): void {
clearTimeout(this.durationTimeoutId);
super.dismiss();
}
/** Dismisses the Toast component after some duration */
dismissAfter(duration: number): void {
this.durationTimeoutId = setTimeout(() => this.dismiss(), Math.min(duration, MAX_TIMEOUT));
}
/** Cancels current dismiss timeout */
cancelDismiss(): void {
clearTimeout(this.durationTimeoutId);
}
}
|
7a4386a710cfacba9693622295cd21e51d14b48d | TypeScript | vjje/threets | /src/helpers/DirectionalLightHelper.ts | 2.703125 | 3 | module THREE {
export class DirectionalLightHelper extends Object3D {
public light;
public color;
public lightPlane;
public targetLine;
constructor(light, size, color) {
super();
this.light = light;
this.light.updateMatrixWorld();
this.matrix = light.matrixWorld;
this.matrixAutoUpdate = false;
this.color = color;
if (size === undefined) size = 1;
var geometry = new BufferGeometry();
geometry.addAttribute('position', new Float32BufferAttribute([
- size, size, 0,
size, size, 0,
size, - size, 0,
- size, - size, 0,
- size, size, 0
], 3));
var material = new LineBasicMaterial({ fog: false });
this.lightPlane = new Line(geometry, material);
this.add(this.lightPlane);
geometry = new BufferGeometry();
geometry.addAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
this.targetLine = new Line(geometry, material);
this.add(this.targetLine);
this.update();
}
public dispose() {
this.lightPlane.geometry.dispose();
this.lightPlane.material.dispose();
this.targetLine.geometry.dispose();
this.targetLine.material.dispose();
};
public update() {
var v1 = new Vector3();
var v2 = new Vector3();
var v3 = new Vector3();
v1.setFromMatrixPosition(this.light.matrixWorld);
v2.setFromMatrixPosition(this.light.target.matrixWorld);
v3.subVectors(v2, v1);
this.lightPlane.lookAt(v3);
if (this.color !== undefined) {
this.lightPlane.material.color.set(this.color);
this.targetLine.material.color.set(this.color);
} else {
this.lightPlane.material.color.copy(this.light.color);
this.targetLine.material.color.copy(this.light.color);
}
this.targetLine.lookAt(v3);
this.targetLine.scale.z = v3.length();
};
}
}
|
5c763efce74267c34b1923664b983b77fda67507 | TypeScript | heathertill/barebones-w-db | /src/server/utils/routerMiddleware.ts | 2.734375 | 3 | import * as passport from 'passport';
import { RequestHandler, Request } from 'express-serve-static-core';
interface ReqUser extends Request {
user: {
role: string
}
}
export const checkToken = (req: any, res: any, next: any) => {
passport.authenticate('bearer', { session: false }, (err, user, info) => {
if (user) {
req.user = user
return next();
} else {
return next();
}
})(req, res, next);
}
// middleware to check your req object for a user property or a specific role on that property
export const isAdmin: RequestHandler = (req: ReqUser, res, next) => {
if (!req.user || req.user.role !== 'admin') {
return res.sendStatus(401)
} else {
return next();
}
}; |
e462f382d80e8d917f34437b218c4623bf0a4d8d | TypeScript | arimah/condict | /packages/server/src/create-logger.ts | 3.109375 | 3 | import chalk, {Chalk} from 'chalk';
import * as winston from 'winston';
import Transport from 'winston-transport';
import {Logger, LoggerOptions, LogLevel} from './types';
const levels: Record<LogLevel, number> = {
error: 0,
warn: 1,
info: 2,
verbose: 3,
debug: 4,
};
const levelColors: Record<LogLevel, Chalk> = {
error: chalk.redBright,
warn: chalk.yellowBright,
info: chalk.cyanBright,
verbose: chalk.greenBright,
debug: chalk.magenta,
};
const consoleFormat = winston.format.combine(
winston.format.timestamp(),
winston.format.printf(
info => {
const timestamp = chalk.gray(`[${info.timestamp}]`);
const level = levelColors[info.level as LogLevel](`[${info.level}]`);
return `${timestamp} ${level} ${info.message}`;
}
)
);
const fileFormat = winston.format.combine(
winston.format.timestamp(),
winston.format.json()
);
/**
* Creates a logger from the specified options.
* @param config Specifies logging options for stdout and files.
* @return A logger.
*/
const createLogger = (config: LoggerOptions): Logger => {
const transports: Transport[] = [];
if (config.stdout) {
transports.push(new winston.transports.Console({
level: config.stdout,
format: consoleFormat,
}));
}
config.files.forEach(file => {
transports.push(new winston.transports.File({
filename: file.path,
level: file.level,
format: fileFormat,
}));
});
if (transports.length === 0) {
return createNullLogger();
}
return winston.createLogger({levels, transports});
};
export default createLogger;
/**
* Creates a logger that discards all incoming messages.
* @return A logger that does nothing.
*/
export const createNullLogger = (): Logger => ({
error() { /* no-op */ },
warn() { /* no-op */ },
info() { /* no-op */ },
verbose() { /* no-op */ },
debug() { /* no-op */ },
});
/**
* Creates a logger that prepends a prefix to all incoming messages.
* @param inner The logger to wrap.
* @param prefix The prefix to add to each message.
* @return A prefixing logger.
*/
export const createPrefixLogger = (inner: Logger, prefix: string): Logger => ({
error(msg, ...extra) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
inner.error(`${prefix} ${msg}`, ...extra);
},
warn(msg, ...extra) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
inner.warn(`${prefix} ${msg}`, ...extra);
},
info(msg, ...extra) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
inner.info(`${prefix} ${msg}`, ...extra);
},
verbose(msg, ...extra) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
inner.verbose(`${prefix} ${msg}`, ...extra);
},
debug(msg, ...extra) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
inner.debug(`${prefix} ${msg}`, ...extra);
},
});
|
4aa88c24646037af6ac5942bb0b7359647a3eb31 | TypeScript | j03m/min-crypto | /src/strategies/slope-trend-advisor.ts | 2.84375 | 3 | import Candle from "../types/candle";
export default {
shouldBuy,
shouldSell,
name: "slope-trend-advisor"
}
import BigNumber from "bignumber.js";
import {getBigNumbersFromCandle} from "../utils/util";
import {QuadBand} from "../indicators/quad-band";
const lookBack = 25
function shouldBuy(indicators:Map<string, Array<any>>, candles:Array<Candle>):boolean{
if (candles.length < lookBack){
return false;
}
const slope = getSlope(candles);
if (slope.isLessThan(0) ){ //don't buy into downtrend
return false;
}
else {
return true;
}
}
function getSlope(candle:Array<Candle>){
const currentCandle = candle[candle.length-1]; //y2
const lookBackCandle = candle[candle.length - lookBack]; //y1
const currentHigh = new BigNumber(currentCandle.high);
const lookBackHigh = new BigNumber(lookBackCandle.high);
return currentHigh.minus(lookBackHigh).dividedBy(lookBack);
}
function shouldSell(indicators:Map<string, Array<any>>, candles:Array<Candle>):boolean{
if (candles.length < lookBack){
return false;
}
const slope = getSlope(candles);
if (slope.isGreaterThan(0) ){ //don't sell into uptrend
return false;
}
else {
return true;
}
} |
e669806dace7dc1b2c9dd6bf8056996c646e12a1 | TypeScript | rajat1883/Covid19TrackingApp | /src/app/chart-service/chart.service.ts | 2.515625 | 3 | import { Injectable } from '@angular/core';
import { SingleDayData } from '../coronavirus-model/single-day-data';
import { Chart } from 'chart.js';
import { CountryData } from '../coronavirus-model/country-data';
@Injectable({
providedIn: 'root'
})
export class ChartService {
private ctx: any;
private chart: any;
private canvas: any;
private chartLabels: string[];
private chartData: number[];
private last5DayData: SingleDayData[];
private chartTracker: Array<string>;
private coronavirusData: CountryData[];
private coronavirusLatestDataIndex: number;
private readonly chartBackgroundColor: Array<string>;
constructor() {
this.chartTracker = new Array<string>();
this.chartBackgroundColor = [
'rgba(255, 99, 132, 1)',
'rgba(250, 226, 105, 1)',
'rgba(149, 230, 117, 1)',
'rgba(89, 145, 200, 1)',
'rgba(132, 132, 132, 1)',
];
}
createCharts(countryName: string, coronavirusData: CountryData[], coronavirusLatestDataIndex: number) {
this.coronavirusData = coronavirusData;
this.coronavirusLatestDataIndex = coronavirusLatestDataIndex;
if (this.chartTracker.indexOf(countryName) > -1) {
return;
}
else {
this.chartTracker.push(countryName);
}
this.last5DayData = this.extractDataForLast5Days(countryName);
this.createBarChart(countryName);
this.createLineChart(countryName);
this.createDoughnutChart(countryName);
}
createBarChart(countryName: string) {
this.formatCountryDataForBarChart();
this.createChart('bar', countryName, 'Confirmed Cases');
}
createLineChart(countryName: string) {
this.formatCountryDataForLineChart();
this.createChart('line', countryName, 'Deaths');
}
createDoughnutChart(countryName: string) {
this.formatCountryDataForDoghnutChart(countryName);
this.createChart('doughnut', countryName, 'Case summary');
}
private createChart(typeOfChart: string, countryName: string, label: string) {
this.canvas = document.getElementById(typeOfChart + 'CoronaLineChart' + countryName);
this.ctx = this.canvas.getContext('2d');
this.chart = new Chart(this.ctx, {
type: typeOfChart,
data: {
labels: this.chartLabels,
datasets: [{
label,
data: this.chartData,
backgroundColor: this.chartBackgroundColor,
fill: false,
borderWidth: 1
}]
},
options: {
responsive: false,
display: true,
legend: {
align: 'start'
}
}
});
}
formatCountryDataForBarChart() {
this.chartLabels = [];
this.chartData = [];
this.fillChartLabels('date');
this.fillChartData('confirmed');
}
formatCountryDataForLineChart() {
this.chartLabels = [];
this.chartData = [];
this.fillChartLabels('date');
this.fillChartData('deaths');
}
private fillChartLabels(property: string) {
this.last5DayData.forEach((singleDayData: SingleDayData) => {
this.chartLabels.push(singleDayData[property]);
});
}
private fillChartData(property: string) {
this.last5DayData.forEach((singleDayData: SingleDayData) => {
this.chartData.push(singleDayData[property]);
});
}
private extractDataForLast5Days(countryName: string): SingleDayData[] {
return (this.coronavirusData[countryName] as SingleDayData[]).slice(1).slice(-5);
}
formatCountryDataForDoghnutChart(countryName: string) {
this.chartLabels = [];
this.chartData = [];
const latestDayData = (this.coronavirusData[countryName][this.coronavirusLatestDataIndex] as SingleDayData);
this.chartLabels.push('Deaths');
this.chartLabels.push('Confirmed');
this.chartLabels.push('Recovered');
this.chartData.push(latestDayData.deaths);
this.chartData.push(latestDayData.confirmed);
this.chartData.push(latestDayData.recovered);
}
}
|
4ed2f8a670f3036ed23feff6760f3508db1a6eae | TypeScript | doulevo/doulevo | /src/lib/command.ts | 2.734375 | 3 | //
// Manages execution of a system command.
//
import { InjectableClass, InjectProperty } from "@codecapers/fusion";
import chalk = require("chalk");
import { exec, ExecOptions } from "child_process";
import * as stream from "stream";
import { IConfiguration, IConfiguration_id } from "../services/configuration";
import { IDetectInterrupt, IDetectInterrupt_id } from "../services/detect-interrupt";
export interface ICommandOptions extends ExecOptions {
//
// Set to true to print the command.
//
showCommand?: boolean;
//
// String to be piped to standard input.
//
stdin?: string;
//
// Set to true to always show output.
//
showOutput?: boolean;
//
// Prefix to show for each line of output.
//
outputPrefix?: string;
//
// Set to true to throw an error for a non-zero exit code.
// Defaults to true.
///
throwOnNonZeroExitCode?: boolean;
}
export interface ICommandResult {
//
// The exit code from the command.
//
exitCode?: number;
//
// Standard output from the command.
//
stdout: string;
//
// Standard error from the command.
//
stderr: string;
}
export interface ICommand {
//
// Executes the command.
//
exec(): Promise<ICommandResult>;
}
@InjectableClass()
export class Command implements ICommand {
@InjectProperty(IDetectInterrupt_id)
detectInterrupt!: IDetectInterrupt;
@InjectProperty(IConfiguration_id)
configuration!: IConfiguration;
//
// The command to execute.
//
cmd: string;
//
// Options to the command.
//
options: ICommandOptions;
constructor(cmd: string, options?: ICommandOptions) {
this.cmd = cmd;
this.options = options || {};
}
//
// Executes the command.
//
exec(): Promise<ICommandResult> {
return new Promise<ICommandResult>((resolve, reject) => {
if (this.options.showCommand || this.configuration.isDebug()) {
console.log(`CMD: ${this.cmd}`);
}
let didTerminate = false;
const proc = exec(this.cmd, this.options);
//
// TODO:
// Is it worth having this? There's problems with it on Windows.
//
// this.detectInterrupt.pushHandler(async () => {
// proc.kill("SIGINT");
// didTerminate = true;
// return true; // Allow process termination.
// });
let stdOutput = "";
const writeOutput = (output: string) => {
if (this.options.outputPrefix) {
const lines = output.split("\n");
for (const line of lines) {
process.stdout.write(`${this.options.outputPrefix}: ${line.trim()}\n`);
}
}
else {
process.stdout.write(output);
}
}
proc.stdout!.on('data', (data) => {
const output = data.toString();
stdOutput += output;
if (this.options.showOutput || this.configuration.isDebug()) {
writeOutput(output);
}
});
let stdError = "";
proc.stderr!.on('data', (data) => {
const output = data.toString();
stdError += output;
if (this.options.showOutput || this.configuration.isDebug()) {
writeOutput(output);
}
});
proc.on("exit", code => {
//TODO: Reconsider this, see above.
// this.detectInterrupt.popHandler();
if (this.options.showCommand || this.configuration.isDebug()) {
console.log(`CMD finished: ${this.cmd}`);
}
const throwOnNonZeroExitCode = !didTerminate && (this.options.throwOnNonZeroExitCode === true || this.options.throwOnNonZeroExitCode === undefined);
if (throwOnNonZeroExitCode && code !== 0) {
const err: any = new Error(`Cmd "${this.cmd}" exited with error code ${code}\n${stdError}`);
err.code = code;
err.stdout = stdOutput;
err.stderr = stdError;
reject(err);
}
else {
resolve({
exitCode: code || undefined,
stdout: stdOutput,
stderr: stdError,
});
}
});
if (this.options.stdin) {
//
// https://stackoverflow.com/a/41343999/25868
//
var stdinStream = new stream.Readable();
stdinStream.push(this.options.stdin); // Add data to the internal queue for users of the stream to consume
stdinStream.push(null); // Signals the end of the stream (EOF)
stdinStream.pipe(proc.stdin!);
}
});
}
} |
47d87a7bd016e949056572a1cd77b4dd1e7abf8a | TypeScript | jfalxa/systyle | /packages/systyle/src/moulinettes/helpers.ts | 2.921875 | 3 | import { By, Props } from '../types'
const rxRules = /^(\&|\@|\:|\#|\.)/
export function isCSS(_: any, key: string) {
if (rxRules.test(key)) return true
return typeof document === 'undefined'
? require('known-css-properties').all.includes(require('kebab-case')(key))
: key in document.body.style
}
export function isVoid(value: any) {
return typeof value === 'undefined' || value === null
}
export function isObject(value: any): value is object {
return (
value !== null &&
typeof value === 'object' &&
value.constructor === Object &&
!value.hasOwnProperty('$$typeof')
)
}
export function isEmpty(value: any) {
return isVoid(value) || Object.keys(value).length === 0
}
export function partition(by: By) {
return (props: Props) => {
const match: Props = {}
const rest: Props = {}
Object.keys(props).forEach(key => {
const value = props[key]
if (by(value, key, props)) {
match[key] = value
} else {
rest[key] = value
}
})
return [match, rest]
}
}
export function compact(props: Props) {
return partition(isVoid)(props)[1]
}
export function replace(by: By) {
const _replace = (props: Props, context: Props = props) => {
let result: Props = {}
for (const key in props) {
const parsed = by(props[key], key, context)
const value = typeof parsed === 'undefined' ? props[key] : parsed
result[key] = isObject(value) ? _replace(value, context) : value
}
return result
}
return _replace
}
export function rename(aliases: { [key: string]: string | string[] }) {
const _rename = (props: Props) => {
const renamed: Props = {}
Object.keys(props).forEach(key => {
const value = props[key]
const alias = key in aliases ? aliases[key] : key
const renamedValue = isObject(value) ? _rename(value) : value
if (Array.isArray(alias)) {
alias.forEach(aliasKey => (renamed[aliasKey] = renamedValue))
} else {
renamed[alias] = renamedValue
}
})
return renamed
}
return _rename
}
|
035a2476f1745ec50d210ccc430b115f0c3ed394 | TypeScript | lineCode/regax | /packages/server/src/service/connectionService.ts | 2.75 | 3 | import { values } from '@regax/common'
import { Application } from '../application'
export interface ConnectionLoginInfo {
loginTime: number,
uid: number | string
address: string
}
export interface ConnectionStatisticsInfo {
serverId: string,
loginedCount: number,
totalConnCount: number,
loginedList: ConnectionLoginInfo[]
}
/**
* connection statistics service
* record connection, login count and list
*/
export class ConnectionService {
protected loginedCount = 0 // login count
protected connCount = 0 // connection count
protected logined: { [uid: string]: ConnectionLoginInfo } = {}
constructor(
protected app: Application
) {
}
get totalConnCount(): number {
return this.connCount
}
/**
* Add logined user
* @param uid user id
* @param info record for logined user
*/
addLoginedUser(uid: string | number, info: ConnectionLoginInfo): void {
if (!this.logined[uid]) {
this.loginedCount ++
}
this.logined[uid] = { ...info, uid }
}
/**
* Update user info.
* @param uid user id
* @param info info for update.
*/
updateUserInfo(uid: string | number, info: {}): void {
const user = this.logined[uid]
if (!user) return
this.logined[uid] = { ...user, ...info }
}
/**
* @param uid user id
*/
removeLoginedUser(uid: string | number): void {
if (this.logined[uid]) {
this.loginedCount --
}
delete this.logined[uid]
}
/**
* Increase connection count
*/
increaseConnectionCount(): void {
this.connCount++
}
decreaseConnectionCount(uid?: string | number): void {
if (this.connCount) {
this.connCount --
}
if (uid) {
this.removeLoginedUser(uid)
}
}
/**
* Get statistics info
*/
getStatisticsInfo(): ConnectionStatisticsInfo {
return {
serverId: this.app.serverId,
loginedCount: this.loginedCount,
totalConnCount: this.connCount,
loginedList: values(this.logined)
}
}
}
|
ba3cff60f68918d0c42eac42f3e7ac23e31f6112 | TypeScript | aconfee/tinycrit-api | /src/services/dummy.service.ts | 2.90625 | 3 | import Dummy from './models/dummy.model';
import DummyDao from '../data/dummy.dao';
import Bluebird from 'bluebird'; // Promise library for Sequelize
import Sequelize from 'sequelize';
import _ from 'lodash';
export interface IDummyService {
findDummySql(id: number): any;
};
/**
* Dummy
*/
class DummyService implements IDummyService {
private dummyDao: Sequelize.Model<{}, {}> = null;
constructor(dummyDao: Sequelize.Model<{}, {}>) {
this.dummyDao = dummyDao;
};
/**
* Get a dummy from the posgres RDS instance.
*
* @return {Bluebird<void | Dummy} A promise whos contents is the dummy with the provided id.
*/
public findDummySql = async (id: number): Bluebird<void | Dummy> => {
const dummyRow: any = await this.dummyDao.findById(1)
.catch((e) => { console.error(e); });
if(_.isNull(dummyRow) || _.isUndefined(dummyRow)){
return null;
}
return new Dummy(dummyRow.get('message'));
};
};
export default DummyService; |
f2a7df62176a0280f4c710eb3b40895bac45138b | TypeScript | sl1673495/typescript-codes | /src/getter-type-easy.ts | 3.25 | 3 | interface Option<G> {
getters: {
[K in keyof G]: () => G[K];
};
}
type Store<G extends {}> = {
[K in keyof G]: G[K];
};
const create = <G>(option: Option<G>): Store<G> => {
return {} as any;
};
const store = create({
getters: {
count() {
return 1 + 1;
}
}
});
// number
const count = store.count;
export { count };
|
efae3fc9d52f082643832653897654bebc0e1d92 | TypeScript | calogar/dog-breeds-selector | /src/app/shared/components/selector/selector.component.ts | 2.6875 | 3 | import { Component, OnInit, Input, Output, EventEmitter, SimpleChanges } from '@angular/core';
import { OptionItem } from '../../models/option-item.model';
import { Select2OptionData } from 'ng-select2';
@Component({
selector: 'app-selector',
templateUrl: './selector.component.html',
styleUrls: ['./selector.component.scss']
})
export class SelectorComponent implements OnInit {
// Array of selectable options.
@Input() data: OptionItem[];
//Default value for selector.
@Input() value: string = null;
// Additional configuration.
@Input() config = {};
// Search placeholder.
@Input() placeholder = '';
// If the component is disabled or not.
@Input() disabled = false;
// Outputs the selected values.
@Output() select = new EventEmitter<OptionItem>();
// The options in the native format of the select2.
nativeOptions: Select2OptionData[];
private _configDefaults = {
width: '400px'
};
constructor() { }
ngOnInit(): void {
this.config = { ...this._configDefaults, ...this.config };
}
ngOnChanges(changes: SimpleChanges) {
if (changes.data) {
this.nativeOptions = this._convertOptionsToNative(this.data);
}
}
/**
* Callback for select changes, that will be projected outside the component
* with the "select" event.
*/
onChanged(id: string) {
const selected: OptionItem = this.data.find(item => item.id === id);
this.select.emit(selected);
}
/**
* Converts the options received by the component into options that are understood by the native select2.
* This is done so app-selector can have its own interface, independent of the implementation.
*/
private _convertOptionsToNative(options: OptionItem[]): Select2OptionData[] {
return options.map(item => ({ id: item.id, text: item.name } as Select2OptionData ));
}
} |
0bcd937bfd7ca70cf7c5d1beda6025826c7174db | TypeScript | ComprosoftCEO/TrappedInside | /src/areas/MazeObject.ts | 3.25 | 3 | /// All objects that can be inside the maze
export enum MazeObject {
Empty,
Wall,
Rock,
Energy,
RedDoor,
YellowDoor,
GreenDoor,
BlueDoor,
RedKey,
YellowKey,
GreenKey,
BlueKey,
Battery,
Lever,
ToggleDoor,
InverseToggleDoor,
ADoor,
BDoor,
CDoor,
ABox,
BBox,
CBox,
Drone,
BigDoor,
Portal,
Map,
Gun,
}
/// List of main doors used by the generator
/// Note: Does not include the inverse toggle door, as this requires a special case algorithm
export const ALL_MAIN_DOORS: MazeObject[] = [
MazeObject.RedDoor,
MazeObject.YellowDoor,
MazeObject.GreenDoor,
MazeObject.BlueDoor,
MazeObject.ToggleDoor,
MazeObject.ADoor,
MazeObject.BDoor,
MazeObject.CDoor,
];
/// List of items required to open a door
export interface DoorItems {
oneTimeItem?: MazeObject; // Items used once to open the door
reuseItem?: MazeObject; // Item that is reused to open the door
}
export const DOOR_ITEMS: { [K in MazeObject]?: DoorItems } = {
[MazeObject.RedDoor]: { oneTimeItem: MazeObject.RedKey },
[MazeObject.YellowDoor]: { oneTimeItem: MazeObject.YellowKey },
[MazeObject.GreenDoor]: { oneTimeItem: MazeObject.GreenKey },
[MazeObject.BlueDoor]: { oneTimeItem: MazeObject.BlueKey },
[MazeObject.ToggleDoor]: { reuseItem: MazeObject.Lever },
[MazeObject.ADoor]: { oneTimeItem: MazeObject.Battery, reuseItem: MazeObject.ABox },
[MazeObject.BDoor]: { oneTimeItem: MazeObject.Battery, reuseItem: MazeObject.BBox },
[MazeObject.CDoor]: { oneTimeItem: MazeObject.Battery, reuseItem: MazeObject.CBox },
};
const MAZE_OBJECT_LOOKUP: Record<string, MazeObject> = {
[' ']: MazeObject.Empty,
['#']: MazeObject.Wall,
['@']: MazeObject.Rock,
['*']: MazeObject.Energy,
['R']: MazeObject.RedDoor,
['Y']: MazeObject.YellowDoor,
['G']: MazeObject.GreenDoor,
['L']: MazeObject.BlueDoor,
['r']: MazeObject.RedKey,
['y']: MazeObject.YellowKey,
['g']: MazeObject.GreenKey,
['l']: MazeObject.BlueKey,
[':']: MazeObject.Battery,
['/']: MazeObject.Lever,
['t']: MazeObject.ToggleDoor,
['T']: MazeObject.InverseToggleDoor,
['A']: MazeObject.ADoor,
['B']: MazeObject.BDoor,
['C']: MazeObject.CDoor,
['a']: MazeObject.ABox,
['b']: MazeObject.BBox,
['c']: MazeObject.CBox,
['d']: MazeObject.Drone,
['n']: MazeObject.BigDoor,
['P']: MazeObject.Portal,
['m']: MazeObject.Map,
['%']: MazeObject.Gun,
};
/**
* Map a string to an array of maze objects
*/
export function stringToMaze(input: string): MazeObject[][] {
// Split by newlines
const lines = input.split(/\r?\n/);
// Figure out the longest line
let maxLength = 0;
for (const line of lines) {
maxLength = Math.max(maxLength, line.length);
}
const result: MazeObject[][] = [];
for (const line of lines) {
const mazeRow: MazeObject[] = [];
for (const char of line) {
const lookup = MAZE_OBJECT_LOOKUP[char];
if (typeof lookup === 'undefined') {
mazeRow.push(MazeObject.Empty);
} else {
mazeRow.push(lookup);
}
}
// Make sure all lines are the same length
while (mazeRow.length < maxLength) {
mazeRow.push(MazeObject.Empty);
}
result.push(mazeRow);
}
return result;
}
|
8e815ae725c1c5c1dc44ef14865cd1e1ee8c31e4 | TypeScript | Anastasia811625/ts__part_of_slyzer | /src/store/reducers/usersListReducer.ts | 2.671875 | 3 | import { Actions, ActionType } from "../../types";
import { UserDataType } from "../../components/RegisterForm/RegisterForm";
const InitialState: UserDataType[] = []
export const usersListReducer = (state = InitialState, action: ActionType) => {
switch (action.type) {
case Actions.GET_USERS_LIST:
return action.payload;
default:
return state;
}
};
|
12f64e1c89211da2615beb963c93dc4ebedb0a5c | TypeScript | joefoxman/BD-ICM | /Bd.Icm.Web/app/services/dialog.service.ts | 2.6875 | 3 | module app.services {
export enum DialogResult {
Yes,
No,
Cancel,
Ok
}
export interface IDialogService {
askYesNo(title: string, message: string): ng.IPromise<DialogResult>;
}
class DialogService implements IDialogService {
static $inject = ["$q", "$uibModal"];
constructor(private $q: ng.IQService,
private $modal: angular.ui.bootstrap.IModalService) {
}
askYesNo = (title: string, message: string): ng.IPromise<DialogResult> => {
var deferred = this.$q.defer();
var modalInstance = this.$modal.open({
templateUrl: '/app/dialog/yesNoCancel.view.html',
controller: 'app.dialog.DialogController as vm',
resolve: {
message: () => message,
title: () => title
}
});
modalInstance.result.then((response: DialogResult) => {
deferred.resolve(response);
});
return deferred.promise;
}
}
factory.$inject = ["$q", "$uibModal"];
function factory($q: ng.IQService,
$modal: angular.ui.bootstrap.IModalService): IDialogService {
return new DialogService($q, $modal);
}
angular.module("app.services")
.factory("app.services.DialogService", factory);
} |
85719d7fc73476dfc23e79cec5e5cb5412c1e01f | TypeScript | minjs1cn/js-toolkits | /src/loader/loadCss.ts | 2.515625 | 3 | import { appendChild, createElement, removeChild } from '../dom'
import { isCrossOrigin } from '../env'
export function loadCss (url: string) {
return new Promise((resolve, reject) => {
const linkTag = createElement('link') as HTMLLinkElement
linkTag.rel = 'stylesheet'
linkTag.type = 'text/css'
if (isCrossOrigin(url)) {
linkTag.crossOrigin = 'anonymous'
}
linkTag.addEventListener('load', resolve)
linkTag.addEventListener('error', (err: ErrorEvent) => {
linkTag.removeEventListener('load', resolve)
removeChild(document.head, linkTag)
reject(err)
})
linkTag.href = url
appendChild(document.head, linkTag)
})
}
|
2fd2b67cd3bab59d70f7ba6d3203ecef791abab6 | TypeScript | minhtuan251295/centerManagement | /app/models/ts/KhoaHoc.ts | 2.625 | 3 | export class KhoaHoc{
public MaKhoaHoc: string;
public TenKhoaHoc: string;
public MoTa: string;
public HinhAnh: string;
public LuotXem: number;
public NguoiTao: string;
constructor(maKhoaHoc:string, tenKhoaHoc:string, moTa:string, hinhAnh:string, luotXem:number, nguoiTao:string){
this.MaKhoaHoc = maKhoaHoc;
this.TenKhoaHoc =tenKhoaHoc;
this.MoTa = moTa;
this.HinhAnh = hinhAnh;
this.LuotXem = luotXem;
this.NguoiTao = this.NguoiTao;
}
} |
508f57a037f1c1cb8c06c35f95d41952bbbd4661 | TypeScript | ShepherdDimaloun/o7 | /src/lib/settings.ts | 2.609375 | 3 | import { getClient, collections } from './db';
import config from '../config.json';
interface Settings {
guildId: string;
prefix: string;
disabledCommands: string[];
}
const cache: { [id: string]: Settings; } = {};
export function defaultSettings(guildId: string): Settings {
return {
guildId,
prefix: config.prefix,
disabledCommands: []
}
}
export async function initSettings() {
const client = getClient();
try {
await client.connect();
await client.getDb()
.collection(collections.settings)
.createIndex({ guildId: 1 });
const cursor = await client.getDb()
.collection(collections.settings)
.find<Settings>({});
if (await cursor.count() === 0) {
console.error('No guild settings documents were found!');
}
await cursor.forEach(settings => {
cache[settings.guildId] = settings;
});
} catch (err) {
console.error(`Failed to find any guild settings. ${err}`);
}
}
initSettings();
export async function setPrefix(guildId: string, prefix: string) {
const client = getClient();
try {
await client.connect();
const db = client.getDb();
await db.collection(collections.settings)
.updateOne({ guildId }, { $set: { prefix }});
cache[guildId].prefix = prefix;
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}
export async function reset(guildId: string) {
const client = getClient();
try {
await client.connect();
const db = client.getDb();
await db.collection(collections.settings)
.updateOne({ guildId: guildId }, { $set: defaultSettings(guildId) }, { upsert: true });
cache[guildId] = defaultSettings(guildId);
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}
export async function deleteGuild(guildId: string) {
const client = getClient();
try {
await client.connect();
const db = client.getDb();
await db.collection(collections.settings)
.deleteOne({ guildId });
delete cache[guildId];
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}
export function getSettings(guildId: string) {
if (cache[guildId]) return cache[guildId];
cache[guildId] = defaultSettings(guildId);
return cache[guildId];
}
|
db8a2f7ade9f13ba3d4263b0f723c709a7ce9cf8 | TypeScript | oparaskos/quantity-fns | /src/volume/volume-conversions.ts | 2.765625 | 3 | import { indexMappingTable } from "../lib/index-mapping-table";
import { findConversionFactor as f } from "../lib/factor-convert";
export interface IConversion {
unitNames: string[];
equivelantTo: number;
[additionalProperties: string]: any;
}
// equivelantTo refers to its value in litres
export const metric: IConversion[] = [
{
unitNames: ["Ml", "ML", "megaliter", "megalitre", "megaliters", "megalitres",
"dam^3", "dam3", "decameters cubed", "decametres cubed", "decameter cubed",
"decametre cubed", "cubic decametres", "cubic decameters", "cubic decametre",
"cubic decameter"], equivelantTo: 1e6,
},
{
unitNames: ["kl", "kL", "kiloliter", "kilolitre", "kiloliters", "kilolitres",
"m^3", "m3", "meters cubed", "metres cubed", "meter cubed", "metre cubed",
"cubic metres", "cubic meters", "cubic metre", "cubic meter"], equivelantTo: 1e3,
},
{
unitNames: ["hl", "hL", "hectolitre", "hectolitres", "hectoliter", "hectoliters"],
equivelantTo: 1e2,
},
{
unitNames: ["dal", "daL", "decalitre", "decalitres", "decaliter", "decaliters"],
equivelantTo: 1e1,
},
{
unitNames: ["l", "L", "ℓ", "liter", "litre", "liters", "litres",
"dm3", "dm^3", "decimeters cubed", "decimetres cubed",
"decimeter cubed", "decimetre cubed", "cubic decimetres", "cubic decimeters",
"cubic decimetre", "cubic decimeter"], equivelantTo: 1,
},
{
unitNames: ["dl", "dL", "decilitre", "deciliter", "decilitres", "deciliters"],
equivelantTo: 1e-1,
},
{
unitNames: ["cl", "cL", "centilitre", "centiliter", "centilitres", "centiliters"],
equivelantTo: 1e-2,
},
{
unitNames: ["ml", "mL", "millilitre", "milliliter", "millilitres", "milliliters",
"cc", "ccm",
...cubed("centimeter", "centimeters", "cm"),
...cubed("centimetre", "centimetres", "cm")], equivelantTo: 1e-3,
},
{
unitNames: ["μl", "μL", "microlitre", "microliter", "microlitres", "microliters",
...cubed("millimeter", "millimeters", "mm"),
...cubed("millimetre", "millimetres", "mm")], equivelantTo: 1e-6,
},
];
export const imperial: IConversion[] = [
{ unitNames: cubed("inch", "inches", "in"), equivelantTo: 61.024 },
{ unitNames: cubed("foot", "feet", "ft"), equivelantTo: 28.31685 },
{ unitNames: cubed("yard", "yards", "yd"), equivelantTo: 764.5549},
];
function cubed(unitSingular: string, unitPlural: string, unitShort: string): string[] {
return [
`${unitShort}3`,
`${unitShort}^3`,
`${unitShort} cu`,
`cu ${unitShort}`,
`${unitSingular} cubed`,
`cubic ${unitSingular}`,
`${unitPlural} cubed`,
`cubic ${unitPlural}`,
];
}
export const metricVolumeConversions: { [unit: string]: number; } = indexMappingTable(metric);
export const imperialVolumeConversions: { [unit: string]: number; } = indexMappingTable(imperial);
export const volumeConversions = { ...metricVolumeConversions, ...imperialVolumeConversions };
export const findConversionFactor = f.bind(null, volumeConversions);
|
92b608799e04f297daff85891f73fe545979ad3b | TypeScript | Fiorella2411/AngularEjercicios | /Ejemplos/ejercicios/02-arr-obj-interface.ts | 3.40625 | 3 | let habilidades: string[]=['Bash','Cuuntere', 'Hola']
interface Personaje{
nombre: string,
hp: number,
habilidades: string[],
puebloNatal?:string
}
habilidades.push()
const personaje:Personaje ={
nombre: 'Fiorella',
hp: 100,
habilidades: ['hila','cjcjh']
}
personaje.puebloNatal ='Cusco'
console.table(personaje) |
fe86727deb6f2fd467b810f81f9bb67d67576a91 | TypeScript | dilmanous/coding-challenge-backend-c | /repositories/cityRepository.ts | 2.78125 | 3 | import { IRepository } from "./IRepository";
import { City } from "../models/city.model";
import * as fs from "fs";
const DATA_FILE_NAME = "cities_canada-usa.tsv";
export class CityRepository implements IRepository<City> {
getAll() {
return fs
.readFileSync(`./data/${DATA_FILE_NAME}`, "utf8")
.split("\n")
.map(this.parseCity);
}
private parseCity(cityJson: string): City {
const columnValus = cityJson.split("\t");
if (columnValus.length !== 19)
throw new Error(
`A city row in the file ${DATA_FILE_NAME} has an invalid number of columns.`
);
return {
id: +columnValus[0],
name: columnValus[1],
ascii: columnValus[2],
alt_name: columnValus[3],
lat: +columnValus[4],
long: +columnValus[5],
feat_class: columnValus[6],
feat_code: columnValus[7],
country: columnValus[8],
cc2: columnValus[9],
admin1: columnValus[10],
admin2: columnValus[11],
admin3: columnValus[12],
admin4: columnValus[13],
population: +columnValus[14],
elevation: +columnValus[15],
dem: columnValus[16],
tz: columnValus[17],
modified_at: new Date(columnValus[18])
};
}
}
|
391e694324a054c8d3f192f41888c295df2c3c4d | TypeScript | 2018-B-GR1-AplicacionesWeb/examen-cargua-ronald | /2018-b-prueba-master/data/CorreccioExamen.ts | 2.78125 | 3 |
declare var require;
const fs = require('fs');
const rxjs = require('rxjs');
const inquirer = require('inquirer');
const map = require('rxjs/operators').map;
const distinct = require('rxjs/operators').distinct;
function buscarTipos(propiedad:string, arreglo:Character[]) {
const arregloRepetido = arreglo.map((caracter)=>{
return caracter[propiedad]
});
rxjs.of(arregloRepetido).pipe(
distinct()
)
}
function clasificar (propiedad:string, arregloPropiedades:string[],arreglo:Character[]){
const respuesta = [];
arregloPropiedades.forEach((prop)=>{
const arregloFiltrado =arreglo.filter((caracter)=>{
return caracter[propiedad] === prop
})
respuesta.push(arregloFiltrado)
})
return respuesta
}
buscarTipos('gender',arreglo).pipe(
map((arregloRepetidos)=>{
return clasificar('gender',arregloRepetidos,arregl)
})
);
const arregloAbecedario = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
];
function buscarPorAbecedario(arregloAbecedario:string[],arreglo){
return arregloAbecedario.map(
(letra)=>{
const object ={};
object[letra] = arreglo.some((caracter)=>{
return caracter.name.slice(0,1)
})
}
)
}
interface Character {
"name": string,
"height": string,
"mass": string,
"hair_color": string,
"skin_color": string,
"eye_color": string,
"birth_year": string,
"gender": string,
"homeworld": string,
"films": string [],
"species": string [],
"vehicles": string [],
"starships":string [],
"created": Date | string | any,
"edited": string | string |any
"url": string
} |
25755e5f81827490c456903e4f56b3ac382484a0 | TypeScript | findawayer/kineto | /src/helpers/elements/creation.ts | 2.96875 | 3 | import type { UnknownObject } from 'typings';
import { setAttributes } from './attributes';
/**
* Create a new HTMLElement with attributes passed.
*
* @param nodeName - The name of element to be created.
* @param attributes - Initial attributes that the new element should have.
*/
export function createElement<T extends HTMLElement>(
nodeName: string,
attributes?: UnknownObject,
): T {
const element = document.createElement(nodeName);
if (attributes) setAttributes(element, attributes);
return element as T;
}
/**
* Create a new SVGElement with attributes passed.
*
* @param nodeName - The name of element to be created.
* @param attributes - Initial attributes that the new element should have.
*/
export function createSVGElement(
nodeName: string,
attributes?: UnknownObject,
): SVGElement {
const namespace = 'http://www.w3.org/2000/svg';
const element = document.createElementNS(namespace, nodeName);
if (attributes) setAttributes(element, attributes);
return element;
}
|
0e1d2a660592731dcd848b7131de7db98f4dc5ff | TypeScript | djkloop666/appic-cli | /src/cli/creator/Creator.ts | 2.578125 | 3 | // import * as inquirer from 'inquirer'
import * as EventEmitter from 'events'
import { clearConsole } from '../../util/clearConsole'
import { loadOptions, defaults } from './options'
import { formatFeatures } from '../../util/features'
interface CreatorInterFace {
name?: string
targetDir?: string
create (opts: any, preset: any): void
run (command: string, args: any): string
}
const log = console.log
const isManualMode = (answers: any) => answers.preset === '__manual__'
export default class Creator extends EventEmitter implements CreatorInterFace {
name?: string
ctx?: string
injectedPrompts?: [] | undefined | any
presetPrompt?: [] | any
outroPrompts?: [] | any
featurePrompt?: []
constructor (name: string, targetDir: string) {
super()
this.name = name
this.ctx = targetDir
this.run = this.run.bind(this)
const { presetPrompt, featurePrompt } = this.resolveIntroPrompts()
this.injectedPrompts = featurePrompt
this.presetPrompt = presetPrompt
this.outroPrompts = []
this.featurePrompt = []
}
// 构建开始
async create (opts: any = {}, preset: any = null) {
const { run, ctx, name } = this
log(name, run, ctx, preset, 'create')
if (!preset) {
if (opts.preset) {
log('ops')
} else if (opts.default) {
log('opts')
} else {
preset = await this.promptAndResolvePreset()
}
}
}
async promptAndResolvePreset (answers: any = null) {
if (!answers) {
// clearConsole(true)
log(this.resolveFinalPrompts())
// answers = await inquirer.prompt(this.resolveFinalPrompts())
}
}
getPresets () {
const savedOptions = loadOptions()
return Object.assign({}, savedOptions.presets, defaults.presets)
}
resolveIntroPrompts () {
const presets = this.getPresets()
log(presets, ' resolveIntroPrompts')
const presetChoices = Object.keys(presets).map(name => {
return {
name: `${name} (${formatFeatures(presets[name])})`,
value: name
}
})
const presetPrompt = {
name: 'preset',
type: 'list',
message: `Please pick a preset:`,
choices: [
...presetChoices,
{
name: 'Manually select features',
value: '__manual__'
}
]
}
const featurePrompt = {
name: 'features',
when: isManualMode,
type: 'checkbox',
message: 'Check the features needed for your project:',
choices: [],
pageSize: 10
}
return {
presetPrompt,
featurePrompt
}
}
resolveFinalPrompts () {
// patch generator-injected prompts to only show in manual mode
this.injectedPrompts.forEach((prompt: any) => {
const originalWhen = prompt.when || (() => true)
prompt.when = (answers: any) => {
return isManualMode(answers) && originalWhen(answers)
}
})
const prompts = [
this.presetPrompt,
this.featurePrompt,
...this.injectedPrompts,
...this.outroPrompts
]
return prompts
}
run (command: string, args: any) {
if (!args) { [command, ...args] = command.split(/\s+/) }
return ''
}
}
|
1ae8eb454dc4f4933be18d671c83b8b7ee0dcf16 | TypeScript | pjmolina/typescript-dotnetmalaga-2016 | /examples/v2.0/unions.ts | 4.46875 | 4 | interface VisibilityItem {
isVisible: boolean;
}
// Intersection type must be both
function doNothing(notification: MyNotification & VisibilityItem) {
// You don't need a new name, but instances must match both types
}
// Union types can be any
function hide(items: VisibilityItem | VisibilityItem[]): void {
// Main problem of union types is naming
// so let's shortcut soon
if (!Array.isArray(items)) {
hide([items]);
} else {
// Control flow based type analysis: `items` is array here.
for (let item of items) {
item.isVisible = false;
}
}
}
// Example from https://www.typescriptlang.org/docs/handbook/advanced-types.html
interface Bird {
// String literal types: they are string, but only allow one value.
// Can be used to discriminate
type: "bird";
fly(): void;
layEggs(): void;
}
interface Fish {
type: "fish";
swim(): void;
layEggs(): void;
}
// Type aliases
type Pet = Bird | Fish;
// Custom type guard
function isFish(pet: Pet): pet is Fish {
const fish = pet as Fish;
// Presence of the swim method is a type marker
return Boolean(fish.swim);
}
function play(pet: Pet): void {
if (isFish(pet)) {
// Control flow based type analysis in all its glory
pet.swim();
} else {
pet.fly();
}
}
// Type narrowing!
// It can also be achieved with typeof (primitives) or instanceof (classes)
// We can use literal types as markers too
function playSwitch(pet: Pet): void {
switch (pet.type) {
case "fish":
return pet.swim();
case "bird":
return pet.fly();
}
}
// Funny literal types
type Falsy = "" | 0 | false | null | undefined; |
2150ee60d18e5e81d036a4610cfa1e50551b38d8 | TypeScript | rt2zz/redux-persist | /tests/complete.spec.ts | 2.703125 | 3 | import test from 'ava'
import { combineReducers, createStore } from 'redux'
import persistReducer from '../src/persistReducer'
import persistStore from '../src/persistStore'
import createMemoryStorage from './utils/createMemoryStorage'
import brokenStorage from './utils/brokenStorage'
const reducer = () => ({})
const config = {
key: 'persist-reducer-test',
version: 1,
storage: createMemoryStorage(),
debug: true,
timeout: 5,
}
test('multiple persistReducers work together', t => {
return new Promise((resolve) => {
const r1 = persistReducer(config, reducer)
const r2 = persistReducer(config, reducer)
const rootReducer = combineReducers({ r1, r2 })
const store = createStore(rootReducer)
const persistor = persistStore(store, {}, () => {
t.is(persistor.getState().bootstrapped, true)
resolve()
})
})
})
test('persistStore timeout 0 never bootstraps', t => {
return new Promise((resolve, reject) => {
const r1 = persistReducer({...config, storage: brokenStorage, timeout: 0}, reducer)
const rootReducer = combineReducers({ r1 })
const store = createStore(rootReducer)
const persistor = persistStore(store, undefined, () => {
console.log('resolve')
reject()
})
setTimeout(() => {
t.is(persistor.getState().bootstrapped, false)
resolve()
}, 10)
})
})
test('persistStore timeout forces bootstrap', t => {
return new Promise((resolve, reject) => {
const r1 = persistReducer({...config, storage: brokenStorage}, reducer)
const rootReducer = combineReducers({ r1 })
const store = createStore(rootReducer)
const persistor = persistStore(store, undefined, () => {
t.is(persistor.getState().bootstrapped, true)
resolve()
})
setTimeout(() => {
reject()
}, 10)
})
})
|
16164077d61a0770d550b4c5d4fc846f5808e867 | TypeScript | fatho/photo-archive | /websrc/routing/HashRouter.ts | 3.15625 | 3 | export class HashRouter {
private routes: Array<Route>;
constructor() {
this.routes = new Array();
window.addEventListener('hashchange', (ev: HashChangeEvent) => {
this.route()
});
}
/// Return whether there is an explicit route set.
hasRoute(): boolean {
return window.location.hash.length > 0;
}
navigate(path: string[], replace: boolean = false) {
if(replace) {
window.location.replace(`#${path.join('/')}`);
} else {
window.location.hash = path.join('/');
}
}
/// Set the current path in the history without doing a navigation action.
replaceHistoryEntry(path: string[]) {
window.history.replaceState(null, '', `#${path.join('/')}`);
}
/// Apply the routing logic to the currently set path.
route() {
let hash = window.location.hash;
if(hash.startsWith('#')) {
hash = hash.substring(1);
}
let path: string[] = hash.split('/')
console.log("Routing: %s", path);
for(let i = 0; i < this.routes.length; i++) {
let args = this.routes[i].match(path);
if (args != null) {
this.routes[i].call(args);
return;
}
}
throw new Error('No route');
}
addRoute(pattern: Array<string | RouteParam>, handler: (...args: any[]) => void) {
this.routes.push(new Route(pattern, handler));
}
}
export class Route {
private handler: (...args: any[]) => void;
private pattern: Array<string | RouteParam>;
constructor(pattern: Array<string | RouteParam>, handler: (...args: any[]) => void) {
this.pattern = pattern;
this.handler = handler;
}
match(path: string[]): Array<any> | null {
if (path.length != this.pattern.length) {
return null;
}
let parsedArgs = new Array();
for(let i = 0; i < path.length; i++) {
let patternComponent = this.pattern[i];
let pathComponent = path[i];
if (typeof patternComponent == 'string') {
if (patternComponent != pathComponent) {
return null;
}
} else if (patternComponent instanceof RouteParam) {
let arg = patternComponent.parse(pathComponent);
if (arg == null) {
return null;
} else {
parsedArgs.push(arg);
}
}
}
return parsedArgs;
}
call(args: any[]) {
this.handler(...args);
}
}
export class RouteParam {
private validator: RegExp;
private parser: (value: string) => any;
constructor(validator: RegExp, parser: (value: string) => any) {
this.validator = validator;
this.parser = parser;
}
parse(value: string): any | null {
if (! this.validator.test(value)) {
return null;
}
return this.parser(value);
}
static int(): RouteParam {
return new RouteParam(/^-?[0-9]+$/, (value) => parseInt(value, 10))
}
}
|
1101ef79d535c069c83695a61ffb02f4b3805662 | TypeScript | majoravery/head-first-design-patterns-typescript | /2-observer-weather-station/src/classes/WeatherData.ts | 3.109375 | 3 | import { Subject } from './../interfaces/Subject';
import { Observer } from './../interfaces/Observer';
export class WeatherData implements Subject {
private observers: Observer[];
private temperature!: number;
private humidity!: number;
private pressure!: number;
constructor() {
this.observers = [];
this.setMeasurements(27, 15, 5.4); // hardcoded for testing purposes
}
public registerObserver(observer: Observer): void {
this.observers.push(observer);
}
public removeObserver(observer: Observer): void {
this.observers.splice(this.observers.indexOf(observer), 1);
}
public notifyObservers(): void {
this.observers.forEach((observer: Observer) => {
observer.update();
});
}
public getTemperature(): number {
return this.temperature;
}
public getHumidity(): number {
return this.humidity;
}
public getPressure(): number {
return this.pressure;
}
public setMeasurements(
temperature: number,
humidity: number,
pressure: number
): void {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
this.measurementsChanged();
}
public measurementsChanged(): void {
this.notifyObservers();
}
}
|
4b6a58204ed820af8f40ff9edc580d5e04d8b2ac | TypeScript | ornitorrincos/qub | /src/math/utils.ts | 2.90625 | 3 | import { Vec3 } from "./vec3";
export function mix (start: number, finish: number, t: number): number {
return (1 - t) * start + t * finish;
}
export function randomInUnitSphere (): Vec3 {
let p: Vec3 = new Vec3();
do {
p = Vec3.sub(Vec3.smul(new Vec3(Math.random(), Math.random(), Math.random()), 2), new Vec3(1, 1, 1));
} while (p.length2() >= 1);
return p;
}
|
ff15710645c2c57824a4eeff1b064734a357e153 | TypeScript | Hypercubed/ifecs | /utils/regexp.ts | 2.921875 | 3 | const tokenMatcher = /(\\[^])|\[\-|[-()|\[\]]/g; // eslint-disable-line no-useless-escape
/**
* Determines if a regex source has a top level alternation
* from https://github.com/pygy/compose-regexp.js/blob/master/compose-regexp.js
*/
export function hasTopLevelChoice(source: string) {
if (source.indexOf("|") === -1) return false;
let depth = 0;
let inCharSet = false;
let match;
tokenMatcher.lastIndex = 0;
while ((match = tokenMatcher.exec(source))) {
if (match[1] != null) continue;
if (!inCharSet && match[0] === "(") depth++;
if (!inCharSet && match[0] === ")") depth--;
if (!inCharSet && (match[0] === "[" || match[0] === "[-")) inCharSet = true;
if (inCharSet && match[0] === "]") inCharSet = false;
if (depth === 0 && !inCharSet && match[0] === "|") return true;
}
return false;
}
|
2bb8d4523c6d157014741e743b1e4b837ffab3ca | TypeScript | JasminBektic/express-typescript-mongoose-starter | /app/middleware/RedirectIfAuthenticated.ts | 2.515625 | 3 | import { Request, Response, NextFunction } from "express";
import { Middleware } from "../middleware/Middleware";
class RedirectIfAuthenticated extends Middleware {
/**
* Logged user redirection
* @param req
* @param res
* @param next
*/
public handle(req: Request, res: Response, next: NextFunction): void {
if (!req.isAuthenticated()) {
return res.redirect('/login');
}
next();
}
}
export default new RedirectIfAuthenticated; |
0af3ec4e6ccbd4ed86e73a36f1eb03998e585c58 | TypeScript | momentechnologies/Metics | /sourcecode/api/src/exceptions/unauthorized.ts | 2.71875 | 3 | import ApiException, { errorResponse } from './apiException';
export const unauthorizedTypes = {
NO_ACCESS: 1,
NOT_LOGGED_IN: 2,
};
const uidMessages = {
[unauthorizedTypes.NO_ACCESS]: 'You do not have access to this resource',
[unauthorizedTypes.NOT_LOGGED_IN]: 'You are not logged in',
};
export default class Unauthorized extends ApiException {
uid;
constructor(message, uid = unauthorizedTypes.NO_ACCESS) {
super(message);
this.uid = uid;
this.shouldReport = false;
}
getStatus() {
return 401;
}
getBody() {
return errorResponse(this.message, 'unauthorized', {
uid: this.uid,
uidMessage: uidMessages[this.uid],
});
}
}
|
a4db065961d4579ba6dcf1803ad7c20c69756c7d | TypeScript | coding-with-binaries/chronos | /chronos-client/src/app/hooks/useClock.ts | 2.703125 | 3 | import { useEffect, useState } from 'react';
import { calculateTimeInTimeZone } from '../utils/time-utils';
export const useClock = (differenceFromGmt: string) => {
const initialTime = calculateTimeInTimeZone(differenceFromGmt);
const [time, setTime] = useState(initialTime);
useEffect(() => {
const id = setInterval(() => {
setTime(() => calculateTimeInTimeZone(differenceFromGmt));
}, 1000);
return () => clearInterval(id);
}, [differenceFromGmt]);
return time;
};
|
14384f065af59af845ef8167f10c9ce4b971cbd7 | TypeScript | Typescript-TDD/ts-auto-mock | /src/extension/method/provider/provider.ts | 2.875 | 3 | import { functionMethod } from './functionMethod';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Method = (name: string, value: any) => () => any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type MethodWithDeferredValue = (name: string, value: () => any) => () => any;
export class Provider {
private _method: Method;
private _isUsingDeprecatedProvideMethod: boolean;
private constructor() {
this._isUsingDeprecatedProvideMethod = false;
}
private static _instance: Provider;
public static get instance(): Provider {
this._instance = this._instance || new Provider();
return this._instance;
}
/**
* @deprecated ts-auto-mock will disable this functionality from version 2 because is not fully compatible with
* call signatures. It will cause an maximum call stack exceeded error.
* @see (https://github.com/Typescript-TDD/ts-auto-mock/blob/master/test/frameworkContext/recursive/recursive.test.deprecated.ts)
*
* Please use provideMethodWithDeferredValue instead
*
* @see [Extension](https://typescript-tdd.github.io/ts-auto-mock/extension)
*/
public provideMethod(method: Method): void {
this._isUsingDeprecatedProvideMethod = true;
this._method = method;
}
public provideMethodWithDeferredValue(method: MethodWithDeferredValue): void {
this._method = method;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public getMethod(name: string, value: () => any): Method {
this._method = this._method || functionMethod;
if (this._isUsingDeprecatedProvideMethod) {
return this._method(name, value());
}
return this._method(name, value);
}
}
|
142cf6386a3d25f0af1a7ef6afc3d809dedafe0f | TypeScript | nonsense9/TypeScriptVideoLessons | /Lesson2.ts | 3.125 | 3 | let numArray1: number[] = [1, 2 ,3];
let numArray2: Array <number> = [1, 2, 3];
let strArray1: string[] = ['1', '2', '3'];
let strArray2: Array <string> = ['1', '2', '3'];
let boolArray1: boolean[] = [true, false];
let boolArray2: Array <boolean> = [true, false];
//tuples
let array: [number, number, string] = [1, 2, '3'];
let array2: [boolean, string, number] = [true, 'str', 22];
//Incorrect version below
let array3: Array<number, string> = [1, 's']; |
fbc441bd21b315915114fcc334efb6d4d28cbfdf | TypeScript | arnaspuidokas6/Gif-Party | /src/api/types.ts | 2.609375 | 3 | export interface FetchGifsRequest {
query?: string;
limit?: string;
}
// https://developers.giphy.com/docs/api/schema/#image-object
export interface IGifResponse {
imageUrl: string;
title: string;
userImage?: string;
importedAt?: string;
displayName?: string;
}
interface IUrl {
url: string;
}
interface IImage {
fixed_height: IUrl;
}
interface IUser {
avatar_url?: string;
display_name?: string;
}
// https://developers.giphy.com/docs/api/schema/#gif-object
export interface IGif {
title?: string;
images?: IImage;
user?: IUser;
import_datetime?: string;
}
|
f74c248bceb4c0e2fb3ce2e2cec0de64d71c7da2 | TypeScript | jaapster/map-workbench | /src/utils/util-get selected-vertices.ts | 2.609375 | 3 | import { POINT } from '../constants';
import {
Co,
SelectionVector,
FeatureCollection } from '../types';
export const getSelectedVertices = (
{ features }: FeatureCollection,
selection: SelectionVector[]
): Co[] => (
selection.reduce((m, [_i, _j, _k, _l]) => (
_i == null
? m
: _j == null
? features[_i].properties.type === POINT
? m.concat([features[_i].geometry.coordinates])
: m
: m.concat([
_k == null
? features[_i].geometry.coordinates[_j]
: _l == null
? features[_i].geometry.coordinates[_j][_k]
: features[_i].geometry.coordinates[_j][_k][_l]
])
), [] as Co[])
);
|
76df8b4342eb77b84cb0500de8f22f946a997eba | TypeScript | Valentin945/helloReact | /progress/client/test.ts | 3.09375 | 3 | class speak {
public static hello(person: string): string {
return "Hello, " + person + ".";
}
}
var user = "World";
console.log(speak.hello(user)); |
a193c96a0f64e79e6706f3ce422baa43d3bd8ace | TypeScript | guitarooman14/todoApp | /src/app/render/animations/animations.ts | 2.53125 | 3 | import {animate, state, style, transition, trigger} from '@angular/animations';
export const visibilityChangedTransition =
trigger('visibilityChanged', [
state('true', style({ opacity: 1 })),
state('false', style({ opacity: 0 })),
transition('1 => 0', animate('300ms')),
transition('0 => 1', animate('900ms'))
]);
export const fadeInAnimation =
// the fade-in/fade-out animation.
trigger('fadeInAnimation', [
// the "in" style determines the "resting" state of the element when it is visible.
state('in', style({ opacity: 1 })),
// fade in when created. this could also be written as transition('void => *')
transition(':enter', [
style({ opacity: 0 }),
animate(600)
]),
// fade out when destroyed. this could also be written as transition('void => *')
transition(':leave',
animate(0, style({ opacity: 0 })))
]);
|
4422f8d70069039c7647beacb441f5ecf4fe0fab | TypeScript | alibail/editor.js | /src/components/modules/renderer.ts | 2.59375 | 3 | import Module from '../__module';
import * as _ from '../utils';
import {ChainData} from '../utils';
import {BlockToolData} from '../../../types';
import {BlockToolConstructable} from '../../../types/tools';
/**
* Editor.js Renderer Module
*
* @module Renderer
* @author CodeX Team
*
* @version 2.0.0
*/
export default class Renderer extends Module {
/**
* @typedef {Object} RendererBlocks
* @property {String} type - tool name
* @property {Object} data - tool data
*/
/**
* @example
*
* blocks: [
* {
* type : 'paragraph',
* data : {
* text : 'Hello from Codex!'
* }
* },
* {
* type : 'paragraph',
* data : {
* text : 'Leave feedback if you like it!'
* }
* },
* ]
*
*/
/**
* Make plugin blocks from array of plugin`s data
* @param {RendererBlocks[]} blocks
*/
public async render(blocks: BlockToolData[]): Promise<void> {
const chainData = blocks.map((block) => ({function: () => this.insertBlock(block)}));
const sequence = await _.sequence(chainData as ChainData[]);
this.Editor.UI.checkEmptiness();
return sequence;
}
/**
* Get plugin instance
* Add plugin instance to BlockManager
* Insert block to working zone
*
* @param {Object} item
* @returns {Promise<void>}
* @private
*/
public async insertBlock(item): Promise<void> {
const { Tools, BlockManager } = this.Editor;
const tool = item.type;
const data = item.data;
const settings = item.settings;
const metadata = item.metadata;
if (tool in Tools.available) {
try {
BlockManager.insert(tool, data, settings, metadata);
} catch (error) {
_.log(`Block «${tool}» skipped because of plugins error`, 'warn', data);
throw Error(error);
}
} else {
/** If Tool is unavailable, create stub Block for it */
const stubData = {
savedData: {
type: tool,
data,
},
title: tool,
};
if (tool in Tools.unavailable) {
const toolToolboxSettings = (Tools.unavailable[tool] as BlockToolConstructable).toolbox;
const userToolboxSettings = Tools.getToolSettings(tool).toolbox;
stubData.title = toolToolboxSettings.title || userToolboxSettings.title || stubData.title;
}
const stub = BlockManager.insert(Tools.stubTool, stubData, settings, metadata);
stub.stretched = true;
_.log(`Tool «${tool}» is not found. Check 'tools' property at your initial Editor.js config.`, 'warn');
}
}
}
|
c11e17d99b7079815d6c6f77a5be8fb95fd433bf | TypeScript | foysavas/polkadot-js-tools | /packages/metadata-cmp/src/compare.ts | 2.5625 | 3 | // Copyright 2018-2021 @polkadot/metadata-cmp authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { RuntimeVersion } from '@polkadot/types/interfaces';
import yargs from 'yargs';
import { ApiPromise, WsProvider } from '@polkadot/api';
import { expandMetadata, Metadata } from '@polkadot/types';
import { assert, stringCamelCase } from '@polkadot/util';
type ArgV = { _: [string, string] };
const [ws1, ws2] = (yargs.demandCommand(2).argv as unknown as ArgV)._;
function chunk (array: string[], size: number): string[][] {
const chunked = [];
const copied = [...array];
const numOfChild = Math.ceil(copied.length / size);
for (let i = 0; i < numOfChild; i++) {
chunked.push(copied.splice(0, size));
}
return chunked;
}
function log (pad: number, title: string, pre: string, text: string, post?: string) {
console.log(createLog(pad, title, pre, text, post));
}
function createLog (pad: number, title: string, pre: string, text: string, post?: string): string {
const titleStr = pad > 0 ? (title ? `[${title}]` : '') : title;
return `${titleStr.padStart(pad)}${pre ? ` ${pre}` : ''} ${text}${post ? ` (${post})` : ''}`;
}
function createCompare (a: string | number = '-', b: string | number = '-'): string {
return `${a === b ? a : `${a} -> ${b}`}`;
}
function logArray (pad: number, title: string, pre: string, arr: string[], chunkSize: number) {
if (arr.length) {
let first = true;
for (const ch of chunk(arr, chunkSize)) {
console.log(createLog(pad, first ? title : '', first ? pre : '', ch.join(', ')));
first = false;
}
}
}
async function getMetadata (url: string): Promise<[Metadata, RuntimeVersion]> {
assert(url.startsWith('ws://') || url.startsWith('wss://'), `Invalid WebSocket endpoint ${url}, expected ws:// or wss://`);
const provider = new WsProvider(url);
const api = await ApiPromise.create({ provider });
provider.on('error', () => process.exit());
return Promise.all([api.rpc.state.getMetadata(), api.rpc.state.getRuntimeVersion()]);
}
// our main entry point - from here we call out
async function main (): Promise<number> {
const [metaA, verA] = await getMetadata(ws1);
const [metaB, verB] = await getMetadata(ws2);
const a = metaA.asLatest;
const b = metaB.asLatest;
// configure padding
const lvlInc = 14;
const deltaInc = 4;
const lvl1 = 20;
const lvl2 = lvl1 + lvlInc;
const lvl3 = lvl1 + 2 * lvlInc;
const lvl5 = lvl1 + 4 * lvlInc;
const chunkSize = 5;
log(lvl1, 'Spec', 'version:', createCompare(verA.specVersion.toNumber(), verB.specVersion.toNumber()));
log(lvl1, 'Metadata', 'version:', createCompare(metaA.version, metaB.version));
const mA = a.modules.map(({ name }) => name.toString());
const mB = b.modules.map(({ name }) => name.toString());
log(lvl1, 'Modules', 'num:', createCompare(mA.length, mB.length));
const mAdd = mB.filter((m) => !mA.includes(m));
const mDel = mA.filter((m) => !mB.includes(m));
logArray(lvl1 + deltaInc, '+', 'modules:', mAdd, chunkSize);
logArray(lvl1 + deltaInc, '-', 'modules:', mDel, chunkSize);
console.log();
const decA = expandMetadata(metaA.registry, metaA);
const decB = expandMetadata(metaB.registry, metaB);
mA
.filter((m) => mB.includes(m))
.forEach((m): void => {
const n = stringCamelCase(m);
const eA = Object.keys(decA.tx[n] || {});
const eB = Object.keys(decB.tx[n] || {});
if (eA.length === eB.length && eA.length === 0) {
return;
}
const sA = Object.keys(decA.query[n] || {});
const sB = Object.keys(decB.query[n] || {});
if (sA.length === sB.length && sA.length === 0) {
return;
}
const count = createCompare(eA.length, eB.length);
const storage = createCompare(sA.length, sB.length);
const post = `calls: ${count}, storage: ${storage}`;
const index = createCompare(decA.tx[n][eA[0]]?.callIndex[0], decB.tx[n][eB[0]]?.callIndex[0]);
log(lvl2, m, 'idx:', index, post);
const eAdd = eB.filter((e) => !eA.includes(e));
const eDel = eA.filter((e) => !eB.includes(e));
logArray(lvl2 + deltaInc, '+', 'calls:', eAdd, chunkSize);
logArray(lvl2 + deltaInc, '-', 'calls:', eDel, chunkSize);
eA
.filter((c) => eB.includes(c))
.forEach((c): void => {
const cA = decA.tx[n][c];
const cB = decB.tx[n][c];
const tA = cA.meta.args.map(({ type }) => type.toString());
const tB = cB.meta.args.map(({ type }) => type.toString());
const typeDiff = tA.length !== tB.length || tA.some((t, index) => tB[index] !== t);
if (cA.callIndex[1] !== cB.callIndex[1] || typeDiff) {
const params = `args: ${createCompare(tA.length, tB.length)}`;
log(lvl3, c, 'idx:', createCompare(cA.callIndex[1], cB.callIndex[1]), params);
const signature = createCompare(`(${tA.join(', ')})`, `(${tB.join(', ')})`);
if (signature !== '()') {
log(lvl3, '', '', signature);
}
}
});
const sAdd = sB.filter((e) => !sA.includes(e));
const sDel = sA.filter((e) => !sB.includes(e));
logArray(lvl2 + deltaInc, '+', 'storage:', sAdd, 5);
logArray(lvl2 + deltaInc, '-', 'storage:', sDel, 5);
sA
.filter((c) => sB.includes(c))
.forEach((c): void => {
const cA = decA.query[n][c];
const cB = decB.query[n][c];
// storage types differ
if (!cA.meta.type.eq(cB.meta.type)) {
if (cA.meta.type.isMap && cB.meta.type.isMap) {
// diff map
const mapA = cA.meta.type.asMap;
const mapB = cB.meta.type.asMap;
const diffs = [];
if (!mapA.hasher.eq(mapB.hasher)) {
diffs.push(`hasher: ${createCompare(mapA.hasher.toString(), mapB.hasher.toString())}`);
}
if (!mapA.key.eq(mapB.key)) {
diffs.push(`key: ${createCompare(mapA.key.toString(), mapB.key.toString())}`);
}
if (!mapA.value.eq(mapB.value)) {
diffs.push(`value: ${createCompare(mapA.value.toString(), mapB.value.toString())}`);
}
logArray(lvl3, c, '', diffs, 1);
} else if (cA.meta.type.isDoubleMap && cB.meta.type.isDoubleMap) {
// diff double map
const mapA = cA.meta.type.asDoubleMap;
const mapB = cB.meta.type.asDoubleMap;
const diffs = [];
if (!mapA.hasher.eq(mapB.hasher)) {
diffs.push(`hasher: ${createCompare(mapA.hasher.toString(), mapB.hasher.toString())}`);
}
if (!mapA.key1.eq(mapB.key1)) {
diffs.push(`key1: ${createCompare(mapA.key1.toString(), mapB.key1.toString())}`);
}
if (!mapA.key2Hasher.eq(mapB.key2Hasher)) {
diffs.push(`key2Hasher: ${createCompare(mapA.key2Hasher.toString(), mapB.key2Hasher.toString())}`);
}
if (!mapA.key2.eq(mapB.key2)) {
diffs.push(`key2: ${createCompare(mapA.key2.toString(), mapB.key2.toString())}`);
}
if (!mapA.value.eq(mapB.value)) {
diffs.push(`value: ${createCompare(mapA.value.toString(), mapB.value.toString())}`);
}
logArray(lvl3, c, '', diffs, 1);
} else if (cA.meta.type.isPlain && cB.meta.type.isPlain) {
// diff plain type
const tA = cA.meta.type.asPlain;
const tB = cB.meta.type.asPlain;
log(lvl3, c, 'type:', createCompare(tA.toString(), tB.toString()));
} else {
// fallback diff if types are completely different
log(lvl3, c, '', cA.meta.type.toString());
log(lvl5, '', '', '->');
log(lvl3, '', '', cB.meta.type.toString());
}
}
});
console.log();
});
return 0;
}
process.on('unhandledRejection', (error): void => {
console.error(error);
process.exit(1);
});
main()
.then((code) => process.exit(code))
.catch((error): void => {
console.error(error);
process.exit(1);
});
|
199a68b0884b5aec9d351370964cfa50cbf94cf3 | TypeScript | spinajs/http | /src/route-args/FromParams.ts | 2.796875 | 3 | import { RouteArgs } from "./RouteArgs";
import { IRouteParameter, ParameterType, IRouteCall } from "../interfaces";
import * as express from 'express';
import { Injectable } from "@spinajs/di";
@Injectable(RouteArgs)
export class FromParams extends RouteArgs {
public get SupportedType(): ParameterType {
return ParameterType.FromParams;
}
public async extract(callData: IRouteCall, param: IRouteParameter, req: express.Request) {
const arg = req.params[param.Name];
let result = null;
const [hydrated, hValue] = await this.tryHydrate(result, param);
if (hydrated) {
result = hValue;
}
else {
switch (param.RuntimeType.name) {
// query params are always sent as strings, even numbers,
// we must try to parse them as integers / booleans / objects
case "String": result = String(arg); break;
case "Number": result = Number(arg); break;
case "Boolean": result = (arg.toLowerCase() === "true") ? true : false; break;
case "Object": result = JSON.parse(arg); break;
default: result = new param.RuntimeType(JSON.parse(arg)); break;
}
}
return { CallData: callData, Args: result };
}
} |
9027c2d06bfb337e029b473d664f0a238161da6b | TypeScript | Scrum/git-update-repos-labels | /index.ts | 2.59375 | 3 | import graphqlGot = require('graphql-got');
interface options {
label: label,
token: string
}
interface label {
id: string,
name: string,
color: string,
description: string
}
export default ({label: {id, name, color, description}, token}: options) => {
description = description === null || description === undefined ? '' : description;
return graphqlGot('https://api.github.com/graphql', {
query: `mutation {
updateLabel(input: {id: "${id}", name: "${name}", color: "${color}", description: "${description}"}) {
label {
id
name
color
description
}
}
}`,
headers: {
'accept': 'application/vnd.github.bane-preview+json'
},
token
}).then(({body: {updateLabel: {label}}}) => label);
}
|
c5f629556eae6404276b1a3eaeaf899a05952dd3 | TypeScript | WorldBrain/storex-backend-firestore | /ts/security-rules/ast.test.ts | 2.625 | 3 | import expect from 'expect'
const stripIndent = require('strip-indent')
import { serializeRulesAST as serializeRulesAst, MatchNode } from './ast';
function normalizeWithSpace(s : string) : string {
return s.replace(/^\s+$/mg, '').split('\n').map(line => line.trimRight()).join('\n')
}
export function expectSecurityRulesSerialization(root : MatchNode, expected : string) {
expect('\n' + normalizeWithSpace(stripIndent(serializeRulesAst(root))))
.toEqual(normalizeWithSpace(stripIndent(expected)))
}
describe('Security rules AST serialization', () => {
function runTest(options : { root : MatchNode, expected : string }) {
expectSecurityRulesSerialization(options.root, options.expected)
}
it('should correctly serialize match nodes', () => {
runTest({
root: {
type: 'match',
path: '/databases/{database}/documents',
content: []
},
expected: `
service cloud.firestore {
match /databases/{database}/documents {
}
}`
})
})
it('should correctly serialize nested match nodes', () => {
runTest({
root: {
type: 'match',
path: '/databases/{database}/documents',
content: [
{
type: 'match',
path: '/test',
content: []
}
]
},
expected: `
service cloud.firestore {
match /databases/{database}/documents {
match /test {
}
}
}`
})
})
it('should correctly serialize multiple nested match nodes', () => {
runTest({
root: {
type: 'match',
path: '/databases/{database}/documents',
content: [
{
type: 'match',
path: '/foo',
content: []
},
{
type: 'match',
path: '/bar',
content: []
},
]
},
expected: `
service cloud.firestore {
match /databases/{database}/documents {
match /foo {
}
match /bar {
}
}
}`
})
})
it('should correctly serialize allow nodes', () => {
runTest({
root: {
type: 'match',
path: '/databases/{database}/documents',
content: [
{
type: 'allow',
operations: ['list', 'get'],
condition: 'true'
}
]
},
expected: `
service cloud.firestore {
match /databases/{database}/documents {
allow list, get: if true;
}
}`
})
})
it('should correctly serialize function nodes', () => {
runTest({
root: {
type: 'match',
path: '/databases/{database}/documents',
content: [
{
type: 'function',
name: 'getTest',
returnValue: 'true'
}
]
},
expected: `
service cloud.firestore {
match /databases/{database}/documents {
function getTest() {
return true;
}
}
}`
})
})
})
|
4395cee5f25c647023ec279719b96608cedd0c9f | TypeScript | sjmeverett/clync | /packages/server/src/bindDataFns.ts | 2.671875 | 3 | import { DataFnType, isDataFn } from '@sjmeverett/clync-define';
export type ActionContext<T, P extends keyof T = keyof T> = {
[K in P]: DataFnType<T[K]>;
};
export function bindDataFns<T, Context>(context: Context, fns: T) {
const result: ActionContext<T> = {} as any;
for (const k in fns) {
const fn = fns[k];
result[k] = isDataFn(fn) ? fn.bind(context) : fn;
}
return result;
}
|
b8cd262c647d3481a309e1e08891646975df39c9 | TypeScript | alfumit/typescript-playground | /theory/generics.ts | 3.734375 | 4 | function merge<T extends object, U extends object>(a: T, b : U) {
return Object.assign(a, b);
}
const title = merge({name: 'Geralt'}, {location: 'Rivia'});
console.log(title);
interface HasLength {
length: number
}
function countAndDescribe<T extends HasLength>(element: T) {
if (!element.length) {console.log("Has no value") }
else if (element.length === 1) { console.log("Has 1 value") }
else { console.log(`Has ${element.length} values`)}
}
countAndDescribe(["Nice", "Array has length"]);
function extract<T extends object, U extends keyof T>(obj: T, key: U) {
return obj[key]
}
extract({argvaar: "arg and var, from Javascriptian planet"}, "argvaar")
|
75df0d82e2fa99830e169023ab18e0f84ab80ac1 | TypeScript | j-hands/CRUDex | /CRUDex/src/app/nature-data.service.ts | 2.640625 | 3 | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Nature } from './nature';
@Injectable()
export class NatureDataService {
private natureUrl = 'http://localhost:57135/api/natures';
constructor(private http: Http) { }
//Returns the natureList from the in-memory data
getNatureList(): Promise<Nature[]> {
return this.http.get(this.natureUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
//Handles errors from the other methods
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
//Takes a Nature name and returns the associated Nature object
getNature(name: string): Promise<Nature> {
return this.getNatureList()
.then(natureList => natureList.find(nature => nature.Name === name));
}
}
|
05be9de7a9929ac232f8774e638361f1e1c05802 | TypeScript | luisgrandegg/coronavirus | /src/Gratitude/Gratitude.ts | 2.703125 | 3 | import { ObjectID } from 'mongodb';
import { Entity, ObjectIdColumn, Column, CreateDateColumn, UpdateDateColumn, BeforeInsert } from "typeorm";
import { IsString, IsOptional, IsBoolean } from 'class-validator';
export interface IGratitude {
id: string;
title: string;
message: string;
name: string;
createdAt: string;
imagePublicId: string | null;
imageUrl: string | null;
active: boolean;
flagged: boolean;
}
@Entity()
export class Gratitude {
@ObjectIdColumn()
id: ObjectID;
@IsString()
@IsOptional()
@Column()
title: string;
@IsString()
@Column()
message: string;
@IsString()
@Column()
name: string;
@IsOptional()
@IsString()
@Column()
imagePublicId: string;
@IsOptional()
@IsString()
@Column()
imageUrl: string;
@IsBoolean()
@Column({
default: false
})
flagged: boolean;
@IsBoolean()
@Column({
default: true
})
active: boolean;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@BeforeInsert()
setFlags(): void {
this.active = true;
this.flagged = false;
}
toJSON(): IGratitude {
return {
id: this.id.toHexString(),
createdAt: this.createdAt.toISOString(),
title: this.title,
message: this.message,
name: this.name,
imagePublicId: this.imagePublicId,
imageUrl: this.imageUrl,
active: this.active,
flagged: this.flagged
};
}
}
|
7db415b7041da3ff0fed9a675c4336b515042501 | TypeScript | philip-jonas/game_prototype_01 | /src/Stores/PlotStore.ts | 2.859375 | 3 | import { observable, computed, action, toJS } from "mobx";
import { make2DArray } from "src/utils/Make2DArray";
import { generateRandomInteger } from "src/utils/GenerateRandomRange";
interface IPosition {
col: number;
row: number;
}
export class PlotStore {
@observable public worldGrid: IPosition[] = [];
@observable public roomCount = 0;
@observable public maxRooms = 0;
@observable public plotsX = 0;
@observable public plotsY = 0;
public plotOffset: number = 2;
public initPlots(plotsX: number = this.plotOffset, plotsY: number = this.plotOffset) {
this.plotsX = plotsX;
this.plotsY = plotsY;
this.maxRooms = (this.plotsX * this.plotsY) - this.plotOffset;
this.layoutPlots();
}
public layoutPlots() {
do {
const position: IPosition = {
col: generateRandomInteger(0, this.plotsX-1),
row: generateRandomInteger(0, this.plotsY-1)
};
const found: IPosition[] = this.worldGrid.filter((value: IPosition) => {
return position.col === value.col && position.row === value.row;
});
if (found.length === 0) {
this.worldGrid.push(
position
);
this.roomCount ++;
}
} while (this.worldGrid.length < this.maxRooms);
}
public isPlot(col, row): boolean {
const found: IPosition[] = this.worldGrid.filter((value: IPosition) => {
return col === value.col && row === value.row;
});
if (found.length > 0) {
return true;
}
return false;
}
} |
57b8d310753adf84bfb1860af260dd502cfecb92 | TypeScript | nahann/jorge-pogger- | /jorge/src/Commands/Info/SearchCommand.ts | 2.71875 | 3 | import Command from "../../Struct/Command";
import fetch from "node-fetch"
import { Message } from "discord.js";
import { CSEImage, Google } from "../../interfaces/google"
export default class SearchCommand extends Command{
constructor(){
super("search",{
aliases: ["search","google"],
description: "Search for anything(except nsfw stuff) on google",
args: [{
id: "query",
type: "string",
default: "google.com"
}]
})
}
async exec(message: Message, { query }: { query: string }){
const url = `https://www.googleapis.com/customsearch/v1?key=${this.client.config.Google}&cx=${this.client.config.CX}&q=${query}`
const { items: [item],searchInformation } = await (await fetch(url)).json() as Google
const image = item.pagemap?.cse_image as CSEImage[] || []
const obj = this.client.embed({
title: item.title,
url: `https://${item.displayLink}`,
description: `"${item.snippet}"\nTime taken to search: ${searchInformation.formattedSearchTime} seconds`,
image: {
url: image[0]?.src || "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_160x56dp.png",
}
},message)
message.util?.reply({ embeds: [obj] })
}
} |
f682cbaf06f5058ab24568ac36e4219f540a53ef | TypeScript | MalikaArora/dpl-react | /src/components/Navigation/types.ts | 2.9375 | 3 | /**
* Navigation Config Types
*/
type onLinkClick = (
e: React.MouseEvent<HTMLElement>,
item: NavigationStateLink
) => void;
type onClick = (e: React.MouseEvent<HTMLAnchorElement>) => void;
export type LinkProps = NavigationStateLink & { onClick?: onClick };
type LinkAs = React.ComponentType<LinkProps>;
type isActiveFn = (url: string, route: string) => boolean;
type NavigationConfigLink = {
/**
* Text to render for the link.
*/
label: string;
/**
* URL to navigate to.
*/
url?: string;
/**
* Optional Icon.
*/
icon?: React.ReactNode;
/**
* Link target.
*/
target?: string;
/**
* Optional function to determine if the link is active. Falls back to
* default.
*/
isActive?: isActiveFn;
/**
* Callback invoked when a link is clicked. Will cause link to be rendered
* as a button.
*/
onClick?: onLinkClick;
};
type NavigationConfigPanel = {
/**
* Text to render for the panel button.
*/
label: string;
/**
* Optional Icon.
*/
icon?: React.ReactNode;
/**
* Child links.
*/
links: NavigationConfigGroup;
};
type NavigationConfigGroup = (NavigationConfigPanel | NavigationConfigLink)[];
type NavigationGlobalOptions = {
/**
* Text to render for the menu title on mobile. Defaults to "Menu".
*/
label?: string;
/**
* Custom function to detect the currently active link
*/
isActive?: isActiveFn;
/**
* Render a custom link in place of standard anchor tag. Use this for option client
* side routing.
*/
linkAs?: LinkAs;
/**
* Callback invoked when a link is clicked.
*/
onLinkClick?: onLinkClick;
/**
* Optional expanded panel icon override
*/
panelExpandedIcon?: React.ReactNode;
/**
* Optional closed panel icon override
*/
panelClosedIcon?: React.ReactNode;
/**
* Optional panel flyout icon override
*/
panelFlyoutIcon?: React.ReactNode;
};
export type NavigationConfig = {
links: NavigationConfigGroup;
} & NavigationGlobalOptions;
/**
* Navigation State Types
*
* The navigation state types are the config types with some
* additional properties that are computed at runtime like "active"
*/
type NavigationLinkState = {
active: boolean;
};
export type NavigationStateLink = NavigationConfigLink & NavigationLinkState;
type NavigationPanelState = {
expanded: boolean;
active: boolean;
};
export type NavigationStatePanel = {
links: NavigationStateGroup;
} & NavigationPanelState &
Omit<NavigationConfigPanel, "links">;
export type NavigationStateGroup = (
| NavigationStatePanel
| NavigationStateLink
)[];
export type NavigationState = {
links: NavigationStateGroup;
} & NavigationGlobalOptions;
export enum NavType {
GLOBAL = "GLOBAL",
HORIZONTAL = "HORIZONTAL",
VERTICAL = "VERTICAL",
}
/**
* Navigation Render Types
*/
export interface INav {
isDesktop: boolean;
variant: NavType;
}
export interface IPanel {
level: number;
isDesktop: boolean;
variant: NavType;
}
export interface IPanelItem {
isDesktop: boolean;
level: number;
active: boolean;
variant: NavType;
/**
* This is used to compute a padding offset in the vertical nav desktop
* styles when icons are used in the nav
*/
parentIconOffset: number;
}
export interface IPanelItemAction extends IPanelItem {}
export interface IPanelItemTrigger extends IPanelItem {
expanded: boolean;
}
export interface INavigationDispatchContext {
closePanel: (label: string) => void;
openPanel: (label: string, variant: NavType, isDesktop?: boolean) => void;
closeNav: () => void;
openNavAtActivePath: () => void;
}
export interface INavigationInternalCallbacks {
onActionItemClick?: (isDesktop: boolean) => void;
}
|
ef6b859480a5d92c0d25933857626be2ab82c3b1 | TypeScript | sz5t/SmartOne-Components-Module | /src/app/resolver/trigger/cn-trigger.base.ts | 2.53125 | 3 | export class CnTriggerBase {
constructor(public _triggerMsg: any, public _componentInstance: any) {}
public beforeOperationValidator(beforeCfg) {
if (!beforeCfg) {
return true;
}
}
public conditionValidator(condCfg): boolean {
if (!condCfg) {
return true;
}
const result = [];
for (const cfg of condCfg.state) {
switch (cfg.type) {
case 'component':
const componentResult = this.checkComponentProperty(cfg);
result.push(componentResult);
break;
}
}
return result.findIndex(res => !res) < 0;
}
public checkComponentProperty(expCfg) {
// 判断取值的类型
const allCheckResult = [];
switch (expCfg.type) {
case 'component':
const componentValue = this._componentInstance[this._componentInstance.COMPONENT_PROPERTY[expCfg.valueName]];
for (const exp of expCfg.expression) {
switch (exp.type) {
case 'property':
const valueCompareObj = this.buildMatchObject(componentValue, exp);
const valueMatchResult = this.matchResolve(valueCompareObj, exp.match);
allCheckResult.push(valueMatchResult);
break;
case 'element':
const elementResult = [];
for (const element of componentValue) {
const elementCompareObj = this.buildMatchObject(element, exp);
elementResult.push(this.matchResolve(elementCompareObj, exp.match));
}
const elementMatchResult = elementResult.findIndex(res => !res) < 0;
allCheckResult.push(elementMatchResult);
}
}
break;
}
return allCheckResult.findIndex(res => !res) < 0;
}
public buildMatchObject(componentValue, expCfg) {
let value;
if (expCfg.name) {
value = componentValue[expCfg.name];
} else { // 读取自身数据
value = componentValue;
}
const matchValue = expCfg.matchValue;
const matchValueFrom = expCfg.matchValueFrom;
const matchValueTo = expCfg.matchValueTo;
return {
value,
matchValue,
matchValueFrom,
matchValueTo
};
}
public matchResolve(compareValue, expression) {
switch (expression) {
case 'eq': // =
return compareValue.value === compareValue.matchValue;
case 'neq': // !=
return compareValue.value !== compareValue.matchValue;
case 'ctn': // like
return compareValue.matchValue.indexOf(compareValue.value) > 0;
case 'nctn': // not like
return compareValue.matchValue.indexOf(compareValue.value) <= 0;
case 'in': // in 如果是input 是这样取值,其他则是多选取值
let in_result = true;
if (Array.isArray(compareValue.matchValue) && compareValue.matchValue.length > 0) {
in_result = compareValue.matchValue.findIndex(compareValue.value) > 0;
}
return in_result;
case 'nin': // not in 如果是input 是这样取值,其他则是多选取值
let nin_result = true;
if (Array.isArray(compareValue.matchValue) && compareValue.matchValue.length > 0) {
nin_result = compareValue.matchValue.findIndex(compareValue.value) <= 0;
}
return nin_result;
case 'btn': // between
return (compareValue.matchValueFrom <= compareValue.value)
&& (compareValue.matchValueTo >= compareValue.value);
case 'ge': // >=
return compareValue.value >= compareValue.matchValue;
case 'gt': // >
return compareValue.value > compareValue.matchValue;
case 'le': // <=
return compareValue.value <= compareValue.matchValue;
case 'lt': // <
return compareValue.value < compareValue.matchValue;
default:
case 'regexp': // 正在表达式匹配
const regexp = new RegExp(compareValue.matchValue);
return regexp.test(compareValue.value);
}
}
}
|
84349219862768099b5f9b43a1885ec5fac9a448 | TypeScript | orta/gluegun | /src/core-extensions/template-extension.test.ts | 2.546875 | 3 | import test from 'ava'
import { startsWith } from 'ramdasauce'
import { Runtime } from '../runtime/runtime'
const createRuntime = () => {
const r = new Runtime()
r.addPlugin(`${__dirname}/../fixtures/good-plugins/generate`)
return r
}
test('generates a simple file', async t => {
const context = await createRuntime().run('generate simple')
t.is(context.result, 'simple file\n')
})
test('supports props', async t => {
const context = await createRuntime().run('generate props Greetings_and_salutations', {
stars: 5,
})
t.is(
context.result,
`greetingsAndSalutations world
red
green
blue
*****
`,
)
})
test('detects missing templates', async t => {
try {
await createRuntime().run('generate missing')
} catch (e) {
t.true(startsWith('template not found', e.message))
}
})
test('supports directories', async t => {
const context = await createRuntime().run('generate special location')
t.is(
context.result,
`location
`,
)
})
|
7c9fef22067e7c46404299bbf3828c899ee494a1 | TypeScript | JesusJimenezValverde/Proyecto_Bases_II_API_Rest | /src/models/product.ts | 2.625 | 3 | import { model, Schema, Document } from 'mongoose'
export interface IProduct extends Document {
name: string
loc: Number
productor: string
}
const prodSchema = new Schema({
name: {
type: String,
unique: false,
required: true,
lowercase: false,
trim: true
},
productor: {
type: String,
unique: false,
required: true,
lowercase: false,
trim: true
},
loc: {
type: Number,
required: true
}
})
export default model<IProduct>('Product', prodSchema, 'productos') |
9886bdcf45e79971553ad1bae3ebd678000d4c29 | TypeScript | GoogleForCreators/web-stories-wp | /packages/story-editor/src/app/story/useStoryReducer/reducers/unselectElement.ts | 2.578125 | 3 | /*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import { produce } from 'immer';
/**
* Internal dependencies
*/
import type {
UnselectElementProps,
ReducerState,
ReducerStateDraft,
} from '../../../../types';
/**
* Remove the given id from the current selection.
*
* If no id is given or id is not in the current selection, nothing happens.
*/
export const unselectElement = (
draft: ReducerStateDraft,
{ elementId }: UnselectElementProps
) => {
const index = draft.selection.indexOf(elementId);
if (index === -1) {
return;
}
draft.selection.splice(index, 1);
};
export default produce<ReducerState, [UnselectElementProps]>(unselectElement);
|
eb46d7d32d3f14fbcd5ed7629ea52b506c6b388b | TypeScript | FrankDouwes/justHike | /src/app/type/town.ts | 3.109375 | 3 | import {Waypoint} from './waypoint';
import {Poi} from './poi';
export interface Town {
trail: string; // abbr. of trail mile belongs to
id: number; // id (mile number, starts at 1 not 0)
label: string; // town name
waypoint: Waypoint; // center of town
type: string; // type, usually 'town', but can also be 'resort', 'trail angel' etc.
radius: number; // radius around center point (mi) (TODO: not sure if I need this...?)
belongsTo: number | Array<number>; // an id of a mile (this is the mile the anchorPoint(s) belong to
anchorPoint?: Waypoint | Array<Waypoint>; // either a static or a calculated point on trail (nearest to town)
amenities?: Array<string> | string; // things you can get/do in town
description?: string; // optional description
pois?: Array<Poi>; // town pois
}
|
423160664c782f053b4e0c1369ac64c0ba273d24 | TypeScript | hcoggins/momo-scheduler | /test/job/findLatest.spec.ts | 2.953125 | 3 | import { DateTime } from 'luxon';
import { ExecutionInfo } from '../../src';
import { JobEntity } from '../../src/repository/JobEntity';
import { findLatest } from '../../src/job/findLatest';
function createJob(lastFinished?: number): JobEntity {
const job = { name: 'test' } as JobEntity;
if (lastFinished !== undefined) {
job.executionInfo = { lastFinished: DateTime.fromMillis(lastFinished).toISO() } as ExecutionInfo;
}
return job;
}
describe('findLatest', () => {
it('handles empty array', () => {
expect(findLatest([])).toBeUndefined();
});
it('handles single job', () => {
const job = createJob(1);
expect(findLatest([job])).toBe(job);
});
it('handles single job when job was never executed', () => {
const job = createJob();
expect(findLatest([job])).toBe(job);
});
it('finds index of latest job', () => {
const job1 = createJob(1);
const job2 = createJob(2);
expect(findLatest([job1, job2])).toBe(job2);
expect(findLatest([job2, job1])).toBe(job2);
});
it('finds index of latest job with equal time', () => {
const job1 = createJob(1);
const job2 = createJob(1);
expect(findLatest([job1, job2])).toBe(job1);
});
it('finds index of latest job when job was never executed', () => {
const job1 = createJob(1);
const job2 = createJob();
expect(findLatest([job1, job2])).toBe(job1);
expect(findLatest([job2, job1])).toBe(job1);
});
it('finds index of latest job in bigger array', () => {
const job0 = createJob();
const job1 = createJob(1);
const job2 = createJob(2);
const job4 = createJob(4);
const job5 = createJob(5);
expect(findLatest([job4, job1, job1, job0, job5, job2])).toBe(job5);
});
});
|
f26892c8949071ece64370e86672f5665877c37d | TypeScript | CourtHive/tods-competition-factory | /src/scaleEngine/governors/ratingsGovernor/aggregators.ts | 2.71875 | 3 | export const aggregateGames = (sets) => {
return (
sets?.reduce(
(aggregate, set) => {
aggregate[0] += set.side1Score;
aggregate[1] += set.side2Score;
return aggregate;
},
[0, 0]
) || [0, 0]
);
};
export const aggregateSets = (sets) => {
return (
sets?.reduce(
(aggregate, set) => {
if (set.winningSide) aggregate[set.winningSide - 1] += 1;
return aggregate;
},
[0, 0]
) || [0, 0]
);
};
|
07e324ec0910a3191c6cb187caaac3b052a65b0f | TypeScript | YuriNikulin/teacher | /front/admin/src/pages/Page/redux/reducer.ts | 2.6875 | 3 | import { ActionsTypes } from './actions';
import * as ACTIONS from './constants';
import * as APP_ACTIONS from '@store/constants';
import { ActionTypes as AppActionTypes } from '@store/actions';
import { IPageReducer, IPage, IBlock } from '../types';
const initialState = {
isLoading: true,
isFormLoading: false,
pages: [],
drafts: {},
};
function reducer(state: IPageReducer = initialState, action: ActionsTypes | AppActionTypes) {
switch (action.type) {
case ACTIONS.GET_PAGES_LIST_REQUEST:
return {
...state,
isLoading: true,
};
case ACTIONS.GET_PAGES_LIST_SUCCESS:
return {
...state,
isLoading: false,
pages: action.payload,
error: undefined,
};
case ACTIONS.GET_PAGES_LIST_FAILURE:
return {
...state,
isLoading: false,
error: action.payload,
};
case ACTIONS.CREATE_PAGE_REQUEST:
case ACTIONS.EDIT_PAGE_REQUEST:
return {
...state,
isFormLoading: true,
};
case ACTIONS.CREATE_PAGE_SUCCESS:
return {
...state,
isFormLoading: false,
error: undefined,
pages: [...state.pages, action.payload],
};
case ACTIONS.CREATE_PAGE_FAILURE:
case ACTIONS.EDIT_PAGE_FAILURE:
return {
...state,
isFormLoading: false,
error: action.payload,
};
case ACTIONS.DELETE_PAGE_REQUEST:
return {
...state,
isLoading: true,
};
case ACTIONS.DELETE_PAGE_SUCCESS:
return {
...state,
isLoading: false,
error: undefined,
pages: [...state.pages.filter(page => page.id !== action.payload)],
};
case ACTIONS.DELETE_PAGE_FAILURE:
return {
...state,
isLoading: false,
};
case ACTIONS.EDIT_PAGE_SUCCESS:
const updatedIndex = state.pages.findIndex((item: IPage) => item.id === action.payload.id);
if (updatedIndex === -1) {
return state;
}
return {
...state,
isFormLoading: false,
error: undefined,
pages: [...state.pages.slice(0, updatedIndex), action.payload, ...state.pages.slice(updatedIndex + 1)],
};
case ACTIONS.CHANGE_DRAFT:
return {
...state,
drafts: {
...state.drafts,
[action.payload.pageId]: action.payload.shouldUpdate ? action.payload.newDraft : undefined,
},
};
case ACTIONS.DELETE_DRAFT:
return {
...state,
drafts: {
...state.drafts,
[action.payload]: undefined,
},
};
case APP_ACTIONS.RESET:
return initialState;
default:
return state;
}
}
export default reducer;
|
3e05d4f15b6cec5cd8cfbffe8fd2411c3b741a9a | TypeScript | inkblotty/StarWarsQuiz | /client/src/store/actions.ts | 2.8125 | 3 | import { QuizState, SingleAnswerField, SingleQuizField, QuizAction } from './types';
export const initQuiz = (configObj : QuizState) : QuizAction => {
if (!configObj || Array.isArray(configObj) || (typeof configObj !== 'object')) {
throw new Error('Invalid config object.');
}
return {
type: 'init',
quizData: configObj,
};
};
export const answerQuizQuestion = ({ correctAnswer } : SingleQuizField, { value, key } : SingleAnswerField) : QuizAction => {
const required = [correctAnswer, key, value];
if (!correctAnswer || !key || !value) {
const missingRequired : string[] = [];
required.forEach(input => {
if (!input) {
missingRequired.push(Object.keys({ input })[0]);
}
});
throw new Error(`Missing required fields: ${missingRequired.join(', ')}`);
}
if (correctAnswer === value) {
return {
type: 'success',
field: {
errored: false,
key,
value,
},
};
}
return {
type: 'error',
field: {
errored: true,
key,
value,
},
};
} |
32f373e53ebc3b308c15e73162827fd29b323e2e | TypeScript | aondenet-sinval/typescript | /converted/converted-ts/stringMethods.ts | 4.15625 | 4 | //-------------------------------------------
//Conversão: 01
//-------------------------------------------
//Java script methods:
//JavaScript métodos usados em strings:
/*
let str: string = "O mar é lindo, muito lindo";
//Retorna o indice em que a string está posicionada
let lindo: number = str.indexOf("lindo");
console.log(lindo);// Retorna 8
//
//Retorna o indice em que está ultima ocorrencia da string
let lastLindo: number = str.lastIndexOf("lindo");
console.log(lastLindo);// Retorna 21
//
str = "O mar é lindo, muito lindo. Lindo demais";
let lastLindoB: number = str.lastIndexOf("lindo");
console.log(lastLindoB);// Retorna 28
//
//Pesquisar string em uma variável caso sensitivo
let lindoSearchA: number = str.search("Lindo");
console.log(lindoSearchA);//Retorna 28 leva em conta miúsculas e minúsculas
//
//Pesquisar string em uma variável caso insensitivo
let lindoSearchB: number = str.search(/Lindo/i);
console.log(lindoSearchB);//Retorna 8
*/
/*
//-------------------------------------------
//Conversão: 02
//-------------------------------------------
//
//Replace troca string por outra
let str: string = "O mar é lindo";
str = str.replace("mar", "amor");
console.log('Replace: ',str);
//
//Extrair uma sequência de caracteres de acordo com o indice solicitado
let extract: string = str.substr(6, 12);
console.log(extract); // Retorna: "é lindo"
//
//Converter para letras minusculas
console.log(str.toLowerCase());
//
//Converter para letras maiúsculas
console.log(str.toUpperCase());
//
//Remove espaço em strings
str = " O mar é lindo ";
console.log(str);//Retorna: " O mar é lindo "
console.log(str.trim());//Retorna: "O mar é lindo"
//Return the first character of a string
let str = "HELLO WORLD";
console.log(str);
str = str.charAt(0);// Returns "H"
console.log(str);
//Return the second character of a string
str = "HELLO WORLD";//Foi necessário reatribuir
str = str.charAt(1);// Returns "E"
console.log(str);
*/
|
6e8a532a4dbc0b429e067cc067c144ec92abef1e | TypeScript | npenin/akala | /packages/json-rpc-ws/src/ws/ws-socket-adapter.ts | 2.8125 | 3 | import ws from 'ws';
import { SocketAdapter, SocketAdapterEventMap } from '../shared-connection.js';
import { Readable } from 'stream';
/**
* json-rpc-ws connection
*
* @constructor
* @param {Socket} socket - web socket for this connection
* @param {Object} parent - parent that controls this connection
*/
export default class WsSocketAdapter implements SocketAdapter<Readable>
{
constructor(private socket: ws)
{
}
pipe(socket: SocketAdapter<unknown>)
{
this.on('message', (message) => socket.send(message));
this.on('close', () => socket.close());
}
get open(): boolean
{
return this.socket.readyState == ws.OPEN;
}
close(): void
{
this.socket.close();
}
send(data: string): void
{
this.socket.send(data, { binary: false });
}
public off<K extends keyof SocketAdapterEventMap>(event: K, handler?: (ev: SocketAdapterEventMap[K]) => void): void
{
if (event === 'message')
{
this.socket.removeAllListeners(event);
}
else
this.socket.off(event, handler);
}
public on<K extends keyof SocketAdapterEventMap>(event: K, handler: (ev: SocketAdapterEventMap[K]) => void): void
{
if (event === 'message')
{
this.socket.on(event, function (data: ws.Data, isBinary: boolean)
{
if (!isBinary)
{
if (Buffer.isBuffer(data))
(handler as (ev: SocketAdapterEventMap['message']) => void).call(this, data.toString('utf8'));
else
(handler as (ev: SocketAdapterEventMap['message']) => void).call(this, data);
}
else
(handler as (ev: SocketAdapterEventMap['message']) => void).call(this, data);
});
}
else
this.socket.on(event, handler);
}
public once<K extends keyof SocketAdapterEventMap>(event: K, handler: (ev: SocketAdapterEventMap[K]) => void): void
{
this.socket.once(event, handler);
}
} |
1d24f4c68b92052b3efbc7488130855bb67b9bfc | TypeScript | harry502/CardGame | /client/src/logic/game/Base/CardManager.ts | 2.71875 | 3 | class CardManager
{
private static inst: CardManager;
private isReady:boolean = false;
private CardsList:number[];
public static getInst() {
if (CardManager.inst == null) {
CardManager.inst = new CardManager();
}
return CardManager.inst;
}
constructor()
{
this.CardsList = new Array<number>(Config.MaxCardsId);
}
public update()
{
var params = {};
HttpManager.getInst().init();
params['userid'] = Userinfo.getInst().userid;
HttpManager.getInst().post("user/getcard",params,this);
}
public getList():number[]
{
return this.CardsList;
}
public setList(cardlist:string)
{
this.CardsList = Array<number>(20);
var list:any = cardlist.split('|');
for(let t of list)
{
var temp:string[] = t.split(':');
this.CardsList[temp[0]] = temp[1];
}
console.log(this.CardsList);
}
public AddCardList(cardlist:number[])
{
for(let t of cardlist)
{
this.CardsList[t]++;
}
console.log(this.CardsList);
}
public saveCard()
{
var liststr:string = "";
for( let t in this.CardsList)
{
liststr += String(t) + ":" + String(this.CardsList[t]) + "|";
}
liststr = liststr.substr(0, liststr.length - 1);
var params = {};
HttpManager.getInst().init();
params['userid'] = Userinfo.getInst().userid;
params['cardlist'] = liststr;
HttpManager.getInst().post("user/setcard",params,this);
}
private onPostComplete(event:egret.Event):void
{
var request = <egret.HttpRequest>event.currentTarget;
console.log("post data : ",request.response);
var result = JSON.parse(request.response);
if(result["Mark"] == "获取成功")
{
this.setList(result["card"]);
}
}
} |
9cd6e183b0c6243b2ac7b49fa12fca9b28a234d3 | TypeScript | excaliburjs/Excalibur | /src/spec/BrowserEventsSpec.ts | 2.625 | 3 | import * as ex from '@excalibur';
describe('The BrowserEvents facade', () => {
let browser: ex.BrowserEvents;
beforeEach(() => {
browser = new ex.BrowserEvents(window, document);
});
afterEach(() => {
browser.clear();
});
it('should exist', () => {
expect(ex.BrowserEvents).toBeDefined();
});
it('can be created', () => {
expect(browser).toBeDefined();
});
it('can register handlers on window', (done) => {
browser.window.on('someevent', () => {
done();
});
window.dispatchEvent(new Event('someevent'));
});
it('can pause handlers on window', () => {
browser.window.on('somewindowevent', () => {
fail();
});
browser.pause();
window.dispatchEvent(new Event('somewindowevent'));
});
it('can register handlers on document', (done) => {
browser.document.on('someevent', () => {
done();
});
document.dispatchEvent(new Event('someevent'));
});
it('can pause handlers on document', () => {
browser.document.on('somedocumentevent', () => {
fail();
});
browser.pause();
window.dispatchEvent(new Event('somedocumentevent'));
});
it('can clear handlers on window', () => {
browser.window.on('somewindowevent2', () => {
fail();
});
browser.clear();
window.dispatchEvent(new Event('somewindowevent2'));
});
it('can clear handlers on window', () => {
browser.document.on('somedocevent2', () => {
fail();
});
browser.clear();
document.dispatchEvent(new Event('somedocevent2'));
});
it('can only have 1 handler per event name at a time', (done) => {
browser.window.on('couldfailevent', () => {
fail();
});
browser.window.on('couldfailevent', () => {
done();
});
window.dispatchEvent(new Event('couldfailevent'));
});
it('can resume handlers', () => {
const spy = jasmine.createSpy();
browser.document.on('somedocumentevent', spy);
browser.pause();
document.dispatchEvent(new Event('somedocumentevent'));
browser.resume();
document.dispatchEvent(new Event('somedocumentevent'));
expect(spy).toHaveBeenCalledTimes(1);
});
});
|
fca3c9d1644340d15aba351e65b94db3791ee368 | TypeScript | jackhutu/lerna-study | /packages/bighouse/src/index.ts | 3.015625 | 3 | // import { bighouse } from './bighouse';
// import house from '@study/house';
// export default function() {
// console.log(bighouse() + 'hello' + house);
// }
import { capitalize } from '@study/house';
export default class Hello {
msg: string;
constructor(msg: string) {
this.msg = capitalize(msg);
}
say(): string {
return 'Hello, ' + this.msg;
}
}
|
4ce1f8bccee586a069280f5347ac2df483eb9c76 | TypeScript | foxz-z/react-application-core | /src/core/util/converter.ts | 3.078125 | 3 | import * as R from 'ramda';
/**
* @stable [21.10.2018]
* @param {Map<TKey, TValue>} map
* @returns {{[p: string]: TValue}}
*/
export const fromMapToObject = <TKey, TValue>(map: Map<TKey, TValue>): { [index: string]: TValue } =>
R.mergeAll(Array.from(map.keys()).map((path) => ({[String(path)]: map.get(path)})));
|
a28d31db923fb369853dc24f063f73ed49b6394a | TypeScript | anibalalvarezg/RxJS | /src/Operators/02-pluck.ts | 2.84375 | 3 | import { range, fromEvent } from 'rxjs';
import { map, pluck } from 'rxjs/operators'
const range$ = range(1,5);
// range$.pipe(
// map<number, string>(x => {
// return (x*10).toString();
// })
// ).subscribe( console.log )
const keyup$ = fromEvent<KeyboardEvent>( document, 'keyup');
const keyupCode$ = keyup$.pipe(map<any, string >(x=>x.code))
const keyupPluck$ = keyup$.pipe(pluck('key'));
keyupCode$.subscribe( val => console.log('map', val) );
keyupPluck$.subscribe( val => console.log('pluck', val) ); |
d15d08a8ac244116964ab3b97ffbf3e9c7fdcbf6 | TypeScript | iPotaje/ionic2-sqlite-example | /src/services/data.service.ts | 2.8125 | 3 | import { Injectable } from '@angular/core';
// import { Observable } from 'rxjs/Observable';
@Injectable()
export class DataService {
public datos = "inicial";
// private data = [
// "uno", "dos", "tres", "cuatro", "cinco"
// ];
// private index = 0;
constructor() {
}
getData(): Promise<string> {
// this.observer.next(this.data[this.index++]);
// (this.index === this.data.length)?
// this.index = 0:
// null;
return Promise.resolve(this.datos);
}
setData(data:string){
this.datos = data;
}
} |
d744d497191d8b14585013e19a5b055e95040c24 | TypeScript | jianh-zhou/TS_study | /code/Part4/src/07泛型.ts | 4.125 | 4 | function fn<T>(a: T): T {
return a
}
fn(20) // 不指定泛型, TS可以自动对类型进行判断
fn<string>('哈哈') // 指定泛型
// 泛型可以定义多个
function fn2<S, A>(a: S, b: A): A {
return b
}
fn2<string, number>('22', 11)
// 定义一个接口
interface twst {
length: number
}
// 泛型可以继承接口,表示泛型必须是接口的实现类(子类)
function fn3<H extends twst>(a: H): H {
return a
}
fn3({ length: 20 })
class MyClass<A>{
name: A
constructor(value: A) {
this.name = value
}
}
const t = new MyClass<String>('哈哈') |
a08e5f2043ed0a2f9985a51e1bf8f8c139e0fe44 | TypeScript | Kcire6/CyclosInfoUGT | /src/app/api/models/ui-element-with-content.ts | 2.78125 | 3 | /* tslint:disable */
import { VersionedEntity } from './versioned-entity';
/**
* Contains definitions for a UI element that has a content
*/
export interface UiElementWithContent extends VersionedEntity {
/**
* The content of this element
*/
content?: string;
}
|
b812ef1ce1976600cc722f5672e1ff252e00e2d6 | TypeScript | Phong111222/Admin-Panel | /src/store/product/reducer.ts | 2.984375 | 3 | import { Reducer } from 'redux';
import {
ProductActions,
ProductState,
ProductType,
ProductTypes,
} from './types';
const initialState: ProductState = {
loading: false,
list: [],
error: null,
};
const productReducer: Reducer<ProductState, ProductActions> = (
state = initialState,
action
) => {
switch (action.type) {
case ProductTypes.GET_LIST_PRODUCTS:
return { ...state, loading: true };
case ProductTypes.GET_LIST_PRODUCTS_FAIL:
return { ...state, loading: false, error: action.payload?.error };
case ProductTypes.GET_LIST_PRODUCTS_SUCCESS:
return {
...state,
loading: false,
list: action.payload?.list as ProductType[],
};
case ProductTypes.CREATE_PRODUCT:
return { ...state, loading: true };
case ProductTypes.CREATE_PRODUCT_SUCCESS: {
const newList = [...state.list];
newList.push(action.payload?.newProduct as ProductType);
return { ...state, loading: false, list: newList };
}
case ProductTypes.CREATE_PRODUCT_FAIL:
return { ...state, loading: false, error: action.payload?.error };
case ProductTypes.UPDATE_PRODUCT:
return { ...state, loading: true };
case ProductTypes.UPDATE_PRODUCT_FAIL:
return { ...state, loading: false, error: action.payload?.error };
case ProductTypes.UPDATE_PRODUCT_SUCCESS: {
const updatedproduct = action.payload?.newProduct;
console.log(updatedproduct);
const newList = state.list.map((product) =>
product._id === action.payload?.productID
? { ...product, ...updatedproduct }
: product
);
return { ...state, loading: false, list: newList };
}
case ProductTypes.TOGGLE_PRODUCT: {
return { ...state, loading: true };
}
case ProductTypes.TOGGLE_PRODUCT_SUCCESS: {
const newList = state.list.map((item) =>
item._id === action.payload?.productID
? { ...item, isActive: !item.isActive }
: item
);
return { ...state, list: [...newList], loading: false };
}
case ProductTypes.TOGGLE_PRODUCT_FAIL:
return { ...state, loading: false, error: action.payload?.error };
default:
return state;
}
};
export default productReducer;
|
dafb0c643b631927ed5c3e502faabf3375473be7 | TypeScript | iter-tools/iter-tools | /src/impls/async-interleave-ready/__tests__/async-interleave-ready.test.ts | 2.515625 | 3 | import { asyncInterleaveReady, asyncToArray } from 'iter-tools-es';
import { delay } from '../../../internal/delay.js';
describe('asyncInterleaveReady', () => {
it('can use the return value of canTakeAny to interleave by promise readiness', async () => {
const a = (async function* () {
await delay(10);
yield 1;
await delay(30);
yield 2;
})();
const b = (async function* () {
await delay(20);
yield 3;
await delay(10);
yield 4;
})();
expect(await asyncToArray(asyncInterleaveReady(a, b))).toEqual([1, 3, 4, 2]);
});
});
|
3754ffcd4e90f5e79cb5d616a61e4e1305b6707c | TypeScript | video-dev/hls.js | /src/utils/discontinuities.ts | 2.75 | 3 | import { logger } from './logger';
import { adjustSliding } from './level-helper';
import type { Fragment } from '../loader/fragment';
import type { LevelDetails } from '../loader/level-details';
import type { Level } from '../types/level';
import type { RequiredProperties } from '../types/general';
export function findFirstFragWithCC(
fragments: Fragment[],
cc: number,
): Fragment | null {
for (let i = 0, len = fragments.length; i < len; i++) {
if (fragments[i]?.cc === cc) {
return fragments[i];
}
}
return null;
}
export function shouldAlignOnDiscontinuities(
lastFrag: Fragment | null,
lastLevel: Level,
details: LevelDetails,
): lastLevel is RequiredProperties<Level, 'details'> {
if (lastLevel.details) {
if (
details.endCC > details.startCC ||
(lastFrag && lastFrag.cc < details.startCC)
) {
return true;
}
}
return false;
}
// Find the first frag in the previous level which matches the CC of the first frag of the new level
export function findDiscontinuousReferenceFrag(
prevDetails: LevelDetails,
curDetails: LevelDetails,
) {
const prevFrags = prevDetails.fragments;
const curFrags = curDetails.fragments;
if (!curFrags.length || !prevFrags.length) {
logger.log('No fragments to align');
return;
}
const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {
logger.log('No frag in previous level to align on');
return;
}
return prevStartFrag;
}
function adjustFragmentStart(frag: Fragment, sliding: number) {
if (frag) {
const start = frag.start + sliding;
frag.start = frag.startPTS = start;
frag.endPTS = start + frag.duration;
}
}
export function adjustSlidingStart(sliding: number, details: LevelDetails) {
// Update segments
const fragments = details.fragments;
for (let i = 0, len = fragments.length; i < len; i++) {
adjustFragmentStart(fragments[i], sliding);
}
// Update LL-HLS parts at the end of the playlist
if (details.fragmentHint) {
adjustFragmentStart(details.fragmentHint, sliding);
}
details.alignedSliding = true;
}
/**
* Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
* contiguous stream with the last fragments.
* The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
* download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
* and an extra download.
* @param lastFrag
* @param lastLevel
* @param details
*/
export function alignStream(
lastFrag: Fragment | null,
lastLevel: Level | null,
details: LevelDetails,
) {
if (!lastLevel) {
return;
}
alignDiscontinuities(lastFrag, details, lastLevel);
if (!details.alignedSliding && lastLevel.details) {
// If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
// Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
// discontinuity sequence.
alignMediaPlaylistByPDT(details, lastLevel.details);
}
if (
!details.alignedSliding &&
lastLevel.details &&
!details.skippedSegments
) {
// Try to align on sn so that we pick a better start fragment.
// Do not perform this on playlists with delta updates as this is only to align levels on switch
// and adjustSliding only adjusts fragments after skippedSegments.
adjustSliding(lastLevel.details, details);
}
}
/**
* Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
* discontinuity sequence.
* @param lastFrag - The last Fragment which shares the same discontinuity sequence
* @param lastLevel - The details of the last loaded level
* @param details - The details of the new level
*/
function alignDiscontinuities(
lastFrag: Fragment | null,
details: LevelDetails,
lastLevel: Level,
) {
if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
const referenceFrag = findDiscontinuousReferenceFrag(
lastLevel.details,
details,
);
if (referenceFrag && Number.isFinite(referenceFrag.start)) {
logger.log(
`Adjusting PTS using last level due to CC increase within current level ${details.url}`,
);
adjustSlidingStart(referenceFrag.start, details);
}
}
}
/**
* Ensures appropriate time-alignment between renditions based on PDT.
* This function assumes the timelines represented in `refDetails` are accurate, including the PDTs
* for the last discontinuity sequence number shared by both playlists when present,
* and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
* times/timelines of `details` accordingly.
* Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
* the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
* are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
* be consistent across playlists, per the HLS spec.
* @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
* @param refDetails - The details of the reference rendition with start and PDT times for alignment.
*/
export function alignMediaPlaylistByPDT(
details: LevelDetails,
refDetails: LevelDetails,
) {
if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
return;
}
const fragments = details.fragments;
const refFragments = refDetails.fragments;
if (!fragments.length || !refFragments.length) {
return;
}
// Calculate a delta to apply to all fragments according to the delta in PDT times and start times
// of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
// If a fragment of the same discontinuity was not found use the middle fragment of both.
let refFrag: Fragment | null | undefined;
let frag: Fragment | null | undefined;
const targetCC = Math.min(refDetails.endCC, details.endCC);
if (refDetails.startCC < targetCC && details.startCC < targetCC) {
refFrag = findFirstFragWithCC(refFragments, targetCC);
frag = findFirstFragWithCC(fragments, targetCC);
}
if (!refFrag || !frag) {
refFrag = refFragments[Math.floor(refFragments.length / 2)];
frag =
findFirstFragWithCC(fragments, refFrag.cc) ||
fragments[Math.floor(fragments.length / 2)];
}
const refPDT = refFrag.programDateTime;
const targetPDT = frag.programDateTime;
if (!refPDT || !targetPDT) {
return;
}
const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
adjustSlidingStart(delta, details);
}
|
e98a72a959af8a578761dace03a73639363b50ac | TypeScript | nickmessing/credit-client | /src/utils/validation.ts | 2.84375 | 3 | /* eslint-disable @typescript-eslint/no-explicit-any */
import { computed, ref, Ref } from 'vue'
import validator from 'validator'
export type ValidatorParameters<T extends (str: string, ...args: any) => any> = T extends (
str: string,
...args: infer P
) => any
? P
: never
export type RuleDefinition = {
[key in keyof typeof validator]: typeof validator[key] extends (str: string, ...args: any) => any
? [ruleName: key, ...options: ValidatorParameters<typeof validator[key]>]
: never
}[keyof typeof validator]
export type Validation = {
rule: RuleDefinition
message: string
}
export type Validations = Validation[]
export type ValidationDeclaration = {
data: string | Ref<string>
validations: Validations
}
export type ValidationResult = {
enable: () => void
disable: () => void
readonly enabled: Ref<boolean>
readonly error: Ref<string>
readonly valid: Ref<boolean>
}
export type UseValidationResult<T extends Record<string, ValidationDeclaration>> = {
enable: () => void
disable: () => void
readonly valid: Ref<boolean>
fields: Record<keyof T, ValidationResult>
}
export const useValidation = <T extends Record<string, ValidationDeclaration>>(
validations: T,
): UseValidationResult<T> => {
const fields = Object.fromEntries(
Object.entries(validations).map(([key, declaration]) => {
const enabledRef = ref(false)
const data = declaration.data
const computedData = typeof data === 'string' ? computed(() => data) : data
const enabled = computed(() => enabledRef.value)
const enable = () => {
enabledRef.value = true
}
const disable = () => {
enabledRef.value = false
}
const valid = computed(() =>
declaration.validations.reduce((valid, validation) => {
if (!valid) {
return false
}
const [rule, ...args] = validation.rule
return (validator[rule] as (...args: any[]) => boolean)(computedData.value, ...args)
}, true),
)
const error = computed(() =>
enabled.value
? declaration.validations.reduce((err, validation) => {
if (err !== '') {
return err
}
const [rule, ...args] = validation.rule
return (validator[rule] as (...args: any[]) => boolean)(computedData.value, ...args)
? ''
: validation.message
}, '')
: '',
)
return [
key,
{
enabled,
enable,
disable,
error,
valid,
} as ValidationResult,
]
}),
) as Record<keyof T, ValidationResult>
const enable = () => Object.values(fields).forEach(field => field.enable())
const disable = () => Object.values(fields).forEach(field => field.disable())
const valid = computed(() => Object.values(fields).every(field => field.valid.value))
return {
fields,
enable,
disable,
valid,
}
}
|
75ae7dc24b2ac0423d2380825f8ad432a919fd1c | TypeScript | eleagnt/ChatService--UI | /src/services/WebsocketService/handlers/UserConnectedHandler.ts | 2.578125 | 3 | import BaseHandler from '@/services/WebsocketService/handlers/BaseHandler'
import { WebsocketReceivePayload } from '@/services/WebsocketService/WebsocketService'
import SocketUser from '@/entities/websocket/SocketUser'
import User from '@/entities/state/User'
interface UserConnectedPayload {
user: SocketUser
}
export default class UserConnectedHandler extends BaseHandler {
handle(payload: WebsocketReceivePayload) {
const { user: socketUser } = payload.data as UserConnectedPayload
const user: User = {
id: socketUser.id,
name: socketUser.id
}
this.store.commit({
type: 'USER_CREATE',
user
})
}
}
|
eb53789c29c999851213feec4908a72830c541dc | TypeScript | QDivision/chip | /src/utils/errors.ts | 3.15625 | 3 | import { log } from './log';
/**
* Prints a succinct error message (without a full stack trace). Useful
* for when non-fatal errors occur. Allows you to log them without polluting
* stdout/stderr with stack traces that detract from other important output.
*/
export const printError = ({ output, message }: any) => {
let msg = output || message || '---';
if (typeof msg === 'string') msg = msg.trim();
log`{red Error:} ${msg}`;
};
export const handleErrors = <T>(fn: (args: T) => Promise<void>) => async (
args: T,
) => {
try {
await fn(args);
} catch (e) {
log`{red An error occurred}`;
console.error(e);
process.exit(1);
}
};
|
e3e427974ca3fe1c1ae7598f6d0127059e65bc6d | TypeScript | ULL-ESIT-INF-DSI-2021/ull-esit-inf-dsi-20-21-prct11-menu-api-grupo-g | /src/models/Menu.ts | 2.703125 | 3 | import {Document, Schema, model} from 'mongoose';
interface MenuInterface extends Document {
name: string,
plates: any[],
price: number,
hydrates: number,
lipids: number,
proteins: number,
kcal: number,
groups: any[],
ingredients: any[],
}
const MenuSchema = new Schema({
name: {
type: String,
required: true,
unique: true,
trim: true,
validate: (value: string) => {
if (!value.match(/^[A-Z]/)) {
throw new Error('Los nombres de los menus deben empezar en mayuscula');
}
}
},
plates: {
type: Object,
required: true
},
price: {
type: Number,
},
hydrates: {
type: Number,
},
lipids: {
type: Number,
},
proteins: {
type: Number,
},
kcal: {
type: Number
},
groups: {
type: Object
},
ingredients: {
type: Object
}
});
export const Menu = model<MenuInterface>('Menu', MenuSchema); |