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 |
|---|---|---|---|---|---|---|
cc4fa5d918adc1b8aaaa0d5722be50ad24378fd6 | TypeScript | cdac-project-pold/POLD-Appointment-Booking-System | /Presentation/cdac_hospital_side/src/app/hospitalLogin/admin.ts | 2.828125 | 3 | import { Login } from '../login';
export class AdminLogin implements Login {
private username: string;
private password: string;
/**
*
*/
constructor() {
this.username = "a@b.com";
this.password = "abc";
}
login(_username: string, _password: string): boolean {
if (this.username === _username && this.password === _password) {
return true;
}
else {
return false;
}
}
logout(): void {
console.log("logged out");
}
}
|
6999a14dd3a293e5119731710d3159b26dfdfa30 | TypeScript | rd-dev-ukraine/rd-redux-http | /dist/typings/redux/api.d.ts | 2.859375 | 3 | import { Middleware } from "redux";
import { HttpRequest, HttpRequestWithBody, MakeRequestActionFactory, MakeRequestWithBodyActionFactory } from "../http";
import { WithReducer, ReduxHttpRequestTypes, ReduxHttpRequestWithBodyTypes } from "./http-request-redux";
/**
* HTTP request augmented for redux integration.
*/
export interface ReduxHttpRequest<TParams, TResult, TError = {}> extends HttpRequest<TParams, TResult, TError>, MakeRequestActionFactory<TParams>, WithReducer<TParams, TResult, TError> {
/**
* Exposes types of params, error, and result.
*
* Useful for avoiding duplication of types.
* Use it as const result: typeof myRequest.types.result = ...
*/
types: ReduxHttpRequestTypes<TParams, TResult, TError>;
}
/**
* HTTP request with body augmented for redux integration.
*/
export interface ReduxHttpRequestWithBody<TBody, TParams, TResult, TError> extends HttpRequestWithBody<TBody, TParams, TResult, TError>, MakeRequestWithBodyActionFactory<TParams, TBody>, WithReducer<TParams, TResult, TError> {
types: ReduxHttpRequestWithBodyTypes<TBody, TParams, TResult, TError>;
}
/**
* A redux middleware which augments rd-redux-http requests with methods for redux integration.
* Apply this middleware to store to run requests when rd-redux-http action is dispatched.
*/
export interface ReduxHttpMiddleware extends Middleware {
/**
* Registers rd-redux-http request in middleware and augment request object with redux integration methods.
*/
register<TParams, TResult, TError, TTransformed = TResult>(request: HttpRequest<TParams, TResult, TError>, transform?: (result: TResult, params?: TParams) => TTransformed): ReduxHttpRequest<TParams, TTransformed, TError>;
/**
* Registers rd-redux-http request with body in middleware and augment request object with redux integration methods.
*/
register<TBody, TParams, TResult, TError, TTransformed = TResult>(request: HttpRequestWithBody<TBody, TParams, TResult, TError>, transform?: (result: TResult, params?: TParams, body?: TBody) => TTransformed): ReduxHttpRequestWithBody<TBody, TParams, TTransformed, TError>;
}
|
3855957a4aec622069132d517cd494fc1f24f72a | TypeScript | statiolake/zenvim | /src/state.ts | 2.71875 | 3 | import * as vscode from 'vscode'
import { Mode, RegisterMode } from './types'
import { hasCommand, run } from './mapping/index'
type State = {
mode: Mode
composedText: string
statusBarItem: vscode.StatusBarItem | null
anchorPosition: vscode.Position
registerMode: RegisterMode
isInComposition: boolean
}
export const state: State = {
mode: Mode.NORMAL,
composedText: '',
statusBarItem: null,
anchorPosition: new vscode.Position(0, 0),
registerMode: RegisterMode.Char,
isInComposition: false
}
export function type(editor: vscode.TextEditor, text: string) {
if (state.mode === Mode.INSERT) {
vscode.commands.executeCommand('default:type', {
text: text
})
return
}
let composedText = state.composedText + text.trim()
if (hasCommand(state.mode, composedText)) {
const res = run(state.mode, editor, composedText)
if (res.run) {
composedText = ''
}
} else {
composedText = ''
}
state.composedText = composedText
}
export function setRegisterMode(registerMode: RegisterMode) {
state.registerMode = registerMode
}
function setCursorStyle(mode: Mode) {
if (!vscode.window.activeTextEditor) {
return
}
let cursorStyle = vscode.TextEditorCursorStyle.Block
if (mode === Mode.INSERT) {
cursorStyle = vscode.TextEditorCursorStyle.Line
} else if (mode === Mode.VISUAL) {
cursorStyle = vscode.TextEditorCursorStyle.LineThin
}
vscode.window.activeTextEditor.options = {
cursorStyle: cursorStyle
}
}
export async function setMode(mode: Mode) {
state.mode = mode
vscode.commands.executeCommand(
'setContext',
Mode.INSERT,
mode === Mode.INSERT
)
vscode.commands.executeCommand(
'setContext',
Mode.NORMAL,
mode === Mode.NORMAL
)
setCursorStyle(mode)
if (mode === Mode.INSERT) {
setStatusBarItemText('-- INSERT --')
} else if (mode === Mode.VISUAL) {
setStatusBarItemText('-- VISUAL --')
} else if (mode === Mode.VISUAL_LINE) {
setStatusBarItemText('-- VISUAL LINE --')
} else {
setStatusBarItemText('-- NORMAL --')
await vscode.commands.executeCommand('cancelSelection')
}
}
function setStatusBarItemText(text: string) {
if (state.statusBarItem) {
state.statusBarItem.text = text
}
}
export function setStatusBarItem(statusBar: vscode.StatusBarItem) {
state.statusBarItem = statusBar
statusBar.show()
}
export function setAnchorPosition(position: vscode.Position) {
state.anchorPosition = new vscode.Position(position.line, position.character)
}
export function replacePrevChar(text: string, replaceCharCnt: number) {
if (state.isInComposition) {
const { composedText } = state
state.composedText =
composedText.substr(0, composedText.length - replaceCharCnt) + text
}
vscode.commands.executeCommand('default:replacePreviousChar', {
text: text,
replaceCharCnt: replaceCharCnt
})
}
export function compositionStart() {
if (state.mode === Mode.INSERT) {
return
}
state.isInComposition = true
}
export function compositionEnd(editor: vscode.TextEditor) {
if (state.mode === Mode.INSERT) {
return
}
state.isInComposition = false
type(editor, state.composedText)
}
|
d981473647c423b51950dcc3701d6bb1317e5d14 | TypeScript | geunseok11/practice | /nested.ts | 3.65625 | 4 | const calc = (value: number, cb : (number) => void): void => {
let add = (a , b) => a + b
function multyply(a,b) {return a * b}
let result = multyply(add(1,2), value)
cb(result)
}
calc(30, (result:number) => console.log(`result is ${result}` )) |
6baab657d539dfeb7f92e0d2a2314dab98f74e89 | TypeScript | inkthought/trity | /src/commands/general/help.ts | 2.90625 | 3 | import { Command as CMD } from "../..";
import Discord from "discord.js";
let eye: number;
type o = {
name: string;
category: string | undefined;
}[];
type ok = {
general: string[];
inkthought: string[];
honkers: string[];
}[];
const Command: CMD = {
async run(client, message, args) {
// array to sort out what commands there are
let obj: o = [];
// sorts out obj according to category
let sorted: ok = [
{
general: [],
inkthought: [],
honkers: [],
},
];
for (eye = 0; eye < client.commands.array().length; eye++) {
obj.push({
name: client.commands.array()[eye].info.name,
category: client.commands.array()[eye].info.category,
});
if (obj[eye].category == "general") {
sorted[0].general.push(`\`${client.commands.array()[eye].info.name}\``);
}
if (obj[eye].category == "inkthought") {
sorted[0].inkthought.push(
`\`${client.commands.array()[eye].info.name}\``
);
}
if (obj[eye].category == "honkers") {
sorted[0].honkers.push(`\`${client.commands.array()[eye].info.name}\``);
}
}
const embed: Discord.MessageEmbed = new Discord.MessageEmbed()
.setTitle(":sparkles: Help")
.setColor("RANDOM")
.addFields(
{
name: "General",
value: sorted[0].general.join(", "),
inline: true,
},
{
name: "inkthought",
value: sorted[0].inkthought.join(", "),
inline: true,
},
{
name: "honkers",
value: sorted[0].honkers.join(", "),
inline: true,
}
)
.setFooter(
message.author.tag,
// @ts-ignore
message.author.avatarURL({
// @ts-ignore
type: "png",
dynamic: true,
size: 2048,
})
)
.setTimestamp();
return message.channel.send(embed);
},
info: {
name: "help",
title: "Help",
res: "",
aliases: ["h"],
},
};
export default Command;
|
91c674b67395a314253d6a63e5d180c72571e364 | TypeScript | juliocamargog/olimpo | /src/app/historico/historico.component.ts | 2.59375 | 3 | import { Component, OnDestroy, OnInit } from '@angular/core';
import { interval, UnsubscriptionError } from 'rxjs';
import { ConexaoService } from 'src/app/service/conexao.service';
import { ControleEntradaSaida, controleEntregasConcluidas, Entrega } from '../service/conexao.model';
interface Tipo {
value: string;
viewValue: string;
}
@Component({
selector: 'app-historico',
templateUrl: './historico.component.html',
styleUrls: ['./historico.component.css']
})
export class HistoricoComponent implements OnInit,OnDestroy {
constructor(private conexaoService:ConexaoService) { }
public controlePessoasEntrada = new Array<ControleEntradaSaida>();
public controlePessoasSaida = new Array<ControleEntradaSaida>();
public controleEntregasPendentes = new Array<Entrega>();
public controleEntregasConcluidas = new Array<controleEntregasConcluidas>();
private historico;
tipos: Tipo[] = [
{value: '0', viewValue: 'Entradas'},
{value: '1', viewValue: 'Saidas'},
{value: '2', viewValue: 'Entregas Pendentes'},
{value: '3', viewValue: 'Entregas Realizadas'},
];
selectedTipo = this.tipos[0].viewValue;
ngOnInit(): void {
this.ionViewDidEnter();
}
ionViewDidEnter(){
this.historico = this.conexaoService.getEntrada().subscribe(
data => {
const response = (data as any);
this.controlePessoasEntrada = response;
},
error =>{
console.log('ERROR');
}
);
}
selecionar(tipo){
if(tipo==="Entradas"){
this.historicoEntrada();
}if(tipo==="Saidas"){
this.historicoSaida();
}if(tipo==="Entregas Pendentes"){
this.entregasPendentes();
}if(tipo==="Entregas Realizadas"){
this.entregasRealizadas();
}
}
historicoEntrada(){
this.controlePessoasEntrada=[];
this.historico = this.conexaoService.getEntrada().subscribe(
data => {
const response = (data as any);
this.controlePessoasEntrada = response;
},
error =>{
console.log('ERROR');
}
);
}
historicoSaida(){
this.controlePessoasSaida=[];
this.historico = this.conexaoService.getSaida().subscribe(
data => {
const response = (data as any);
this.controlePessoasSaida = response;
},
error =>{
console.log('ERROR');
}
);
}
entregasPendentes(){
this.controleEntregasPendentes=[];
this.historico = this.conexaoService.getEntregasPendentes().subscribe(
data => {
const response = (data as any);
this.controleEntregasPendentes = response;
},
error =>{
console.log('ERROR');
}
);
}
entregasRealizadas(){
this.controleEntregasConcluidas=[];
this.historico = this.conexaoService.getEntregasConcluidas().subscribe(
data => {
const response = (data as any);
this.controleEntregasConcluidas = response;
},
error =>{
console.log('ERROR');
}
);
}
entregar(pendentes){
let indice = this.controleEntregasPendentes.indexOf(pendentes);
//Remove a entrega no banco de dados. pendentes valores em um array: {viewValue:'',bloco:'',num:,obs:''} //lembrando que num é do tipo number
this.conexaoService.entregasConcluidas(pendentes);
//Remove o item da lista de Entregas Pendentes.
while(indice>=0){
this.controleEntregasPendentes.splice(indice,1);
indice = this.controleEntregasPendentes.indexOf(pendentes);
}
}
ngOnDestroy(){
this.historico.unsubscribe();
}
}
|
5ab4e20779562b29fff22bf8201e96e584191882 | TypeScript | mhbarros/basic-auth | /backend/src/helpers/crypt.ts | 2.5625 | 3 | import bcrypt from 'bcrypt';
const passCrypt = '$mh$';
export async function hashPassword(password: string){
return await bcrypt.hash(password + passCrypt, 10);
}
export async function checkPassword(password: string, hash: string){
return await bcrypt.compare(password + passCrypt, hash);
} |
855445edf42a451aaa5190dea83093aece01fe9a | TypeScript | aman26ci/upstreet-task | /src/KYC/index.ts | 2.8125 | 3 | import dotenv from 'dotenv'; //it will parse .env file and add it to process.env
import axios from 'axios'; // used to call third party api
import { constants } from '../utils/constants';
import { validationError } from '../validators';
dotenv.config();
interface kycType {
birthDate: string;
givenName: string;
familyName: string;
licenceNumber: string;
stateOfIssue: string;
expiryDate: string;
middleName?: string;
}
export default class KYC {
private async checkKYC(kycBody) {
const config = {
headers: { Authorization: constants.CF_APITOKEN }
};
// if validation error is there that handled in validation file
if (validationError(kycBody, 'checkKYC')) return false;
try {
const {
data: { verificationResultCode: VRCode }
} = await axios.post(`${constants.BASEURL}/driverlicence`, kycBody, config);
if (VRCode) {
if (VRCode === 'Y') return { kycResult: true };
if (VRCode === 'N') return { kycResult: false };
if (VRCode === 'D' || VRCode === 'S') {
throw { code: VRCode, message: 'Document Error' };
}
}
} catch (error) {
return error;
}
}
//this function is created just to log the result .. :)
async checkYourKYC(kycBody: kycType) {
let result = await this.checkKYC(kycBody);
result = result || '';
console.log(result);
}
}
|
4e1785c28dcc86cb858dbb90fa8d3d6edea98c1b | TypeScript | levanthanh-ptit/techbase-code-challenge | /src/domains/models/department.model.ts | 2.640625 | 3 | import { ApiProperty } from '@nestjs/swagger';
import {
BelongsTo,
Column,
ForeignKey,
HasMany,
Model,
Table,
} from 'sequelize-typescript';
import { Team } from './team.model';
import { User } from './user.model';
export interface IDepartment {
id: number;
name: string;
managerId: number;
}
export interface IDepartmentCreator extends Omit<IDepartment, 'id'> {}
@Table
export class Department extends Model implements IDepartment {
@ApiProperty()
id: number;
@ApiProperty()
@Column
name: string;
@ForeignKey(() => User)
managerId: number;
@BelongsTo(() => User, {
foreignKey: 'managerId',
})
manager: User;
@HasMany(() => Team, {
foreignKey: 'departmentId',
})
teams: Array<Team>;
}
|
e2ee817e78a2c12f83f1af345bb69460ca2064ed | TypeScript | wikiwi/typeless | /src/check-parse-results.ts | 2.578125 | 3 | import { TypingsData, existsTypesDataFileSync, readTypings } from "./lib/common";
import { Logger, logger, writeLog } from "./util/logging";
import { done } from "./util/util";
if (!module.parent) {
if (!existsTypesDataFileSync()) {
console.log("Run parse-definitions first!");
} else {
done(main());
}
}
export default async function main(): Promise<void> {
const infos = await readTypings();
const [log, logResult] = logger();
check(infos, info => info.libraryName, "Library Name", log);
check(infos, info => info.projectName, "Project Name", log);
await writeLog("conflicts.md", logResult());
}
function check(infos: TypingsData[], func: (info: TypingsData) => string | undefined, key: string, log: Logger): void {
const lookup: { [libName: string]: string[] } = {};
infos.forEach(info => {
const name = func(info);
if (name !== undefined) {
(lookup[name] || (lookup[name] = [])).push(info.typingsPackageName);
}
});
for (const k of Object.keys(lookup)) {
if (lookup[k].length > 1) {
log(` * Duplicate ${key} descriptions "${k}"`);
lookup[k].forEach(n => log(` * ${n}`));
}
}
}
|
9619ddfc0d597f391860ad40669ccd60a4d93480 | TypeScript | AnandChowdhary/train-natural | /index.spec.ts | 2.875 | 3 | import { train } from "./index";
import { BayesClassifier, LogisticRegressionClassifier } from "natural";
import { join } from "path";
import { writeFile, mkdirp, readdir } from "fs-extra";
describe("train-natural", () => {
it("finds labels to train", async () => {
const classifier = new BayesClassifier();
const { labels } = await train(classifier, join(".cache"));
expect(labels).toEqual(["india", "the-netherlands"]);
});
it("trains BayesClassifier and detects IN", async () => {
const classifier = new BayesClassifier();
await train(classifier, join(".cache"));
const result = classifier.classify(
"Southern Asian country with a rich culture"
);
expect(result).toBe("india");
});
it("trains BayesClassifier and detects NL", async () => {
const classifier = new BayesClassifier();
await train(classifier, join(".cache"));
const result = classifier.classify(
"Liberal European country with tall people"
);
expect(result).toBe("the-netherlands");
});
it("does not report files as labels", async () => {
const classifier = new BayesClassifier();
const files = await readdir(join(".cache"));
const { labels } = await train(classifier, join(".cache"));
expect(files.length === labels.length).toBeFalsy();
});
it("works with LogisticRegressionClassifier", async () => {
const classifier = new LogisticRegressionClassifier();
await train(classifier, join(".cache"));
const result = classifier.classify(
"Southern Asian country with a rich culture"
);
expect(result).toBe("india");
});
beforeAll(async () => {
await mkdirp(join(".cache", "india"));
await mkdirp(join(".cache", "the-netherlands"));
await writeFile(join(".cache", "1.txt"), "Example file");
await writeFile(
join(".cache", "india", "1.txt"),
"India is a country in south Asia"
);
await writeFile(
join(".cache", "india", "2.txt"),
"India known for its rich culture, diversity, and cuisine"
);
await writeFile(
join(".cache", "the-netherlands", "1.txt"),
"The Netherlands is a country in Northwestern Europe"
);
await writeFile(
join(".cache", "the-netherlands", "2.txt"),
"The Netherlands is known for social tolerance, freedom, tall people"
);
});
});
|
ee684bd58c286b978258d6cc26567767438a971b | TypeScript | shijianjian/elememo | /src/app/store/memo.reducer.ts | 2.71875 | 3 | import { MemoModel } from 'app/model/memo.model';
import { List } from 'immutable';
import { ADD_MEMO_ACTION, EDIT_MEMO_ACTION, DeleteMemoAction, DELETE_MEMO_ACTION, AddMemoAction, EditMemoAction, CALLBACK_ACTION, CallbackAction, LOAD_DATA_ACTION, LoadDataAction } from './memo.action';
import { Action } from '@ngrx/store';
import { MemoState, INITIAL_MEMO_STATE } from './memo.state';
export function memoReducer(state: MemoState = INITIAL_MEMO_STATE, action: Action) : MemoState {
console.log(action.type)
switch (action.type) {
case ADD_MEMO_ACTION:
return handleAddMemoAction(state, <AddMemoAction>action);
case EDIT_MEMO_ACTION:
return handleEditMemoAction(state, <EditMemoAction>action);
case DELETE_MEMO_ACTION:
return handleDeleteMemoAction(state, <DeleteMemoAction>action);
case CALLBACK_ACTION:
return handleCallbackAction(state, <CallbackAction>action);
case LOAD_DATA_ACTION:
return handleLoadDataAction(state, <LoadDataAction>action);
default:
return state;
}
}
function handleAddMemoAction(state: MemoState, action: AddMemoAction): MemoState {
const newState = {
items: state.items ? state.items.push(action.payload) : List<MemoModel>([action.payload])
}
return newState;
}
function handleEditMemoAction(state: MemoState, action: EditMemoAction): MemoState {
let index = findMemoIndex(state, action.payload);
const newState = {
items: state.items.set(index, action.payload)
}
return newState;
}
function handleDeleteMemoAction(state: MemoState, action: DeleteMemoAction): MemoState {
let index = findMemoIndex(state, action.payload);
const newState = {
items: state.items.remove(index)
}
return newState;
}
function handleLoadDataAction(state: MemoState, action: LoadDataAction) : MemoState {
let newCollection = action.rewrite ? List<MemoModel>([]) : state.items
action.payload.forEach((value) => {
newCollection = newCollection.push(value);
})
console.log(action)
return {
items: newCollection
};
}
function handleCallbackAction(state: MemoState, action: CallbackAction) : MemoState {
console.log(action);
if(action.status) {
return state;
}
// Rollback error
return state;
}
function findMemoIndex(state: MemoState, value: MemoModel): number {
let index: number;
state.items.forEach((memo: MemoModel, i: number) => {
if(memo.id === value.id) {
index = i;
return false;
}
})
if(typeof index === 'undefined') {
throw new ReferenceError(`Target memo '${value.title}' not found ...`);
}
return index;
} |
fffaf4fa3aeb460189337aea17efbc22691a788c | TypeScript | jjwall/ggj2020 | /src/engine/behavior.ts | 2.953125 | 3 | import { BaseState } from "../basestate";
import { Entity } from "./entity";
export enum BehaviorResult {
SUCCESS,
FAIL
}
export type Behavior = any;
export function sequence(...behaviors: (() => Behavior)[]) {
return function* (): Behavior {
for (const b of behaviors) {
const result = yield* b();
if (result === BehaviorResult.FAIL) {
return BehaviorResult.FAIL;
}
}
return BehaviorResult.SUCCESS;
};
}
export function choice(...behaviors: (() => Behavior)[]): () => Behavior {
return function* (): Behavior {
for (const b of behaviors) {
const result = yield* b();
if (result === BehaviorResult.SUCCESS) {
return BehaviorResult.SUCCESS;
}
}
return BehaviorResult.FAIL;
};
}
|
deb6f72bb2a9f3c5bf400cdd88ad7cfee80d78a7 | TypeScript | PaaS-TA/PAAS-TA-PORTAL-WEBUSER | /src/app/model/domain.ts | 2.96875 | 3 | export class Domain {
/*
// DATA MODEL IS...
private metadata = {
created_at: null,
guid: null,
updated_at: null,
url: null
};
private entity = {
name: null,
owning_organization_guid: null,
router_group_guid: null,
router_group_type: null,
shared_organizations: null
}
*/
private _metadata;
private _entity;
constructor(metadata?, entity?) {
this.metadata = metadata;
this.entity = entity;
}
static empty() {
return new Domain(null, null);
}
private get metadata(){
return this._metadata;
}
private set metadata(extMetadata) {
if (extMetadata === null || extMetadata === undefined) {
this._metadata = {
created_at: '(created_at_dummy)',
guid: '(id_dummy)',
updated_at: '(updatedAt_dummy)',
url: '(quota_url_dummy)'
};
} else {
this._metadata = extMetadata;
}
}
private get entity() {
return this._entity;
}
private set entity(extEntity) {
if (extEntity === null || extEntity === undefined) {
this._entity = {
name: '(name_dummy)',
owning_organization_guid: '(org_guid_dummy)',
router_group_guid: null,
router_group_type: null,
shared_organizations: null
};
} else {
this._entity = extEntity;
}
}
////// in metadata //////
get guid() {
return this.metadata.guid;
}
get createdAt() {
return this.metadata.created_at;
}
get updatedAt() {
return this.metadata.updated_at;
}
get url() {
return this.metadata.url;
}
////// in entity //////
get name() {
return this.entity.name;
}
get owningOrganizationId() {
return this.entity.owning_organization_guid;
}
get routerGroupGuid() {
return this.entity.router_group_guid;
}
get routerGroupType() {
return this.entity.router_group_type;
}
get sharedOrganizations(): Array<String> {
return this.entity.shared_organizations.split(',').map((v) => {
return v.trim();
});
}
get shared(): boolean {
return (this.owningOrganizationId === null || this.owningOrganizationId === undefined);
}
}
|
116d7c767bd15fa4595b2858465430419b9667de | TypeScript | workfel/kata-social-network-clean-archi | /libs/social-network-redux/src/core/use-cases/publish-message-to-timeline/publish-message-to-timeline.reducers.ts | 2.609375 | 3 | import * as actionCreators from './publish-message-to-timeline.actions';
import { CANNOT_PUBLISH_TIMELINE_MESSAGE, PUBLISH_TIMELINE_MESSAGE } from './publish-message-to-timeline.actions';
import { combineReducers } from 'redux';
const messages = (state: string[] = [],
action: actionCreators.Actions) => {
if (action.type === PUBLISH_TIMELINE_MESSAGE) {
return state.concat(action.payload.publishMessage);
}
return state;
};
const publishError = (state: string= '',
action: actionCreators.Actions) => {
if (action.type === CANNOT_PUBLISH_TIMELINE_MESSAGE) {
return action.payload.reason;
}
return state;
};
export default combineReducers({
messages,
publishError
});
|
5030c5d0185b96c005f3fbe49aa0338f366f442d | TypeScript | 0n3W4y/Tiny-Tale-Fight-OOP | /source/ts_scripts/Game.ts | 2.53125 | 3 | class Game {
public fps;
public commonTick:any;
public entityRoot:any;
public battle:any;
public userInterface:any;
private preStartDone:boolean;
private player:any;
private helper:any;
constructor( fps ){
this.fps = fps;
this.preStartDone = false;
}
public init( creaturesData, creatureClassData, humanoidsData, humanoidsClassData, humanoidsHelperData, orbsData, orbsClassData, leftBlock, rightBlock, journal, helperBlock, enemylist, orbsBlock ){
this.commonTick = new CommonTick( this, this.fps );
this.entityRoot = new EntityRoot( this, creaturesData, creatureClassData, humanoidsData, humanoidsClassData, humanoidsHelperData, orbsData, orbsClassData );
this.battle = new Battle( this );
this.userInterface = new UserInterface( this, leftBlock, rightBlock, journal, helperBlock, enemylist, orbsBlock );
}
public start(){
this.commonTick.startLoop();
}
public stop(){
this.commonTick.stopLoop();
}
public pause(){
this.commonTick.togglePause();
}
public update( delta ){
this.battle.update( delta );
if( this.preStartDone ){
if( !this.battle.isFighting ){
this.askForNextBattle();
}
}
}
public generatePlayer(){
var player = this.entityRoot.generateEntity( "Player", null, null, {Name:{ name:"Ostin", surname:"Powers"}} );
this.battle.addPlayerToFight( 1, player );
var fullName = player.getComponent( "Name" ).getFullName();
var playerClass = player.getComponent( "Type" ).class;
var string = fullName + " created! Class: " + playerClass;
this.userInterface.journal.addLineToJournal( string );
this.player = player;
}
public generateMob(){
//var entityList = this.entityRoot.getListOfEntities();
var lvl = 1;
if( this.player != null )
lvl = this.player.getComponent( "ExperienceStats" ).lvl;
var min = lvl - 2;
var max = lvl + 2;
if( min < 1 )
min = 1;
if( max > 100 )
max = 100;
var mobLevel = Math.floor( Math.random()*(max - min + 1) + min );
var mob = this.entityRoot.generateEntity( "Mob", null, null, null );
mob.getComponent( "ExperienceStats" ).lvl = mobLevel;
mob.getComponent( "ExperienceStats" ).updateComponent();
this.battle.addPlayerToFight( 2, mob );
}
private generateHelper(){
var helper = this.entityRoot.generateEntity( "Helper", null, null, {Name:{ name:"Super", surname:"Helper"}} );
this.battle.addPlayerToFight( 1, helper );
var fullName = helper.getComponent( "Name" ).getFullName();
var playerClass = helper.getComponent( "Type" ).class;
var string = fullName + " created! Class: " + playerClass;
this.userInterface.journal.addLineToJournal( string );
this.helper = helper;
}
//must be deleted!!!
public preStart(){
//TODO: create player - > generate Mobs -> start fight;
this.generatePlayer();
this.generateHelper();
var playerLvl = this.player.getComponent( "ExperienceStats" ).lvl;
var max = Math.round( 4 + playerLvl/5 );
var min = Math.round( 1 + playerLvl/5 );
this.generateSomeMobs( min, max );
this.preStartDone = true;
this.battle.startFight();
}
public reset(){
location.reload(true);
}
private askForNextBattle(){
if( this.player.getComponent( "FightingStats" ).killedBy != null )
this.generatePlayer();
this.battle.addPlayerToFight( 1, this.player );
if( this.helper.getComponent( "FightingStats" ).killedBy != null )
this.generateHelper();
this.battle.addPlayerToFight( 1, this.helper );
var playerLvl = this.player.getComponent( "ExperienceStats" ).lvl;
var max = Math.round( 4 + playerLvl/5 );
var min = Math.round( 1 + playerLvl/5 );
this.generateSomeMobs( min, max );
this.preStartDone = true;
this.battle.startFight();
}
private generateSomeMobs( min, max ){
var randomNum = Math.floor( min + Math.random() * ( max - min + 1 ) );
for( var i = 0; i < randomNum; i++ ){
this.generateMob();
}
}
} |
a49caa70f016c95b4dc01943112fbfbe768999e3 | TypeScript | gaabriel165/api-graphql | /server-graphql/src/resolver/resolvers.ts | 2.828125 | 3 | import {
getUsers,
newUser,
updateUserById,
deleteUserById,
} from "../repository/User";
export const resolvers = {
Query: {
getUser: async () => {
const users = await getUsers();
const usersParsed = users.map((e) => {
const createdAt = String(e.createdAt).split(" ");
const dto = {
id: e.id,
name: e.name,
type: e.type,
createdAt: String(
createdAt[1] + " " + createdAt[2] + " " + createdAt[3]
),
updatedAt: e.updatedAt,
};
return dto;
});
return usersParsed;
},
},
Mutation: {
newUser: async (_: any, { name, type }: { name: string; type: string }) => {
const user = {
name: name,
type: type,
};
return newUser(user);
},
updateUserById: async (
_: any,
{ id, name, type }: { id: number; name: string; type: string }
) => {
const result = await updateUserById(id, name, type);
if (result.affected) {
return true;
} else {
return false;
}
},
deleteUserById: async (_: any, { id }: { id: number }) => {
const result = await deleteUserById(id);
if (result.affected) {
return true;
} else {
return false;
}
},
},
};
|
cbe328c3db82563abbbc0f8936f6f312cdd1e102 | TypeScript | SuyaSaju/InfantNutritionBackend | /src/products/entities/review.entity.ts | 2.546875 | 3 | import { Column, Entity, ObjectID, ObjectIdColumn } from 'typeorm';
@Entity({ name: 'reviews' })
export class Review {
@ObjectIdColumn()
id: ObjectID;
@Column()
brandId: string;
@Column()
productId: string;
@Column()
name: string;
@Column()
rating: number;
@Column()
title: string;
@Column()
date: Date;
@Column()
isVerifiedPurchase: boolean;
@Column()
textContent: string;
@Column()
foundHelpful: number;
@Column()
sentiment: ReviewSentiment;
}
export interface ReviewSentiment {
positive: number
negative: number
neutral: number
compound: number
}
|
c50f56f66dccb7f1985c357e331d1fc689888c53 | TypeScript | iffameah/component | /about.component.ts | 2.515625 | 3 | import { Component } from '@angular/core';
import {Config} from './config.service';
import {Video} from './video';
import {playlistComponent} from './playlist.component';
@Component({
selector: 'about',
templateUrl: './components/about.component.html'
})
export class AboutComponent {
/*using the class var in data binding & using call fn for codes in Config*/
mainHeading = Config.MAIN_HEADING;
videos:Array<Video>; //bt satu list video dlm bntk array& letak var type sbgai video
constructor(){
/*inserting information about the videos*/
this.videos = [
new Video(1,"Fairy Tail", "f9Q4BHPr674", "watch it on9 baby!"),
new Video(2,"Deadpool", "4eP49zRmMFM", "suckerss!hahahahhaa"),
new Video(3,"Civil War", "0NHyXQCKsaU", "CAPTAIN <3!"),
]
}
} |
fa8146a001e86af5e9452413752ad3603aad68d2 | TypeScript | keff6/100AlgorithmsChallenge | /boxBlur/boxBlur.ts | 3.09375 | 3 | function boxBlur(image: number[][]): number[][] {
const widthLen = image[0].length - 3;
const heightLen = image.length - 3;
const result = [];
for(let i=0; i <= widthLen; i++) {
const currentPixelLine = [];
for(let j = 0; j <= heightLen; j++) {
const currentMatrix = image.slice(i,i+3).map(line => line.slice(j,j+3));
const pixel = getPixel(currentMatrix);
currentPixelLine.push(pixel);
}
result.push(currentPixelLine);
}
return result;
}
function getPixel(matrix) {
const valuesFromMatrix = [];
matrix.forEach(val => valuesFromMatrix.push(...val));
return Math.floor(valuesFromMatrix.reduce((acum, curr) => acum += curr) / 9);
}
console.log(boxBlur([[1, 1, 1],
[1, 7, 1],
[1, 1, 1]])); |
364176547ce55fa4d4b4ac883cac12530255a130 | TypeScript | motion-canvas/motion-canvas | /packages/core/src/utils/debug.ts | 3.3125 | 3 | import {useLogger} from './useScene';
import {LogPayload} from '../app';
function stringify(value: any): string {
switch (typeof value) {
case 'string':
// Prevent strings from getting quoted again
return value;
case 'undefined':
// Prevent `undefined` from being turned into `null`
return 'undefined';
default:
// Prevent `NaN` from being turned into `null`
if (Number.isNaN(value)) {
return 'NaN';
}
return JSON.stringify(value);
}
}
/**
* Logs a debug message with an arbitrary payload.
*
* @remarks
* This method is a shortcut for calling `useLogger().debug()` which allows
* you to more easily log non-string values as well.
*
* @example
* ```ts
* export default makeScene2D(function* (view) {
* const circle = createRef<Circle>();
*
* view.add(
* <Circle ref={circle} width={320} height={320} fill={'lightseagreen'} />,
* );
*
* debug(circle().position());
* });
* ```
*
* @param payload - The payload to log
*/
export function debug(payload: any) {
const result: LogPayload = {message: stringify(payload)};
if (payload && typeof payload === 'object') {
result.object = payload;
}
useLogger().debug(result);
}
|
459ec840a82555398ce99571de88b9396668d26f | TypeScript | joalisson/eng-zap-challenge-nodejs | /src/utils/DataSource.ts | 2.640625 | 3 | import fs from 'fs';
import logger from '../../logger';
import client from '../client';
import { IDataSource } from '../interfaces/datasource.interface';
import { IServiceFilter } from '../interfaces/service.interface';
const path = './datasource/data.json';
class DataSource {
private async get() {
try {
let data = fs.existsSync(path);
if (!data) {
logger.info('Get response from API');
const response = await client();
fs.writeFileSync(path, JSON.stringify(response), 'utf8');
}
const buffer = fs.readFileSync(path, 'utf8');
return JSON.parse(buffer);
} catch (error) {
logger.error(error);
}
}
private formatResponse(data: IDataSource[], limit: number, offset: number) {
const totalCount = data.length;
const listings = data.slice(offset * limit, (offset * limit) + limit);
return {
listings,
totalCount,
pageNumber: offset + 1,
pageSize: listings.length
}
}
private checkBoundingBox(lat: number, lon: number) {
const minLon = -46.693419;
const minLat = -23.568704;
const maxLon = -46.641146;
const maxLat = -23.546686;
return (lat > maxLat && lat < minLat) && (minLon > lon && maxLon < lon);
}
private checkEligibleProperty(item: IDataSource, type: string, portal: string) {
if (
item.usableAreas === 0 ||
item.address.geoLocation.location.lat === 0 ||
item.address.geoLocation.location.lon === 0
) {
return false;
}
switch (portal) {
case 'zap':
if (type === 'sale' && item.usableAreas > 350) {
return item;
}
if (type === 'rent' && item.usableAreas <= 350) {
return item;
}
case 'viva-real':
if (type === 'rent') {
let percent = 30;
const boundingBox = this.checkBoundingBox(item.address.geoLocation.location.lat, item.address.geoLocation.location.lon);
if (boundingBox) {
percent = 50;
}
const monthlyCondoFee = parseInt(item.pricingInfos.monthlyCondoFee);
const total = (percent * 100) / parseInt(item.pricingInfos.price);
if (typeof monthlyCondoFee !== 'number' || total > monthlyCondoFee) {
return false;
}
return item;
}
default:
break;
}
}
private getDataByPortal(data: IDataSource[], type: string, portal: string) {
return data.filter((item: IDataSource) => {
const checked = this.checkEligibleProperty(item, type, portal);
return checked !== false;
});
}
public async service({ type, limit, offset, service }: IServiceFilter) {
const data = await this.get();
const res = this.getDataByPortal(data, type, service);
return this.formatResponse(res, limit, offset);
}
};
export default DataSource; |
aba19de5e085ebf1c81d47148027778d91e71c37 | TypeScript | rasha08/react-form-fp | /src/form/actions.ts | 2.703125 | 3 | import {
ADD_FIELD,
CLEAR_FIELD_ERROR,
FieldName,
FieldValue,
FormActionDispatcher,
FormContextState,
SET_FILED_ERROR,
SET_FILED_VALUE,
UseFormActions
} from './types'
export const useFormActions = <FormName extends string | number, T>(
state: FormContextState<FormName, T>,
dispatch: FormActionDispatcher<FormName, T>
): UseFormActions<FormName, T> => {
const setFieldValueAction = (
formName: FormName,
field: FieldName<T>,
value: FieldValue
): void => {
dispatch({
type: SET_FILED_VALUE,
payload: {
formName,
field,
value
}
})
}
const setFieldErrorAction = (
formName: FormName,
field: FieldName<T>,
error: string
): void => {
dispatch({
type: SET_FILED_ERROR,
payload: {
formName,
field,
error
}
})
}
const clearFieldError = (formName: FormName, field: FieldName<T>): void => {
if (!state.errors[formName] || !state.errors[formName][field]) {
return
}
dispatch({
type: CLEAR_FIELD_ERROR,
payload: {
formName,
field
}
})
}
const addFieldAction = (
formName: FormName,
field: string,
value: FieldValue
): void => {
dispatch({
type: ADD_FIELD,
payload: {
formName,
field,
value
}
} as any)
}
const removeFieldAction = (formName: FormName, field: string): void => {
dispatch({
type: ADD_FIELD,
payload: {
formName,
field
}
} as any)
}
return {
setFieldValueAction,
setFieldErrorAction,
clearFieldError,
addFieldAction,
removeFieldAction
}
}
|
7fc702afe1d1b56a6ab9b808cb4dbd66d155cc65 | TypeScript | jfouche/moria | /app/views/game-view.ts | 2.828125 | 3 | import { MoriaGame } from "../game"
import { MazeView } from "./maze-view";
import { HeroView } from "./hero-view";
import p5 = require('p5')
import { RoomView } from "./cell-view";
/**
* GameView
*/
export class GameView {
public readonly game: MoriaGame;
public readonly width: number;
public readonly height: number;
constructor(game: MoriaGame) {
this.game = game;
this.height = this.game.nRows * RoomView.width + 1;
this.width = this.game.nCols * RoomView.width + 1;
}
public draw(p: p5) {
p.background(0);
const mv = new MazeView(this.game.maze());
mv.draw(p);
const hero = this.game.getHero();
const hv = new HeroView(hero);
hv.draw(p);
const level = this.game.getLevel() + 1;
document.getElementById("nLevel").innerHTML = `Level ${level}`;
const life = hero.life.toString();
document.getElementById("life").innerHTML = `Life ${life}`;
}
}
|
d2a60038c3fe0b1c923b3f7eb4c52eaa6d0fd34f | TypeScript | boyanstanchev/crwn-clothing | /src/redux/user/user.reducer.ts | 2.828125 | 3 | import UserActionTypes from './user.types'
import { User, UserState } from './user.models'
import BaseAction from '../base-action.model'
const INITIAL_STATE = {
currentUser: null,
}
const userReducer = (
state: UserState = INITIAL_STATE,
action: BaseAction<UserActionTypes, User>
) => {
switch (action.type) {
case UserActionTypes.SET_CURRENT_USER:
return {
...state,
currentUser: action.payload,
}
default:
return state
}
}
export default userReducer
|
e3f3f5dffac40e578db30e54ac14f59372157da5 | TypeScript | nathan-charles/react-native-blog-app | /src/redux/post/actions.ts | 2.765625 | 3 | import { Action } from 'redux';
import { ThunkAction } from 'redux-thunk';
import { AppState } from '../index';
import {
Post,
FETCH_USER_POSTS_PENDING,
FETCH_USER_POSTS_SUCCESS,
FETCH_USER_POSTS_ERROR,
FETCH_OTHER_POSTS_PENDING,
FETCH_OTHER_POSTS_SUCCESS,
FETCH_OTHER_POSTS_ERROR,
} from './types';
const API_ENDPOINT = 'https://jsonplaceholder.typicode.com';
export const fetchUserPosts = (
userId: number,
): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
try {
dispatch({
type: FETCH_USER_POSTS_PENDING,
});
const response = await fetch(`${API_ENDPOINT}/posts?userId=${userId}`);
const posts: [Post] = await response.json();
dispatch({
type: FETCH_USER_POSTS_SUCCESS,
payload: posts,
});
} catch (error) {
dispatch({
type: FETCH_USER_POSTS_ERROR,
payload: error,
});
}
};
export const fetchOtherPosts = (
userId: number,
): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
try {
dispatch({
type: FETCH_OTHER_POSTS_PENDING,
});
const response = await fetch(`${API_ENDPOINT}/posts`);
const posts: [Post] = await response.json();
dispatch({
type: FETCH_OTHER_POSTS_SUCCESS,
payload: posts.filter(p => p.userId !== userId),
});
} catch (error) {
dispatch({
type: FETCH_OTHER_POSTS_ERROR,
payload: error,
});
}
};
|
5cf484701782a3af64d659b7ed3cd90b0efaf0f6 | TypeScript | adacahq/creator | /src/types/User.ts | 2.640625 | 3 | import { Omit } from 'types/util/Omit';
export interface User {
id: string;
email: string;
}
export type UserNew = Omit<User, 'id'>;
|
c098f0500095fa17b9e1112e71656d7cef78c0cf | TypeScript | Simone3/ReactMediaTracker | /react-media-tracker/app/data/models/api/common.ts | 3.296875 | 3 | import { IsDefined, IsOptional, IsString } from 'class-validator';
/**
* Type shared by all API requests
*/
export class CommonRequest {
}
/**
* Type shared by all API responses
*/
export class CommonResponse {
/**
* A generic message for easy response reading, should never be displayed to the user
*/
@IsOptional()
@IsString()
public message?: string;
}
/**
* Generic response for a failure outcome
*/
export class ErrorResponse extends CommonResponse {
/**
* A unique error code, should never be displayed to the user
*/
@IsOptional()
@IsString()
public errorCode: string;
/**
* An error description, should never be displayed to the user
*/
@IsOptional()
@IsString()
public errorDescription: string;
/**
* Optional details for the error, should never be displayed to the user
*/
@IsOptional()
@IsString()
public errorDetails?: string;
/**
* Constructor
* @param errorCode source code
* @param errorDescription source description
* @param errorDetails source details
*/
public constructor(errorCode: string, errorDescription: string, errorDetails?: string) {
super();
this.errorCode = errorCode;
this.errorDescription = errorDescription;
this.errorDetails = errorDetails;
}
}
/**
* Type that can be extended by insert or update API requests for common fields
*/
export class CommonSaveRequest extends CommonRequest {
}
/**
* Type that can be extended by "add new" APIs to return the new entity ID
*/
export class CommonAddResponse extends CommonResponse {
/**
* The new element unique ID
*/
@IsDefined()
@IsString()
public uid!: string;
}
|
73dbdf3f09553c60b413a4bd8114064423ed58bf | TypeScript | Eazymov/urtk-express-mongodb | /src/api/instance.ts | 2.625 | 3 | import Axios, { AxiosInstance } from 'axios';
type Data = {
[key: string]: any;
}
const instance: AxiosInstance = Axios.create({
baseURL: '/api',
timeout: 3000,
transformResponse: [transformResponse],
});
function transformResponse (response: any): any {
const data: Data = JSON.parse(response);
const err: ApiError | undefined = data.err;
if (err) {
throw Error(err.message || err.errmsg);
}
return data;
}
export default instance;
|
0ecf817e1774e871ac5051b869dfeebfe754462f | TypeScript | future4code/Pedro-Severo | /semana-14/RedeSocial/SOLID/src/animal.ts | 2.828125 | 3 | import { Bird } from "./bird";
export abstract class Animal {
// constructor(public name: string) {}
constructor(protected name: string) {}
public getName(): string {
return this.name;
}
}
|
40f777c01809121cd230ae269e75fa6d3fc9802f | TypeScript | lyon1986/i3yun.ViewerGallery | /ref/Sippreep.Extensions.PickPoint.d.ts | 2.53125 | 3 | /// <reference types="THREE" />
declare namespace Sippreep {
namespace Extensions {
namespace PickPoint {
/**
* 拾取三维点插件
*/
export interface PickPointExtension {
/**
* 启用拾取点
*/
enableMode(): void;
/**
* 注册拾取点回调函数(如果重复则返回false,否则返回true)
* @param callback 回调函数
*/
registerPointCallback(callback: (point: THREE.Vector3) => void): boolean;
/**
* 解除拾取点回调函数(如果解除存在则返回true,否则返回false)
* @param callback 回调函数
*/
unregisterPointCallback(callback: (point: THREE.Vector3) => void): boolean;
}
}
}
} |
58a75a0f4e4f7b45670ec05a2c06beff14341dde | TypeScript | CodeExpertsLearning/workshop-angular-na-pratica-presencial | /ts/test.ts | 2.59375 | 3 | class Export {
sayHello(hello: string) {
console.log(hello);
}
}
function sayHello(hello: string) {
console.log(hello);
}
sayHello(12);
|
d8ba05c1851d119105778a34a4569f08323eda34 | TypeScript | NemoTravel/flights.search.widget | /src/store/form/passengers/reducer.ts | 2.90625 | 3 | import { ADD_PASSENGER, REMOVE_PASSENGER, SET_PASSENGER_COUNTER } from '../../actions';
import { PassengersState, passengersState, PassengerState } from '../../../state';
import { PassengersAction } from './actions';
export const setPassengersCounterReducer = (state: PassengerState, count: number): PassengerState => {
return { ...state, count };
};
export const passengersReducer = (state: PassengerState, { type, payload }: PassengersAction): PassengerState => {
switch (type) {
case ADD_PASSENGER:
return { ...state, count: state.count + 1 };
case REMOVE_PASSENGER:
return { ...state, count: state.count - 1 };
case SET_PASSENGER_COUNTER:
return setPassengersCounterReducer(state, payload);
}
return state;
};
export default (state: PassengersState = passengersState, action: PassengersAction): PassengersState => {
if (action.passengerType) {
return {
...state,
[action.passengerType]: passengersReducer(state[action.passengerType], action)
};
}
return state;
};
|
cc4ba15c2fd75d17bf2db43cec881d354c7dc6b1 | TypeScript | gdeb/crap-framework | /tests/domain.test.ts | 3.15625 | 3 | import { tokenize, evaluate } from "../src/domain";
describe("tokenizer", () => {
test("basic properties", () => {
expect(tokenize("")).toEqual([]);
expect(tokenize("1")).toEqual([{ type: "value", value: 1 }]);
expect(tokenize("1 2")).toEqual([
{ type: "value", value: 1 },
{ type: "value", value: 2 }
]);
expect(tokenize("-1")).toEqual([{ type: "value", value: -1 }]);
expect(tokenize("OR")).toEqual([{ type: "or" }]);
expect(tokenize("AND")).toEqual([{ type: "and" }]);
expect(tokenize("=")).toEqual([{ type: "=" }]);
expect(tokenize("(")).toEqual([{ type: "open" }]);
expect(tokenize("abc")).toEqual([{ type: "field", value: "abc" }]);
expect(tokenize('"abc"')).toEqual([{ type: "value", value: "abc" }]);
expect(tokenize('"abc"')).toEqual([{ type: "value", value: "abc" }]);
});
test("tokenizer and parenthesis", () => {
expect(tokenize("(1 2)")).toEqual([
{ type: "open" },
{ type: "value", value: 1 },
{ type: "value", value: 2 },
{ type: "close" }
]);
expect(tokenize("(()")).toEqual([
{ type: "open" },
{ type: "open" },
{ type: "close" }
]);
expect(tokenize("(a = 1)")).toEqual([
{ type: "open" },
{ type: "field", value: "a" },
{ type: "=" },
{ type: "value", value: 1 },
{ type: "close" }
]);
});
test("tokenizer and strings", () => {
expect(tokenize('"hello world"')).toEqual([
{ type: "value", value: "hello world" }
]);
});
});
describe("domain evaluation", () => {
test("basic domain expressions", () => {
expect(evaluate('hello = "world"', { id: "1", hello: "world" })).toBe(true);
expect(evaluate('hello = "world"', { id: "1", hello: "not world" })).toBe(
false
);
expect(evaluate("a = 1", { id: "1", a: 1 })).toBe(true);
expect(evaluate("a = 1 AND b = 2", { id: "1", a: 1, b: 2 })).toBe(true);
expect(evaluate("a = 1 AND b = 4", { id: "1", a: 1, b: 2 })).toBe(false);
expect(evaluate("a = 13 OR b = 2", { id: "1", a: 1, b: 2 })).toBe(true);
});
test("basic domain expressions, with parenthesis", () => {
expect(evaluate("(a = 1)", { id: "1", a: 1 })).toBe(true);
expect(
evaluate("(a = 1) AND (b = 1 OR (c = 3))", { id: "1", a: 1, b: 2, c: 3 })
).toBe(true);
});
test("throw errors if invalid expression", () => {
expect(() => {
evaluate("and", { id: "1", a: 1 });
}).toThrow();
expect(() => {
evaluate("a = 1 and b = 2", { id: "1", a: 1, b: 2 });
}).toThrow();
expect(() => {
evaluate("(", { id: "1", a: 1 });
}).toThrow();
});
test("and/or precedence", () => {
expect(
evaluate("a = 1 AND b = 1 OR c = 3", { id: "1", a: 1, b: 2, c: 3 })
).toBe(true);
expect(
evaluate("a = 1 OR b = 2 AND c = 3", { id: "1", a: 1, b: 2, c: 4 })
).toBe(true);
});
test("empty domain should always match", () => {
expect(evaluate("", { id: "1", a: 1 })).toBe(true);
});
});
|
41e59600f1ca82e4dcdb7a3e3c2e50290137de10 | TypeScript | jdrew1303/prettygoat | /scripts/projections/IProjection.ts | 2.53125 | 3 | import {ISnapshotStrategy} from "../snapshots/ISnapshotStrategy";
import IFilterStrategy from "../filters/IFilterStrategy";
import {Event} from "../streams/Event";
import {SpecialState} from "./SpecialState";
export interface IWhen<T extends Object> {
$init?:() => T;
$any?:(s:T, payload:Object, event?:Event) => T;
[name:string]:(s:T, payload:Object, event?:Event) => T|SpecialState<T>;
}
export interface ISplit {
$default?:(e:Object, event?:Event) => string;
[name:string]:(e:Object, event?:Event) => string;
}
export interface IProjection<T> {
name:string;
split?:ISplit;
definition:IWhen<T>;
snapshotStrategy?:ISnapshotStrategy;
filterStrategy?: IFilterStrategy<T>;
}
|
2dc4d343a44510d1aeaa2a0b6ee046965bd43dc5 | TypeScript | rluvaton/bulk-download-packages-from-platform | /src/progress-adapter.ts | 3 | 3 | import {Bar} from 'cli-progress';
import {PackagesGetterProgressInfo} from './common/progress/packages-getter-progress-info';
import {isNil} from './helpers/validate-helper';
import {humanFileSize} from './helpers/utils';
export class ProgressAdapter {
protected bar: Bar;
constructor() {
// create new progress bar
this.bar = new Bar({
format: 'CLI Progress | {bar} | {percentage}% || {pageValue}/{pageTotal} pages || {pckValue}/{pckTotal} Packages || Speed: {speed}',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true
});
}
public start(progressInfo: PackagesGetterProgressInfo) {
// initialize the bar - defining payload token "speed" with the default value "N/A"
this.bar.start(progressInfo.packages.total, progressInfo.packages.downloaded, this._createPayloadFromProgressInfo(progressInfo));
}
public updateProgress(progressInfo: PackagesGetterProgressInfo) {
// update values
this.bar.update(progressInfo.packages.downloaded, this._createPayloadFromProgressInfo(progressInfo));
}
public finishProgress() {
this.bar.stop();
}
private _createPayloadFromProgressInfo(progressInfo: PackagesGetterProgressInfo): any {
return {
pageValue: progressInfo.pages.currentNum,
pageTotal: progressInfo.pages.total,
pckValue: progressInfo.packages.downloaded,
pckTotal: progressInfo.packages.total,
speed: this.prettifySize(progressInfo.speedInBytesPerSec)
};
}
/**
* @TODO - Add type of size (byte / MB / etc...) to convert
*/
private prettifySize(speed: number) {
return (isNil(speed) || speed < 0) ? 'N/A' : `${humanFileSize(speed)}/s`;
}
}
|
138ad03e0d19e6d2c45fa34a44823c9efe3ca6d2 | TypeScript | tinkeshwar/react-coreui-app-template | /src/features/user/helper/index.ts | 2.59375 | 3 | import { DropdownItemType, MetaType, PermissionListCustomType, PermissionResponseType, RoleListCustomType, RoleResponseType, UserListCustomType, UserResponseType } from '../type'
/* start total pages */
export const getTotalPages = (meta: MetaType|undefined) => {
return (meta !== undefined) ? Math.ceil(meta.total/meta.per_page)||1:1
}
/* end total pages */
/* start user list */
export const getUsersForList = (users: UserResponseType[]) => {
return users?.map((user: UserResponseType) => {
return {
Id:user.id,
Name:`${user.firstname} ${user.middlename || ''} ${user.lastname || ''}`,
Email:user.email,
Phone:user.phone,
Status:(user.status ? 'Active':'Not Active'),
} as UserListCustomType
})
}
/* end user list */
/* start role list */
export const getRolesForList = (roles: RoleResponseType[]) => {
return roles?.map((role: RoleResponseType) => {
return {
Id:role.id,
Name:role.name,
Description:role.description,
Status:(role.status ? 'Active':'Not Active')
} as RoleListCustomType
})
}
/* end role list */
/* start permission list */
export const getPermissionsForList = (permissions: PermissionResponseType[]) => {
return permissions?.map((permission: PermissionResponseType) => {
return {
Id:permission.id,
Name:permission.name,
Level:permission.level,
Status:permission.status?'Active':'Not Active'
} as PermissionListCustomType
})
}
export const getPermissionsForDropdown = (permissions: PermissionResponseType[]) => {
return permissions?.map((permission: PermissionResponseType) => {
return {
id:permission.id,
title:permission.name
} as DropdownItemType
})
}
export const getRolesForDropdown = (roles: RoleResponseType[]) => {
return roles?.map((role: RoleResponseType) => {
return {
id:role.id,
title:role.name
} as DropdownItemType
})
}
export const getFormattedPermissions = (permissions:DropdownItemType[])=>{
let newList = [] as any
permissions.forEach((permission: DropdownItemType) => {
const permissionSplit: any = permission.title.split('.')
if(permissionSplit[0] in newList){
newList[permissionSplit[0]].push({id: permission.id, title: permissionSplit[1]})
}else{
newList[permissionSplit[0]] = [{id: permission.id, title: permissionSplit[1]}]
}
})
let data = [] as any
for(let key in newList){
data.push({label: key,group: newList[key]})
}
return data
}
export const getPillColor = (text: string) => {
switch (text) {
case 'list':
return 'primary'
case 'create':
return 'success'
case 'show':
return 'info'
case 'update':
return 'warning'
case 'destroy':
return 'danger'
case 'status':
return 'dark'
default:
return 'primary'
}
}
/* end permission list */
|
ee258222ecb3051a6deaf1314178e7c387075987 | TypeScript | MLamson/FriendlyDateRanges | /spec/friendlyDateRanges.spec.ts | 3.09375 | 3 | import {DateRanges} from "../src/friendlyDateRanges";
describe('Friendly Date Ranges', () => {
it('should input array of start and end dates with same year and month and return date with just start month and day and end day', () => {
expect(DateRanges.makeNamedDates(["2016-07-01", "2016-07-04"])).toEqual(["July 1st","4th"]);
});
it('should input array of start and end dates with same year and return date with start year month and day and end month and day', () => {
expect(DateRanges.makeNamedDates(["2017-03-01", "2017-05-05"])).toEqual(["March 1st, 2017","May 5th"]);
});
it('should input array of start and end dates with same year, month, day and return date with start year month and day', () => {
expect(DateRanges.makeNamedDates(["2018-01-13", "2018-01-13"])).toEqual(["January 13th, 2018"]);
});
it('should input array of start and end dates with same different year and different month, day and return date with start month and day, end month and day', () => {
expect(DateRanges.makeNamedDates(["2016-12-01", "2017-02-03"])).toEqual(["December 1st","February 3rd"]);
});
it('should input array of start and end dates with same different year and same month, different day and return date with start year, month and day, end month and day', () => {
expect(DateRanges.makeNamedDates(["2022-09-05", "2023-09-04"])).toEqual(["September 5th, 2022","September 4th"]);
});
it('should input array of start and end dates with same different year and same month and day, and return date with start year, month and day, end year, month and day', () => {
expect(DateRanges.makeNamedDates(["2022-09-05", "2023-09-05"])).toEqual(["September 5th, 2022","September 5th, 2023"]);
});
it('should input array of start and end dates with year 2 years apart, and return date with start year, month and day, end year, month and day', () => {
expect(DateRanges.makeNamedDates(["2016-12-01", "2018-02-03"])).toEqual(["December 1st, 2016","February 3rd, 2018"]);
});
}); |
c5ace7e1a23a7ff52e032e325a58e38786ccd035 | TypeScript | future4code/bouman-Food4U-grupo1 | /src/data/RecipeDatabase.ts | 2.578125 | 3 | import MainDB from "./MainDatabase";
import Recipe from "../business/entities/Recipe";
export default class RecipeDB extends MainDB {
async createRecipe (recipe:Recipe) {
await this.connection.raw(
`INSERT INTO RECIPES VALUES (
"${recipe.getId()}",
"${recipe.getTitle()}",
"${recipe.getDescription()}",
"${recipe.getCreationDate()}",
"${recipe.getAuthorId()}"
)`
)
}
async getFeed(id:string){
const query = await this.connection.raw(
`SELECT email, title, description, creation_date FROM FOLLOWERS
JOIN RECIPES ON user_id = author_id
JOIN USERS ON author_id = USERS.id
WHERE follower_id = "${id}"
ORDER BY creation_date;
`
)
return query[0]
}
} |
59053a546469cf8cc64efcccc55e69cba940eca6 | TypeScript | joshburgess/typescript-tuple | /index.ts | 4.375 | 4 | /**
* Choose type base on whether or not a tuple is finite
* @example `IsFinite<[0, 1, 2]>` → `true`
* @example `IsFinite<[0, 1, 2, ...number[]]>` → `false`
* @example `IsFinite<[0], 'Finite', 'Infinite'>` → `'Finite'`
* @example `IsFinite<[0, ...number[]], 'Finite', 'Infinite'>` → `Infinite`
*/
export type IsFinite<Tuple extends any[], Finite = true, Infinite = false> = utils.IsFinite<Tuple, Finite, Infinite>
/**
* Split an infinite tuple into a finite tuple and an array
* @example `SplitInfiniteTuple<[0, 1, 2, ...number[]]>` → `[[0, 1, 2], number[]]`
*/
export type SplitInfiniteTuple<Tuple extends any[]> = utils.SplitInfiniteTail<Tuple>
/**
* Get type of first element
* @example `First<[0, 1, 2]>` → `0`
*/
export type First<Tuple extends [any, ...any[]]> = Tuple[0]
/**
* Get type of last element
* @example `Last<[0, 1, 2]>` → `2`
*/
export type Last<Tuple extends any[]> = utils.Last<Tuple>
/**
* Add an element to the end of a tuple
* @example `Append<[0, 1, 2], 'new'>` → `[0, 1, 2, 'new']`
*/
export type Append<Tuple extends any[], Addend> = Reverse<Prepend<Reverse<Tuple>, Addend>>
/**
* Add an element to the beginning of a tuple
* @example `Prepend<[0, 1, 2], 'new'>` → `['new', 0, 1, 2]`
*/
export type Prepend<Tuple extends any[], Addend> = utils.Prepend<Tuple, Addend>
/**
* Reverse a tuple
* @example `Reverse<[0, 1, 2]>` → `[2, 1, 0]`
*/
export type Reverse<Tuple extends any[]> = utils.Reverse<Tuple>
/**
* Concat two tuple into one
* @example `Concat<[0, 1, 2], ['a', 'b', 'c']>` → `[0, 1, 2, 'a', 'b', 'c']`
*/
export type Concat<Left extends any[], Right extends any[]> = utils.Concat<Left, Right>
/**
* Repeat a certain type into a tuple
* @example `Repeat<'foo', 4>` → `['foo', 'foo', 'foo', 'foo']`
* @warning To avoid potential infinite loop, `Count` must be an integer greater than or equal to 0
*/
export type Repeat<Type, Count extends number> = utils.Repeat<Type, Count, []>
/**
* Concat multiple tuples
* @example `ConcatMultiple<[], [0], [1, 2], [3, 4, 5]>` → `[0, 1, 2, 3, 4, 5]`
*/
export type ConcatMultiple<TupleSet extends any[][]> = utils.ConcatMultiple<TupleSet>
/**
* Create a set of tuple of single element
* @example `SingleTupleSet<[0, 1, 2]>` → `[[0], [1], [2]]`
* @example `SingleTupleSet<[0, 1, 2, ...number[]]>` → `[[0], [1], [2], ...[number][]]`
*/
export type SingleTupleSet<Types extends any[]> = utils.SingleTupleSet<Types>
/**
* Fill a tuple of types
* @example `FillTuple<[0, 1, 2], 'x'>` → `['x', 'x', 'x']`
* @example `FillTuple<any[], 'x'>` → `'x'[]`
*/
export type FillTuple<Tuple extends any[], Replacement> = utils.FillTuple<Tuple, Replacement>
/**
* Compare length of two tuple
* @example `CompareLength<[0, 1, 2], ['a', 'b', 'c']>` → `'equal'`
* @example `CompareLength<[0, 1], ['a', 'b', 'c']>` → `'shorterLeft'`
* @example `CompareLength<[0, 1, 2], ['a', 'b']>` → `'shorterRight'`
*/
export type CompareLength<Left extends any[], Right extends any[]> = utils.CompareLength<Left, Right>
/**
* Sort two tuples in order of [shorter, longer]
* @example `SortTwoTuple<[0, 1, 2, 3], ['a', 'b']>` → `[['a', 'b'], [0, 1, 2, 3]]`
* @example `SortTwoTuple<[0, 1], ['a', 'b', 'c', 'd']>` → `[[0, 1], ['a', 'b', 'c', 'd']]`
* @example `SortTwoTuple<[0, 1, 2], ['a', 'b', 'c']>` → `[[0, 1, 2], ['a', 'b', 'c']]`
* @example `SortTwoTuple<[0, 1, 2], ['a', 'b', 'c'], 'EQUAL'>` → `'EQUAL'`
*/
export type SortTwoTuple<Left extends any[], Right extends any[], WhenEqual = [Left, Right]> = utils.SortTwoTuple<Left, Right, WhenEqual>
/**
* Find shortest tuple in a set of tuples
* @example `ShortestTuple<[[0, 1, 2], [true, false], ['a', 'b', 'c', 'd']]>` → `[true, false]`
*/
export type ShortestTuple<TupleSet extends [any[], ...any[][]]> = utils.ShortestTuple<TupleSet>
export namespace utils {
export type IsFinite<Tuple extends any[], Finite, Infinite> = {
empty: Finite,
nonEmpty: ((..._: Tuple) => any) extends ((_: infer First, ..._1: infer Rest) => any)
? IsFinite<Rest, Finite, Infinite>
: never,
infinite: Infinite
}[
Tuple extends [] ? 'empty' :
Tuple extends (infer Element)[] ?
Element[] extends Tuple ?
'infinite'
: 'nonEmpty'
: never
]
export type SplitInfiniteTail<Tuple extends any[]> =
_SplitInfiniteTail<Tuple> extends [infer Finite, infer Infinite] ?
Finite extends any[] ?
[Reverse<Finite>, Infinite]
: never
: never
export type _SplitInfiniteTail<Tuple extends any[], Holder extends any[] = []> = {
matched: [Holder, Tuple],
unmatched: ((..._: Tuple) => any) extends ((_: infer First, ..._1: infer Rest) => any)
? _SplitInfiniteTail<Rest, Prepend<Holder, First>>
: never,
finite: [Tuple, []]
}[
Tuple extends (infer Element)[] ?
Element[] extends Tuple ? 'matched' : 'unmatched'
: never
]
export type Last<Tuple extends any[], Default = never> = {
empty: Default,
single: Tuple extends [infer SoleElement] ? SoleElement : never,
multi: ((..._: Tuple) => any) extends ((_: any, ..._1: infer Next) => any) ? Last<Next> : Default,
infinite: Tuple extends (infer Element)[] ? Element : never
}[
Tuple extends [] ? 'empty' :
Tuple extends [any] ? 'single' :
Tuple extends (infer Element)[]
? Element[] extends Tuple ? 'infinite'
: 'multi'
: never
]
export type Prepend<Tuple extends any[], Addend> =
((_: Addend, ..._1: Tuple) => any) extends ((..._: infer Result) => any) ? Result : never
export type Reverse<Tuple extends any[], Prefix extends any[] = []> = {
empty: Prefix,
nonEmpty: ((..._: Tuple) => any) extends ((_: infer First, ..._1: infer Next) => any)
? Reverse<Next, Prepend<Prefix, First>>
: never,
infinite: {
ERROR: 'Cannot reverse an infinite tuple',
CODENAME: 'InfiniteTuple'
}
}[
Tuple extends [any, ...any[]]
? IsFinite<Tuple, 'nonEmpty', 'infinite'>
: 'empty'
]
export type Concat<Left extends any[], Right extends any[]> = {
emptyLeft: Right,
singleLeft: Left extends [infer SoleElement]
? Prepend<Right, SoleElement>
: never,
multiLeft: ((..._: Reverse<Left>) => any) extends ((_: infer LeftLast, ..._1: infer ReversedLeftRest) => any)
? Concat<Reverse<ReversedLeftRest>, Prepend<Right, LeftLast>>
: never,
infiniteLeft: {
ERROR: 'Left is not finite',
CODENAME: 'InfiniteLeft' & 'Infinite'
}
}[
Left extends [] ? 'emptyLeft' :
Left extends [any] ? 'singleLeft' :
IsFinite<Left, 'multiLeft', 'infiniteLeft'>
]
export type Repeat<Type, Count extends number, Holder extends any[] = []> =
number extends Count
? Type[]
: {
fit: Holder,
unfit: Repeat<Type, Count, Prepend<Holder, Type>>,
union: Count extends Holder['length'] | infer Rest ?
Rest extends number ?
Repeat<Type, Holder['length']> | Repeat<Type, Rest>
: never
: never
}[
Holder['length'] extends Count ? // It is possible for Count to be a union
Count extends Holder['length'] ? // Make sure that Count is not a union
'fit'
: 'union'
: 'unfit'
]
export type ConcatMultiple<TupleSet extends any[][]> = {
empty: [],
nonEmpty: ((..._: Reverse<TupleSet>) => any) extends ((_: infer Last, ..._1: infer ReversedRest) => any) ?
Last extends any[] ?
ReversedRest extends any[][] ?
Concat<ConcatMultiple<Reverse<ReversedRest>>, Last> :
never :
never :
never,
infinite: {
ERROR: 'TupleSet is not finite',
CODENAME: 'InfiniteTupleSet' & 'Infinite'
}
}[
TupleSet extends [] ? 'empty' : IsFinite<TupleSet, 'nonEmpty', 'infinite'>
]
export type SingleTupleSet<Types extends any[], Holder extends [any][] = []> = {
empty: Holder,
nonEmpty: ((..._: Reverse<Types>) => any) extends ((_: infer Last, ..._1: infer ReversedRest) => any)
? SingleTupleSet<Reverse<ReversedRest>, Prepend<Holder, [Last]>>
: never,
infinite: SplitInfiniteTuple<Types> extends [infer Finite, infer Infinite] ?
Finite extends any [] ?
Infinite extends (infer RepeatedElement)[] ?
SingleTupleSet<Finite, [RepeatedElement][]>
: never
: never
: never
}[
Types extends [] ? 'empty' : IsFinite<Types, 'nonEmpty', 'infinite'>
]
export type FillTuple<Tuple extends any[], Replacement, Holder extends any[] = []> = {
empty: Holder,
nonEmpty: ((...a: Tuple) => any) extends ((a: infer First, ...b: infer Rest) => any)
? FillTuple<Rest, Replacement, Prepend<Holder, Replacement>>
: never,
infinite: Replacement[]
}[
Tuple extends [] ? 'empty' : IsFinite<Tuple, 'nonEmpty', 'infinite'>
]
export type CompareLength<Left extends any[], Right extends any[]> = {
fitBoth: 'equal',
fitLeft: 'shorterLeft',
fitRight: 'shorterRight',
unfit: ((..._: Left) => any) extends ((_: any, ..._1: infer LeftRest) => any) ?
((..._: Right) => any) extends ((_: any, ..._1: infer RightRest) => any) ?
CompareLength<LeftRest, RightRest>
: never
: never
}[
Left['length'] extends Right['length'] ? 'fitBoth' :
Left extends [] ? 'fitLeft' :
Right extends [] ? 'fitRight' :
'unfit'
]
export type SortTwoTuple<Left extends any[], Right extends any[], WhenEqual = [Left, Right]> = {
equal: WhenEqual,
shorterLeft: [Left, Right],
shorterRight: [Right, Left]
}[CompareLength<Left, Right>]
export type ShortestTuple<TupleSet extends any[][], Shortest = any[]> = {
empty: Shortest,
nonEmpty: ((..._: TupleSet) => any) extends ((_: infer Head, ..._1: infer Tail) => any) ?
Tail extends any[] ?
Shortest extends any[] ?
Head extends any[] ?
ShortestTuple<Tail, SortTwoTuple<Shortest, Head>[0]>
: never
: never
: never
: never,
infinite: {
ERROR: 'TupleSet is not finite',
CODENAME: 'InfiniteTupleSet' & 'Infinite'
}
}[
TupleSet extends [] ? 'empty' : IsFinite<TupleSet, 'nonEmpty', 'infinite'>
]
}
|
2b783e048f9cc0c8187b0e5f6881cd6587bfba80 | TypeScript | hrocha85/aula-angular-conversor | /conversor-alunos/src/app/cadastro/cadastro.component.ts | 2.546875 | 3 |
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControlName, FormControl ,Validators } from '@angular/forms';
@Component({
selector: 'app-cadastro',
templateUrl: './cadastro.component.html',
styleUrls: ['./cadastro.component.css']
})
export class CadastroComponent implements OnInit {
nomeDoUsuario = "henrique rocha"
formCadastro = new FormGroup({
nome: new FormControl('', Validators.required),
email :new FormControl('', Validators.compose([Validators.required,
Validators.email])),
data : new FormControl(''),
senha: new FormControl('',Validators.compose([Validators.required,
Validators.minLength(4),Validators.maxLength(8)])),
})
constructor( private formBuilder: FormBuilder) { }
ngOnInit(): void {
}
verificarData(){
let dataAtual = new Date()
console.log(dataAtual)
}
cadastratar(){
console.log(this.formCadastro.get('senha')?.invalid)
console.log(this.formCadastro, "meu formulario")
}
}
|
19f366eb08e70f0eee96e376fbdb773746057122 | TypeScript | andy-schulz/thekla | /packages/thekla-assertion/src/utils/assert.ts | 2.703125 | 3 | import {TheklaAssertionOptions} from "../interfaces/TheklaAssertionOptions";
class AssertionError extends Error {
public constructor(message: string) {
super(message);
this.name = this.constructor.name;
}
}
export const assert = (
expression: boolean,
failMessage: string,
negatedFailMessage: string,
options: TheklaAssertionOptions
): boolean => {
if (!expression)
if (options.not)
throw new AssertionError(negatedFailMessage);
else
throw new AssertionError(failMessage);
return true;
}; |
8d84d35d706e9fb89722f1cbcbf5976789c87295 | TypeScript | ppak10-archives/dog-ceo | /src/breeds/reducer.ts | 2.875 | 3 | /**
* reducer.ts
* Reducer for managing dog breeds.
*/
const INITIAL_STATE = {
all: {},
};
export default function reducer(state = INITIAL_STATE, {payload, type}) {
switch (type) {
case 'SET_BREEDS_ALL':
return {
...state,
all: payload.message,
};
default:
return state;
}
}
|
acacd1abc9c6b97b74653c701945e6597020d526 | TypeScript | sno2/dmm | /src/commands/info.ts | 2.796875 | 3 | import { colours } from "../../deps.ts";
import DenoService from "../services/deno_service.ts";
/**
* Supplies information on the given module in the first
* index of `modules`
*
* @param modules - List of modules to get info on. Currently, we only support 1, so `modules[0]` will be used
*/
export async function info(modules: string[]): Promise<void> {
if (modules.length === 0 || modules.length > 1) {
console.error(
colours.red(
"Specify a single module to get information on. See --help",
),
);
Deno.exit(1);
}
const moduleToGetInfoOn = modules[0];
const stdResponse = await fetch(
"https://github.com/denoland/deno/tree/master/std/" + moduleToGetInfoOn,
);
const thirdPartyResponse = await fetch(
DenoService.DENO_CDN_URL + moduleToGetInfoOn + "/meta/versions.json",
); // Only used so we can check if the module exists
const isStd = stdResponse.status === 200;
const isThirdParty = thirdPartyResponse.status === 200;
if (!isStd && !isThirdParty) {
console.error(
colours.red("No module was found with " + moduleToGetInfoOn),
);
Deno.exit(1);
}
const name = moduleToGetInfoOn;
let description;
let denoLandUrl;
let gitHubUrl;
let latestVersion;
if (isStd) {
latestVersion = await DenoService.getLatestModuleRelease("std");
description = "Cannot retrieve descriptions for std modules";
denoLandUrl = "https://deno.land/std@" + latestVersion + "/" +
name;
gitHubUrl = "https://github.com/denoland/deno/tree/master/std/" + name;
}
if (isThirdParty) {
description = await DenoService.getThirdPartyDescription(name);
gitHubUrl = "https://github.com/" +
await DenoService.getThirdPartyRepoAndOwner(name);
latestVersion = await DenoService.getLatestModuleRelease(name);
denoLandUrl = "https://deno.land/x/" + name + "@" + latestVersion;
}
const importLine = "import * as " + name + ' from "' + denoLandUrl + '";';
console.info(
"\n" +
`Information on ${name}\n\n - Name: ${name}\n - Description: ${description}\n - deno.land Link: ${denoLandUrl}\n - GitHub Repository: ${gitHubUrl}\n - Import Statement: ${importLine}\n - Latest Version: ${latestVersion}` +
"\n",
);
Deno.exit();
}
|
451906996e6b66435118c943eae8ad0294479ea5 | TypeScript | kedoska/0xa | /test/04_bearer.spec.ts | 2.609375 | 3 | import * as express from 'express'
import * as request from 'supertest'
import router, { RouterProps } from '../src/api'
import { requiredRules, tokenize } from '../src/auth/middleware'
import { Client } from '../src/clients'
const tokenSecret = process.env['TOKEN_SECRET'] || ''
const app = express()
beforeAll(() => {
const routerProps: RouterProps = {
clientEndpoint: process.env['CLIENT_ENDPOINT'] || '',
policyendpoint: process.env['POLICY_ENDPOINT'] || '',
tokenSecret,
authorization: requiredRules,
}
app.use(router(routerProps))
})
it('should generate a token', async (done) => {
const email = 'britneyblankenship@quotezart.com'
request(app)
.get(`/auth?email=${email}`)
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) return done(err)
interface Token {
access_token: string
token_type: string
expires_in: number
}
const data = res.body as Token
expect(data.token_type).toBe('Bearer')
expect(data.expires_in).toBe(60 * 60)
done()
})
})
it('should fail without token', (done) => {
request(app)
.get('/v1/users/a0ece5db-cd14-4f21-812f-966633e7be86')
.expect(401)
.end(done)
})
it('should authorize and admin via Bearer token', async (done) => {
const id = 'a0ece5db-cd14-4f21-812f-966633e7be86'
const scope = 'admin'
const token = await tokenize({id, scope}, tokenSecret)
request(app)
.get('/v1/users')
.set('Authorization', 'Bearer ' + token)
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) return done(err)
const data = res.body as Client[]
expect(data.length).toBeGreaterThanOrEqual(1)
done()
})
})
it('should deny access to user', async (done) => {
const id = 'a3b8d425-2b60-4ad7-becc-bedf2ef860bd'
const scope = 'user'
const token = await tokenize({id, scope}, tokenSecret)
request(app)
.get('/v1/users/a3b8d425-2b60-4ad7-becc-bedf2ef860bd/policies')
.set('Authorization', 'Bearer ' + token)
.expect(401)
.end(done)
})
|
b3b642109c3bfefc5edec88b19dac34cf23b8637 | TypeScript | Sangrene/FoxLog | /tests/statsGeneration.test.ts | 2.640625 | 3 | import chai, {expect} from "chai";
import "mocha";
import statsGeneration, {isStatusError, getSectionPath} from "../src/analysis/statsGeneration";
import { fakeEntries } from "./fakeLog"
describe("statistics generation", () => {
it("Detects error in status code", () => {
expect(isStatusError("200")).to.be.false;
expect(isStatusError("304")).to.be.false;
expect(isStatusError("400")).to.be.true;
expect(isStatusError("500")).to.be.true;
});
it("Get section from path", () => {
expect(getSectionPath("/jambon/mie/sans/?q=\"couenne\"")).to.eqls("/jambon")
});
it("Returns the 3 most visited paths", () => {
const stats = statsGeneration({last10Seconds: fakeEntries, last2Minutes: fakeEntries}, 10);
expect(stats.mostVisitedSections).to.eql([
{
path: "/users",
requestsNumber: 4,
errorsNumber: 1
},
{
path: "/shops",
requestsNumber: 1,
errorsNumber: 0
}
]);
});
it("Returns an alert when last 2 minutes trafic is higher than threshold", () => {
const { requestNumberAlert } = statsGeneration({last10Seconds: fakeEntries, last2Minutes: fakeEntries}, 4);
expect(requestNumberAlert).to.eqls(5);
});
it("Doesn't alert when last 2 minutes trafic is lower than threshold", () => {
const { requestNumberAlert } = statsGeneration({last10Seconds: fakeEntries, last2Minutes: fakeEntries}, 6);
expect(requestNumberAlert).to.be.null;
});
}) |
d3f9681ee92ca396ac96d4213874c484d3ae47d8 | TypeScript | LemberTeam/node-nest-ts-code-samples | /src/session.service.ts | 2.53125 | 3 | import { Injectable } from '@nestjs/common';
import { SessionRegistry } from './session.registry';
import { Session } from './session.model';
@Injectable()
export class SessionService {
constructor(private readonly sessionRegistry: SessionRegistry) {}
async getSessions(userId: number): Promise<Session[]> {
return this.sessionRegistry.findAllByUser(userId);
}
async getById(id: number): Promise<Session> {
return this.sessionRegistry.findOneById(id);
}
async authorize(sessionId: string): Promise<Session | null> {
return this.sessionRegistry.access(sessionId);
}
async logoutById(id: number, userId: number): Promise<boolean> {
const session = await this.sessionRegistry.findOneById(id);
if (!session) {
return false;
}
if (session.userId !== userId) {
return false;
}
await this.sessionRegistry.delete(session.id);
return true;
}
async logout(sessionId: string): Promise<boolean> {
const session = await this.sessionRegistry.findOneBySessionId(sessionId);
if (!session) {
return false;
}
await this.sessionRegistry.delete(session.id);
return true;
}
async createSession(
userId: number,
userAgent: string,
ip: string,
extended: boolean,
): Promise<Session> {
const session = await this.sessionRegistry.create(
userId,
userAgent,
ip,
extended,
);
return session;
}
}
|
67e86fa75dd0278e19ceed2f01621576b3cb0261 | TypeScript | MarlonFrancisco/clean-architecture | /src/validation/validators/email-field/email-field-validation.spec.ts | 2.78125 | 3 | import faker from "faker";
import { EmailFieldValidation } from "./email-field-validation";
import { InvalidFieldError } from "@/validation/errors";
type SubTypes = {
sut: EmailFieldValidation;
};
const makeSut = (): SubTypes => {
const sut = new EmailFieldValidation("email");
return {
sut,
};
};
describe("EmailFieldValidation", () => {
it("should validation method return an error message", () => {
const { sut } = makeSut();
const status = sut.validate(faker.random.words(12));
expect(status).toEqual(new InvalidFieldError("email"));
});
it("should validation method return none error message", () => {
const { sut } = makeSut();
const status = sut.validate(faker.internet.email());
expect(status).toBeFalsy();
});
});
|
78b6b903da0d86404206028bc785108e84e33a4a | TypeScript | dtmarangoni/solar-art-gallery | /backend/src/layers/ports/AWS/S3/fileStoreAccess.ts | 2.65625 | 3 | import 'source-map-support/register';
import * as AWS from 'aws-sdk';
import * as AWSXRay from 'aws-xray-sdk';
export class FileStoreAccess {
/**
* Constructs a FileStoreAccess instance.
* @param s3Client The S3 file store client.
* @param s3Bucket The S3 bucket name.
* @param signedUrlExp The S3 bucket pre-signed URL expiration time
* in seconds.
*/
constructor(
private readonly s3Client = FileStoreAccess.createS3Client(),
private readonly s3Bucket = process.env.IMAGES_S3_BUCKET,
private readonly signedUrlExp = process.env.S3_SIGNED_URL_EXP
) {}
/**
* Return the live or offline S3 client depending on serverless
* running mode.
* @returns The S3 client.
*/
private static createS3Client() {
// Serverless running in offline mode
if (process.env.IS_OFFLINE) {
// Serverless offline doesn't support X-Ray so far
return new AWS.S3({
s3ForcePathStyle: true,
accessKeyId: 'S3RVER',
secretAccessKey: 'S3RVER',
endpoint: new AWS.Endpoint('http://localhost:6000'),
});
} else {
// Running in live mode, thus encapsulate AWS SDK to use
// AWS X-Ray
const XAWS = AWSXRay.captureAWS(AWS);
return new XAWS.S3({ signatureVersion: 'v4' });
}
}
/**
* Gets the S3 file store http address.
* @returns The S3 file store http address.
*/
getFileStoreAddress() {
return `https://${this.s3Bucket}.s3.amazonaws.com`;
}
/**
* Generates a pre-signed URL allowing an object download from S3
* file store.
* @param folderPath The full folder path where the object resides
* in the file store.
* @param objKeyName The key name of the object to be downloaded.
* @returns The pre-signed URL allowing the GET object operation to
* S3 file store.
*/
genGetPreSignedUrl(folderPath: string, objKeyName: string) {
return this.s3Client.getSignedUrl('getObject', {
Bucket: this.s3Bucket,
Key: `${folderPath}/${objKeyName}`,
Expires: +this.signedUrlExp,
});
}
/**
* Generates a pre-signed URL allowing a new object upload to S3
* file store.
* @param folderPath The full folder path where to insert the
* object in the file store.
* @param objKeyName The key name of the object to be uploaded.
* @returns The pre-signed URL allowing the PUT object operation to
* S3 file store.
*/
genPutPreSignedUrl(folderPath: string, objKeyName: string) {
return this.s3Client.getSignedUrl('putObject', {
Bucket: this.s3Bucket,
Key: `${folderPath}/${objKeyName}`,
Expires: +this.signedUrlExp,
});
}
/**
* Lists all objects inside a path in S3 file store.
* @param folderPath The full folder path where the objects resides
* in the file store.
* @returns The S3 List Objects V2 Output.
*/
async listObjects(folderPath?: string) {
return await this.s3Client
.listObjectsV2({ Bucket: this.s3Bucket, Prefix: folderPath })
.promise();
}
/**
* Deletes an object from S3 file store.
* @param folderPath The full folder path where the object resides
* in the file store.
* @param objKeyName The key name of the object to be deleted.
* @returns The S3 file store Delete Object Output.
*/
async deleteObject(folderPath: string, objKeyName: string) {
return await this.s3Client
.deleteObject({ Bucket: this.s3Bucket, Key: `${folderPath}/${objKeyName}` })
.promise();
}
/**
* Delete multiple objects from S3 file store.
* @param objects The objects array containing the file store
* folder path and the key name for each object to be deleted.
* @returns The S3 file store Delete Objects Output.
*/
async deleteObjectsByKeys(objects: { folderPath: string; keyName: string }[]) {
return await this.s3Client
.deleteObjects({
Bucket: this.s3Bucket,
Delete: {
Objects: objects.map((object) => ({
Key: `${object.folderPath}/${object.keyName}`,
})),
},
})
.promise();
}
/**
* Delete multiple objects from S3 file store.
* @param objectsPaths The array containing the file store full
* folder path for each object to be deleted.
* @returns The S3 file store Delete Objects Output.
*/
async deleteObjectsByPath(objectsPaths: string[]) {
return await this.s3Client
.deleteObjects({
Bucket: this.s3Bucket,
Delete: { Objects: objectsPaths.map((objPath) => ({ Key: `${objPath}` })) },
})
.promise();
}
}
|
a20c529588a4aaac145882884dfdc21d22fa3dfe | TypeScript | aizatto/interview-preparation | /src/question-roman-to-integer.ts | 3.71875 | 4 | /*
* Assume:
* - Everything is properly formatted
*
* https://projecteuler.net/about=roman_numerals
* https://www.interviewbit.com/problems/roman-to-integer/
* https://www.geeksforgeeks.org/converting-roman-numerals-decimal-lying-1-3999/
*/
const map = new Map([
['I', 1],
['V', 5],
['X', 10],
['L', 50],
['C', 100],
['D', 500],
['M', 1000],
]);
export function romanToInteger(roman: string): number {
let value = 0;
for (let pos = 0; pos < roman.length; pos++) {
const value1 = map.get(roman[pos]);
if (pos + 1 < roman.length) {
const value2 = map.get(roman[pos + 1]);
if (value1 >= value2) {
value += value1;
} else {
value = value + value2 - value1;
pos += 1;
}
} else {
value += value1;
}
}
return value;
}
|
28984231b469e940d73ee9db8c1537387fbf38c7 | TypeScript | akrasnyi/ReactTrainingExamples | /Presentations/B3 TS/TypeScriptExamples/interfacesAndClasses.ts | 4.1875 | 4 | // The easiest way to see how interfaces work is to start with a simple example
function sayHi(user: { name: string }): void {
console.log(`Hi ${user.name}`!);
}
// We can write the same example again, this time using an interface to describe the requirement of having the name
// property that is a string. We have simple convention - every interface name start from "I".
interface IUser {
name: string;
}
// TODO create Object with type User and show autocomplete. Try to add another property.
// Not all properties of an interface may be required. Some exist under certain conditions or may not be there at all.
interface ISquareConfig {
color?: string;
width?: number;
}
interface ISquare {
color: string;
area: number | null;
}
function createSquare(config: ISquareConfig): ISquare {
return {
color: config.color ? config.color : 'defaultColor',
area: config.width ? config.width * config.width : null
};
}
// Some properties should only be modifiable when an object is first created. You can specify this by putting
// readonly before the name of the property
interface IPoint {
readonly x: number;
readonly y: number;
}
const p1: IPoint = { x: 10, y: 20 };
//p1.x = 5; // error!
const arr: number[] = [1, 2, 3, 4];
const ro: ReadonlyArray<number> = arr;
// ro[0] = 12; // error!
// ro.push(5); // error!
// ro.length = 100; // error!
// To describe a function type with an interface, we give the interface a call signature.
interface ISearchFunc {
(source: string, subString: string): boolean;
}
const mySearch: ISearchFunc = function (source: string, subString: string): boolean {
const result: number = source.search(subString);
return result > -1;
};
// Indexable types have an index signature that describes the types we can use to index into the object, along with
// the corresponding return types when indexing
interface StringArray {
[index: number]: string;
}
const myArray: StringArray = ['Bob', 'Fred'];
// Implementing an interface
interface IClock {
currentTime: Date;
}
class Clock implements IClock {
public currentTime: Date = new Date();
}
// We can also describe methods in an interface that are implemented in the class.
// To reuse our code we can extends our interfaces. IDigitalClock will have property currentTime and it's own property.
interface IDigitalClock extends IClock {
setTime: (time: Date) => void;
}
class DigitalClock implements IDigitalClock {
public currentTime: Date = new Date();
public setTime = (time: Date) => {
this.currentTime = time;
};
}
// An interface can extend multiple interfaces, creating a combination of all of the interfaces.
interface IShape {
color: string;
}
interface IPenStroke {
penWidth: number;
}
interface IRectangle extends IShape, IPenStroke {
sideLength: number;
}
const square = <IRectangle>{}; // type assertion.
square.color = 'blue';
square.sideLength = 10;
square.penWidth = 5.0;
// TODO create interface for class below.
class User {
public readonly name: any;
public surname: any;
public constructor(name: any, surname: any) {
this.name = name;
this.surname = surname;
}
public setSurname = (surname: any): any => {
this.surname = surname;
};
}
// In TypeScript, we can use common object-oriented patterns. One of the most fundamental patterns in class-based
// programming is being able to extend existing classes to create new ones using inheritance.
class Animal {
public move(distanceInMeters: number = 0): void {
console.log(`Animal moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
public bark(): void {
console.log('Woof! Woof!');
}
}
const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();
// This example shows the most basic inheritance feature: classes inherit properties and methods from base classes.
// Here, Dog is a derived class that derives from the Animal base class using the extends keyword.
// TODO create basic class Bird, that can fly, and class Duck, that can quack
// In our examples, we’ve been able to freely access the members that we declared throughout our programs. This is
// because we use the word "public" to accomplish this. But TypeScript has ability to mark some property or method
// like "protected" or "private".
class Employee {
private _name: string; // This is also convention - every private property or method start from "_"
protected surname: string;
public constructor(name: string, surname: string) {
this._name = name;
this.surname = surname;
}
public get getName(): string { // if you want to get private property you can create getter for this.
return this._name;
}
}
class Developer extends Employee {
public constructor(name: string, surname: string) {
super(name, surname);
}
public sayHi = () => {
//console.log(`Hi - ${this._name}`) // error, because we can call private property or method only in base class
console.log(`Hi - ${this.surname}`); // we can call protected property or method in child class.
};
}
const dev: Developer = new Developer('Mike', 'Vazovsky');
//const devName: string = dev._name // error, we can not call private or protected property or method on instance.
//const devSurname: string = dev.surname
const developerName: string = dev.getName;
// Private and protected property and methods are using for encapsulation data.
// TODO create class Vector with property firstPoint(x, y) and secondPoint(x, y) and method for calculation vector length
// TypeScript has a lot of fiches(static method, abstract classes etc), which we can present in advanced course.
// But if someone want to look on it now - this is simple implementation of design pattern observer, decorator and adapter
// https://stackblitz.com/edit/typescript-383bgb
// https://stackblitz.com/edit/typescript-gg7pzs
// https://stackblitz.com/edit/typescript-jno5k6 |
993b81fb3c54cebdad52633e0321fe6efb18c9fa | TypeScript | tcd/frame-data-scraping | /src/lib/write-json-file.ts | 2.796875 | 3 | import * as fs from "fs"
export const writeJsonFile = (filePath, data) => {
try {
let outData = JSON.stringify(data, null, 2)
fs.writeFileSync(filePath, outData)
console.log(`file written: ${filePath}`)
} catch (error) {
console.log(error)
process.exit(1)
}
}
|
a12db748e39fee8bbb674d5cdf711f50247f3034 | TypeScript | project-blurple/blurple-hammer | /src/commands/chatInput/channels/lock.ts | 2.765625 | 3 | import { inspect } from "util";
import type { ForumChannel, Snowflake, StageChannel, TextChannel, VoiceChannel } from "discord.js";
import { ApplicationCommandOptionType, ChannelType } from "discord.js";
import type { SecondLevelChatInputCommand } from "..";
import config from "../../../config";
import Emojis from "../../../constants/emojis";
export default {
name: "lock",
description: "Lock a channel",
options: [
{
type: ApplicationCommandOptionType.Channel,
name: "channel",
description: "The channel to lock",
channelTypes: [
ChannelType.GuildForum,
ChannelType.GuildStageVoice,
ChannelType.GuildText,
ChannelType.GuildVoice,
],
},
{
type: ApplicationCommandOptionType.String,
name: "channel_group",
description: "The channel group to lock",
choices: [
{ name: "All public channels", value: "public" },
{ name: "Blurplefier channels", value: "blurplefier" },
],
},
{
type: ApplicationCommandOptionType.String,
name: "reason",
description: "The reason for locking the channel",
},
],
async execute(interaction) {
await interaction.deferReply({ ephemeral: true });
const channels: Snowflake[] = [];
const singularChannel = interaction.options.getChannel("channel");
if (singularChannel) channels.push(singularChannel.id);
const channelGroup = interaction.options.getString("channel_group") as "blurplefier" | "public" | undefined;
if (channelGroup === "blurplefier") channels.push(...config.channels.blurplefierChannels);
if (channelGroup === "public") channels.push(...config.channels.publicChannels);
const reason = interaction.options.getString("reason");
const success: Snowflake[] = [];
const errors: string[] = [];
const interval = setInterval(() => {
void interaction.editReply({
content: [
`${Emojis.Loading} Locking channels... (${success.length + errors.length}/${channels.length})`,
`Locked: ${success.map(channelId => `<#${channelId}>`).join(", ")} | In queue: ${channels.slice(success.length + errors.length).map(channelId => `<#${channelId}>`)
.join(", ")}`,
errors.length && `Failed to lock channels:\n${errors.map(error => `• ${error}`).join("\n")}`,
].filter(Boolean).join("\n"),
});
}, 1000);
for (const channelId of channels) {
const channel = interaction.guild.channels.cache.get(channelId);
if (channel) {
const result = await lockChannel(channel as never, reason);
if (typeof result === "string") errors.push(`Failed to lock channel <#${channelId}>: ${result}`);
else success.push(channelId);
} else errors.push(`Channel ${channelId} not found.`);
}
clearInterval(interval);
return void interaction.editReply({
content: [
`${Emojis.ThumbsUp} Channels are now locked: ${success.map(channelId => `<#${channelId}>`).join(", ") || "*None.*"}`,
errors.length && errors.map(error => `• ${error}`).join("\n"),
].filter(Boolean).join("\n"),
});
},
} as SecondLevelChatInputCommand;
function lockChannel(channel: ForumChannel | StageChannel | TextChannel | VoiceChannel, reason: string | null): Promise<string | true> {
if (channel.permissionOverwrites.cache.find(overwrite => overwrite.id === channel.guild.roles.everyone.id)?.deny.has("SendMessages")) return Promise.resolve("Channel is already locked.");
return channel.permissionOverwrites.edit(channel.guild.roles.everyone, { SendMessages: false, SendMessagesInThreads: false, CreatePublicThreads: false, CreatePrivateThreads: false, AddReactions: false })
.then(async () => {
if ("send" in channel) await channel.send(`${Emojis.WeeWoo} ***This channel is now locked.*** ${reason ? `\n>>> *${reason}*` : ""}`);
return true as const;
})
.catch(err => inspect(err).split("\n")[0]!.trim());
}
|
30bca73ba1624ec6c7e79dbbd5e19fae970b3287 | TypeScript | tomshanan/Packable | /src/app/shared/app-colors.ts | 2.515625 | 3 | import { Injectable } from '@angular/core';
// var ColorFac = require('color');
import * as ColorFac from 'color'
export var disabledColor = "#c6c6c6"
@Injectable({
providedIn: 'root'
})
export class AppColors {
public danger = new Color('#ff4400')//,'#e23b00')
public action = new Color('#007bff')//,'#0056b3')
public accent = new Color('#ff4081')//,'#bb1950')
public active = new Color('#31d441')//,'#26a532')
public muted = new Color('#939ea8')//, '#79848d')
}
export class Color {
inactive: string;
hover: string;
click: string;
ripple: string;
disabled: string;
muted:string;
constructor(
inactive: string,
hover?: string,
click?: string){
this.inactive = inactive;
this.hover = hover || ColorFac(inactive).lighten(0.2) ;
this.click = click || ColorFac(inactive).lighten(0.2);
this.ripple = ColorFac(inactive).fade(0.7)
this.muted = ColorFac(inactive).desaturate(0.5).lighten(0.3)
this.disabled = disabledColor;
}
} |
13be81c9a255ad20abac67d8fae2b0d4c309bb88 | TypeScript | rectcircle/new-file-by-type | /src/util/toSource.ts | 2.703125 | 3 |
/* toSource by Marcello Bastea-Forte - zlib license */
/* modify and fix bug from https://github.com/marcello3d/node-tosource */
export function toSource (object: any, filter: Function | undefined, indent: string | undefined, startingIndent: string | undefined) {
var seen: any[] = [];
return walk(object, filter, indent === undefined ? ' ' : (indent || ''), startingIndent || '', seen);
function walk (object: any, filter: Function | undefined, indent: string, currentIndent: string, seen: any[]):any {
var nextIndent = currentIndent + indent;
object = filter ? filter(object) : object;
switch (typeof object) {
case 'string':
return JSON.stringify(object);
case 'boolean':
case 'number':
case 'undefined':
return '' + object;
case 'function':
return object.toString();
}
if (object === null) {
return 'null';
}
if (object instanceof RegExp) {
return stringifyRegExp(object);
}
if (object instanceof Date) {
return 'new Date(' + object.getTime() + ')';
}
var seenIndex = seen.indexOf(object) + 1;
if (seenIndex > 0) {
return '{$circularReference:' + seenIndex + '}';
}
seen.push(object);
function join(elements: any[]) {
return '\n' + nextIndent + elements.join(',\n' + nextIndent) + '\n' + nextIndent.substr(indent.length);
}
if (Array.isArray(object)) {
return object.length === 0 ? '[]' : '[' + join(object.map(function (element) {
return walk(element, filter, indent, nextIndent, seen.slice());
})) + ']';
}
var keys = Object.keys(object);
return keys.length ? '{' + join(keys.map(function (key) {
return (legalKey(key) ? key : JSON.stringify(key)) + ':' + walk(object[key], filter, indent, nextIndent, seen.slice());
})) + '}' : '{}';
}
}
var KEYWORD_REGEXP = /^(abstract|boolean|break|byte|case|catch|char|class|const|continue|debugger|default|delete|do|double|else|enum|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|undefined|var|void|volatile|while|with)$/;
function legalKey (string: string) {
return /^[a-z_$][0-9a-z_$]*$/gi.test(string) && !KEYWORD_REGEXP.test(string);
}
// Node.js 0.10 doesn't escape slashes in re.toString() or re.source
// when they were not escaped initially.
// Here we check if the workaround is needed once and for all,
// then apply it only for non-escaped slashes.
var isRegExpEscaped = (new RegExp('/')).source === '\\/';
function stringifyRegExp (re: RegExp) {
if (isRegExpEscaped) {
return re.toString();
}
var source = re.source.replace(/\//g, function (found, offset, str) {
if (offset === 0 || str[offset - 1] !== '\\') {
return '\\/';
}
return '/';
});
var flags = (re.global && 'g' || '') + (re.ignoreCase && 'i' || '') + (re.multiline && 'm' || '');
return '/' + source + '/' + flags;
}
|
0872ca715d52347fcff094eadcd1f6bb9b10fe5b | TypeScript | shuangmianxiaoQ/ref-ui | /src/utils/numbers.ts | 2.921875 | 3 | import BN from 'bn.js';
import * as math from 'mathjs';
const BPS_CONVERSION = 10000;
const ROUNDING_OFFSETS: BN[] = [];
const BN10 = new BN(10);
for (let i = 0, offset = new BN(5); i < 24; i++, offset = offset.mul(BN10)) {
ROUNDING_OFFSETS[i] = offset;
}
export const sumBN = (...args: string[]): string => {
return args
.reduce((acc, n) => {
return acc.add(new BN(n));
}, new BN(0))
.toString();
};
export const toReadableNumber = (
decimals: number,
number: string = '0'
): string => {
if (!decimals) return number;
const wholeStr = number.substring(0, number.length - decimals) || '0';
const fractionStr = number
.substring(number.length - decimals)
.padStart(decimals, '0')
.substring(0, decimals);
return `${wholeStr}.${fractionStr}`.replace(/\.?0+$/, '');
};
export const toNonDivisibleNumber = (
decimals: number,
number: string
): string => {
if (decimals === null || decimals === undefined) return number;
const [wholePart, fracPart = ''] = number.split('.');
return `${wholePart}${fracPart.padEnd(decimals, '0').slice(0, decimals)}`
.replace(/^0+/, '')
.padStart(1, '0');
};
export const toPrecision = (
number: string,
precision: number,
withCommas: boolean = false,
atLeastOne: boolean = true
): string => {
const [whole, decimal = ''] = number.split('.');
let str = `${withCommas ? formatWithCommas(whole) : whole}.${decimal.slice(
0,
precision
)}`.replace(/\.$/, '');
if (atLeastOne && Number(str) === 0 && str.length > 1) {
var n = str.lastIndexOf('0');
str = str.slice(0, n) + str.slice(n).replace('0', '1');
}
return str;
};
export const toRoundedReadableNumber = ({
decimals,
number,
precision = 6,
}: {
decimals: number;
number?: string;
precision?: number;
}): string => {
return toPrecision(toReadableNumber(decimals, number), precision, true);
};
export const convertToPercentDecimal = (percent: number) => {
return math.divide(percent, 100);
};
export const calculateFeePercent = (fee: number) => {
return math.divide(fee, 100);
};
export const calculateFeeCharge = (fee: number, total: string) => {
return math.round(
math.evaluate(`(${fee} / ${BPS_CONVERSION}) * ${total}`),
2
);
};
export const calculateExchangeRate = (
fee: number,
from: string,
to: string
) => {
return math.round(math.evaluate(`${to} / ${from}`), 4);
};
export const percentOf = (percent: number, num: number | string) => {
return math.evaluate(`${convertToPercentDecimal(percent)} * ${num}`);
};
export const percentLess = (percent: number, num: number | string) => {
return math.format(math.evaluate(`${num} - ${percentOf(percent, num)}`), {
notation: 'fixed',
});
};
export function formatWithCommas(value: string): string {
const pattern = /(-?\d+)(\d{3})/;
while (pattern.test(value)) {
value = value.replace(pattern, '$1,$2');
}
return value;
}
export const percent = (numerator: string, denominator: string) => {
return math.evaluate(`(${numerator} / ${denominator}) * 100`);
};
export const calculateFairShare = ({
shareOf,
contribution,
totalContribution,
}: {
shareOf: string;
contribution: string;
totalContribution: string;
}) => {
return math.format(
math.evaluate(`(${shareOf} * ${contribution}) / ${totalContribution}`),
{
notation: 'fixed',
precision: 0,
}
);
};
export const toInternationalCurrencySystem = (
labelValue: string,
percent?: number
) => {
return Math.abs(Number(labelValue)) >= 1.0e9
? (Math.abs(Number(labelValue)) / 1.0e9).toFixed(percent || 2) + 'B'
: Math.abs(Number(labelValue)) >= 1.0e6
? (Math.abs(Number(labelValue)) / 1.0e6).toFixed(percent || 2) + 'M'
: Math.abs(Number(labelValue)) >= 1.0e3
? (Math.abs(Number(labelValue)) / 1.0e3).toFixed(percent || 2) + 'K'
: Math.abs(Number(labelValue)).toFixed(percent || 2);
};
|
2815d8ca9d49c3d40e075778e93709569be1b0de | TypeScript | laurencefass/react-redux-observables | /src/Epics/epics.ts | 2.796875 | 3 | import { Observable, Observer } from 'rxjs'
import {
debounceTime,
throttleTime,
mapTo,
delay,
tap
} from 'rxjs/operators';
import { ofType } from "redux-observable";
import {
INCREMENT,
INCREMENT_THROTTLE,
DECREMENT_DEBOUNCE,
PING,
INTERVAL,
INTERVAL_THROTTLE,
pongAction,
incrementAction,
decrementAction,
throttleIntervalAction
} from "../Actions/actions"
const THROTTLE_TIME = 2000;
export const intervalEpic = (action$: Observable<any>) =>
action$.pipe(
ofType(INTERVAL),
tap(val => console.log(`intervalEpic tap: ${JSON.stringify(val)}`)),
throttleTime(THROTTLE_TIME),
mapTo(throttleIntervalAction())
);
export const pingEpic = (action$: Observable<any>) =>
action$.pipe(
ofType(PING),
tap(val => console.log(`pingEpic tap: ${JSON.stringify(val)}`)),
delay(1000),
mapTo(pongAction())
);
export const incThrottleEpic = (action$: Observable<any>) =>
action$.pipe(
ofType(INCREMENT_THROTTLE),
tap(val => console.log(`incThrottleEpic tap: ${JSON.stringify(val)}`)),
throttleTime(1000),
mapTo(incrementAction())
);
export const decDebounceEpic = (action$:Observable<any>) =>
action$.pipe(
ofType(DECREMENT_DEBOUNCE),
tap(val => console.log(`decDebounceEpic tap: ${JSON.stringify(val)}`)),
debounceTime(1000),
mapTo(decrementAction())
);
|
f7ba2a5782dd1fa1d3fb26b9f67d33bd2ac098d9 | TypeScript | luangm/learn4ts | /src/expression/binary/Power.ts | 2.5625 | 3 | import {ShapeUtils, Tensor, TensorMath} from "tensor4js";
import Graph from "../../Graph";
import Expression from "../Expression";
import {ExpressionTypes} from "../ExpressionTypes";
import BinaryExpression from "./BinaryExpression";
import Multiply from "./Multiply";
export default class Power extends BinaryExpression {
private readonly _shape: number[];
get shape() {
return this._shape;
}
get type() {
return ExpressionTypes.Power;
}
constructor(left: Expression, right: Expression, graph: Graph, name?: string) {
super(left, right, graph, name);
this._shape = ShapeUtils.broadcastShapes(left.shape, right.shape);
}
static evaluate(expression: Expression): Tensor {
let node = expression as Power;
let left = node.left.value;
let right = node.right.value;
return TensorMath.pow(left, right);
}
static gradients(expression: Expression, grad: Expression): Expression[] {
let node = expression as Power;
let x = node.left;
let y = node.right;
let z = node;
let pair = ShapeUtils.getReductionIndices(x.shape, y.shape);
let one = node.factory.constant(Tensor.scalar(1), "ONE");
let zero = node.factory.constant(Tensor.scalar(0), "ZERO");
let leftGrad = grad.multiply(y).multiply(x.pow(y.subtract(one)));
let rightGrad = grad.multiply(z);
let logX = x.greater(zero).conditional(x.log(), node.factory.fill(0, x.shape));
rightGrad = rightGrad.multiply(logX);
if (pair.left) {
leftGrad = leftGrad.reduceSum(pair.left);
}
if (pair.right) {
rightGrad = rightGrad.reduceSum(pair.right);
}
leftGrad = leftGrad.reshape(node.left.shape);
rightGrad = rightGrad.reshape(node.right.shape);
return [leftGrad, rightGrad];
}
} |
9784fb837f4012ac02a023f3ed748ac5707a1b76 | TypeScript | alistairvu/organise-next-app | /pages/api/user/register.ts | 2.515625 | 3 | import connectDB from "../../../mongo"
import User from "../../../mongo/models/userModel"
import type { NextApiRequest, NextApiResponse } from "next"
import bcrypt from "bcryptjs"
import jwt from "jsonwebtoken"
const registerUser = async (req: NextApiRequest, res: NextApiResponse) => {
try {
if (req.method !== "PUT") {
return res.status(401).send(`Cannot ${req.method} /api/user/register`)
}
const { name, email, password } = req.body
await connectDB()
if (!(name && password && email)) {
return res.status(400).json({ message: "Data not formatted properly" })
}
const existingUser = await User.findOne({
email,
})
if (existingUser) {
res.status(400).json({ message: "User already exists" })
return
}
const salt = await bcrypt.genSalt(10)
const userPassword = await bcrypt.hash(password, salt)
const newUser = new User({
name,
email,
password: userPassword,
toDoItems: [],
})
newUser.save()
const token = jwt.sign({ id: newUser._id }, process.env.JWT_TOKEN)
res.status(200).json({
userInfo: { id: newUser._id, name: newUser.name, email: newUser.email },
token: token,
})
} catch (err) {
console.log(err)
res.status(400).json({ message: "Data not formatted properly" })
}
}
export default registerUser
|
74fcbe7501c1cc6c4e0c207a89cb799e836bfd60 | TypeScript | cheng1994/axe-result-pretty-print | /test/index.test.ts | 2.515625 | 3 | import { prettyPrintAxeReport } from '../src';
const axeRawViolations = require('./__mock_data__/rawViolations.json');
const axeRawPasses = require('./__mock_data__/rawPasses.json');
describe('printAxeReport() test', () => {
it('Verify not throwing an error', async () => {
prettyPrintAxeReport({ violations: axeRawViolations, passes: axeRawPasses });
});
it('outputs with url', async () => {
prettyPrintAxeReport({
violations: axeRawViolations,
passes: axeRawPasses,
url: 'www.example.com',
});
});
it('skips report table', async () => {
prettyPrintAxeReport({
violations: axeRawViolations,
passes: axeRawPasses,
url: 'www.example.com',
skipResultTable: true,
});
});
it('no violations', async () => {
prettyPrintAxeReport({
violations: [],
url: 'www.example.com',
});
});
it('Verify throwing an error if violations are not passed', async () => {
expect(() => {
//@ts-ignore
prettyPrintAxeReport({ passes: axeRawPasses });
}).toThrow(
'prepareReportData() requires violations to be passed as an object: prepareReportData({violations: Result[]})'
);
});
});
|
4f719b981bfd4cf414fedd5d256f612a1b71f08c | TypeScript | goodCat56/ng-sample | /src/app/services/fake.service.ts | 2.609375 | 3 | /**
* Created by Python on 11/7/2016.
*/
import { Injectable } from '@angular/core';
import {Service} from "./service";
import {HttpClient} from "./http-client.service";
import {Observable} from "rxjs/Rx";
const _API_BASE = 'https://jsonplaceholder.typicode.com/';
//Do not forget to register the service in the app module in the 'providers' array.
//To use this service just inject it into the constructor of any component.
@Injectable()
export class FakeService extends Service{
constructor(private http:HttpClient) {super(); }
//A method to fetch all posts and it will return observable to subscribe to and read the data.
getPosts():Observable<any>{
let url = _API_BASE+'posts';
return this.http.get(url)
.map(this.extractData)
.catch(this.handleError);
}
getPost(id):Observable<any>{
let url = _API_BASE+'posts/'+id;
return this.http.get(url)
.map(this.extractData)
.catch(this.handleError);
}
}
|
480c0b7c5b142fe8a18ec8543c174c7b4bd9b576 | TypeScript | johnstonbl01/react-skeletor | /src/createSkeletonElement.ts | 2.515625 | 3 | /*
* Copyright (c) Trainline Limited, 2017. All rights reserved.
* See LICENSE.txt in the project root for license information.
*/
import * as React from 'react';
import { contextTypes, Context, Styling } from './utils';
const createStyle = (styles: (React.CSSProperties | undefined)[]) =>
styles
// tslint:disable-next-line:no-any
.filter((style: any): style is React.CSSProperties => !!style)
.reduce((acc, next) => ({ ...acc, ...next }), {});
const createClassName = (classnames: (string | undefined)[]) =>
classnames
.filter(Boolean)
.join(' ');
const unwrapStyle = (style?: Styling) =>
typeof style === 'function' ?
style() :
(style || undefined);
export interface InjectedProps {
style?: React.CSSProperties;
className?: string;
'aria-hidden'?: boolean;
}
// tslint:disable-next-line:no-any
export const createSkeletonElement = <T = any>(
type: React.SFC<T> | string,
pendingStyle?: Styling
) => {
const ExportedComponent: React.StatelessComponent<T> = (
props: T & InjectedProps,
{ skeletor }: Context
) => {
const { isPending = false, styling = undefined } = skeletor || {};
// tslint:disable-next-line:no-any
const newProps: T & InjectedProps = { ...(props as any) };
if (isPending) {
const [ contextStyle, propStyle ] = [ styling, pendingStyle ].map(unwrapStyle);
newProps.style = createStyle([
props.style,
typeof contextStyle !== 'string' && contextStyle || undefined,
typeof propStyle !== 'string' && propStyle || undefined
]);
newProps.className = createClassName([
props.className,
typeof contextStyle === 'string' && contextStyle || undefined,
typeof propStyle === 'string' && propStyle || undefined
]);
newProps['aria-hidden'] = true;
}
return React.createElement(type, newProps);
};
ExportedComponent.contextTypes = contextTypes;
return ExportedComponent;
};
|
a1b25109afa42e0b9c9267f4077fed284469d330 | TypeScript | swc-project/swc | /crates/swc_bundler/tests/.cache/deno/8dbd05883dea58125dac08eec329300c7b32871f.ts | 3.421875 | 3 | // Loaded from https://deno.land/x/ramda@v0.27.2/source/replace.js
import _curry3 from './internal/_curry3.js';
/**
* Replace a substring or regex match in a string with a replacement.
*
* The first two parameters correspond to the parameters of the
* `String.prototype.replace()` function, so the second parameter can also be a
* function.
*
* @func
* @memberOf R
* @since v0.7.0
* @category String
* @sig RegExp|String -> String -> String -> String
* @param {RegExp|String} pattern A regular expression or a substring to match.
* @param {String} replacement The string to replace the matches with.
* @param {String} str The String to do the search and replacement in.
* @return {String} The result.
* @example
*
* R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo'
* R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo'
*
* // Use the "g" (global) flag to replace all occurrences:
* R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar'
*/
var replace = _curry3(function replace(regex, replacement, str) {
return str.replace(regex, replacement);
});
export default replace;
|
4f60fc3f11663cfbb877c3cf09f17a3c245a32cd | TypeScript | vercel/vercel | /packages/build-utils/src/fs/download.ts | 2.578125 | 3 | import path from 'path';
import debug from '../debug';
import FileFsRef from '../file-fs-ref';
import { File, Files, Meta } from '../types';
import { remove, mkdirp, readlink, symlink, chmod } from 'fs-extra';
import streamToBuffer from './stream-to-buffer';
export interface DownloadedFiles {
[filePath: string]: FileFsRef;
}
const S_IFDIR = 16384; /* 0040000 directory */
const S_IFLNK = 40960; /* 0120000 symbolic link */
const S_IFMT = 61440; /* 0170000 type of file */
export function isDirectory(mode: number): boolean {
return (mode & S_IFMT) === S_IFDIR;
}
export function isSymbolicLink(mode: number): boolean {
return (mode & S_IFMT) === S_IFLNK;
}
async function prepareSymlinkTarget(
file: File,
fsPath: string
): Promise<string> {
const mkdirPromise = mkdirp(path.dirname(fsPath));
if (file.type === 'FileFsRef') {
const [target] = await Promise.all([readlink(file.fsPath), mkdirPromise]);
return target;
}
if (file.type === 'FileRef' || file.type === 'FileBlob') {
const targetPathBufferPromise = streamToBuffer(await file.toStreamAsync());
const [targetPathBuffer] = await Promise.all([
targetPathBufferPromise,
mkdirPromise,
]);
return targetPathBuffer.toString('utf8');
}
throw new Error(
`file.type "${(file as any).type}" not supported for symlink`
);
}
export async function downloadFile(
file: File,
fsPath: string
): Promise<FileFsRef> {
const { mode } = file;
if (isDirectory(mode)) {
await mkdirp(fsPath);
await chmod(fsPath, mode);
return FileFsRef.fromFsPath({ mode, fsPath });
}
// If the source is a symlink, try to create it instead of copying the file.
// Note: creating symlinks on Windows requires admin priviliges or symlinks
// enabled in the group policy. We may want to improve the error message.
if (isSymbolicLink(mode)) {
const target = await prepareSymlinkTarget(file, fsPath);
await symlink(target, fsPath);
return FileFsRef.fromFsPath({ mode, fsPath });
}
const stream = file.toStream();
return FileFsRef.fromStream({ mode, stream, fsPath });
}
async function removeFile(basePath: string, fileMatched: string) {
const file = path.join(basePath, fileMatched);
await remove(file);
}
export default async function download(
files: Files,
basePath: string,
meta?: Meta
): Promise<DownloadedFiles> {
const {
isDev = false,
skipDownload = false,
filesChanged = null,
filesRemoved = null,
} = meta || {};
if (isDev || skipDownload) {
// In `vercel dev`, the `download()` function is a no-op because
// the `basePath` matches the `cwd` of the dev server, so the
// source files are already available.
return files as DownloadedFiles;
}
debug('Downloading deployment source files...');
const start = Date.now();
const files2: DownloadedFiles = {};
const filenames = Object.keys(files);
await Promise.all(
filenames.map(async name => {
// If the file does not exist anymore, remove it.
if (Array.isArray(filesRemoved) && filesRemoved.includes(name)) {
await removeFile(basePath, name);
return;
}
// If a file didn't change, do not re-download it.
if (Array.isArray(filesChanged) && !filesChanged.includes(name)) {
return;
}
// Some builders resolve symlinks and return both
// a file, node_modules/<symlink>/package.json, and
// node_modules/<symlink>, a symlink.
// Removing the file matches how the yazl lambda zip
// behaves so we can use download() with `vercel build`.
const parts = name.split('/');
for (let i = 1; i < parts.length; i++) {
const dir = parts.slice(0, i).join('/');
const parent = files[dir];
if (parent && isSymbolicLink(parent.mode)) {
console.warn(
`Warning: file "${name}" is within a symlinked directory "${dir}" and will be ignored`
);
return;
}
}
const file = files[name];
const fsPath = path.join(basePath, name);
files2[name] = await downloadFile(file, fsPath);
})
);
const duration = Date.now() - start;
debug(`Downloaded ${filenames.length} source files: ${duration}ms`);
return files2;
}
|
b82e94c1ddfd2bb1fe429fed2c7e61e3945abaee | TypeScript | green-fox-academy/adamcsigas | /Foundation/week-1/day_4/Thursday-javava/Workshop-exercisesjava01/coding-hours.ts | 3.484375 | 3 | 'use strict';
// An average Green Fox attendee codes 6 hours daily
// The semester is 17 weeks long
//
/*
Coding hours a day = x
Working days of the semester = y (we are not counting with the vacation days!)
weekend = z
*/
let x : number = 6;
let y : number = 17*5;
// Print how many hours is spent with coding in a semester by an attendee,
// if the attendee only codes on workdays.
// Hours In Semester = HIS
let HIS : number = (x*y);
//console.log(HIS);
// Print the percentage of the coding hours in the semester if the average
// work hours weekly is 52
// Total Average Hours = TAH
let TAH : number = 52*17;
//console.log(TAH);
console.log((HIS/TAH)*100); |
43caa1c8b4edfbd61ff872ef13ce66374df7f8f7 | TypeScript | stemyke/ngx-utils | /src/ngx-utils/pipes/filter.pipe.ts | 2.671875 | 3 | import {Pipe, PipeTransform} from "@angular/core";
import {ObjectUtils} from "../utils/object.utils";
export function defaultFilter() {
return true;
}
@Pipe({
name: "filter"
})
export class FilterPipe implements PipeTransform {
transform(values: any, filter: any = defaultFilter, params: any = {}): any {
const isObject = ObjectUtils.isObject(values);
if (!isObject && !ObjectUtils.isArray(values)) return [];
const filterFunc = ObjectUtils.isFunction(filter) ? filter : (value, key, params, values) => {
const index = key;
return ObjectUtils.evaluate(filter, {value, key, params, values, index});
};
if (isObject) {
return Object.keys(values).filter(key => {
return filterFunc(values[key], key, params, values);
}).reduce((result, key) => {
result[key] = values[key];
return result;
}, {})
}
return values.filter((value, key) => {
return filterFunc(value, key, params, values);
});
}
}
|
451819fcf5dc18e1bc52b8d0aea758b4390ca577 | TypeScript | oguz-yilmaz/Dependency-Checker | /src/IO/Input/__test__/Cli.test.ts | 2.625 | 3 | import { Cli } from '../Cli'
it('parses first argument as repo name', async () => {
const cli = new Cli()
process.argv = ['npm', 'start', 'testName']
const res = cli.parseInput()
expect(res.repos[0].repoUser).toEqual('testName')
})
it('parses second argument as repo user', async () => {
const cli = new Cli()
process.argv = ['npm', 'start', 'testName', 'testRepo']
const res = cli.parseInput()
expect(res.repos[0].repoName).toEqual('testRepo')
})
it('parses arguments after second one as emails', async () => {
const cli = new Cli()
process.argv = ['npm', 'start', 'testName', 'testRepo', 'email1', 'email2']
const res = cli.parseInput()
expect(res.repos[0].emails).toEqual(['email1', 'email2'])
})
|
2a09cbba81724d31effda65bbc37ed4143372e5b | TypeScript | calebjmatthews/NewSummer | /client/models/traveler/dialogue.ts | 2.640625 | 3 | import Condition from './condition';
import ConditionalObject from './conditional_object';
import Field from '../../models/field';
import Homestead from '../../models/homestead';
import RecordBook from '../../models/record_book';
import Cast from '../../models/traveler/cast';
import Economy from '../../models/economy';
import { Comparitors } from '../enums/comparitors';
import { utils } from '../utils';
export default class Dialogue extends ConditionalObject implements DialogueInterface {
index: number;
conditions: Condition[];
important: boolean;
probability: number;
text: string;
constructor(dialogue: DialogueInterface) {
super(dialogue);
Object.assign(this, dialogue);
}
parseDialogueText(gameState: {
fields: { [id: number] : Field },
homestead: Homestead,
recordBook: RecordBook,
cast: Cast,
economy: Economy
}): string {
let pText = '';
let splitText = this.text.split('|');
splitText.map((piece, index) => {
if (index % 2 == 0) {
pText += (piece);
}
else if (index % 2 == 1) {
pText += utils.parseDeepValue(gameState, piece.split(','));
}
});
return pText;
}
}
interface DialogueInterface {
index: number;
conditions: Condition[];
important: boolean;
probability: number;
text: string;
}
|
a92b2f637b26b7a9fe8fbfcd5732a40866762099 | TypeScript | MRamosObinte/pwa | /src/app/entidadesTO/inventario/LugarEntrgea.ts | 2.71875 | 3 | export class LugarEntrega {
public nombre: string = null;
constructor(data?) {
data ? this.hydrate(data) : null;
}
hydrate(data) {
this.nombre = data.nombre ? data.nombre : this.nombre;
}
} |
c95609cfb2206eb93f51175624c11c06ca123b5c | TypeScript | qingniao99/lit | /packages/labs/ssr/src/lib/element-renderer.ts | 2.703125 | 3 | /// <reference lib="dom" />
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
export type Constructor<T> = {new (): T};
import {createRequire} from 'module';
const require = createRequire(import.meta.url);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const escapeHtml = require('escape-html') as typeof import('escape-html');
import {RenderInfo} from './render-lit-html.js';
export type ElementRendererConstructor = (new (
tagName: string
) => ElementRenderer) &
typeof ElementRenderer;
type AttributesMap = Map<string, string>;
export const getElementRenderer = (
{elementRenderers}: RenderInfo,
tagName: string,
ceClass: typeof HTMLElement = customElements.get(tagName),
attributes: AttributesMap = new Map()
): ElementRenderer | undefined => {
if (ceClass === undefined) {
console.warn(`Custom element ${tagName} was not registered.`);
return;
}
// TODO(kschaaf): Should we implement a caching scheme, e.g. keyed off of
// ceClass's base class to prevent O(n) lookups for every element (probably
// not a concern for the small number of element renderers we'd expect)? Doing
// so would preclude having cross-cutting renderers to e.g. no-op render all
// custom elements with a `client-only` attribute, so punting for now.
for (const renderer of elementRenderers) {
if (renderer.matchesClass(ceClass, tagName, attributes)) {
return new renderer(tagName);
}
}
return undefined;
};
/**
* An object that renders elements of a certain type.
*/
export abstract class ElementRenderer {
element?: HTMLElement;
tagName: string;
/**
* Should be implemented to return true when the given custom element class
* and/or tagName should be handled by this renderer.
*
* @param ceClass - Custom Element class
* @param tagName - Tag name of custom element instance
* @param attributes - Map of attribute key/value pairs
* @returns
*/
static matchesClass(
_ceClass: typeof HTMLElement,
_tagName: string,
_attributes: AttributesMap
) {
return false;
}
constructor(tagName: string) {
this.tagName = tagName;
}
/**
* Should implement server-appropriate implementation of connectedCallback
*/
abstract connectedCallback(): void;
/**
* Should implement server-appropriate implementation of attributeChangedCallback
*/
abstract attributeChangedCallback(
name: string,
old: string | null,
value: string | null
): void;
/**
* Handles setting a property.
*
* Default implementation sets the property on the renderer's element instance.
*
* @param name Name of the property
* @param value Value of the property
*/
setProperty(name: string, value: unknown) {
if (this.element !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(this.element as any)[name] = value;
}
}
/**
* Handles setting an attribute on an element.
*
* Default implementation calls `setAttribute` on the renderer's element
* instance, and calls the abstract `attributeChangedCallback` on the
* renderer.
*
* @param name Name of the attribute
* @param value Value of the attribute
*/
setAttribute(name: string, value: string) {
if (this.element !== undefined) {
const old = this.element.getAttribute(name);
this.element.setAttribute(name, value);
this.attributeChangedCallback(name, old, value);
}
}
/**
* Render a single element's ShadowRoot children.
*/
abstract renderShadow(
_renderInfo: RenderInfo
): IterableIterator<string> | undefined;
/**
* Render an element's light DOM children.
*/
abstract renderLight(renderInfo: RenderInfo): IterableIterator<string>;
/**
* Render an element's attributes.
*
* Default implementation serializes all attributes on the element instance.
*/
*renderAttributes(): IterableIterator<string> {
if (this.element !== undefined) {
const {attributes} = this.element;
for (
let i = 0, name, value;
i < attributes.length && ({name, value} = attributes[i]);
i++
) {
if (value === '') {
yield ` ${name}`;
} else {
yield ` ${name}="${escapeHtml(value)}"`;
}
}
}
}
}
|
d20291624b086b16649503a242e4230283da5acb | TypeScript | owid/owid-grapher | /packages/@ourworldindata/core-table/src/OwidTableSynthesizers.ts | 2.75 | 3 | import {
sampleFrom,
getRandomNumberGenerator,
range,
countries,
OwidVariableDisplayConfigInterface,
ColumnSlug,
} from "@ourworldindata/utils"
import { TimeRange } from "./CoreTableConstants.js"
import { ColumnTypeNames } from "./CoreColumnDef.js"
import { OwidTable } from "./OwidTable.js"
import { OwidColumnDef, OwidTableSlugs } from "./OwidTableConstants.js"
interface SynthOptions {
entityCount: number
entityNames: string[]
timeRange: TimeRange
columnDefs: OwidColumnDef[]
}
const SynthesizeOwidTable = (
options?: Partial<SynthOptions>,
seed = Date.now()
): OwidTable => {
const finalOptions: SynthOptions = {
entityNames: [],
entityCount: 2,
timeRange: [1950, 2020],
columnDefs: [],
...options,
}
const { entityCount, columnDefs, timeRange, entityNames } = finalOptions
const colSlugs = (
[
OwidTableSlugs.entityName,
OwidTableSlugs.entityCode,
OwidTableSlugs.entityId,
OwidTableSlugs.year,
] as ColumnSlug[]
).concat(columnDefs.map((col) => col.slug!))
const entities = entityNames.length
? entityNames.map((name) => {
return {
name,
code: name.substr(0, 3).toUpperCase(),
}
})
: sampleFrom(countries, entityCount, seed)
const rows = entities.map((entity, index) => {
let values = columnDefs.map((def) => def.generator!())
return range(timeRange[0], timeRange[1])
.map((year) => {
values = columnDefs.map((def, index) =>
Math.round(
values[index] * (1 + def.growthRateGenerator!() / 100)
)
)
return [entity.name, entity.code, index, year, ...values].join(
","
)
})
.join("\n")
})
return new OwidTable(
`${colSlugs.join(",")}\n${rows.join("\n")}`,
columnDefs
)
}
export const SynthesizeNonCountryTable = (
options?: Partial<SynthOptions>,
seed = Date.now()
): OwidTable =>
SynthesizeOwidTable(
{
entityNames: ["Fire", "Earthquake", "Tornado"],
columnDefs: [
{
slug: SampleColumnSlugs.Disasters,
type: ColumnTypeNames.Integer,
generator: getRandomNumberGenerator(0, 20, seed),
growthRateGenerator: getRandomNumberGenerator(
-50,
50,
seed
),
},
],
...options,
},
seed
)
export enum SampleColumnSlugs {
Population = "Population",
GDP = "GDP",
LifeExpectancy = "LifeExpectancy",
Fruit = "Fruit",
Vegetables = "Vegetables",
Disasters = "Disasters",
}
export const SynthesizeGDPTable = (
options?: Partial<SynthOptions>,
seed = Date.now(),
display?: OwidVariableDisplayConfigInterface
): OwidTable =>
SynthesizeOwidTable(
{
columnDefs: [
{
...SynthSource(SampleColumnSlugs.Population),
slug: SampleColumnSlugs.Population,
type: ColumnTypeNames.Population,
generator: getRandomNumberGenerator(1e7, 1e9, seed),
growthRateGenerator: getRandomNumberGenerator(-5, 5, seed),
display,
},
{
...SynthSource(SampleColumnSlugs.GDP),
slug: SampleColumnSlugs.GDP,
type: ColumnTypeNames.Currency,
generator: getRandomNumberGenerator(1e9, 1e12, seed),
growthRateGenerator: getRandomNumberGenerator(
-15,
15,
seed
),
display,
},
{
...SynthSource(SampleColumnSlugs.LifeExpectancy),
slug: SampleColumnSlugs.LifeExpectancy,
type: ColumnTypeNames.Age,
generator: getRandomNumberGenerator(60, 90, seed),
growthRateGenerator: getRandomNumberGenerator(-2, 2, seed),
display,
},
],
...options,
},
seed
)
const SynthSource = (
name: string
): {
sourceName: string
sourceLink: string
dataPublishedBy: string
dataPublisherSource: string
retrievedDate: string
additionalInfo: string
} => {
return {
// id: name.charCodeAt(0) + name.charCodeAt(1) + name.charCodeAt(2),
sourceName: `${name} Almanac`,
sourceLink: "http://foo.example",
dataPublishedBy: `${name} Synthetic Data Team`,
dataPublisherSource: `${name} Institute`,
retrievedDate: "1/1/2000",
additionalInfo: `Downloaded via FTP`,
}
}
export const SynthesizeFruitTable = (
options?: Partial<SynthOptions>,
seed = Date.now()
): OwidTable =>
SynthesizeOwidTable(
{
columnDefs: [
{
...SynthSource(SampleColumnSlugs.Fruit),
slug: SampleColumnSlugs.Fruit,
type: ColumnTypeNames.Numeric,
generator: getRandomNumberGenerator(500, 1000, seed),
growthRateGenerator: getRandomNumberGenerator(
-10,
10,
seed
),
},
{
...SynthSource(SampleColumnSlugs.Vegetables),
slug: SampleColumnSlugs.Vegetables,
type: ColumnTypeNames.Numeric,
generator: getRandomNumberGenerator(400, 1000, seed),
growthRateGenerator: getRandomNumberGenerator(
-10,
12,
seed
),
},
],
...options,
},
seed
)
export const SynthesizeFruitTableWithNonPositives = (
options?: Partial<SynthOptions>,
howManyNonPositives = 20,
seed = Date.now()
): OwidTable => {
const rand = getRandomNumberGenerator(-1000, 0)
return SynthesizeFruitTable(options, seed).replaceRandomCells(
howManyNonPositives,
[SampleColumnSlugs.Fruit, SampleColumnSlugs.Vegetables],
undefined,
() => rand()
)
}
const stringValues = ["NA", "inf", "..", "/", "-", "#VALUE!"]
export const SynthesizeFruitTableWithStringValues = (
options?: Partial<SynthOptions>,
howMany = 20,
seed = Date.now()
): OwidTable => {
return SynthesizeFruitTable(options, seed).replaceRandomCells(
howMany,
[SampleColumnSlugs.Fruit, SampleColumnSlugs.Vegetables],
undefined,
() => sampleFrom(stringValues, 1, Date.now())[0]
)
}
|
a6a4f724277bf39fb17d0353d46f5305bf13cc0a | TypeScript | Commodity-Metaverse/arsnova.click-v2-frontend | /src/app/pipes/justafew/justafew.pipe.ts | 2.515625 | 3 | import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'justafew',
})
export class JustAFewPipe implements PipeTransform {
public transform<T>(value: Array<T>, start: number): Array<T> {
if (!start || value.length < start) {
return value;
}
return value.slice(0, start);
}
}
|
af61985412c80e666ece135f683d4f4a14747eda | TypeScript | tomaszwpasternak/ng2-iban | /projects/ng2-iban/src/lib/pipe/iban/ng2-iban.pipe.ts | 2.5625 | 3 | import {Pipe, PipeTransform} from '@angular/core';
import * as IBAN from 'iban';
import {Ng2IbanOptionInterface} from './ng2-iban-option.interface';
@Pipe({
name: 'ibanConverter'
})
export class Ng2IbanPipe implements PipeTransform {
readonly DEFAULT_OPTIONS: Partial<Ng2IbanOptionInterface> = {
locale: null,
separator: ' ',
formatWithLocale: true
};
transform(iban: any, options?: Partial<Ng2IbanOptionInterface>): any {
const pipeOptions = {
...this.DEFAULT_OPTIONS,
...options
};
if (!iban || typeof iban !== 'string') {
return iban;
}
if (pipeOptions.locale) {
iban = pipeOptions.locale + iban;
}
const regexp = new RegExp(pipeOptions.separator, 'g');
if (!IBAN.isValid(iban.replace(regexp, ''))) {
return iban;
}
if (pipeOptions.formatWithLocale === true) {
return IBAN.printFormat(iban, pipeOptions.separator);
}
return IBAN.printFormat(iban, pipeOptions.separator).substring(2);
}
}
|
23dfcdd1f6258ad8c077707ad76e98ae46938b7d | TypeScript | ngnhuuthai/nodesrv | /src/mob/race/eventConsumer/halfling/halflingMvBonusEventConsumer.ts | 2.53125 | 3 | import { injectable } from "inversify"
import {EventType} from "../../../../event/enum/eventType"
import {createModifiedMobMoveEvent} from "../../../../event/factory/eventFactory"
import EventConsumer from "../../../../event/interface/eventConsumer"
import EventResponse from "../../../../event/messageExchange/eventResponse"
import {Terrain} from "../../../../region/enum/terrain"
import MobMoveEvent from "../../../event/mobMoveEvent"
import {RaceType} from "../../enum/raceType"
@injectable()
export default class HalflingMvBonusEventConsumer implements EventConsumer {
public static terrains = [ Terrain.Forest, Terrain.Plains ]
public getConsumingEventTypes(): EventType[] {
return [ EventType.MobMoved ]
}
public async isEventConsumable(event: MobMoveEvent): Promise<boolean> {
return event.mob.raceType === RaceType.Halfling &&
HalflingMvBonusEventConsumer.terrains.includes(event.source.region.terrain)
}
public consume(event: MobMoveEvent): Promise<EventResponse> {
return EventResponse.modified(createModifiedMobMoveEvent(event, event.mvCost / 2))
}
}
|
c16e39332c1e385a0357e4f6ec9f40e659a95600 | TypeScript | Sammons/barkcount | /src/redux/soundSubscriptionStore.ts | 2.734375 | 3 | import { ReducerTemplate } from './helpers/reducerHelpers';
import { SoundService } from '../services/SoundService';
enum ActionTypes {
setSubscription
}
let soundSubscriptionTemplate = new ReducerTemplate({
subscriptions: {} as {[id: string]: number}
});
export type SoundSubscriptionState = typeof soundSubscriptionTemplate.defaultState;
interface SetSubscriptionDispatchType { type: number; subscription: number; id: string }
soundSubscriptionTemplate.addReducer((state, action: SetSubscriptionDispatchType) => {
return soundSubscriptionTemplate.assign(state, {
subscriptions: Object.assign(state.subscriptions, { [action.id]: action.subscription })
});
}, ActionTypes.setSubscription)
export const setSubscription = (canvasId: string, prevSubscription: number, cb: (volume: number) => void): SetSubscriptionDispatchType => {
if (prevSubscription) { SoundService.unsubscribe(prevSubscription); }
let newSub = SoundService.subscribeToVolumeChange(cb);
return {
type: ActionTypes.setSubscription,
subscription: newSub,
id: canvasId
}
}
export const SoundSubscriptionReducer = soundSubscriptionTemplate.rootReducer; |
85b17fd35b8a1f9a5ab0b083184bb98522253dd4 | TypeScript | JamesBonddu/nestjs-book | /src/helpers/hash.helper.ts | 2.859375 | 3 | import bcrypt from 'bcryptjs'
export class HashHelper {
private static salt = 10
static async encrypt(str: string): Promise<string> {
return await bcrypt.hash(str, HashHelper.salt)
}
static async compare(plain: string, encrypted: string): Promise<boolean> {
return await bcrypt.compare(plain, encrypted)
}
}
|
5234c22d639ab227f7932abdaf30a4418e3ffcca | TypeScript | itershukov/redux-communications | /src/strategies/base.ts | 2.796875 | 3 | import { connect } from 'react-redux';
import { IAction, IBuilderConfig, IFullState, IReducers, IStrategy } from '../types';
import { getStateBranchName } from '../helpers';
export class BaseStrategy<InjectedProps> implements IStrategy<InjectedProps> {
public readonly config: IBuilderConfig;
constructor(config: IBuilderConfig) {
this.config = config;
}
buildActions() {
return {};
}
public buildReducers() {
const { namespace, branches } = this.config;
const reducers: IReducers = branches.reduce(
(accum, branch) => ({
...accum,
...branch.buildBranchReducers(namespace)
}),
{}
);
const res: IReducers = {};
const initialState = branches.reduce((accumulator: IFullState, branch) => {
accumulator[branch.name] = branch.initialState;
return accumulator;
}, {});
res[namespace] = (state: IFullState = initialState, action: IAction<unknown>) => {
return reducers[action.type] ? { ...state, ...reducers[action.type](state, action) } : state;
};
return res;
}
public buildInjector() {
const { namespace, branches } = this.config;
const mapStateToProps = (state: IFullState) => ({
...branches.reduce(
(accum, branch) => ({
...accum,
[getStateBranchName(namespace, branch.name)]: state[namespace][branch.name]
}),
{}
)
});
const mapDispatchToProps = dispatch =>
branches.reduce(
(accum, next) => ({
...accum,
...next.buildBranchDispatchers(namespace, dispatch)
}),
{}
);
return connect(
mapStateToProps,
mapDispatchToProps
);
}
public buildSagas() {
const { namespace, branches, sagas = [] } = this.config;
const saga = branches.reduce(
(accum, branch) => {
const branchSagas = branch.buildBranchSagas(namespace);
return [...accum, ...branchSagas];
},
[] as IterableIterator<unknown>[]
);
return [...saga, ...sagas];
}
}
|
770a07008fc1d9bf8dd8dcfa05f62314186ddb4a | TypeScript | nguyer/aws-sdk-js-v3 | /clients/node/client-dynamodb-node/types/_AutoScalingTargetTrackingScalingPolicyConfigurationUpdate.ts | 2.90625 | 3 | /**
* <p>Represents the settings of a target tracking scaling policy that will be modified.</p>
*/
export interface _AutoScalingTargetTrackingScalingPolicyConfigurationUpdate {
/**
* <p>Indicates whether scale in by the target tracking policy is disabled. If the value is true, scale in is disabled and the target tracking policy won't remove capacity from the scalable resource. Otherwise, scale in is enabled and the target tracking policy can remove capacity from the scalable resource. The default value is false.</p>
*/
DisableScaleIn?: boolean;
/**
* <p>The amount of time, in seconds, after a scale in activity completes before another scale in activity can start. The cooldown period is used to block subsequent scale in requests until it has expired. You should scale in conservatively to protect your application's availability. However, if another alarm triggers a scale out policy during the cooldown period after a scale-in, application autoscaling scales out your scalable target immediately. </p>
*/
ScaleInCooldown?: number;
/**
* <p>The amount of time, in seconds, after a scale out activity completes before another scale out activity can start. While the cooldown period is in effect, the capacity that has been added by the previous scale out event that initiated the cooldown is calculated as part of the desired capacity for the next scale out. You should continuously (but not excessively) scale out.</p>
*/
ScaleOutCooldown?: number;
/**
* <p>The target value for the metric. The range is 8.515920e-109 to 1.174271e+108 (Base 10) or 2e-360 to 2e360 (Base 2).</p>
*/
TargetValue: number;
}
export type _UnmarshalledAutoScalingTargetTrackingScalingPolicyConfigurationUpdate = _AutoScalingTargetTrackingScalingPolicyConfigurationUpdate;
|
3a2ec93ce1cdc879b32a889143f18d608c2b2cec | TypeScript | PalKriah/Automatons | /src/classes/Stack.ts | 3.671875 | 4 | export class Stack<T> {
private storage: T[] = [];
constructor() { }
push(item: T): void {
this.storage.push(item);
}
pop(): T | undefined {
return this.storage.pop();
}
peek(): T | undefined {
return this.storage[this.size() - 1];
}
size(): number {
return this.storage.length;
}
toListCopy(): T[] {
let stackCopy: T[] = [];
for (let i = this.storage.length - 1; i >= 0; i--) {
stackCopy.push(this.storage[i]);
}
return stackCopy;
}
} |
7f48e25fdf7afc26728123031405030899a1274e | TypeScript | seebees/aws-sdk-js-v3 | /packages/client-xray-node/types/_Http.ts | 2.515625 | 3 | /**
* _Http shape
*/
export interface _Http {
/**
* _String shape
*/
HttpURL?: string;
/**
* _NullableInteger shape
*/
HttpStatus?: number;
/**
* _String shape
*/
HttpMethod?: string;
/**
* _String shape
*/
UserAgent?: string;
/**
* _String shape
*/
ClientIp?: string;
}
export type _UnmarshalledHttp = _Http; |
33d7890e1adfe6e8c7a71b5c5b3b138bc19b21b8 | TypeScript | louisbeullens/KonAInenHokken | /player4.ts | 2.953125 | 3 | import { IPlayer, IGamestate, EDieSymbol, BasePlayer } from "./shared"
const generateTrueOrFalse = () => Math.random() < 0.5? true : false
class Player extends BasePlayer implements IPlayer {
name: string = "Monkey"
async doContinue(gameState: IGamestate) {
return generateTrueOrFalse()
}
async pickHutch(gamestate: IGamestate, dice: EDieSymbol[]) {
return generateTrueOrFalse()
}
async pickDice(
gamestate: IGamestate,
dice: EDieSymbol[]
): Promise<[EDieSymbol[], boolean]> {
return [dice.filter(() => generateTrueOrFalse()), generateTrueOrFalse()]
}
}
export default new Player()
|
fcd1f4f67d3a05053ead9969b0286364fd4cbf70 | TypeScript | bobbylight/DragonWarriorJS | /src/app/dw/mapLogic/overworld.ts | 2.609375 | 3 | import DwGame from '../DwGame';
import AbstractMapLogic, { NpcTextGeneratorMap } from './AbstractMapLogic';
import { NpcText } from './MapLogic';
const talks: NpcTextGeneratorMap = {
npc: (game: DwGame): NpcText => {
return [
'I speak with... \\ddelays...',
'Did you notice that?'
];
}
};
/**
* Logic for the overworld.
*/
export default class Overworld extends AbstractMapLogic {
constructor() {
super(talks);
}
}
|
fd282b57f1093728e4f0dafdbfea822aabe79f3f | TypeScript | jasonbyrne/whamsauce | /public/app/rule.ts | 3.109375 | 3 |
namespace Whamsauce {
export class Rule {
public pattern:RegExp;
public componentName:string;
public componentPath:string;
protected rawPattern:string;
protected params:Array<string> = [];
/**
*
* @param pattern
* @param component
*/
constructor(pattern:string, component:string) {
this.rawPattern = pattern;
this.componentName = component;
this.componentPath = component.replace('_', '/');
// Get pattern parameters
let matches = pattern.match(/{[a-z0-9_]+}/ig);
if (matches != null) {
for (let i=0; i < matches.length; i++) {
let param:string = matches[i];
this.params.push(param.substring(1, param.length - 1));
}
}
// Turn pattern into regex
pattern = pattern.replace(/{[a-z0-9_]+}/ig, '([a-z0-9_]+)');
this.pattern = new RegExp('^' + pattern + '$', 'i');
}
/**
*
* @param path
* @returns {any}
*/
public getParams(path:string):any {
let out:any = {},
matches = path.match(this.pattern);
if (matches != null) {
for (let i=1; i < matches.length; i++) {
let key:string = this.params[i - 1];
out[key] = matches[i];
}
}
return out;
}
/**
*
* @param path
* @returns {boolean}
*/
public isMatch(path:string):boolean {
return this.pattern.test(path);
}
}
} |
3e288965e208278c3e104b3fb153f4c0d267723c | TypeScript | thaytuandm/antiutils | /src/internal/types/asEqualFunction.ts | 2.6875 | 3 | import { as } from './as';
import { EqualFunction } from './types';
/**
* An identity function that downcasts a value to an `EqualFunction`.
*/
export const asEqualFunction: <T>(
value: EqualFunction<T>,
) => EqualFunction<T> = as;
|
8b4f2bff3f40e9b2f701492e3c1854d59f238e92 | TypeScript | jacobx1/of-sdk | /packages/of-types/src/Document.ts | 2.609375 | 3 | import FileWrapper from './FileWrapper';
export default interface Document {
close: (didCancel: (() => void) | null) => void;
save: () => void;
makeFileWrapper: (
baseName: string,
type: string | null
) => Promise<FileWrapper>;
undo: () => void;
redo: () => void;
show: (resultFunction: (() => void) | null) => void;
readonly canRedo: boolean;
readonly canUndo: boolean;
readonly fileType: string | null;
readonly name: string | null;
readonly writeableTypes: string[];
}
export interface DocumentStatic {
new (): Document;
makeNew: (resultFunction: (() => Document) | null) => Promise<Document>;
makeNewAndShow: (
resultFunction: (() => Document) | null
) => Promise<Document>;
}
|
d2ac8bb7453367de3f9e3ef2e40cdc31bd199a06 | TypeScript | ColtonProvias/TSJS-lib-generator | /src/helpers.ts | 2.8125 | 3 | import * as Browser from "./types";
export function filter(obj: any, fn: (o: any, n: string | undefined) => boolean): any {
if (typeof obj === "object") {
if (Array.isArray(obj)) {
return mapDefined(obj, e => fn(e, undefined) ? filter(e, fn) : undefined);
}
else {
const result: any = {};
for (const e in obj) {
if (fn(obj[e], e)) {
result[e] = filter(obj[e], fn);
}
}
return result;
}
}
return obj;
}
export function filterProperties<T>(obj: Record<string, T>, fn: (o: T) => boolean): Record<string, T> {
const result: Record<string, T> = {};
for (const e in obj) {
if (fn(obj[e])) {
result[e] = obj[e];
}
}
return result;
}
export function merge<T>(src: T, target: T, shallow?: boolean): T {
if (typeof src !== "object" || typeof target !== "object") {
return target;
}
for (const k in target) {
if (Object.getOwnPropertyDescriptor(target, k)) {
if (Object.getOwnPropertyDescriptor(src, k)) {
const srcProp = src[k];
const targetProp = target[k];
if (Array.isArray(srcProp) && Array.isArray(targetProp)) {
mergeNamedArrays(srcProp, targetProp);
}
else {
if (Array.isArray(srcProp) !== Array.isArray(targetProp)) {
throw new Error("Mismatch on property: " + k + JSON.stringify(targetProp));
}
if (shallow && "name" in src[k] && "name" in target[k]) {
src[k] = target[k];
}
else {
src[k] = merge(src[k], target[k], shallow);
}
}
}
else {
src[k] = target[k];
}
}
}
return src;
}
function mergeNamedArrays<T extends { name: string; "new-type": string; }>(srcProp: T[], targetProp: T[]) {
const map: any = {};
for (const e1 of srcProp) {
const name = e1.name || e1["new-type"];
if (name) {
map[name] = e1;
}
}
for (const e2 of targetProp) {
const name = e2.name || e2["new-type"];
if (name && map[name]) {
merge(map[name], e2);
}
else {
srcProp.push(e2);
}
}
}
export function distinct<T>(a: T[]): T[] {
return Array.from(new Set(a).values());
}
export function mapToArray<T>(m: Record<string, T>): T[] {
return Object.keys(m || {}).map(k => m[k]);
}
export function arrayToMap<T, U>(array: ReadonlyArray<T>, makeKey: (value: T) => string, makeValue: (value: T) => U): Record<string, U> {
const result: Record<string, U> = {};
for (const value of array) {
result[makeKey(value)] = makeValue(value);
}
return result;
}
export function map<T, U>(obj: Record<string, T> | undefined, fn: (o: T) => U): U[] {
return Object.keys(obj || {}).map(k => fn(obj![k]));
}
export function mapDefined<T, U>(array: ReadonlyArray<T> | undefined, mapFn: (x: T, i: number) => U | undefined): U[] {
const result: U[] = [];
if (array) {
for (let i = 0; i < array.length; i++) {
const mapped = mapFn(array[i], i);
if (mapped !== undefined) {
result.push(mapped);
}
}
}
return result;
}
export function toNameMap<T extends { name: string }>(array: T[]) {
const result: Record<string, T> = {};
for (const value of array) {
result[value.name] = value;
}
return result;
}
export function isArray(value: any): value is ReadonlyArray<{}> {
return Array.isArray ? Array.isArray(value) : value instanceof Array;
}
export function flatMap<T, U>(array: ReadonlyArray<T> | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray<U> | undefined): U[] {
let result: U[] | undefined;
if (array) {
result = [];
for (let i = 0; i < array.length; i++) {
const v = mapfn(array[i], i);
if (v) {
if (isArray(v)) {
result.push(...v);
}
else {
result.push(v);
}
}
}
}
return result || [];
}
export function concat<T>(a: T[] | undefined, b: T[] | undefined): T[] {
return !a ? b || [] : a.concat(b || []);
}
export function getEmptyWebIDL(): Browser.WebIdl {
return {
"callback-functions": {
"callback-function": {}
},
"callback-interfaces": {
"interface": {}
},
"dictionaries": {
"dictionary": {}
},
"enums": {
"enum": {}
},
"interfaces": {
"interface": {}
},
"mixins": {
"mixin": {}
},
"typedefs": {
"typedef": []
}
}
}
|
c9576cde743887e92c1d245287a9486efce87228 | TypeScript | stoyan-krusharski/angular-recipes-nutrition | /src/app/core/calculation.service.ts | 2.78125 | 3 | import { Injectable } from '@angular/core';
import { Nutrition } from '../models/nutrition';
@Injectable()
export class CalculationService {
public constructor() { }
shortenNutritionValues(nutrition: Nutrition): Nutrition {
for (const key in nutrition) {
if (nutrition.hasOwnProperty(key)) {
nutrition[key].value = +(nutrition[key].value.toFixed(0));
}
}
return nutrition;
}
sumNutritionValues(nutritionArray: Nutrition[]): Nutrition {
return nutritionArray.reduce((acc, curr) => {
for (const key in acc) {
if (acc.hasOwnProperty(key)) {
acc[key].value += curr[key].value;
}
}
return acc;
}, {
PROCNT: { description: 'Protein', unit: 'g', value: 0 },
FAT:
{ description: 'Total lipid (fat)', unit: 'g', value: 0 },
CHOCDF:
{
description: 'Carbohydrate, by difference',
unit: 'g',
value: 0
},
ENERC_KCAL: { description: 'Energy', unit: 'kcal', value: 0 },
SUGAR: { description: 'Sugars, total', unit: 'g', value: 0 },
FIBTG: { description: 'Fiber, total dietary', unit: 'g', value: 0 },
CA: { description: 'Calcium, Ca', unit: 'mg', value: 0 },
FE: { description: 'Iron, Fe', unit: 'mg', value: 0 },
P: { description: 'Phosphorus, P', unit: 'mg', value: 0 },
K: { description: 'Potassium, K', unit: 'mg', value: 0 },
NA: { description: 'Sodium, Na', unit: 'mg', value: 0 },
VITA_IU:
{ description: 'Vitamin A, IU', unit: 'IU', value: 0 },
TOCPHA:
{
description: 'Vitamin E (alpha-tocopherol)',
unit: 'mg',
value: 0
},
VITD: { description: 'Vitamin D', unit: 'IU', value: 0 },
VITC:
{
description: 'Vitamin C, total ascorbic acid',
unit: 'mg',
value: 0
},
VITB12: { description: 'Vitamin B-12', unit: 'µg', value: 0 },
FOLAC: { description: 'Folic acid', unit: 'µg', value: 0 },
CHOLE: { description: 'Cholesterol', unit: 'mg', value: 0 },
FATRN:
{
description: 'Fatty acids, total trans',
unit: 'g',
value: 0
},
FASAT:
{
description: 'Fatty acids, total saturated',
unit: 'g',
value: 0
},
FAMS:
{
description: 'Fatty acids, total monounsaturated',
unit: 'g',
value: 0
},
FAPU:
{
description: 'Fatty acids, total polyunsaturated',
unit: 'g',
value: 0
}
});
}
public calculateHelperProd(ing) {
const measureOfItem = ing.calcArr.find((measure) => {
return `${measure.amount} ${measure.measure}` === ing.measures;
});
const weightInGrams = measureOfItem.gramsPerMeasure * ing.amount;
const totalNutritionValue = this.calculateNutrition(weightInGrams, ing.nutrition);
return {
weightInGrams,
totalNutritionValue,
};
}
public calculateHelperSub(sub) {
const weightInGrams = sub.amount * sub.gramsPerMeasure;
const totalNutritionValue = this.calculateNutrition(weightInGrams, sub.nutrition);
return {
weightInGrams,
totalNutritionValue,
};
}
public calculateNutrition(weightInGrams: number, nutrition: Nutrition) {
const calculateNutrient = (wghtInGr, field) => {
return wghtInGr * field.value / 100;
};
const nutrients = {
PROCNT: JSON.parse(JSON.stringify(nutrition.PROCNT)),
FAT: JSON.parse(JSON.stringify(nutrition.FAT)),
CHOCDF: JSON.parse(JSON.stringify(nutrition.CHOCDF)),
ENERC_KCAL: JSON.parse(JSON.stringify(nutrition.ENERC_KCAL)),
SUGAR: JSON.parse(JSON.stringify(nutrition.SUGAR)),
FIBTG: JSON.parse(JSON.stringify(nutrition.FIBTG)),
CA: JSON.parse(JSON.stringify(nutrition.CA)),
FE: JSON.parse(JSON.stringify(nutrition.FE)),
P: JSON.parse(JSON.stringify(nutrition.P)),
K: JSON.parse(JSON.stringify(nutrition.K)),
NA: JSON.parse(JSON.stringify(nutrition.NA)),
VITA_IU: JSON.parse(JSON.stringify(nutrition.VITA_IU)),
TOCPHA: JSON.parse(JSON.stringify(nutrition.TOCPHA)),
VITD: JSON.parse(JSON.stringify(nutrition.VITD)),
VITC: JSON.parse(JSON.stringify(nutrition.VITC)),
VITB12: JSON.parse(JSON.stringify(nutrition.VITB12)),
FOLAC: JSON.parse(JSON.stringify(nutrition.FOLAC)),
CHOLE: JSON.parse(JSON.stringify(nutrition.CHOLE)),
FATRN: JSON.parse(JSON.stringify(nutrition.FATRN)),
FASAT: JSON.parse(JSON.stringify(nutrition.FASAT)),
FAMS: JSON.parse(JSON.stringify(nutrition.FAMS)),
FAPU: JSON.parse(JSON.stringify(nutrition.FAPU)),
};
for (const nutrient in nutrients) {
if (nutrients.hasOwnProperty(nutrient)) {
nutrients[nutrient].value = calculateNutrient(weightInGrams, nutrients[nutrient]);
}
}
return nutrients;
}
}
|
339369132bdb8fcb7a16ce23f5f5ea2c2815b7c5 | TypeScript | itslenny/GA-TypeScript-Angular | /day1_typescript/examples/one_basics/moudles.ts | 3.375 | 3 | module TimeUtils {
export function getCleanTime():string {
var d = new Date();
return d.toLocaleTimeString();
}
}
module CatParty {
export function letsParty(): void {
// console.log(whatever() + " The Cat Party has Started " + something.random(other.maxRandom));
console.log(`It's ${TimeUtils.getCleanTime()} and the Cat Party has Started!!`);
}
function whatever() {
return "hi";
}
module other {
export var maxRandom = 10;
}
}
module CatParty.something {
export function random(max: number): number{
return Math.round(Math.random() * max);
}
}
module DogParty {
export function letsParty(): void {
// console.log("The Dog Party has Started");
console.log(`It's ${TimeUtils.getCleanTime()} and the Dog Party has Started!!`);
}
}
module app {
export var startTheParties = function() {
CatParty.letsParty();
DogParty.letsParty();
}
}
app.startTheParties(); |
61c95b6d6996cdd7d515db023f534f32561b9fb7 | TypeScript | th4t-gi/apcsa-lotr-game | /ts-version/src/index.ts | 3.015625 | 3 |
function printHealths(combatants: Warrior[]): void {
let maxs: number[] = combatants.map(w => {
let numTabs: number = `${w.getName()} (${w.getType()})`.length / 8
return Math.floor(numTabs) + 1
})
let maxTabs = maxs.reduce((prev, curr) => (prev > curr) ? prev : curr)
let healthboard = combatants.map((w, i) => {
return `${w.getIndex()} - ${w.printName()} (${w.getType()})${"\t".repeat(maxTabs - maxs[i])}${w.getHealthBar()}`
})
console.log("***HEALTHBOARD***\n", healthboard.join("\n"));
} |
71db79a8c06638863af127af89def06719783a58 | TypeScript | ruslan547/async-race | /async-race/src/pages/winners/t-body/t-body.ts | 2.546875 | 3 | import { Component, Winner } from '../../../shared/interfaces';
import { StoreService } from '../../../shared/services/store.service';
import { UtilService } from '../../../shared/services/util.service';
import { TRow } from '../t-row/t-row';
export class TBody implements Component {
private storeService = new StoreService();
private tbody = document.createElement('tbody');
private fillTable = async (): Promise<void> => {
await UtilService.getWinners();
const { winners } = this.storeService.getState();
const rows = winners.map((winner: Winner, index: number) => new TRow(winner, index).render());
this.tbody.append(...rows);
};
public render = (): HTMLElement => {
this.fillTable();
this.tbody.classList.add();
return this.tbody;
};
}
|
642387d0febc9ff749c8036bee300b03d6e9a180 | TypeScript | bsunam/notepad-automate | /src/app/shared/reducers/notes.reducers.ts | 2.59375 | 3 | import { createEntityAdapter, EntityState } from '@ngrx/entity';
import { createReducer, on } from '@ngrx/store';
import { Note } from '../models/note';
import * as noteActions from '../actions/notes.actions';
export interface NotesState extends EntityState<Note> {
selectedNoteId: number,
searchValue: String
}
export const adapter = createEntityAdapter<Note>({
});
export const initialNotesState = adapter.getInitialState({
selectedNoteId: null,
searchValue: ''
});
export const notesReducer = createReducer(
initialNotesState,
on(noteActions.loadAllNotes,
(state, action) => adapter.addAll(
action.notes, state)),
on(noteActions.setSelectedNote,
(state, action) => ({ ...state, selectedNoteId: action.noteId })),
on(noteActions.createNote,
(state, action) => adapter.addOne(action.note, state)),
on(noteActions.updateNote,
(state, action) => adapter.updateOne(action.note, state)),
on(noteActions.deleteNote,
(state, action) => adapter.removeOne(action.id, state)),
on(noteActions.setSearchValue,
(state, action) => ({ ...state, searchValue: action.value }))
);
export const {
selectIds: selectNoteIds,
selectEntities: selectNoteEntities,
selectAll: selectAllNotes,
selectTotal: notesCount
} = adapter.getSelectors();
|
9d67f7a77b4f63400909493f08050a6d300c3ae1 | TypeScript | qiYuei/rich-text | /src/util/EventEmitter.ts | 3.015625 | 3 | class EventEmitter{
public listeners:{
[key: string]: Function[]
}
constructor(){
this.listeners = {}
}
on(event:string, cb:Function){
const listeners = this.listeners
if (listeners[event] instanceof Array) {
if (listeners[event].indexOf(cb) === -1) {
listeners[event].push(cb)
}
} else {
listeners[event] = [].concat(cb)
}
}
emit(event:string,...args: string[]){
// var args = Array.prototype.slice.call(arguments)
// args.shift()
this.listeners[event] && this.listeners[event].forEach(cb => {
cb.apply(null, args)
})
}
removeListener(event:string, listener:Function){
var listeners = this.listeners
var arr = listeners[event] || []
var i = arr.indexOf(listener)
if (i >= 0) {
listeners[event].splice(i, 1)
}
}
once(event:string, listener:Function) {
var self = this
function fn() {
var args = Array.prototype.slice.call(arguments)
listener.apply(null, args)
// 异步清除
Promise.resolve().then(() => {
self.removeListener(event, fn)
})
}
this.on(event, fn)
}
removeAllListener(event:string) {
this.listeners[event] = []
}
}
export default EventEmitter |
6dbd05fb043076098467ab410fb337e06c3bcfa7 | TypeScript | nagimi-net/chirami | /src/interfaces/Source.ts | 2.53125 | 3 | import { Book, BookChapter, BookPage } from './Book';
export enum RestrictionType {
DEV = 'dev',
NORMAL = 'normal',
EXPLICIT = 'explicit',
}
export interface SourceOptions {
/** id of source manager */
id: string;
/** url source */
url: string;
/** icon source */
logo: string;
/** restriction */
label: RestrictionType[];
/** add description for this source */
description?: string;
/** backdrop color, for design purpose */
backdrop_color?: string;
}
export interface Pamflet extends BookChapter {
book: BookCover;
}
export interface BookCover {
}
type Window = {
source: {
LIST: SourceOptions[],
log: string[]
};
}
export class SourceManager {
public static LIST = (window as unknown as Window).source.LIST;
public static LOG = (window as unknown as Window).source.log;
public static getUpdates(sourceIndex: string): Promise<Pamflet[]> {
return (window as any).source.api.getUpdates(sourceIndex);
}
public static directory(sourceIndex: string): Promise<BookCover[]> {
return (window as any).source.api.getDirectory(sourceIndex);
}
public static getBook(sourceIndex: string, bookIndex: string): Promise<Book> {
return (window as any).source.api.getBook(sourceIndex, bookIndex);
}
public static getChapter(sourceIndex: string, bookIndex: string, chapterIndex: string): Promise<BookPage[]> {
return (window as any).source.api.getChapter(sourceIndex, bookIndex, chapterIndex);
}
}
|
f032f68965720c7a3e10029f607abaf7354fd423 | TypeScript | flycatto/dikenang-server | /dikser/src/relationship/relationship.service.spec.ts | 2.65625 | 3 | import { Test, TestingModule } from '@nestjs/testing'
import { getRepositoryToken } from '@nestjs/typeorm'
import { User } from '../users/entities/user.entity'
import { UsersService } from '../users/users.service'
import { CreateRelationshipInput } from './dto/create-relationship.input'
import { DeleteRelationshipResponse } from './dto/delete-relationship.dto'
import { Relationship } from './entities/relationship.entity'
import { RelationshipService } from './relationship.service'
describe('RelationshipService', () => {
let service: RelationshipService
const mockRelationshipRepository = {
create: jest.fn(
(createRelationshipInput: CreateRelationshipInput) =>
createRelationshipInput
),
save: jest.fn((createRelationshipInput: CreateRelationshipInput) => {
return {
id: 'example id',
...createRelationshipInput,
}
}),
findOneOrFail: jest.fn((relationshipId: string) => {
return {
id: relationshipId,
description: 'example description',
type: 'example type',
partnership: [User, User],
}
}),
delete: jest.fn((_relationshipId: string) => {
const previous_data = new Relationship()
return new DeleteRelationshipResponse(previous_data, 'DELETED', 200)
}),
}
const mockUsersService = {
findById: jest.fn(() => {
const user = new User()
user.relationship = new Relationship()
return user
}),
}
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
RelationshipService,
{
provide: getRepositoryToken(Relationship),
useValue: mockRelationshipRepository,
},
{
provide: UsersService,
useValue: mockUsersService,
},
],
}).compile()
service = module.get<RelationshipService>(RelationshipService)
})
it('should be defined', () => {
expect(service).toBeDefined()
})
describe('create new relationship', () => {
it('it should create new relationship and return the created values', async () => {
const userId = 'example id'
const expectedResult = {
id: expect.any(String),
description: 'example description',
type: 'example type',
partnership: expect.any(Array),
}
expect(
await service.create(userId, {
target: 'example target id',
description: 'example description',
type: 'example type',
})
).toEqual(expectedResult)
})
})
describe('find relationship', () => {
it('it should return relationship matches specified id', async () => {
const relationshipId = 'example id'
const expectedResult = {
id: 'example id',
description: 'example description',
type: 'example type',
partnership: expect.any(Array),
}
expect(await service.findById(relationshipId)).toEqual(
expectedResult
)
})
})
describe('delete relationship', () => {
it('it should delete the relationship and return pre defined response', async () => {
const userId = 'example user id'
expect(await service.delete(userId)).toBeInstanceOf(
DeleteRelationshipResponse
)
})
})
})
|
c61652e4fab3ab2f2f463ac77bbd706a17becb19 | TypeScript | BeeRadLeeLLC/testapi6 | /src/components/output/Schema.ts | 2.671875 | 3 | import { context } from "@/Context";
import chalk from "chalk";
import { toJsonSchema } from "../doc/DocUtils";
import { Tag } from "../Tag";
/**
* Print schema of data
*
* ```yaml
* - Vars:
* obj: {
* name: "test",
* age: 123
* }
*
* - Schema: ${obj}
* ```
*/
export class Schema extends Tag {
msg: any
init(attrs: any) {
super.init(attrs, 'msg')
}
async exec() {
if (this.msg !== null && this.msg !== undefined) {
this.msg = toJsonSchema(this.msg, false)
}
context.log(chalk.yellow('%j'), this.msg)
}
} |
8f2777c0bd18dddee5eefbb99fd2fe68212a50d1 | TypeScript | frontity/frontity | /packages/html2react/__tests__/types.test.ts | 3.484375 | 3 | import { expectType } from "frontity/types/helpers";
import { Processor, Node, Element, Text, Comment } from "../types";
// 1. Processor by default accepts Element, Text or Comment.
const proc1: Processor = {
test: ({ node }) => {
expectType<"element" | "text" | "comment">(node.type);
if (node.type === "element") expectType<Element>(node);
if (node.type === "text") expectType<Text>(node);
if (node.type === "comment") expectType<Comment>(node);
return true;
},
processor: ({ node }) => {
expectType<"element" | "text" | "comment">(node.type);
if (node.type === "element") expectType<Element>(node);
if (node.type === "text") expectType<Text>(node);
if (node.type === "comment") expectType<Comment>(node);
return node;
},
};
// 2. Processor with default Element should receive correct types.
const proc2: Processor<Element> = {
test: ({ node }) => {
expectType<Element>(node);
expectType<string | React.ComponentType>(node.component);
expectType<Element>(node.parent);
expectType<Node[]>(node.children);
// Test CSS prop.
expectType<Element["props"]["css"]>(node.props.css);
// Test some HTML props.
expectType<string>(node.props.id);
expectType<string>(node.props.className);
expectType<string>(node.props.src);
expectType<string>(node.props.srcSet);
return true;
},
processor: ({ node }) => {
expectType<Element>(node);
expectType<string | React.ComponentType>(node.component);
expectType<Element>(node.parent);
expectType<Node[]>(node.children);
// Test CSS prop.
expectType<Element["props"]["css"]>(node.props.css);
// Test some HTML props.
expectType<string>(node.props.id);
expectType<string>(node.props.className);
expectType<string>(node.props.src);
expectType<string>(node.props.srcSet);
return node;
},
};
// 3. Element can be extended with custom props.
interface CustomElement extends Element {
props: Element["props"] & {
hasCustomProp: true;
};
}
const proc3: Processor<CustomElement> = {
test: ({ node }) => {
expectType<Element>(node);
expectType<CustomElement>(node);
expectType<true>(node.props.hasCustomProp);
return true;
},
processor: ({ node }) => {
expectType<Element>(node);
expectType<CustomElement>(node);
expectType<true>(node.props.hasCustomProp);
return node;
},
};
// 4. Element can be extended with custom relatives.
interface MyElementParent extends Element {
props: Element["props"] & {
isParent: true;
};
}
interface MyElementChild extends Element {
props: Element["props"] & {
isChild: true;
};
parent: MyElement;
}
interface MyElement extends Element {
props: Element["props"] & {
isElement: true;
};
parent: MyElementParent;
children: [Element, Text, Comment, MyElementChild];
}
const proc4: Processor<MyElement> = {
test: ({ node }) => {
// Test node.
expectType<MyElement>(node);
expectType<true>(node.props.isElement);
// Test parent.
expectType<MyElementParent>(node.parent);
expectType<true>(node.parent.props.isParent);
// Test children.
expectType<Element>(node.children[0]);
expectType<Text>(node.children[1]);
expectType<Comment>(node.children[2]);
expectType<MyElementChild>(node.children[3]);
expectType<true>(node.children[3].props.isChild);
expectType<MyElement>(node.children[3].parent);
return true;
},
processor: ({ node }) => {
// Test node.
expectType<MyElement>(node);
expectType<true>(node.props.isElement);
// Test parent.
expectType<MyElementParent>(node.parent);
expectType<true>(node.parent.props.isParent);
// Test children.
expectType<Element>(node.children[0]);
expectType<Text>(node.children[1]);
expectType<Comment>(node.children[2]);
expectType<MyElementChild>(node.children[3]);
expectType<true>(node.children[3].props.isChild);
expectType<MyElement>(node.children[3].parent);
return node;
},
};
test("Types are fine!", () => {});
|
5de18e819a3894eee62afa67eaab607ecea865c0 | TypeScript | mengzhiwu/vue-app-example | /src/Router.ts | 2.546875 | 3 | import Vue from 'vue';
import VueMeta from 'vue-meta';
import VueRouter from 'vue-router';
import { RawLocation, Route, RouteConfig, RouterMode, RouterOptions } from 'vue-router/types/router'; // tslint:disable-line
import store from 'store';
import SignIn from 'components/pages/sign-in/SignIn.vue';
import SignUp from 'components/pages/sign-up/SignUp.vue';
const Profile = () => System.import('components/pages/profile/Profile.vue');
/**
* Describes vue-router configuration.
*
* More info: http://router.vuejs.org/en/
*/
export default class Router implements RouterOptions {
/**
* List of all routes, supported by application.
* Each router must implement RouteConfig interface, and has at least
* "path" and "component" properties.
*/
public routes: RouteConfig[] = [
{ path: '/', component: SignIn },
{ path: '/login', component: SignIn },
{ path: '/sign_up', component: SignUp },
{ path: '/profile', component: Profile, meta: { requiresAuth: true } },
];
/**
* Vue-router operating mode.
* Available values:
* - hash
* - history
* - abstract
*
* More info: http://router.vuejs.org/en/api/options.html
*/
public mode: RouterMode = 'history';
/**
* Vue-router initialized instance.
*/
private router: VueRouter;
/**
* Creates router instance with pre-configured class properties.
*/
public constructor() {
Vue.use(VueRouter);
Vue.use(VueMeta);
this.router = new VueRouter(this);
this.router.beforeEach(this.beforeEach);
this.router.afterEach(this.afterEach);
this.router.onReady(this.onReady);
}
/**
* Returns vue-router instance.
*/
public get instance(): VueRouter {
return this.router;
}
/**
* Function, that will be executed before each page navigation.
*
* @param to Route, to which navigation is performed.
* @param from Route, from which navigation is performed.
* @param next Function, that MUST be called after performing all other
* actions.
*/
private beforeEach(
to: Route,
from: Route,
next: (to?: RawLocation | false | ((vm: Vue) => any) | void) => void,
) {
store.state.loading = true;
if (to.matched.some((record) => record.meta.requiresAuth)) {
next();
if (!store.state.user.authorized) {
next({
path: '/login',
});
} else {
next();
}
} else {
next();
}
}
/**
* Function, that will be executed after each page navigation.
*
* @param to Route, to which navigation was performed.
* @param from Route, from which navigation was performed.
*/
private afterEach(to: Route, from: Route) {
store.state.loading = false;
}
/**
* Function, that will be performed, after route initialization was
* performed.
*/
private onReady() {
store.state.loading = false;
}
}
|
2f515e5db37677e6bbe1b0b31fb7cad0079e4df3 | TypeScript | ameernuri/prefix | /packages/client/theme/theme.ts | 2.640625 | 3 | import { ThemeProps } from 'styled-components'
export interface Theme {
colors: {
primary?: string
background?: string
foreground?: string
light?: string
}
}
export const colors = (props: ThemeProps<any> = { theme: darkTheme }) => {
return props.theme.colors
}
export const darkTheme: Theme = {
colors: {
primary: '#11aa77',
background: '#070b12',
foreground: '#ffffff',
light: '#eeeeee',
},
}
|
39f210b563aff15888025ec6eb23672e169218e8 | TypeScript | A-aras/PM_AWS | /UI/project-management/projects/shared-api/src/lib/rules/ClassRuleBuilder.ts | 2.625 | 3 | import { IReactiveClassModel } from "../model/IReactiveClassModel";
import { ClassRule } from "./ClassRule";
export abstract class ClassRuleBuilder<TModel extends IReactiveClassModel>{
public Build(): ClassRule<TModel> {
let target = new ClassRule<TModel>();
this.ApplyImpl(target);
return target;
}
public abstract ApplyImpl(target: ClassRule<TModel>);
} |
201e353f7f3abcdcab73f4e798b366b3f27ed505 | TypeScript | EvilPalace/GuessSmallest | /assets/scripts/Test/Test1.ts | 2.65625 | 3 |
const {ccclass, property} = cc._decorator;
// 【描述作用】
@ccclass
export default class Test1 extends cc.Component {
@property(cc.Label)
private tip : cc.Label = null;
startTime = 0;
start(){
this.startTime = Date.now();
}
update(dt){
this.tip.string = "从开始到现在:" + (Date.now() - this.startTime);
}
} |