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
|
|---|---|---|---|---|---|---|
1b83491c8bce5b540f192fee8a01c37fe3aa2a37
|
TypeScript
|
loic5/abaplint
|
/packages/core/src/abap/types/method_definitions.ts
| 2.734375
| 3
|
import {MethodDefinition} from "./method_definition";
import {StructureNode} from "../nodes";
import * as Structures from "../3_structures/structures";
import {MethodDef} from "../2_statements/statements";
import {Visibility} from "../4_file_information/visibility";
import {CurrentScope} from "../5_syntax/_current_scope";
import {IMethodDefinitions} from "./_method_definitions";
import {IMethodDefinition} from "./_method_definition";
export class MethodDefinitions implements IMethodDefinitions {
private readonly all: {[index: string]: IMethodDefinition} = {};
private readonly filename: string;
public constructor(node: StructureNode, filename: string, scope: CurrentScope) {
this.all = {};
this.filename = filename;
this.parse(node, scope);
}
public* getAll(): Generator<IMethodDefinition, void, undefined> {
for (const a in this.all) {
yield this.all[a];
}
}
public getByName(name: string | undefined): IMethodDefinition | undefined {
if (name === undefined) {
return undefined;
}
return this.all[name.toUpperCase()];
}
///////////////////////
private parseInterface(node: StructureNode, scope: CurrentScope) {
const defs = node.findAllStatements(MethodDef);
for (const def of defs) {
const m = new MethodDefinition(def, Visibility.Public, this.filename, scope);
this.all[m.getName().toUpperCase()] = m;
}
}
private parse(node: StructureNode, scope: CurrentScope) {
const idef = node.findDirectStructure(Structures.Interface);
if (idef) {
return this.parseInterface(node, scope);
}
const cdef = node.findDirectStructure(Structures.ClassDefinition);
if (!cdef) {
throw new Error("MethodDefinitions, expected ClassDefinition as part of input node");
}
const pri = cdef.findDirectStructure(Structures.PrivateSection);
for (const def of pri?.findAllStatements(MethodDef) || []) {
const m = new MethodDefinition(def, Visibility.Private, this.filename, scope);
this.all[m.getName().toUpperCase()] = m;
}
const pro = node.findDirectStructure(Structures.ProtectedSection);
for (const def of pro?.findAllStatements(MethodDef) || []) {
const m = new MethodDefinition(def, Visibility.Protected, this.filename, scope);
this.all[m.getName().toUpperCase()] = m;
}
const pub = node.findDirectStructure(Structures.PublicSection);
for (const def of pub?.findAllStatements(MethodDef) || []) {
const m = new MethodDefinition(def, Visibility.Public, this.filename, scope);
this.all[m.getName().toUpperCase()] = m;
}
}
}
|
4defdedf728cbd697695def797096f0c06738d49
|
TypeScript
|
Byteclaw/hooks
|
/packages/use-static-callback/src/index.ts
| 3.640625
| 4
|
import { useRef } from 'react';
type ExtractArgs<T> = T extends (...args: infer A) => any ? A : undefined;
type ExtractReturn<T> = T extends (...args: any) => infer R ? R : never;
function arraysNotEqual(a: any[], b: any[]): boolean {
const aLength = a.length;
const bLength = b.length;
if (aLength !== bLength) {
return true;
}
const mLength = Math.max(aLength, bLength);
for (let i = 0; i < mLength; i++) {
if (a[i] !== b[i]) {
return true;
}
}
return false;
}
/**
* Creates a callback from function declaration
*
* On call it passes arguments provided as an array in second argument
*/
export function useStaticCallback<T extends () => any>(
callback: T,
): () => ExtractReturn<T>;
export function useStaticCallback<T extends (...args: any[]) => any>(
callback: T,
args: ExtractArgs<T>,
): () => ExtractReturn<T>;
export function useStaticCallback(
callback: Function,
args: any[] = [],
): Function {
const previousCallback = useRef<Function>();
const previousArgs = useRef([]);
const returnedCallback = useRef<Function>();
if (
previousCallback.current !== callback ||
arraysNotEqual(previousArgs.current, args)
) {
previousCallback.current = callback;
previousArgs.current = args as any;
returnedCallback.current = () => callback(...args);
}
return returnedCallback.current!;
}
/**
* Creates a callback using a callback creator
*
* Passes arguments provided as an array in second argument to the callback creator
* and returns the result as a callback
*/
export function useStaticCallbackCreator<
T extends () => (...args: any[]) => any,
>(callback: T): ExtractReturn<T>;
export function useStaticCallbackCreator<
T extends (...args: any[]) => (...args1: any[]) => any,
>(callback: T, args: ExtractArgs<T>): ExtractReturn<T>;
export function useStaticCallbackCreator(
callbackCreator: Function,
args: any[] = [],
): Function {
const previousCallbackCreator = useRef<Function>();
const previousArgs = useRef([]);
const returnedCallback = useRef<Function>();
if (
previousCallbackCreator.current !== callbackCreator ||
arraysNotEqual(previousArgs.current, args)
) {
previousCallbackCreator.current = callbackCreator;
previousArgs.current = args as any;
returnedCallback.current = callbackCreator(...args);
}
return returnedCallback.current!;
}
|
6eea812b38145ab021646fe70695e32767f2b9e8
|
TypeScript
|
wang119c/rarity-frontend
|
/src/state/rarity/reducer.ts
| 2.5625
| 3
|
import { createReducer } from '@reduxjs/toolkit'
import { Metadata, updateMetadata } from './actions'
export interface UserState {
readonly metadata: Metadata
}
const initialState: UserState = {
metadata: {
summoners: 0,
barbarians: 0,
bards: 0,
clerics: 0,
druids: 0,
fighters: 0,
monks: 0,
paladins: 0,
rangers: 0,
rogues: 0,
sorcerers: 0,
wizards: 0,
},
}
export default createReducer(initialState, (builder) =>
builder.addCase(updateMetadata, (state, action) => {
state.metadata = action.payload
})
)
|
da79c764868688b961e04341925efed59f460bb6
|
TypeScript
|
annezheng/GoogleMapApp
|
/src/app/marker.service.ts
| 2.71875
| 3
|
import { Injectable } from '@angular/core';
import { Marker } from './classes/marker';
@Injectable()
export class MarkerService {
markers: Marker[] = [];
labels: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
labelIndex: number = 0;
constructor() {
this.load();
}
private load() {
let savedMarkers = localStorage.getItem('markers');
if (!savedMarkers) {
console.log('No saved markers...');
return
}
console.log('Loading saved markers...');
// console.log(savedBooks);
savedMarkers = JSON.parse(savedMarkers);
// console.log(savedBooks);
for (let i = 0; i < savedMarkers.length; i++) {
let savedMarker = savedMarkers[i];
// console.log(savedBook);
//noinspection TypeScriptValidateTypes,TypeScriptUnresolvedFunction
this.markers.push(Object.assign(new Marker(null, null, null, null, null, null, null), savedMarker));
}
console.log(this.markers);
let label = this.markers[this.markers.length-1].label;
this.labelIndex = this.labels.indexOf(label) + 1;
}
private save() {
localStorage.setItem('markers', JSON.stringify(this.markers));
}
hasMarker(marker: Marker): boolean {
return this.indexOf(marker) !== -1;
}
indexOf(marker: Marker): number {
for (let i = 0; i < this.markers.length; i++) {
if (this.markers[i].lat === marker.lat && this.markers[i].lng === marker.lng) {
return i
}
}
return -1;
}
addMarker(marker: Marker) {
if (!this.hasMarker(marker)) {
this.markers.push(marker);
this.save();
}
}
removeMarker(marker: Marker) {
let index = this.indexOf(marker);
this.markers.splice(index, 1);
this.save();
}
updateMarker(oldMarker, newMarker){
let index = this.indexOf(oldMarker);
this.markers.splice(index, 1, newMarker);
this.save();
}
clearMarkers(){
this.markers = [];
localStorage.clear();
this.labelIndex = 0;
}
getNextLabel(){
return this.labels[this.labelIndex++ % this.labels.length];
}
}
|
90a8a4a56f6ee4a4a53288c5ed5214b3ceb8f583
|
TypeScript
|
EvdRidder/resource-peek
|
/src/resource-hover-provider.ts
| 2.5625
| 3
|
import * as vscode from 'vscode'
import { TextDocument, Position, CancellationToken, ProviderResult, HoverProvider, Hover } from 'vscode'
import * as utils from './utils'
export class ResourceHoverProvider implements HoverProvider {
provideHover(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Hover> {
const clickedKey = utils.GetKeyAtPositionInDocument(position, document);
if (!clickedKey) {
return null; // Returns null when no key exists.
}
return utils.FindObjectsForKeyInResourceFiles(clickedKey)
.then(foundObjects => {
if (!foundObjects) {
// Return null because the clicked key was not found in any resource files.
return null
}
// Return a Hover with the key's value.
return new Hover(foundObjects[0].value);
});
}
}
|
9e6d6861f8eb8597c8667441b0c6d40af8590279
|
TypeScript
|
alexisbssn/SkillTree
|
/src/model/rules/ParentValidRule.ts
| 2.609375
| 3
|
import { Rule } from './rule';
import { Ruleable } from '../ruleable';
import { Group } from '../group';
export class ParentValidRule extends Rule{
public Type: string = "ParentValid";
public Parent: Group
public IsValid(subject: Ruleable): boolean{
return this.Parent.isValid();
}
}
|
b01d97a078ff0f5a3564d343552bb5b84eaaa486
|
TypeScript
|
AnGaoLang/simple-vue
|
/src/@types/index.d.ts
| 2.546875
| 3
|
declare const sym: unique symbol // 声明唯一的symbol
declare namespace IVOptions {
type El = string
interface Data {
[Symbol.toStringTag]?: any
[sym]?:any
[index: string]: any
}
interface Methods {
[index: string]: () => any
}
}
interface IVueOptions {
el: IVOptions.El
data: IVOptions.Data
methods: IVOptions.Methods
}
declare interface IVue {
$el: Element | string | never
$data: IVOptions.Data
$methods: IVOptions.Methods
$options: IVueOptions
[index:string]: any
[sym]?:any
[Symbol.toStringTag]?: any
_proxyData(data: IVOptions.Data): IVue
}
|
3ed65bfa5e6eb09f68dbabb523ddcba3ec1f40dd
|
TypeScript
|
xpfw/xpfw
|
/packages/data/src/client.ts
| 2.53125
| 3
|
export interface IUiClient {
client: any
connectTo: (url: string, options?: {
authOptions?: any,
makeAuth?: boolean,
useRest?: boolean,
userStore?: any
/**
* Pass the dbStore to get realtime updates
*/
dbStore?: any
/**
* Realtime Updates will only be fetched for collections defined here
*/
collections?: string[]
}) => void
disconnect: () => void,
login: (loginData: any) => Promise<{user: any, custom?: any}>,
register: (registerData: any) => Promise<any>,
logout: () => Promise<any>,
get: (collection: string, id: any) => Promise<any>,
remove: (collection: string, id: any) => Promise<any>,
create: (collection: string, createData: any) => Promise<any>,
find: (collection: string, createData: any) => Promise<any>,
patch: (collection: string, id: any, createData: any) => Promise<any>,
}
export interface IBackendClient {
client: IUiClient
}
const emptyClient: IUiClient & any = {
client: {},
currentId: 0,
data: {},
ensureCol: (col: string) => {
if (emptyClient.data[col] == null) {
emptyClient.data[col] = {}
}
},
login: (createData: any) => Promise.resolve({user: createData}),
logout: () => Promise.resolve(),
register: (createData: any) => Promise.resolve(createData),
create: (col: any, createData: any) => {
emptyClient.ensureCol(col)
createData._id = emptyClient.currentId
emptyClient.data[col][emptyClient.currentId] = createData
emptyClient.currentId++
return Promise.resolve(createData)
},
patch: (col: string, id: any, createData: any) => {
emptyClient.ensureCol(col)
createData._id = id
emptyClient.data[col][id] = createData
return Promise.resolve(createData)
},
get: (col: string, id: any) => {
emptyClient.ensureCol(col)
return Promise.resolve(emptyClient.data[col][id])
},
find: (col: string, createData: any) => {
const data = []
for (const k of Object.keys(emptyClient.data[col])) {
data.push(emptyClient.data[col][k])
}
return Promise.resolve({
limit: 0, skip: 0, total: data.length, data
})
},
remove: (col: string, id: any) => {
emptyClient.ensureCol(col)
const removedRecord = emptyClient.data[col][id]
delete emptyClient.data[col][id]
return Promise.resolve(removedRecord)
},
connectTo: () => Promise.resolve(),
disconnect: () => null
}
const BackendClient: IBackendClient = {
client: emptyClient
}
export default BackendClient
|
1e6eaf236fe75d807d52a508c5332352de6920c6
|
TypeScript
|
alefemoreira/perfil-api
|
/src/app/models/UserSchema.ts
| 2.796875
| 3
|
import mongoose, { Document, Model } from "mongoose";
import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";
const userSchema = new mongoose.Schema({
username: String,
password_hash: String,
name: String,
github_username: String,
image: String,
});
userSchema.methods.checkPassword = function (password: String) {
return bcrypt.compare(password, this.password_hash);
};
userSchema.methods.generateToken = function () {
const app_secret = process.env.APP_SECRET as string;
return jwt.sign({ id: this.id }, app_secret);
};
userSchema.statics.findAll = function () {
return this.find({});
};
export interface iUser {
username: string;
password_hash: string;
name: string;
github_username: string;
image: string;
}
export interface iUserBaseDocument extends iUser, Document {
checkPassword(password: string): Promise<boolean>;
generateToken(): string;
}
export interface iUSerModel extends Model<iUserBaseDocument> {
findAll(): Promise<Array<iUserBaseDocument>>;
}
export default mongoose.model<iUserBaseDocument, iUSerModel>(
"User",
userSchema
);
|
7e8d7c0ee85c9afef1ae8acd91af60eeb9ac8132
|
TypeScript
|
kkjasoncheung/shopify-challenge
|
/src/app/search/search.component.ts
| 2.65625
| 3
|
import { Component, OnInit, Output } from '@angular/core';
import { GithubService } from '../services/github.service';
import { Repo } from '../services/Repo';
import { FormControl, Validators } from '@angular/forms';
import { FavouritesService } from '../favourites.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
public repos: Repo[] = [];
public keyword = new FormControl('', [Validators.required]);
constructor(private githubService: GithubService, private favouritesService: FavouritesService) {
}
ngOnInit() {
// Listen to key changes and reset list if input cleared
this.keyword.valueChanges.subscribe((userInput: string) => {
if (userInput.length === 0) {
this.repos = [];
}
});
}
/** Method to call GitHub service to fetch repos with keyword as query */
public search(): void {
this.githubService.getRepos(this.keyword.value).subscribe((result) => {
this.repos = [];
var newRepo: Repo;
// Get repo info
for (let i = 0; i < 10; i++) {
if (result.items[i] == undefined) {
break;
}
newRepo = {
name: result.items[i].full_name,
language: result.items[i].language,
tag: '-',
tags_url: result.items[i].tags_url,
link: result.items[i].html_url,
favourited: false
}
// Check if repo is favourited
for (let favourite of this.favouritesService.getFavourites()) {
if (favourite.name === newRepo.name) {
newRepo.favourited = true;
}
}
this.repos.push(newRepo);
}
this.getLatestTags();
});
}
/** Get the latest tags for repos */
public getLatestTags(): void {
// Get tags for each repo
for (let repo of this.repos) {
this.githubService.getLatestTag(repo.tags_url).then((tags) => {
if (tags.length > 0) {
repo.tag = tags[0].name;
}
});
}
}
/** Given a repo, adds it to a favourites list */
public addFavourite(repo: Repo): void {
repo.favourited = true;
this.favouritesService.add(repo);
}
}
|
ef424658b7da4693da78e490c9b953cee7f02c50
|
TypeScript
|
joseanavarro/Angular4_test
|
/src/app/services/gnomes/gnomes.service.ts
| 2.640625
| 3
|
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/timeout';
import { Observable } from 'rxjs/Observable';
import { HabItem } from '../../models/HabItem';
import { AppConstant } from '../app-constant/app-constant.service';
@Injectable()
export class GnomesService {
Gnomes: HabItem[];
constructor(
private http: Http,
private CN: AppConstant
) {
// Load data
this.getGnomeData();
}
// PRIVATE METHODS
/**
* Retrieve data from server
*
* @private
* @returns {Observable<any>}
* @memberof GnomesService
*/
private downloadData(): Observable<any> {
const listUrl: string = this.CN.DAT_URL;
return this.http.get(listUrl)
.map(response => response.json().Brastlewark);
}
// PUBLIC METHODS
/**
* Load gnome data into Gnomes
*
* @private
* @memberof GnomesService
*/
public getGnomeData(): Promise<any> {
const ctx = this;
return new Promise((resolve, reject) => {
this.downloadData().subscribe((res) => {
ctx.Gnomes = res;
console.log('Received:' + ctx.Gnomes[0].name);
resolve();
}, (err) => {
console.error('Error: ' + err);
reject();
});
});
}
/**
* Return all gnomes
*
* @returns {HabItem[]}
* @memberof GnomesService
*/
public getAllGnomes(): HabItem[] {
return this.Gnomes;
}
/**
* Return a gnome defoined by index
*
* @param {*} i
* @returns {HabItem}
* @memberof GnomesService
*/
public getGnome(i: any): HabItem {
return this.Gnomes[i];
}
}
|
897fd26ea596e1228a76ffe3e9d8017fffb9910b
|
TypeScript
|
mikedevelops/adventure-factory
|
/src/Manager/LoadGameStateManager.ts
| 2.734375
| 3
|
import { GameState } from "../State/Game/GameState";
import { GameStateSerialiser } from "../Service/GameStateSerialiser";
import { SceneHydrator } from "../Hydrators/SceneHydrator";
import { Scene } from "../Entities/Scene";
export class LoadGameStateManager {
public async load(serialisedState: string): Promise<GameState> {
const parsedState: any = GameStateSerialiser.parse(serialisedState);
const scenes: Scene[] = parsedState.scenes.map(SceneHydrator.hydrate);
const gameState = new GameState();
scenes.forEach(gameState.addScene.bind(gameState));
return gameState;
}
}
|
9b632a37734090f9b2879cfd6d0810af98f8a490
|
TypeScript
|
rifanid98/eureka-educate
|
/src/main/repositories/categories.test.ts
| 2.53125
| 3
|
import { expect } from 'chai';
import sinon from 'sinon';
import faker from 'faker';
import CategoriesRepository from './categories';
import { Category } from '../types';
const Models = require('../models/index.js');
describe('CategoriesRepository', () => {
const stubValue: Category = {
id: faker.datatype.number(1),
name: faker.name.findName(),
description: faker.name.findName(),
created_at: faker.date.past().toString(),
updated_at: faker.date.past().toString(),
};
const stubValues: Category[] = [
{
id: faker.datatype.number(1),
name: faker.name.findName(),
description: faker.name.findName(),
created_at: faker.date.past().toString(),
updated_at: faker.date.past().toString(),
},
{
id: faker.datatype.number(1),
name: faker.name.findName(),
description: faker.name.findName(),
created_at: faker.date.past().toString(),
updated_at: faker.date.past().toString(),
},
];
describe('get', () => {
it('should get all categories from the db', async () => {
const stub = sinon.stub(Models.Categories, 'findAll').returns(stubValues);
const categories = await CategoriesRepository.get({});
expect(stub.calledOnce).to.be.true;
categories.forEach((category: Category, index: number) => {
expect(category.id).to.equal(stubValues[index].id);
expect(category.name).to.equal(stubValues[index].name);
expect(category.description).to.equal(stubValues[index].description);
expect(category.created_at).to.equal(stubValues[index].created_at);
expect(category.updated_at).to.equal(stubValues[index].updated_at);
});
});
});
describe('getOne', () => {
it('should get all categories from the db', async () => {
const stub = sinon.stub(Models.Categories, 'findOne').returns(stubValue);
const category = await CategoriesRepository.getOne({
id: stubValue.id,
});
expect(stub.calledOnce).to.be.true;
expect(category.id).to.equal(stubValue.id);
expect(category.name).to.equal(stubValue.name);
expect(category.description).to.equal(stubValue.description);
expect(category.created_at).to.equal(stubValue.created_at);
expect(category.updated_at).to.equal(stubValue.updated_at);
});
});
describe('save', () => {
it('should add new category to the db', async () => {
const stub = sinon.stub(Models.Categories, 'create').returns(stubValue);
const category = await CategoriesRepository.save(stubValue);
expect(stub.calledOnce).to.be.true;
expect(category.id).to.equal(stubValue.id);
expect(category.name).to.equal(stubValue.name);
expect(category.description).to.equal(stubValue.description);
expect(category.created_at).to.equal(stubValue.created_at);
expect(category.updated_at).to.equal(stubValue.updated_at);
});
});
describe('update', () => {
it('should update one category from the db', async () => {
const stub = sinon.stub(Models.Categories, 'update').returns([1]);
const category = await CategoriesRepository.update(stubValue, {
id: stubValue.id,
});
expect(stub.calledOnce).to.be.true;
expect(category).to.be.true;
});
});
describe('delete', () => {
it('should delete one category from the db', async () => {
const stub = sinon.stub(Models.Categories, 'destroy').returns([1]);
const category = await CategoriesRepository.delete(stubValue);
expect(stub.calledOnce).to.be.true;
expect(category).to.be.true;
});
});
});
|
3af3d6758ceffd62080bd311eb66f7dcc902ee61
|
TypeScript
|
tinotjgithub/Generate
|
/src/utility/sorting/comparers/standardisationsetup/stdorginalsessioncomparer.ts
| 2.859375
| 3
|
import comparerInterface = require('../../sortbase/comparerinterface');
import comparerhelper = require('../../comparerhelper');
/**
* This is a Centre number comparer class and method
*/
class StdOrginalSessionComparer implements comparerInterface {
/**
* Comparer to sort standardisation sestup script id in descending order
* @param a StandardisationResponseDetails
* @param b StandardisationResponseDetails
*/
public compare(a: StandardisationResponseDetails, b: StandardisationResponseDetails) {
let value: number;
value = comparerhelper.stringSort(a.originalSession, b.originalSession);
if (value === 0) {
return comparerhelper.integerSort(a.candidateScriptId, b.candidateScriptId);
}
return value;
}
}
export = StdOrginalSessionComparer;
|
cdaf3d2b0736a868d70cee57c292fcce0ddd0c93
|
TypeScript
|
UCSDTESC/Check-in
|
/src/client/reducers/UserEvents.ts
| 2.515625
| 3
|
import { handleActions } from 'redux-actions';
import { ActionType } from 'typesafe-actions';
import { replaceUserEvents, addUserEvent } from '~/actions';
import * as Types from '~/actions/types';
import { UserEventsState } from './types';
const initialState: UserEventsState = {};
export default handleActions({
[Types.REPLACE_USER_EVENTS]: (state, action: ActionType<typeof replaceUserEvents>) =>
action.payload
.reduce((result: UserEventsState, current) => {
result[current.alias] = current;
return result;
}, {}),
[Types.ADD_USER_EVENT]: (state, action: ActionType<typeof addUserEvent>) => ({
...state,
[action.payload.alias]: action.payload,
} as UserEventsState),
[Types.DELETE_USER_EVENTS]: () => ({
}),
}, initialState);
|
3256858a615e8278efdd7403554394c57cb286b3
|
TypeScript
|
chriswburton/huggg-api
|
/src/app.controller.e2e.spec.ts
| 2.59375
| 3
|
import request from 'supertest';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { AppModule } from './app.module';
import brands from './brands.json';
import { StoreInterface } from './interfaces/store.interface';
describe('AppModule', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleRef.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
});
describe('GET brand/:brandId', () => {
const brandStub = brands.data[0];
it(`should throw an exception if an invalid Brand ID is provided`, () => {
return request(app.getHttpServer()).get(`/brand/INVALID_ID`).expect(404);
});
it(`should return the Brand with the corresponding ID`, () => {
return request(app.getHttpServer())
.get(`/brand/${brandStub.id}`)
.expect(200)
.then((res) => {
// ensure that all our desired properties exist
expect(brandStub).toStrictEqual(expect.objectContaining(res.body));
});
});
});
describe('GET brand/:brandId/products', () => {
const brandStub = brands.data[0];
it(`should throw an exception if an invalid Brand ID is provided`, () => {
return request(app.getHttpServer())
.get(`/brand/INVALID_ID/products`)
.expect(404);
});
it(`should return an array of Products for the corresponding Brand ID`, () => {
return request(app.getHttpServer())
.get(`/brand/${brandStub.id}/products`)
.expect(200)
.then((res) => {
expect(res.body.map(({ id }) => id)).toEqual(brandStub.products);
});
});
});
describe('GET brand/:brandId/stores', () => {
const brandStub = brands.data[0];
it(`should throw an exception if an invalid Brand ID is provided`, () => {
return request(app.getHttpServer())
.get(`/brand/INVALID_ID/stores`)
.expect(404);
});
it(`should return an array of Stores for the corresponding Brand ID`, () => {
return request(app.getHttpServer())
.get(`/brand/${brandStub.id}/stores`)
.expect(200)
.then((res) => {
expect(res.body.map(({ id }) => id)).toEqual(brandStub.stores);
});
});
});
describe('GET product/:productId/stores', () => {
const productStub = brands.embedded.products[0];
const productStores = brands.embedded.stores.filter(
({ brand_id }: StoreInterface) => productStub.brand_id === brand_id,
);
it(`should throw an exception if an invalid Product ID is provided`, () => {
return request(app.getHttpServer())
.get(`/product/INVALID_ID/stores`)
.expect(404);
});
it(`should return the Stores that correspond to Product ID provided`, () => {
return request(app.getHttpServer())
.get(`/product/${productStub.id}/stores`)
.expect(200)
.then((res) => {
// ensure all IDs match, thereby confirming we have the right data
// TODO: improve test logic
expect(productStores.map(({ id }) => id)).toEqual(
res.body.map(({ id }) => id),
);
});
});
});
});
|
ebdbf256de209785f6df5a273864a2291d644bb1
|
TypeScript
|
mkissarli/book-keeping
|
/src/app.ts
| 2.71875
| 3
|
import express from 'express';
import bodyParser from 'body-parser';
import db from 'mongoose';
import { add_appointment, get_filtered_appointments } from './api/counsellors/controller';
import { counsellor_model } from './api/counsellors/model';
// Create a new express application instance
const app: express.Application = express()
//app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
// Should be in .env
db.connect('mongodb://localhost/spill');
db.Promise = global.Promise;
app.get('/sanity_check', function (req, res) {
res.send('Hello World!');
});
// DO NOT RUN THIS MORE THAN ONCE!
app.post('/populate', async function (req, res) {
var data = require("../data.json");
await data.forEach((counsellor: any) => {
(new counsellor_model(counsellor)).save();
});
res.send({
status: 201,
message: "We've populated the data."
});
});
// Get appointements. If a parameter is left empty assume all is fine.
// @params
// start_date : date
// end_date : date
// appointment_types: [String]
// apointment_mediums: [String]
app.get('/appointments/', async function (req, res) {
// Check if defined.
if (req.body.start_date == undefined ||
req.body.end_date == undefined ||
req.body.appointment_types == undefined ||
req.body.appointment_mediums == undefined) {
res.send({
status: 400,
message: "Fail, ensure that all the parameters are included."
})
}
// Check is a datetime string.
if (!Date.parse(req.body.start_date) || !Date.parse(req.body.end_date)) {
res.send({
status: 400,
message: "Dates in incompatible format, insure that they are compatible dates."
})
}
// Check if arrays
if (!Array.isArray(req.body.appointment_mediums) || !Array.isArray(req.body.appointment_types)) {
res.send({
status: 400,
message: "appointment_mediums or appointment_types are not arrays, please ensure they are arrays."
})
}
// Run
var val: any = await get_filtered_appointments(new Date(req.body.start_date), new Date(req.body.end_date), req.body.appointment_types, req.body.appointment_mediums)
.then(async (result: any) => {
return {
status: 200,
message: "Got filtered appointments list",
result: result
};
})
.catch((err) => {
return {
status: 500,
message: "fail?",
error: err
}
})
res.send(val);
});
function postMiddleware(req, res, next) {
// checks
next()
}
app.post('/counsellors/:id/appointments/add', async function (req, res) {
// Check payload exists.
if (req.body == undefined && req.body.datetimes == undefined) {
res.send({
staus: 400,
message: "No datetimes provided to add."
});
}
// Check payload is array
else if (!Array.isArray(req.body.datetimes)) {
res.send({
status: 400,
message: "datetimes must be an array"
});
}
// Check it isn't empty
else if (req.body.datetimes.length == 0) {
res.send({
status: 200,
message: "Empty list of dates. No appointments added."
})
}
// Check if all the values in the array can be turned into a datetime using Date. This isn't perfect as Date is weird but good enough for this.
req.body.datetimes.forEach((x: any) => {
if (!Date.parse(x)) {
res.send({
status: 400,
message: "datetimes includes a incompatible datetime string: " + x
})
}
else if (Date.parse(x) < Date.now()) {
res.send({
status: 400,
message: "datetimes includes a datetime that is in the past: " + x
})
}
})
// Adds the appointments.
var val: any = await counsellor_model.findById(req.params.id)
.then(() => {
req.body.datetimes.forEach(async (x: any) => {
add_appointment(req.params.id, new Date(x))
.catch((err) => {
return {
status: 500,
message: "fail?",
error: err
}
});
});
return {
status: 201,
message: "Appointments added."
}
})
.catch((err: any) => {
return {
status: 404,
message: "No counsellor by the id: " + req.params.id,
error: err
}
});
res.send(val);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
|
40a82d9b579511b273cc053f340fb4b8cfa8ff9f
|
TypeScript
|
vovanmozg/few-hundred
|
/src/store/appState/setTopicsSettings.ts
| 2.765625
| 3
|
import type { TAppState, TTopic } from 'app/types/TAppState';
export function setTopicsSettings(
set: (partial: (state: TAppState) => Partial<TAppState>) => void,
) {
return (isEnabled: boolean, topic: TTopic): void =>
set((state: TAppState) => {
const settings = {
...state.settings,
topics: {
...state.settings.topics,
[topic]: { isEnabled },
},
};
return {
settings,
};
});
}
|
6c0f497985926476d17f2f1ece582b5a589b7782
|
TypeScript
|
lanemt/definitelytyped.github.io
|
/types/labeled-stream-splicer/labeled-stream-splicer-tests.ts
| 2.53125
| 3
|
import splicer = require("labeled-stream-splicer");
import * as stream from "stream";
const readable = new stream.Readable();
const duplex = new stream.Duplex();
const writable = new stream.Writable();
let pipeline: splicer = splicer();
pipeline = splicer([readable, duplex, writable]);
pipeline = splicer(["r", readable, "d", duplex, "w", writable], { encoding: "utf8" });
pipeline = splicer.obj();
pipeline = splicer.obj([readable, duplex, writable]);
pipeline = splicer(["r", readable, "d", duplex, "w", writable], { encoding: "utf8" });
let length: number = pipeline.length;
length = pipeline.push(duplex, writable);
length = pipeline.unshift(readable, duplex);
let streams = pipeline.splice(0, 1);
streams = pipeline.splice("w", 1);
streams = pipeline.splice(1, 0, duplex, duplex);
streams = pipeline.splice("w", 0, duplex, duplex);
let streamOrEmpty = pipeline.get(1);
streamOrEmpty = pipeline.get("w");
streamOrEmpty = pipeline.pop();
streamOrEmpty = pipeline.shift();
let index: number = pipeline.indexOf(readable);
index = pipeline.indexOf("r");
|
769920350923744097fdd20f9cf641440e2a7b74
|
TypeScript
|
petedarling/test-for-vscode
|
/angular5-play/Agtestapp/src/app/mytest.component.ts
| 2.515625
| 3
|
import { Component, Input } from '@angular/core'
@Component({
selector: 'mytest',
templateUrl: 'mytest.component.html',
styles: [`
.glyphicon-thumbs-down {
color: red;
}
.glyphicon-star {
color: orange;
}
`]
})
export class MyTestComponent{
@Input() myValue = 'What do you think?';
@Input() myOtherValue = 'Boo 2';
onClick(value){
this.myValue = value;
}
}
|
4c764380f826a91be6687ef377385ee69ede6c18
|
TypeScript
|
reg-viz/storycap
|
/packages/storycap/src/client/with-screenshot.ts
| 2.65625
| 3
|
import { StoryKind, makeDecorator } from '@storybook/addons';
import { ScreenshotOptions } from '../shared/types';
import { triggerScreenshot } from './trigger-screenshot';
export interface WithScreenshot {
/**
*
* @deprecated
* You can use `addParameters` instead of call decorator as a function with Storybook v5 or later.
*
*/
<T = Function>(options?: Partial<ScreenshotOptions>): T;
}
// NOTE:
// `makeDecorator` is only available with @storybook/addons@^5.0.0 .
const withScreenshotDecorator =
makeDecorator &&
makeDecorator({
name: 'withScreenshot',
parameterName: 'screenshot',
skipIfNoParametersOrOptions: false,
allowDeprecatedUsage: true,
wrapper: (getStory, context, { parameters, options }) => {
if (typeof process !== 'undefined' && process?.env.JEST_WORKER_ID !== undefined) {
return getStory(context);
}
const screenshotOptions = parameters || options;
triggerScreenshot(screenshotOptions, context);
return getStory(context);
},
});
function withScreenshotLegacy(screenshotOptions: ScreenshotOptions = {}) {
return (storyFn: Function, ctx: StoryKind | undefined) => {
const wrapperWithContext = (context: any) => {
triggerScreenshot(screenshotOptions, context);
return storyFn(context);
};
if (ctx) {
return wrapperWithContext(ctx);
}
return (context: StoryKind) => wrapperWithContext(context);
};
}
const withScreenshot: WithScreenshot = (withScreenshotDecorator || withScreenshotLegacy) as any;
export { withScreenshot };
|
80488d4306974c7b7a34606a19102a27991c5a5f
|
TypeScript
|
klapouchy/frontend-developer-test
|
/source/utilities/FeeldAPI.ts
| 3.125
| 3
|
import axios, { AxiosError, AxiosRequestConfig, Method } from "axios";
import MockAdapter from "axios-mock-adapter";
import users from "./demoUsers";
import { UserDecision } from "./Types";
// Feeld Developer Test API url to get 20 random users
const USERS_URL = "https://fld-devtest-api.herokuapp.com/api/v1/users";
// This URL doesn't exist, I just list it here for the sake of example
const DECISION_URL = "https://fld-devtest-api.herokuapp.com/api/v1/decision";
const SESSION_TOKEN =
"3TtY+AVtEJMaOPWGyEulVEgVBWZ8gqM75gag6wCcA3rJCYWMkX/ZmAOJxrZ4bPyBLJBch7VyMYD8ZCWoNPCUnJbT5M2iRWjJteGrfNhFzd+0oDbWQwiNAIdG0W9rHw7sKAAWk5uEzjs+lPykJnmy56LRwSFpoyxHC7p9G3KTQoQ=";
function getAxiosConfig(method: Method, url: string, data?: any): AxiosRequestConfig {
return {
method,
url,
data,
timeout: 15 * 1000, // time in milliseconds
headers: {
"session-token": SESSION_TOKEN,
},
};
}
/**
* Gets 20 random users (out of 100) from the Feeld developer test API.
*
* Note that the users returned are not unique. That means a response can contain the same user
* object multiple times. I have for example seen a request that included the same user 3 times.
*
* After a bit of testing here are few responses that I've seen. Of note is that the the status
* attribute is "status" on successful requests but "statusCode" on unsuccessful one.
*
* Response with a successful response:
*
* {
* "status": 200
* "data": [...] // List of user objects
* }
*
* Unauthorized response:
*
* {
* "statusCode": 401,
* "error": "Unauthorized",
* "message": "You cannot access this resource"
* }
*
* Resource not found response:
*
* {
* "statusCode": 404,
* "error": "Not Found",
* "message": "Not Found"
* }
*
* Potential improvements:
* + Improve the return types for the promise fulfilment. Currently Any, but it would be better
* if it were User[] or something along those lines.
*
*/
export function get20Users() {
const axiosConfig: AxiosRequestConfig = getAxiosConfig("get", USERS_URL);
return axios(axiosConfig)
.then(response => response.data.data)
.catch(error => console.log(error));
// When debugging, append local mock users first
// return axios(axiosConfig)
// .then(response => {
// return [users[1], users[2], users[3], ...response.data.data];
// })
// .catch(error => console.log(error));
}
export function getLocalUsers() {
const mock = new MockAdapter(axios);
mock.onGet(USERS_URL).reply(200, {
status: 200,
data: users,
});
return get20Users();
}
/**
* An example of a function that would submit to the Feeld API once a user has taken a
* reject/skip/approve decision on another user. This is non-functional because the endpoint
* doesn't exist.
*/
export function postUserDecision(userDecision: UserDecision) {
const axiosConfig: AxiosRequestConfig = getAxiosConfig("post", DECISION_URL, userDecision);
// Since there isn't an endpoint to submit user decisions we just fire and forget here.
//return axios(axiosConfig);
}
|
b076011c4a575921e7103349ebc17c85232c9d60
|
TypeScript
|
galmail/va-experiment
|
/src/nlp/weatherEngine.ts
| 3.109375
| 3
|
import * as ip from "what-is-my-ip-address";
import { queryByLocation, queryByGeoLocation } from "../apis/weather";
import { getLocationByIP } from "../apis/ip2location";
import { knownPlaces } from "../consts";
export const getWeatherData = async (words: string[]) => {
let city = await findLocation(words);
const geoLocation = await findCurrentGeoLocation();
let weather;
if (city) {
weather = await queryByLocation(city);
} else if (geoLocation) {
weather = await queryByGeoLocation(geoLocation);
city = "your location";
} else {
return `I can only find the weather for ${knownPlaces.join(", ")}`;
}
if (!weather) return `I couldn't find the weather report for ${city}`;
return `
The current weather in ${city} is ${weather.state}
with min temp of ${weather.minTemp} degrees and max temp of ${weather.maxTemp} degrees
`;
};
async function findLocation(words) {
const composedWords = handleComposedPlaces(words);
for (const place of knownPlaces) {
if (composedWords.includes(place.toLowerCase())) {
return Promise.resolve(place);
}
}
return null;
}
async function findCurrentGeoLocation() {
const ipv4 = await ip.v4();
const getLocation = await getLocationByIP(ipv4);
return getLocation;
}
// for example: New York is a composed word, so we want to join them together
// at the moment, we handle only 2 composed words
function handleComposedPlaces(words: string[]) {
const composedWords = [];
for (let i = 0; i < words.length; i++) {
const word = words[i];
const placeIdx = knownPlaces.findIndex((place) =>
place.toLowerCase().includes(word)
);
if (placeIdx < 0) {
composedWords.push(word);
continue;
}
const nextWord = words[i + 1];
const currentPlace = knownPlaces[placeIdx];
if (
!nextWord ||
!currentPlace.toLowerCase().includes(nextWord.toLowerCase())
) {
composedWords.push(word);
continue;
}
// the place is composed
composedWords.push(currentPlace.toLowerCase());
i++; // skip the next word
}
return composedWords;
}
|
d3fbf233e214ccc09bb119d027b3a73602d7f5e9
|
TypeScript
|
eternal7s/typescript-study
|
/chapter6/src/IterableUsingGenerator-test.ts
| 2.59375
| 3
|
import {IterableUsingGenerator} from "./IterableUsingGenerator";
for(let item of new IterableUsingGenerator([1, 2, 3]))
console.log(item);
for(let item of new IterableUsingGenerator(['hello', 'world', '!']))
console.log(item);
|
21f917d909a30213fe2d6c22dadb2517f4c221e6
|
TypeScript
|
hinstw/h-rebasor
|
/src/string.ts
| 2.640625
| 3
|
export function replaceText(text: string, oldSubString: string, newSubText: string): string {
return text.split(oldSubString).join(newSubText);
}
|
29d4130fee63759bd778918aab36186c50f63771
|
TypeScript
|
micomoko/sample
|
/src/app/core/models/domain/location.domain.ts
| 2.734375
| 3
|
import { Injectable } from '@angular/core';
@Injectable()
export class LocationDomain {
private static readonly location = [
{
locationID: 1,
locationName: 'Makati City'
},
{
locationID: 2,
locationName: 'Quezon City'
},
{
locationID: 3,
locationName: 'Pasig City'
},
{
locationID: 4,
locationName: 'Tagaytay'
},
{
locationID: 5,
locationName: 'Laguna'
},
{
locationID: 6,
locationName: 'Cavite'
},
{
locationID: 7,
locationName: 'Cebu'
}
];
/*
* Get Location List.
*/
getLocations(){
return LocationDomain.location;
}
/*
* Get Location Name by ID.
*/
getLocationID(locationID: number){
return LocationDomain.location.filter(loc => loc.locationID === locationID);
}
}
|
f2c213703635e2b9fd7b4824a075be7313a0a4e6
|
TypeScript
|
uiftikhar/ngx-lightning
|
/projects/ngx-lightning/src/lib/tabs/tabs.ts
| 2.578125
| 3
|
import { AfterContentInit, Component, ContentChildren, EventEmitter, Input, Output, QueryList } from '@angular/core';
import { isInt, toBoolean } from '../util/util';
import { NglTabDirective } from './tab';
@Component({
selector : 'ngl-tabs',
templateUrl: './tabs.html'
})
export class NglTabsComponent implements AfterContentInit {
@Input() type: 'default' | 'scoped' = 'default';
@ContentChildren(NglTabDirective) tabs: QueryList<NglTabDirective>;
activeTab: NglTabDirective;
selected: string | number | NglTabDirective;
@Input('selected') set setSelected(selected: string | number | NglTabDirective) {
if (selected === this.selected) {
return;
}
this.selected = selected;
if (!this.tabs) {
return;
} // Wait for content to initialize
this.activate();
}
@Output() selectedChange = new EventEmitter<NglTabDirective>();
@Input() set titleCaps(titleCaps: any) {
this._titleCaps = toBoolean(titleCaps);
}
get titleCaps() {
return this._titleCaps;
}
private _titleCaps = true;
ngAfterContentInit() {
// Initial selection after all tabs are created
this.activate();
if (!this.activeTab) {
setTimeout(() => this.select(this.tabs.first));
}
}
select(tab: NglTabDirective) {
this.selectedChange.emit(tab);
}
move(evt: Event, moves: number) {
evt.preventDefault();
const tabs = this.tabs.toArray();
const selectedIndex = tabs.indexOf(this.activeTab);
this.select(tabs[(tabs.length + selectedIndex + moves) % tabs.length]);
}
private activate() {
if (this.activeTab) {
this.activeTab.active = false;
}
this.activeTab = this.findTab();
if (this.activeTab) {
this.activeTab.active = true;
}
}
private findTab(value: any = this.selected): NglTabDirective {
if (value instanceof NglTabDirective) {
return value;
}
if (isInt(value)) {
return this.tabs.toArray()[+value];
}
return this.tabs.toArray().find((t: NglTabDirective) => {
return t.nglTabId && t.nglTabId === value;
});
}
}
|
98d479c542ac70407bf7d4eb2156007fca172d07
|
TypeScript
|
Andrey-Matos/track-correios
|
/src/utils/address.ts
| 2.53125
| 3
|
import type { Unidade } from './';
export function getAddress(unidade: Unidade) {
if (!unidade) return '';
const {
nome,
tipo,
endereco: { cidade, uf },
} = unidade;
return [tipo, nome, cidade, uf].filter(x => x).join(" - ");
}
|
fc55da16e1551fdb1088f856682a409f4b0cbdf6
|
TypeScript
|
rashedm/lfs_contracts
|
/src/contracts/requests/PutUser.request.ts
| 2.671875
| 3
|
import * as yup from 'yup';
export class PutUserRequest {
id:string;
name:string;
roles:PutUserRequestRole[];
}
export class PutUserRequestRole {
id:string;
}
export const PutUserRequestSchema = yup.object<PutUserRequest>({
id: yup.string().required(),
name: yup.string().required(),
roles: yup.array().of(yup.object<PutUserRequestRole>({
id: yup.string().required()
}).required()).required()
});
|
52d967932fdc4e8bc2e03ce9ad9c763b38b778da
|
TypeScript
|
jaked/programmable-matter
|
/src/util/Signal/Signal.test.ts
| 2.8125
| 3
|
import * as Immutable from 'immutable';
import * as Immer from 'immer';
import Signal from './index';
import Try from '../Try';
import { bug } from '../bug';
const err = new Error('fail');
describe('constant', () => {
describe('ok', () => {
const s = Signal.ok(7);
it('is ok', () => {
expect(s.get()).toBe(7);
});
it('maps', () => {
const s2 = s.map(x => x + 1);
expect(s2.get()).toBe(8);
});
it('flatMaps', () => {
const s2 = s.flatMap(x => Signal.ok(x + 1));
expect(s2.get()).toBe(8);
});
});
describe('err', () => {
const s = Signal.err(err);
it('is err', () => {
expect(() => s.get()).toThrow(err);
});
it('maps', () => {
const s2 = s.map(x => x + 1);
expect(() => s2.get()).toThrow(err);
});
it('flatMaps', () => {
const s2 = s.flatMap(x => Signal.ok(x + 1));
expect(() => s2.get()).toThrow(err);
});
});
});
describe('cell', () => {
it('is ok', () => {
const s = Signal.cellOk(7);
expect(s.get()).toBe(7);
});
it('maps', () => {
const s = Signal.cellOk(7);
const s2 = s.map(x => x + 1);
expect(s2.get()).toBe(8);
});
it('flatMaps', () => {
const s = Signal.cellOk(7);
const s2 = s.flatMap(x => Signal.ok(x + 1));
expect(s2.get()).toBe(8);
});
it('setOk', () => {
const s = Signal.cellOk(7);
s.setOk(8);
expect(s.get()).toBe(8);
});
it('setErr', () => {
const s = Signal.cellOk(7);
s.setErr(err);
expect(() => s.get()).toThrow(err);
});
it('unchanged value', () => {
const s = Signal.cellOk(7);
expect(s.version).toBe(1);
s.setOk(7);
expect(s.get()).toBe(7);
expect(s.version).toBe(1);
});
it('changed value', () => {
const s = Signal.cellOk(7);
expect(s.version).toBe(1);
s.setOk(9);
expect(s.get()).toBe(9);
expect(s.version).toBe(2);
});
});
describe('map', () => {
it('propagates changes', () => {
let calls = 0;
const c = Signal.cellOk(7);
const m = c.map(x => { calls++; return x + 1; })
expect(m.get()).toBe(8);
expect(calls).toBe(1);
c.setOk(7);
expect(m.get()).toBe(8);
expect(calls).toBe(1);
c.setOk(9);
expect(m.get()).toBe(10);
expect(calls).toBe(2);
});
it('propagates dirty bit', () => {
const c = Signal.cellOk(7);
const m = c.map(x => x + 1);
const n = m.map(x => x + 1);
n.reconcile();
expect(m.isDirty).toBe(false);
expect(n.isDirty).toBe(false);
c.setOk(9);
expect(m.isDirty).toBe(true);
expect(n.isDirty).toBe(true);
});
it('does not bump version on equal value', () => {
let calls = 0;
const c = Signal.cellOk(7);
const m = c.map(x => { calls++; return x % 2; })
expect(m.get()).toBe(1);
expect(calls).toBe(1);
expect(m.version).toBe(1);
c.setOk(9);
expect(m.get()).toBe(1);
expect(calls).toBe(2);
expect(m.version).toBe(1);
});
it('handles errors in function', () => {
const c = Signal.cellOk(7);
const m = c.map(x => { throw 'fail' });
expect(() => m.reconcile()).not.toThrow();
expect(() => m.get()).toThrow();
});
});
describe('flatMap', () => {
it('propagates outer changes', () => {
let calls = 0;
const c = Signal.cellOk(7);
const m = c.flatMap(x => { calls++; return Signal.ok(x + 1); })
expect(m.get()).toBe(8);
expect(calls).toBe(1);
c.setOk(7);
expect(m.get()).toBe(8);
expect(calls).toBe(1);
c.setOk(9);
expect(m.get()).toBe(10);
expect(calls).toBe(2);
});
it('propagates inner changes', () => {
let calls = 0;
const c1 = Signal.cellOk(7);
const c2 = Signal.cellOk(9);
const m = c1.flatMap(x => c2.map(y => { calls++; return x + y }))
expect(m.get()).toBe(16);
expect(calls).toBe(1);
c2.setOk(11);
expect(m.get()).toBe(18);
expect(calls).toBe(2);
});
it('does not bump version on outer equal value', () => {
let calls = 0;
const c = Signal.cellOk(7);
const m = c.flatMap(x => { calls++; return Signal.ok(x % 2); })
expect(m.get()).toBe(1);
expect(calls).toBe(1);
expect(m.version).toBe(1);
c.setOk(9);
expect(m.get()).toBe(1);
expect(calls).toBe(2);
expect(m.version).toBe(1);
});
it('does not bump version on inner equal value', () => {
let outerCalls = 0;
let innerCalls = 0;
const c = Signal.cellOk(7);
const m = Signal.ok(11).flatMap(x => {
outerCalls++;
return c.map(y => {
innerCalls++;
return y % 2
});
})
expect(m.get()).toBe(1);
expect(outerCalls).toBe(1);
expect(innerCalls).toBe(1);
expect(m.version).toBe(1);
c.setOk(9);
expect(m.get()).toBe(1);
expect(outerCalls).toBe(1);
expect(innerCalls).toBe(2);
expect(m.version).toBe(1);
});
it('handles errors in function', () => {
const c = Signal.cellOk(7);
const m = c.flatMap(x => { throw 'fail' });
expect(() => m.reconcile()).not.toThrow();
expect(() => m.get()).toThrow();
});
});
describe('liftToTry', () => {
it('lifts ok', () => {
const c = Signal.ok(7);
const s = c.liftToTry();
expect(s.get()).toEqual(Try.ok(7));
});
it('lifts err', () => {
const err = new Error('error!');
const c = Signal.err(err);
const s = c.liftToTry();
expect(s.get()).toEqual(Try.err(err));
});
});
describe('join', () => {
it('joins', () => {
const c1 = Signal.ok(7);
const c2 = Signal.ok(9);
const j = Signal.join(c1, c2);
expect(j.get()).toEqual([7, 9]);
});
it('propagates errors', () => {
const c1 = Signal.ok(7);
const c2 = Signal.ok(9);
const j = Signal.join(Signal.err(err), c2);
expect(() => j.get()).toThrow(err);
const j2 = Signal.join(c1, Signal.err(err));
expect(() => j2.get()).toThrow(err);
});
it('propagates changes', () => {
let calls = 0;
const c1 = Signal.cellOk(7);
const c2 = Signal.cellOk(9);
const j = Signal.join(c1, c2).map(([t1, t2]) => { calls++; return [t1, t2] });
expect(j.get()).toEqual([7, 9]);
expect(calls).toBe(1);
c1.setOk(7);
expect(j.get()).toEqual([7, 9]);
expect(calls).toBe(1);
c2.setOk(9);
expect(j.get()).toEqual([7, 9]);
expect(calls).toBe(1);
c1.setOk(11);
expect(j.get()).toEqual([11, 9]);
expect(calls).toBe(2);
});
});
describe('joinImmutableMap', () => {
it('joins', () => {
const c1 = Signal.ok(7);
const c2 = Signal.ok(9);
const map = Signal.ok(Immutable.Map({ c1, c2 }));
const j = Signal.joinImmutableMap(map);
expect(j.get()).toEqual(Immutable.Map({ c1: 7, c2: 9 }));
});
it('propagates errors', () => {
const c1 = Signal.ok(7);
const c2 = Signal.err(err);
const map = Signal.ok(Immutable.Map({ c1, c2 }));
const j = Signal.joinImmutableMap(map);
expect(() => j.get()).toThrow(err);
});
it('propagates outer changes', () => {
let calls = 0;
const c1 = Signal.ok(7);
const c2 = Signal.ok(9);
const map = Signal.cellOk(Immutable.Map({ c1, c2 }));
const j = Signal.joinImmutableMap(map).map(map => { calls++; return map });
expect(j.get()).toEqual(Immutable.Map({ c1: 7, c2: 9 }));
expect(calls).toBe(1);
const c3 = Signal.ok(11);
map.setOk(Immutable.Map({ c1, c3 }));
expect(j.get()).toEqual(Immutable.Map({ c1: 7, c3: 11 }));
expect(calls).toBe(2);
});
it('propagates inner changes', () => {
let calls = 0;
const c1 = Signal.cellOk(7);
const c2 = Signal.cellOk(9);
const map = Signal.ok(Immutable.Map({ c1, c2 }));
const j = Signal.joinImmutableMap(map).map(map => { calls++; return map });
expect(j.get()).toEqual(Immutable.Map({ c1: 7, c2: 9 }));
expect(calls).toBe(1);
c1.setOk(11);
expect(j.get()).toEqual(Immutable.Map({ c1: 11, c2: 9 }));
expect(calls).toBe(2);
});
it('handles no signals', () => {
const s = Signal.join(...[]);
expect(s.get()).toEqual([]);
});
});
describe('mapImmutableMap', () => {
it('maps', () => {
let calls = 0;
function f(x: number) { calls++; return x + 1; }
const map = Signal.cellOk(Immutable.Map({ a: 7, b: 9 }));
const fmap = Signal.mapImmutableMap(map, f);
expect(fmap.get()).toEqual(Immutable.Map({ a: 8, b: 10 }));
expect(calls).toBe(2);
map.setOk(map.get().set('b', 10));
expect(fmap.get()).toEqual(Immutable.Map({ a: 8, b: 11 }));
expect(calls).toBe(3);
map.setOk(map.get().set('c', 13));
expect(fmap.get()).toEqual(Immutable.Map({ a: 8, b: 11, c: 14 }));
expect(calls).toBe(4);
map.setOk(map.get().delete('a'));
expect(fmap.get()).toEqual(Immutable.Map({ b: 11, c: 14 }));
expect(calls).toBe(4);
});
});
describe('mapMap', () => {
it('maps', () => {
let calls = 0;
function f(x: number) { calls++; return x + 1; }
const map = Signal.cellOk(new Map([['a', 7], ['b', 9]]));
const fmap = Signal.mapMap(map, f);
expect(fmap.get()).toEqual(new Map([['a', 8], ['b', 10]]));
expect(calls).toBe(2);
map.setOk(Immer.produce(map.get(), map => { map.set('b', 10) }));
expect(fmap.get()).toEqual(new Map([['a', 8], ['b', 11]]));
expect(calls).toBe(3);
map.setOk(Immer.produce(map.get(), map => { map.set('c', 13) }));
expect(fmap.get()).toEqual(new Map([['a', 8], ['b', 11], ['c', 14]]));
expect(calls).toBe(4);
map.setOk(Immer.produce(map.get(), map => { map.delete('a') }));
expect(fmap.get()).toEqual(new Map([['b', 11], ['c', 14]]));
expect(calls).toBe(4);
});
});
describe('splitMap', () => {
it('splits', () => {
const map = Signal.cellOk(new Map([['a', 7], ['b', 9]]));
const split = Signal.splitMap(map);
const a = split.get().get('a') ?? bug('expected a');
const b = split.get().get('b') ?? bug('expected b');
expect(a.get()).toEqual(7);
expect(b.get()).toEqual(9);
expect(a.isDirty).toBe(false);
expect(b.isDirty).toBe(false);
});
it('dirties only inner Signal on value change', () => {
const map = Signal.cellOk(new Map([['a', 7], ['b', 9]]));
const split = Signal.splitMap(map);
const a = split.get().get('a') ?? bug('expected a');
const b = split.get().get('b') ?? bug('expected b');
expect(a.get()).toEqual(7);
expect(b.get()).toEqual(9);
map.produce(map => map.set('a', 8));
expect(split.isDirty).toBe(false);
expect(a.isDirty).toBe(true);
expect(b.isDirty).toBe(false);
expect(a.get()).toEqual(8);
// works the second time
map.produce(map => map.set('a', 9));
expect(split.isDirty).toBe(false);
expect(a.isDirty).toBe(true);
expect(b.isDirty).toBe(false);
expect(a.get()).toEqual(9);
});
it('dirties only outer Signal on key change', () => {
const map = Signal.cellOk(new Map([['a', 7], ['b', 9]]));
const split = Signal.splitMap(map);
const a = split.get().get('a') ?? bug('expected a');
const b = split.get().get('b') ?? bug('expected b');
expect(a.get()).toEqual(7);
expect(b.get()).toEqual(9);
map.produce(map => map.set('c', 11));
expect(split.isDirty).toBe(true);
expect(a.isDirty).toBe(false);
expect(b.isDirty).toBe(false);
});
it('value change resets outer dependency', () => {
const map = Signal.cellOk(new Map([['a', 7], ['b', 9]]));
const mapped = map.map(x => x, true);
const split = Signal.splitMap(mapped);
expect([...split.get().keys()]).toEqual(['a', 'b']);
map.produce(map => map.set('a', 11));
expect([...split.get().keys()]).toEqual(['a', 'b']);
map.produce(map => map.set('c', 17));
expect([...split.get().keys()]).toEqual(['a', 'b', 'c']);
});
});
describe('splitMapWritable', () => {
it('splits', () => {
const map = Signal.cellOk(new Map([['a', 7], ['b', 9]]));
const split = Signal.splitMapWritable(map);
const a = split.get().get('a') ?? bug('expected a');
const b = split.get().get('b') ?? bug('expected b');
expect(a.get()).toEqual(7);
expect(b.get()).toEqual(9);
expect(a.isDirty).toBe(false);
expect(b.isDirty).toBe(false);
});
it('dirties only inner Signal on value change', () => {
const map = Signal.cellOk(new Map([['a', 7], ['b', 9]]));
const split = Signal.splitMapWritable(map);
const a = split.get().get('a') ?? bug('expected a');
const b = split.get().get('b') ?? bug('expected b');
expect(a.get()).toEqual(7);
expect(b.get()).toEqual(9);
map.produce(map => map.set('a', 8));
expect(split.isDirty).toBe(false);
expect(a.isDirty).toBe(true);
expect(b.isDirty).toBe(false);
expect(a.get()).toEqual(8);
map.produce(map => map.set('a', 9));
expect(split.isDirty).toBe(false);
expect(a.isDirty).toBe(true);
expect(b.isDirty).toBe(false);
expect(a.get()).toEqual(9);
});
it('dirties only outer Signal on key change', () => {
const map = Signal.cellOk(new Map([['a', 7], ['b', 9]]));
const split = Signal.splitMapWritable(map);
const a = split.get().get('a') ?? bug('expected a');
const b = split.get().get('b') ?? bug('expected b');
expect(a.get()).toEqual(7);
expect(b.get()).toEqual(9);
map.produce(map => map.set('c', 11));
expect(split.isDirty).toBe(true);
expect(a.isDirty).toBe(false);
expect(b.isDirty).toBe(false);
})
it('value change updates underlying map', () => {
const map = Signal.cellOk(new Map([['a', 7], ['b', 9]]));
const split = Signal.splitMapWritable(map);
const a = split.get().get('a') ?? bug('expected a');
const b = split.get().get('b') ?? bug('expected b');
expect(a.get()).toEqual(7);
expect(b.get()).toEqual(9);
a.setOk(8);
expect(split.isDirty).toBe(false);
expect(a.isDirty).toBe(true);
expect(b.isDirty).toBe(false);
expect(map.get().get('a')).toBe(8);
});
it('value change resets outer dependency', () => {
const map = Signal.cellOk(new Map([['a', 7], ['b', 9]]));
const mapped = map.mapInvertible(x => x, x => x, true);
const split = Signal.splitMapWritable(mapped);
expect([...split.get().keys()]).toEqual(['a', 'b']);
map.produce(map => map.set('a', 11));
expect([...split.get().keys()]).toEqual(['a', 'b']);
map.produce(map => map.set('c', 17));
expect([...split.get().keys()]).toEqual(['a', 'b', 'c']);
});
});
describe('ref', () => {
it('throws exception if unset', () => {
const r = Signal.ref();
expect(() => r.get()).toThrow();
});
it('passes through to underlying signal once set', () => {
const r = Signal.ref();
const s = Signal.cellOk('foo');
r.set(s);
expect(r.get()).toBe('foo');
s.setOk('bar');
expect(r.get()).toBe('bar');
expect(r.version).toBe(s.version);
});
it('cannot be set more than once', () => {
const r = Signal.ref();
r.set(Signal.ok('foo'));
expect(() => r.set(Signal.ok('bar'))).toThrow();
});
});
describe('mapInvertible', () => {
it('set pushes down inverse mapping', () => {
const cell = Signal.cellOk(7);
const plus = cell.mapInvertible(x => x + 1, x => x - 1);
const plusplus = plus.map(x => x + 1);
expect(plus.get()).toBe(8);
expect(plusplus.get()).toBe(9);
plus.setOk(9);
expect(cell.get()).toBe(8);
expect(plusplus.get()).toBe(10);
});
it('unchanged value', () => {
const cell = Signal.cellOk(7);
expect(cell.version).toBe(1);
const plus = cell.mapInvertible(x => x + 1, x => x - 1);
expect(plus.get()).toBe(8);
plus.setOk(8);
expect(cell.version).toBe(1);
expect(cell.get()).toBe(7);
});
});
describe('mapProjection', () => {
it('set calls set function on underlying signal', () => {
const cell = Signal.cellOk({ foo: 7, bar: 9 });
const foo = cell.mapProjection(x => x.foo, (x, foo) => x.foo = foo);
const plus = foo.map(x => x + 1);
expect(foo.get()).toBe(7);
expect(plus.get()).toBe(8);
foo.setOk(11);
expect(cell.get().foo).toBe(11);
expect(plus.get()).toBe(12);
});
it('chained projections', () => {
const cell = Signal.cellOk({ foo: { bar: 9, baz: 11 }, quux: 13 });
const foo = cell.mapProjection(x => x.foo, (x, foo) => x.foo = foo);
const bar = foo.mapProjection(x => x.bar, (x, bar) => x.bar = bar);
bar.reconcile();
bar.setOk(17);
expect(cell.get().foo.bar).toBe(17);
});
});
|
fc3306409c791e71354cdd561f9de4b8bebdd85f
|
TypeScript
|
shynome/uapi
|
/src/uapi.ts
| 2.71875
| 3
|
import { ServerRequest, delay } from "./deps.ts";
import { Router } from "./router.ts";
import * as NotFoundModule from "./404.ts";
import { fillHost } from "./utils.ts";
/**api config. now nothing can be config */
export interface Config {
/**api 超时时间, 设为 0 则不限制超时时间 */
timeout?: number;
}
export interface Handler {
(req: ServerRequest): any;
}
export interface APIModule {
default: Handler;
config: Config;
}
export enum ResponseKind {
Normal,
Timeout,
Error,
}
export type Response = {
kind: ResponseKind;
value?: any;
};
export const buildHandler = (router: Router) => {
return async (req: ServerRequest) => {
let host = req.headers.get("host") || fillHost;
let mpath = router.findModule(host, req.url);
let module: APIModule = mpath === ""
? NotFoundModule
: await router.mcache.import(mpath);
if (typeof module.default !== "function") {
module = NotFoundModule as any as APIModule;
}
let timeout = module?.config?.timeout || 10e3;
let response: Response = await Promise.race([
Promise.resolve()
.then(async () => {
return {
kind: ResponseKind.Normal,
value: await module.default(req),
};
})
.catch(async (e) => {
return {
kind: ResponseKind.Error,
value: e,
};
}),
...(timeout > 0
? [delay(timeout).then(() => ({ kind: ResponseKind.Timeout }))]
: []),
]);
if (req.w.buffered() !== 0) {
return response;
}
switch (response.kind) {
case ResponseKind.Timeout:
req.respond({ status: 500, body: "api timeout" });
break;
case ResponseKind.Error:
req.respond({ status: 500, body: "api throw error" });
break;
case ResponseKind.Normal:
let value = response.value;
if (
typeof value === "string" ||
value instanceof Uint8Array ||
typeof value.read === "function"
) {
req.respond({ body: value });
} else if (
typeof value === "object" &&
("body" in value || "status" in value)
) {
req.respond(value);
} else {
req.respond({ status: 500, body: "bad logic way" });
}
break;
}
return response;
};
};
|
1616525cf73eba7ce31afaa3f2538e081f0b1ef9
|
TypeScript
|
romain78160/NestJs
|
/src/todos/todos.service.ts
| 2.984375
| 3
|
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateTodoDto, UpdateTodoDto } from './Dto/todo.dto';
import { Todo } from './interfaces/todo.interface';
@Injectable()
export class TodosService {
todos: Todo[] = [
{
id: 1,
title: 'Titre todo',
description: 'faire ce todo',
done: false,
},
{
id: 2,
title: 'Course',
description: 'Acheter du pain',
done: false,
},
{
id: 3,
title: 'Lettre',
description: 'Poster la lettre',
done: true,
},
{
id: 4,
title: 'Loyer',
description: "Payer loyer du mois d'avril",
done: false,
},
];
findAll(): Todo[] {
return this.todos;
}
findOne(id: number): Todo {
return this.todos.find((todo) => todo.id === id);
}
create(aTodo: Todo) {
aTodo.id = this.todos.length + 1;
this.todos = [...this.todos, aTodo];
}
update(id: number, aTodo: UpdateTodoDto) {
//trouver le todo
let todoToUpdate = this.findOne(id);
if (!todoToUpdate) {
return new NotFoundException('Todo not found');
} else {
todoToUpdate = { ...todoToUpdate, ...aTodo };
}
//parcourir le tableau pour modifier que celui qu'on vient ce modifier
const updatedTodos = this.todos.map((t) =>
t.id !== id ? t : todoToUpdate,
);
//application du nouveau tableau
this.todos = [...updatedTodos];
return { updated: 1, todos: this.todos };
}
delete(id: number) {
const lengthBefore = this.todos.length;
const aTodo = this.findOne(id);
if (aTodo) {
this.todos = [...this.todos.filter((t) => t.id !== +id)];
}
if (this.todos.length < lengthBefore) {
return { deletedTodos: 1, newLength: this.todos.length };
} else {
return new NotFoundException('Delete impossible: todo not found');
}
}
}
|
0911fa597f725613aae7eb20db869cba18f7b67f
|
TypeScript
|
Amazing-Web-Study/B-trello-frontend
|
/src/api/api.ts
| 2.984375
| 3
|
import { useReducer, useEffect } from 'react'
function reducer(state:any, action:any) {
switch (action.type) {
case 'LOADING':
return {
loading: true,
data: [],
error: ''
}
case 'SUCCESS':
return {
loading: false,
data: action.data,
error: ''
}
case 'ERROR':
return {
loading: false,
data: [],
error: '에러 발생'
}
default:
throw new Error(action.type)
}
}
function useFetch(callback:any, deps:any = []) {
const [state, dispatch] = useReducer(reducer, {
loading: false,
data: [],
error: ''
})
const fetchData = async () => {
dispatch({type: 'LOADING'})
try {
const response = await callback()
let data = await response.json()
console.log(data)
dispatch({type: 'SUCCESS', data: data})
} catch (e) {
dispatch({type: 'ERROR', error: '에러 발생'})
}
}
useEffect(() => {
fetchData()
}, deps)
return [state, fetchData]
}
export default useFetch
|
37bdf2750b9ec2201ebe120d6d93e36b1c3d6f42
|
TypeScript
|
atomic-package/scrollspy
|
/src/ts/component/Target.ts
| 2.828125
| 3
|
/**
* ScrollSpy Target View Class
* @public
* @param option
**/
let _created_scroll_spy_target_num: number = 0;
export class Target {
constructor(
public id: number,
public triggerId: number,
public idName: string,
public className: string,
public coordinate: number,
public node: any
) {
this.id = this.createContentsId();
if(this.node && this.coordinate == 0) {
this.coordinate = this.getCoordinate(this.node);
}
}
/**
* Static Function
**/
static fromData(data: any): Target {
return new Target(
0,
data.triggerId ? data.triggerId : null,
data.node && data.node.id ? data.node.id : null,
data.node && data.node.className ? data.node.className : null,
data.coordinate ? data.coordinate : 0,
data.node ? data.node : null
);
}
/**
* Private Function
**/
private createContentsId(): number {
return ++_created_scroll_spy_target_num;
}
private getCoordinate(node) {
var rect = node.getBoundingClientRect();
return rect.top + window.pageYOffset;
}
/**
* Public Function
**/
public getItemNode(node) {
//return this.getChildren(node);
}
public scroll() {
window.scrollTo(0, this.coordinate);
}
}
export default Target;
|
f9353db129483cc7c19018dafae39a046cf0f7c2
|
TypeScript
|
MarkProvanP/racetrack2
|
/src/server/error-handling.ts
| 2.515625
| 3
|
import { Emailer } from './emailer';
export function errorHandling(emailer: Emailer) {
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled rejection!', reason, promise);
emailer.sendUnhandledRejectionEmail(reason, promise)
.catch(err => {
console.error('Oh noes! An error occured while trying to handle an error! This is absolutely awful!')
console.error('New error', err);
});
});
process.on('uncaughtException', (exception) => {
console.error('Uncaught exception!', exception);
emailer.sendUncaughtExceptionEmail(exception)
.catch(err => {
console.error('Oh noes! An error occured while trying to handle an error! This is absolutely awful!')
console.error('New error', err);
});
});
}
|
3ba7940d0da8d8e69fb9b8225784866331a7e5a7
|
TypeScript
|
nonoroazoro/typescript-react-boilerplate
|
/src/typings/json.d.ts
| 3.234375
| 3
|
/**
* JSON scalar.
*/
type JSONScalar = boolean | number | string | null;
/**
* JSON value.
*/
type JSONValue = JSONArray | JSONObject | JSONScalar;
/**
* JSON object.
*/
type JSONObject = {
[key in string]?: JSONValue
};
/**
* JSON array.
*/
interface JSONArray extends Array<JSONValue> { }
|
da075b54ba2756057dd6917cbb842b89f4bea7ad
|
TypeScript
|
mabiamabia/reditus
|
/pagarme_integration/pagarmeTransactionStatus.ts
| 2.6875
| 3
|
export enum PagarmeTransactionStatus {
processing = "processing",
authorized = "authorized",
paid = "paid",
refunded = "refunded",
waitingPayment = "waiting_payment",
pendingRefund = "pending_refund",
refused = "refused",
chargedback = "chargedback",
analyzing = "analyzing",
pendingReview = "pending_review",
}
async function isCompletableStatus(
status: PagarmeTransactionStatus
): Promise<Boolean> {
return status === PagarmeTransactionStatus.paid;
}
async function isCancelableStatus(
status: PagarmeTransactionStatus
): Promise<Boolean> {
const listOfStatuses = [
PagarmeTransactionStatus.refunded,
PagarmeTransactionStatus.refused,
PagarmeTransactionStatus.chargedback,
];
return listOfStatuses.includes(status);
}
export { isCompletableStatus, isCancelableStatus };
|
4582968d5d2979c18f04bd71abd131de126ae3f6
|
TypeScript
|
khadija-el/portfolio
|
/copy.script.ts
| 2.53125
| 3
|
import * as fs from 'fs';
async function main() {
try {
const content = await fs.promises.readFile(`${__dirname}/docs/index.html`, 'utf8');
const cname = await fs.promises.readFile(`${__dirname}/CNAME`, 'utf8');
await fs.promises.writeFile(`${__dirname}/docs/404.html`, content);
await fs.promises.writeFile(`${__dirname}/docs/CNAME`, cname);
console.log('404.html created/updated succesfully');
} catch (error) {
console.log('404.html error occur : ', error);
}
}
// launch the programme
main();
|
2639d7363b5d890587c28556c4db0067f258214b
|
TypeScript
|
KonradKlimczak/test
|
/src/App.ts
| 2.640625
| 3
|
import { Box } from "./Box";
import { BoxKeeper } from "./BoxKeeper";
import { Cube } from "./Cube";
export function App(boxX: number, boxY: number, boxZ: number, ...cubes: number[]) {
const box = new Box(boxX, boxY, boxZ);
const mrBob = new BoxKeeper(
box,
cubes.map((amount: number, rawCubeSize: number): Cube => ({ amount, size: rawCubeSize + 1 }))
);
return mrBob.putCubesIntoTheBox();
}
|
788a661f9cbe7d30acd4f17131296e3ea7b4449c
|
TypeScript
|
un-loop/wareentryresourceguide
|
/website/src/Reducers/RootReducer.ts
| 2.71875
| 3
|
import { assign } from "lodash";
import { AnyAction, Reducer } from "redux";
import { TypeKeys } from "../Actions";
import { SiteState } from "../State/SiteState";
import { Organization } from "../State/Organization";
import { Set } from "immutable";
export const RootReducer: Reducer<SiteState> = (state: SiteState, action: AnyAction): SiteState =>
{
switch (action.type)
{
case TypeKeys.SET_COUNTIES:
return assign({}, state, {countyFilter: action.counties});
case TypeKeys.SET_SERVICE_CATEGORIES:
return assign({}, state, {serviceCategoryFilter: action.serviceCategories});
case TypeKeys.SET_GENDERS:
return assign({}, state, {genderFilter: action.genders});
case TypeKeys.SET_ORGANIZATIONS:
let orgs: Set<Organization> = action.organizations;
return assign({}, state, {
availableCounties: orgs.flatMap(o => o.countiesServed),
availableServiceCategories: orgs.flatMap(o => o.servicesCategories),
availableGenders: orgs.flatMap(o => o.gendersServed),
organizations: orgs,
});
default:
return state;
}
};
|
659efd73f13537d375723a049d97be053b9fa8ce
|
TypeScript
|
admorenog/rhapsody
|
/core/system/console/repl/Commands.ts
| 3.078125
| 3
|
import Command from './Command';
import ExitCommand from './commands/ExitCommand';
import HelpCommand from './commands/HelpCommand';
import SaveCommand from './commands/SaveCommand';
import LoadCommand from './commands/LoadCommand';
import EditCommand from './commands/EditCommand';
export default class Commands
{
private static commands: typeof Command[] = [];
static register (): void
{
/**
* We need to register manually because dynamically could
* give us problems when is compiled (giving to the final
* user the possibility to read our commands easily).
* Maybe we can autoload all commands in a compiled file.
*/
Commands.add( ExitCommand );
Commands.add( HelpCommand );
Commands.add( SaveCommand );
Commands.add( LoadCommand );
Commands.add( EditCommand );
}
public static add ( command: typeof Command )
{
Commands.commands.push( command );
}
public static all () : typeof Command[]
{
return Commands.commands;
}
static execute ( sentence: string ): boolean
{
let command = Commands.getCommand( sentence );
let args = Commands.getArguments( sentence );
return command.fn( args );
}
static getCommand ( sentence: string ): typeof Command
{
let cmd = sentence.split( " " )[ 0 ];
let command = Command;
command.cmd = cmd;
for ( let idxCommand in this.commands )
{
if ( cmd == this.commands[ idxCommand ].cmd )
{
command = this.commands[ idxCommand ];
}
}
return command;
}
static getArguments ( sentence: string ): string[]
{
let args = sentence.split( " " );
args.shift();
return args;
}
/**
* The console requires a boolean to know if should close the repl
* so all command must return true but exit.
*
* The help command will show the commands and their description.
*
* The load command will eval the script (the modules should be imported by the user)
*
* save will get the history commands and save it on a file. If a command throw an
* Error we going to write a comment with the description of the Error.
*
* edit going to create a temp file and will try to execute the application with the
* tmp file as a param. We need to attach fs listeners (fswatch) to check when is saved
* to read the content and execute it. When the child_process is closed we will show
* a message in the repl.
*/
}
|
d2f2447261c3739fef600a63afba649140f05eb9
|
TypeScript
|
PixelGore/React
|
/src/Components/Common/Validators/Validators.ts
| 3.34375
| 3
|
//Field is Required
export const required :FieldValidatorType= (value)=> {
if (value) return undefined;
return 'Field is required';
}
//Exceeded max numbers of symbols
export const maxLengthCreator = (maxLength:number):FieldValidatorType => (value) => {
if (value.length > maxLength ) return `Exceeded max numbers of symbols ${maxLength} `;
return undefined;
}
//Field ValidatorType
export type FieldValidatorType = (value:string)=> string | undefined
|
efd20907b7f4be051914a6eb6e5379715d73c557
|
TypeScript
|
GeoffreyPlichard/puissance4
|
/src/app/board/board.service.ts
| 2.765625
| 3
|
import { Injectable, ViewChild, TemplateRef } from '@angular/core';
import { Cell, BoardConstants } from './board';
import { PlayerService } from '../player/player.service';
import { PlayerTokens, Player } from '../player/player';
@Injectable({
providedIn: 'root'
})
export class BoardService {
public board = [];
public tokensPerColumn = [];
public playingPlayer: Player;
public targetedCell: Cell;
public totalTokens: number = BoardConstants.BOARD_TOKENS;
constructor(private playerService: PlayerService) {
}
/**
* Generate the board, a 2D array
* @param row number of rows
* @param col number of columns
* @returns The game board
*/
public generateBoard(row: number, col: number) {
this.board = [];
for(let i = 0; i < row; i++) {
this.board.push([]);
for(let j = 0; j < col; j++) {
this.board[i].push(new Cell("col-" + j, j, i));
}
}
return this.board;
}
public removeTokenFromTotal() {
this.totalTokens --;
}
/**
* Generate an array with the number of tokens available for each column
* @param row number of rows
* @param col number of columns
*/
public generateTokensPerColumn(row: number, col: number) {
this.tokensPerColumn = [];
for(let i = 0; i < col; i++) {
this.tokensPerColumn[i] = row;
}
}
/**
* Loop around the targeted cell to check if the player has won
* @returns un boolean
*/
public checkIfPlayerWon() {
let playerTokens = new PlayerTokens(0, 0, 0, 0);
// We loop 3 times to check 3 levels around the current cell
for(let i = 1; i <=3; i++) {
// In case we found already 2 tokens in the 1st loop, we do only 2 loops
// TODO Find a better way to fix this case
if(i === 2) {
for(let token in playerTokens) {
if(playerTokens[token] === 2) {
i = 4;
}
}
}
this.checkLeft(this.targetedCell, playerTokens, i);
this.checkLeftDown(this.targetedCell, playerTokens, i);
this.checkRightDown(this.targetedCell, playerTokens, i);
this.checkRight(this.targetedCell, playerTokens, i);
this.checkRightUp(this.targetedCell, playerTokens, i);
this.checkUp(this.targetedCell, playerTokens, i);
this.checkLeftUp(this.targetedCell, playerTokens, i);
}
return this.isConnectFour(playerTokens);
}
// TODO REFACTOR !
public checkLeft(currentCell, playerTokens, index) {
// console.log("CHECK LEFT");
// console.log("CURRENT CELL", currentCell);
// console.log("PLAYER TOKENS", playerTokens);
if(currentCell.x - index >= 0) {
let leftCell = this.board[currentCell.y][currentCell.x - index];
// console.log("LEFT CELL", leftCell);
if(leftCell.player && leftCell.player.pseudo === currentCell.player.pseudo) {
playerTokens["LR"] += 1;
}
}
}
public checkLeftDown(currentCell, playerTokens, index) {
// console.log("CHECK LEFT DOWN");
// console.log("CURRENT CELL", currentCell);
// console.log("PLAYER TOKENS", playerTokens);
if(currentCell.x - index >= 0) {
if(currentCell.y - index >= 0) {
let leftDownCell = this.board[currentCell.y - index][currentCell.x - index];
// console.log("LEFT DOWN CELL", leftDownCell);
if(leftDownCell.player && leftDownCell.player.pseudo === currentCell.player.pseudo) {
playerTokens["LDRU"] += 1;
}
}
}
}
public checkRightDown(currentCell, playerTokens, index) {
// console.log("CHECK RIGHT DOWN");
// console.log("CURRENT CELL", currentCell);
// console.log("PLAYER TOKENS", playerTokens);
if(currentCell.x + index < 7) {
if(currentCell.y - index >= 0) {
let rightDownCell = this.board[currentCell.y - index][currentCell.x + index];
// console.log("RIGHT DOWN CELL", rightDownCell);
if(rightDownCell.player && rightDownCell.player.pseudo === currentCell.player.pseudo) {
playerTokens["LURD"] += 1;
}
}
}
}
public checkRight(currentCell, playerTokens, index) {
// console.log("CHECK RIGHT");
// console.log("CURRENT CELL", currentCell);
// console.log("PLAYER TOKENS", playerTokens);
if(currentCell.x + index < 7) {
let rightCell = this.board[currentCell.y][currentCell.x + index];
// console.log("RIGHT CELL", rightCell);
if(rightCell.player && rightCell.player.pseudo === currentCell.player.pseudo) {
playerTokens["LR"] += 1;
}
}
}
public checkRightUp(currentCell, playerTokens, index) {
// console.log("CHECK RIGHT UP");
// console.log("CURRENT CELL", currentCell);
// console.log("PLAYER TOKENS", playerTokens);
if(currentCell.x + index < 7) {
if(currentCell.y + index < 6) {
let rightUpCell = this.board[currentCell.y + index][currentCell.x + index];
// console.log("RIGHT UP", rightUpCell);
if(rightUpCell.player && rightUpCell.player.pseudo === currentCell.player.pseudo) {
playerTokens["LDRU"] += 1;
}
}
}
}
public checkUp(currentCell, playerTokens, index) {
// console.log("CHECK UP");
// console.log("CURRENT CELL", currentCell);
// console.log("PLAYER TOKENS", playerTokens);
if(currentCell.y + index < 6) {
let upCell = this.board[currentCell.y + index][currentCell.x];
// console.log("UP", upCell);
if(upCell.player && upCell.player.pseudo === currentCell.player.pseudo) {
playerTokens["DU"] += 1;
}
}
}
public checkLeftUp(currentCell, playerTokens, index) {
// console.log("CHECK LEFT UP");
// console.log("CURRENT CELL", currentCell);
// console.log("PLAYER TOKENS", playerTokens);
if(currentCell.x - index >= 0) {
if(currentCell.y + index < 6) {
let leftUpCell = this.board[currentCell.y + index][currentCell.x - index];
// console.log("LEFT UP", leftUpCell);
if(leftUpCell.player && leftUpCell.player.pseudo === currentCell.player.pseudo) {
playerTokens["LURD"] += 1;
}
}
}
}
/**
* Check the player number of tokens
* @param playerTokens The player tokens related to X(LR), Y(DU), XY(LURD), YX(LDRU)
* @returns boolean
*/
public isConnectFour(playerTokens: PlayerTokens) {
for(let token in playerTokens) {
if(playerTokens[token] === 3) {
return true;
}
}
return false;
}
}
|
18cb4cfee68a6ff23338ba90b1181619ab2089f5
|
TypeScript
|
CheezItMan/typescript-syntax
|
/tuple.ts
| 4.28125
| 4
|
// Kind of like an array where specific elements have specific types
// why not use an array of objects...
// An object
const drink = {
color: 'brown',
carbonated: true,
sugar: 40,
};
// An array
// const pepsi = ['brown', true, 45];
// Tuple
const pepsi: [string, boolean, number] = ['brown', true, 45];
// error 40 is not assignable to type string
// pepsi[0] = 40;
// Type alias
type Drink = [string, boolean, number];
const drPepper: Drink = ['brown', true, 38];
// We don't use tuples often, mostly for things like reading from a CSV.
// I would still use an object
|
533c94773715aa8991e2088c9e66f77d95c072b1
|
TypeScript
|
tcgdex/cards-database
|
/data/Diamond & Pearl/Secret Wonders/36.ts
| 2.59375
| 3
|
import { Card } from '../../../interfaces'
import Set from '../Secret Wonders'
const card: Card = {
name: {
en: "Plusle",
fr: "Posipi",
},
illustrator: "Masakazu Fukuda",
rarity: "Rare",
category: "Pokemon",
set: Set,
dexId: [
311,
],
hp: 60,
types: [
"Lightning",
],
stage: "Basic",
abilities: [
{
type: "Poke-POWER",
name: {
en: "Plus Charge",
fr: "Recharge positive",
},
effect: {
en: "Once during your turn (before your attack), if any of your Pokémon were Knocked Out during your opponent's last turn, you may search your discard pile for up to 2 basic Energy cards, show them to your opponent, and put them into your hand. You can't use more than 1 Plus Charge Poké-Power each turn. This power can't be used if Plusle is affected by a Special Condition.",
fr: "Une seule fois lors de votre tour (avant votre attaque), si vos Pokémon ont été mis K.O lors du dernier tour de votre adversaire, vous pouvez chercher dans votre pile de défausse jusqu'à 2 cartes Énergie de base. Montrez-les à votre adversaire et placez-les dans votre main. Vous ne pouvez pas utiliser plus d'1 Poké-Power Recharge positive par tour. Ce pouvoir ne peut pas être utilisé si Posipi est affecté par un État Spécial.",
},
},
],
attacks: [
{
cost: [
"Lightning",
],
name: {
en: "Tag Play (+)",
fr: "Jeu du chat (+)",
},
effect: {
en: "If you have Minun on your Bench, you may do 20 damage to any 1 Benched Pokémon instead. (Don't apply Weakness and Resistance for Benched Pokémon.)",
fr: "Si Negapi se trouve sur votre Banc, vous pouvez infliger 20 dégâts à n'importe quel Pokémon de Banc. (Vous ne pouvez pas appliquer la Faiblesse et la Résistance aux Pokémon de Banc).",
},
damage: 20,
},
],
weaknesses: [
{
type: "Fighting",
value: "+10"
},
],
resistances: [
{
type: "Metal",
value: "-20"
},
],
retreat: 1,
}
export default card
|
f2e7c05e8bab24953ed36d4d2ea9e48eea921c4d
|
TypeScript
|
sarahlawrence/topaz
|
/client/src/store/reducer.ts
| 2.640625
| 3
|
import { createReducer, createAction } from "@reduxjs/toolkit";
const initialState = {
current: "",
};
const setProfile = createAction<string>("set_profile");
export const profileReducer = createReducer(initialState, (builder) => {
builder.addCase(setProfile, (state, action) => {
state.current = action.payload;
});
builder.addDefaultCase((state, action) => state);
});
|
c2b34753dc49fde21dfc9de29cc5b1fd76d46891
|
TypeScript
|
souvenir-lee/nyam-nyam_client
|
/src/lib/auth.ts
| 2.5625
| 3
|
import * as SecureStore from 'expo-secure-store';
import { TextPropTypes } from 'react-native';
import { decode } from 'js-base64';
import { fork, take, put, call, select } from 'redux-saga/effects';
import {
invalidToken,
signinError,
signinSuccess,
validToken,
} from '@base/modules/signin';
import * as authAPI from '@base/api/auth';
import { isOfType } from 'typesafe-actions';
//테스트 코드
const testToken = async (type: string, token?: string) => {
console.log('리프레시 토큰 테스트 시작');
if (!token) {
if (type === 'refresh') {
const token = await SecureStore.getItemAsync('refresh_token');
} else if (type === 'access') {
const token = await SecureStore.getItemAsync('access_token');
}
}
console.log(type, ': ', token);
if (token) {
try {
const payload = JSON.parse(decode(token.split('.')[1]));
console.log('test token payload: ', payload);
const { exp } = payload;
console.log('exp: ', exp);
console.log(type, 'token expired:', exp < Date.now() / 1000);
return false;
} catch (e) {
console.error('invalid token');
}
} else {
console.error(type, 'token not exist');
}
};
//access token, refresh token 저장
export async function storeTokens(accessToken: string, refreshToken?: string) {
try {
console.log('store tokens: access:', accessToken, 'refresh:', refreshToken);
console.log(
'access type:',
typeof accessToken,
'refresh type:',
typeof refreshToken
);
await SecureStore.setItemAsync('access_token', accessToken);
if (refreshToken) {
await SecureStore.setItemAsync('refresh_token', refreshToken);
}
const access = await SecureStore.getItemAsync('access_token');
const refresh = await SecureStore.getItemAsync('refresh_token');
console.log('after store tokens: access:', access, 'refresh:', refresh);
} catch (e) {
console.error('cannot store tokens:', e);
}
}
export async function clearTokens() {
try {
await SecureStore.deleteItemAsync('access_token');
await SecureStore.deleteItemAsync('refresh_token');
const access = await SecureStore.getItemAsync('access_token');
const refresh = await SecureStore.getItemAsync('refresh_token');
console.log('clear tokens:', access, '|||', refresh);
} catch (e) {
console.error(e);
}
}
//token 만료기간 체크
export function* isTokenExpired(token: string) {
//access token의 payload를 분리한 후 base64 디코딩
try {
const payload = JSON.parse(decode(token.split('.')[1]));
console.log('token payload: ', payload);
const { exp } = payload; //토큰 만료시간
console.log('is token expired: ', exp < Date.now() / 1000);
if (exp < Date.now() / 1000) return true;
//만료 시간이 지났다면
else false;
} catch (e) {
yield put(invalidToken(403));
throw Error('유효한 토큰이 아닙니다.');
}
}
const preventTokenCheckIfAlreadyChecked = (
error: string,
service: 'store' | 'customer'
) => {
if (error && service) {
//서비스 중에 에러가 난 것이기 때문에 리소스 요청 중에 인증이 실패한 것
console.log('인증 실패');
return true;
}
return false;
};
function* verifyToken(token: string) {
//access token이 존재한다면 만료기간 확인
let isExpired;
try {
isExpired = yield call(isTokenExpired, token);
} catch (e) {
console.error('token이 유효하지 않음');
yield put(invalidToken(403));
return null;
}
return isExpired;
}
function* refresh(accessToken: string, refreshToken: string) {
let res;
console.log(
'before refresh tokens[access, refresh]: ',
accessToken,
refreshToken
);
try {
res = yield call(authAPI.refresh, accessToken, refreshToken);
console.log('refresh result:', res);
//access token 재발급이 성공했다면
const { access_token } = res.data; //유저 정보도 받아와야 함
storeTokens(access_token);
// 토큰과 유저정보 저장
yield put(validToken(accessToken));
return [true, access_token];
} catch (e) {
//refresh token이 유효하지 않다면
res = e.response;
console.error('refresh api error:', res);
yield put(invalidToken(res.status));
return [false, null];
}
}
function* fetchUserData(accessToken: string) {
try {
const res = yield call(authAPI.autoSignin, accessToken);
const { userdata, storedata } = res.data;
console.log('auto signin success:', res.data);
yield put(signinSuccess(userdata, storedata, accessToken));
} catch (e) {
const res = e.response;
console.log('auto signin failed:', res);
yield put(signinError(res.status));
}
}
export function* autoSignin(): any {
const { error, service } = yield select((state) => state.signin);
//리소스 요청 중에 인증 실패해서 인증 페이지로 이동했을 때는 이전에 이미 토큰을 체크했기 때문에 토큰 체크 안함
if (preventTokenCheckIfAlreadyChecked(error, service)) {
return;
}
const accessToken = yield call([SecureStore, 'getItemAsync'], 'access_token');
console.log('auto signin token:', accessToken);
if (accessToken && typeof accessToken === 'string') {
//access token이 존재한다면
const isAccessTokenInvalid = yield call(verifyToken, accessToken);
//access token이 유효하지 않다면
if (isAccessTokenInvalid === null) {
yield put(signinError(getAuthErrMsg(403) as string));
return;
}
if (isAccessTokenInvalid) {
//access token 만료기간이 유효하지 않다면
console.log('access token의 만료기간 지남');
const refreshToken = yield call(
[SecureStore, 'getItemAsync'],
'refresh_token'
);
if (refreshToken && typeof refreshToken === 'string') {
//refresh token의 만료기간을 확인한다
const isRefreshTokenInvalid = yield call(verifyToken, refreshToken);
if (isRefreshTokenInvalid === null) {
//토큰이 유효하지 않다면
console.error('refresh token is invalid');
yield put(signinError(getAuthErrMsg(403) as string));
}
if (isRefreshTokenInvalid) {
//refresh token의 만료기간이 유효하지 않다면
console.error('refresh token is expired');
testToken(refreshToken, 'refresh');
yield put(signinError(getAuthErrMsg(401) as string));
} else {
//refresh token의 만료 기간이 유효하다면 access token을 새로 발급받는다
const [isRefreshSuccess, refreshedAccessToken] = yield call(
refresh,
accessToken,
refreshToken
);
if (isRefreshSuccess) {
yield call(fetchUserData, refreshedAccessToken);
}
}
} else {
//refresh token이 존재하지 않으면
console.error('refresh token이 존재하지 않음');
yield put(invalidToken(400));
}
} else {
//access token이 만료기간이 유효하다면
yield call(fetchUserData, accessToken);
}
} else {
//access token이 존재하지 않다면
yield put(signinError(getAuthErrMsg(400) as string));
}
}
export function* checkToken() {
console.log('check token in api call');
//secure storage에서 access token 얻기
const accessToken = yield call([SecureStore, 'getItemAsync'], 'access_token');
console.log('access token when check token: ', accessToken);
//access token이 존재한다면 만료기간 확인
if (accessToken && typeof accessToken === 'string') {
const isAccessTokenInvalid = yield call(verifyToken, accessToken);
//access token이 유효하지 않다면
if (isAccessTokenInvalid === null) return false;
if (isAccessTokenInvalid) {
console.log('access token의 만료기간 지남');
const refreshToken = yield call(
[SecureStore, 'getItemAsync'],
'refresh_token'
);
if (refreshToken && typeof refreshToken === 'string') {
//refresh token의 만료기간을 확인한다
const isRefreshTokenInvalid = yield call(verifyToken, refreshToken);
if (isRefreshTokenInvalid === null) false; //토큰이 유효하지 않다면
if (isRefreshTokenInvalid) {
//refresh token의 만료기간이 유효하지 않다면
console.error('refresh token is expired');
testToken(refreshToken, 'refresh');
yield put(invalidToken(401));
return false;
} else {
//refresh token의 만료 기간이 유효하다면 access token을 새로 발급받는다
const isRefreshSuccess = yield call(
refresh,
accessToken,
refreshToken
);
return isRefreshSuccess;
}
} else {
//refresh token이 존재하지 않으면
console.error('refresh token이 존재하지 않음');
yield put(invalidToken(400));
return false;
}
} else {
//access token의 만료 기간이 유효하다면
return true;
}
} else {
//access token이 존재하지 않다면
console.error('access token이 존재하지 않음');
return false;
}
}
type Sagas = any[];
export function createAuthCheckSaga(isAppLoaded = false) {
if (isAppLoaded) {
return function* () {
console.log('check token when app start');
yield call(autoSignin);
};
} else {
let callCount = 0;
return function* (actions: any[], sagas: Sagas) {
while (true) {
const action = yield take(actions);
console.log('saga action: ', action);
//처음 앱을 켰을 때 auto sign만 dispatch
//자동 로그인 이후에는 check token dispatch
let isTokenValid;
console.log('call count in resource api auth saga:', callCount);
if (callCount > 0) {
console.log('start resource api authentication');
isTokenValid = yield call(checkToken);
} else {
//자동 로그인할 때 token 검증 안함
console.log('already auth checked in auto signin');
isTokenValid = yield select((state) => state.signin.isSignin);
}
if (isTokenValid) {
const accessToken = yield select((state) => state.signin.accessToken);
console.log('auth saga: true, ', accessToken);
for (let i = 0; i < sagas.length; i++) {
//사가에서 api요청 보낼 때 헤더에 access token 추가
yield fork(sagas[i], action, accessToken);
}
}
callCount++;
}
};
}
}
export const getAuthErrMsg = (statusCode: string | number) => {
if (statusCode === 400) {
return '토큰이 존재하지 않습니다.';
} else if (statusCode === 401) {
return '토큰 만료기간이 지났습니다';
} else if (statusCode === 403) {
return '유효한 토큰이 아닙니다.';
}
return null;
};
//리소스 api에서 인증 실패시 에러 처리
export function* handleIfAuthError(statusCode: number | string) {
if (statusCode === 401) {
yield put(invalidToken(statusCode));
return true;
} else if (statusCode === 403) {
yield put(invalidToken(statusCode));
return true;
}
return false;
}
|
7ed177c15ec0fd32616c7a27ecce24bcdc98b597
|
TypeScript
|
asdf148/deploy_test
|
/src/comment/comment.controller.ts
| 2.53125
| 3
|
import { Body, Controller, Delete, Get, Headers, HttpStatus, Param, Post, Put, Res } from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { Comment } from 'src/entity/comment.entity';
import { CreateComment } from 'src/entity/comment_dto/createComment.dto';
import { UpdateComment } from 'src/entity/comment_dto/updateComment.dto';
import { DeleteResult, UpdateResult } from 'typeorm';
import { CommentService } from './comment.service';
@Controller('comment')
@ApiTags('Comment')
export class CommentController {
constructor(private readonly commentService:CommentService) {}
@Get('/findAll/:id')
@ApiOperation({summary:"해당 게시물 댓글 다 가져오기", description:"해당 게시물 댓글 다 가져오기"})
@ApiOkResponse({description:"해당 게시물 댓글 다 가져오기", type:Array})
async findAll(@Param('id') post_id:string, @Res() res:Response):Promise<Response<any, Record<string, any>>>{
const comments:Comment[] = await this.commentService.findAll(post_id);
return res.status(HttpStatus.OK).json({comments:comments});
}
@Post('/write/:id')
@ApiOperation({summary:"해당 게시물 댓글 달기", description:"해당 게시물 댓글 달기"})
@ApiOkResponse({description:"해당 게시물 댓글 달기", type:Comment})
async write(@Headers('Authorization') token:string,@Param('id') post_id:string, @Body() createComment:CreateComment, @Res() res:Response):Promise<Response<any, Record<string, any>>>{
const comment:Comment|string = await this.commentService.create(token, post_id, createComment);
if(typeof comment == "string"){
return res.status(HttpStatus.BAD_REQUEST).json({error:comment});
}
return res.status(HttpStatus.OK).json({comment:comment});
}
@Put('/:id')
@ApiOperation({summary:"댓글 수정", description:"댓글 수정"})
@ApiOkResponse({description:"댓글 수정", type:UpdateResult})
async modify(@Param('id') id:string, @Body() updateComment:UpdateComment, @Res() res:Response):Promise<Response<any, Record<string, any>>>{
const result:UpdateResult = await this.commentService.update(id, updateComment);
return res.status(HttpStatus.OK).json({result:result});
}
@Delete('/:id')
@ApiOperation({summary:"댓글 삭제", description:"댓글 삭제"})
@ApiOkResponse({description:"댓글 삭제", type:DeleteResult})
async delete(@Param('id') id:string, @Res() res:Response):Promise<Response<any, Record<string, any>>>{
const result:DeleteResult = await this.commentService.delete(id);
return res.status(HttpStatus.OK).json({result:result});
}
}
|
d72c2a5ff8dba57e95e3fdbb267e08a55b779567
|
TypeScript
|
airdcpp-web/airdcpp-webui
|
/src/utils/FileUtils.ts
| 2.859375
| 3
|
export const getFilePath = (fullPath: string): string => {
if (isDirectory(fullPath)) {
return fullPath;
}
return fullPath.replace(/[^\\/]*$/, '');
};
export const getFileName = (fullPath: string): string => {
return fullPath.replace(/^.*[\\/]/, '');
};
export const isDirectory = (fullPath: string): boolean => {
return fullPath ? !!fullPath.match(/[\\/]$/) : false;
};
export const getParentPath = (fullPath: string): string => {
if (isDirectory(fullPath)) {
return fullPath.replace(/[^\\/]+[\\/]$/, '');
}
return getFilePath(fullPath);
};
export const getLastDirectory = (fullPath: string): string => {
const path = isDirectory(fullPath) ? fullPath : getParentPath(fullPath);
const result = path.match(/([^\\/]+)[\\/]$/);
return result ? result[1] : fullPath;
};
export const fileToBase64 = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
let encoded = (reader.result as string).replace(/^data:(.*;base64,)?/, '');
if (encoded.length % 4 > 0) {
encoded += '='.repeat(4 - (encoded.length % 4));
}
resolve(encoded);
};
reader.onerror = function (error) {
reject(error);
};
});
};
export const fileToText = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsText(file);
reader.onload = (e) => {
resolve((e.target! as any).result);
};
reader.onerror = function (error) {
reject(error);
};
});
};
|
0de5389d2e33cac48409aa449c1767133e7ca089
|
TypeScript
|
valtikamore/cards
|
/src/redux/registrationReducer/registrationReducer.ts
| 2.84375
| 3
|
import {authAPI} from "../../api/auth-api";
export const SUCCESS = 'registrationReducer/SUCCESS' as const
export const LOADING = 'registrationReducer/LOADING'as const
export const ERROR = 'registrationReducer/ERROR'as const
type addedUserType = {
created: string
email: string
isAdmin: boolean
name: string
publicCardPacksCount: number
rememberMe: boolean
updated: string
verified: boolean
__v: number
_id: string
}
type InitialStateType = {
loading:boolean
error:string
registrationSuccess: boolean
}
const initialState = {
registrationSuccess:false,
loading:false,
error:''
}
type PropertiesType<ActionType> = ActionType extends {[key: string]: infer ResponseType } ? ResponseType : never;
type ActionsType = ReturnType<PropertiesType<typeof actions>>
const registrationReducer = (state: InitialStateType = initialState, action: ActionsType): InitialStateType => {
switch (action.type) {
case SUCCESS: {
return {
...state,
registrationSuccess: action.payload.registrationSuccess
}
}
case LOADING: {
return {
...state,
error:'',
loading:action.payload.loading,
registrationSuccess:false
}
}
case ERROR: {
return {
...state,
error:action.payload.error,
loading:false,
registrationSuccess:false
}
}
default:
return state
}
}
export const actions = {
registrationAC: (registrationSuccess:boolean) => {
// data:addedUserType,
return ({
type: SUCCESS,
payload: {
// data,
registrationSuccess: registrationSuccess
}
})
},
registrationLoadingAC: (loading:boolean) => {
return({
type:LOADING,
payload : {
loading
}
})
},
registrationErrorAC: (error:string) => {
return({
type:ERROR,
payload : {
error
}
})
}
}
export const RegistrationTC = (email: string, password: string) => (dispatch: any) => {
dispatch(actions.registrationLoadingAC(true))
authAPI.registration(email, password)
.then((data) => {
dispatch(actions.registrationAC(true))
dispatch(actions.registrationLoadingAC(false))
})
.catch((error) => {
dispatch(actions.registrationErrorAC('error'))
console.log('error')
})
}
export default registrationReducer;
|
1d76b696223fcf84b7ea2f3d74737de60db5293d
|
TypeScript
|
adalfonso/electron_music
|
/tests/Logger.test.ts
| 2.984375
| 3
|
import { Logger as Sut } from "../src/renderer/Logger";
import { expect } from "chai";
describe("Logger", () => {
["log", "info", "warn", "error"].forEach(level => {
it(`Logs for a ${level} level`, () => {
const results = {};
const context = { cat: 23 };
const sut = new Sut(getLog(results));
sut[level]("something", context);
expect(Object.keys(results)).to.deep.equal([level]);
expect(results[level].message).to.equal("something");
expect(results[level].context).to.equal(context);
});
});
it(`allows context to be optionals`, () => {
const results = {};
const sut = new Sut(getLog(results));
sut.log("something");
sut.info("something");
sut.warn("something");
sut.error("something");
expect(Object.keys(results)).to.deep.equal([
"log",
"info",
"warn",
"error",
]);
expect(results["log"].context).to.deep.equal({});
expect(results["info"].context).to.deep.equal({});
expect(results["warn"].context).to.deep.equal({});
expect(results["error"].context).to.deep.equal({});
});
});
const getLog = (results: Record<string, unknown>) => {
return {
log: output => {
results.log = output;
},
info: output => {
results.info = output;
},
warn: output => {
results.warn = output;
},
error: output => {
results.error = output;
},
};
};
|
c453cf17cbb11c18b8a65b64bbb976ff9c1fefac
|
TypeScript
|
gustavoafranca/letter-santaclaus
|
/src/controller/UserController.ts
| 2.53125
| 3
|
import {Request, Response} from 'express'
import { getRepository } from 'typeorm'
import User from '../models/User'
import UserView from '../views/UserView'
export default {
async create(req: Request, res: Response){
const user = <User> req.body
try {
const repository = getRepository(User)
const create = repository.create(user)
const save = await repository.save(create)
return res.status(201).json(save)
} catch {
return res.sendStatus(400)
}
},
async update(req: Request, res: Response){
const {id} = req.params
const user = <User> req.body
try {
const repository = getRepository(User)
await repository.update(id, user)
const value = <User> await repository.findOne(id)
return res.status(200).json(UserView.render(value))
} catch {
return res.sendStatus(400)
}
},
async delete(req: Request, res: Response){
const {id} = req.params
try {
const repository = getRepository(User)
await repository.delete(id)
return res.sendStatus(204)
} catch {
return res.sendStatus(400)
}
},
async index(req: Request, res: Response){
try {
const repository = getRepository(User)
const user = await repository.find()
return res.status(200).json(UserView.renderMany(user))
} catch {
return res.sendStatus(400)
}
},
async show(req:Request, res: Response){
const {id} = req.params
try {
const repository = getRepository(User)
const user = await repository.findOneOrFail(id)
return res.status(200).json(UserView.render(user))
} catch {
return res.sendStatus(400)
}
},
}
|
ab80c17c455dadafe3b6dcb8a9d71b7d33950f0e
|
TypeScript
|
pogotc/Monte-Carlo-Tree-Search
|
/src/MCTS.test.ts
| 2.9375
| 3
|
import MCTS from './MCTS';
import { ThreeInARowGameState } from './testHelper';
import TicTacToeGameState from './example/tictactoe/TicTacToeGameState';
describe('MCTS', () => {
// let mcts;
test('Test run for a single move', () => {
const mcts = new MCTS();
const gameState = new ThreeInARowGameState([0, 2, 2, 1, 1, 0, 0, 0, 0]);
const bestMove = mcts.findNextMove(gameState, 1);
expect(bestMove).toEqual(5);
});
test('failed scenario', () => {
const mcts = new MCTS();
const gameState = new TicTacToeGameState([0, 0, 2, 2, 1, 1, 0, 0, 1]);
const bestMove = mcts.findNextMove(gameState, 2);
expect(bestMove).toEqual(0);
});
test('failed scenario - 2', () => {
const mcts = new MCTS();
const gameState = new TicTacToeGameState([0, 0, 0, 1, 1, 0, 2, 0, 0]);
const bestMove = mcts.findNextMove(gameState, 2);
expect(bestMove).toEqual(5);
});
// test('Playing TicTacToe', () => {
// const mcts = new MCTS();
// let gameState = new TicTacToeGameState([0, 0, 0, 0, 0, 0, 0, 0, 0]);
// // player one
// gameState = gameState.applyAction({ move: 4, player: 1 });
// // console.log(gameState.getPlayer());
// // CPU first move
// let bestMove = mcts.findNextMove(gameState, 2);
// gameState = gameState.applyAction({ move: bestMove, player: 2 });
// // player one - second move
// gameState = gameState.applyAction({ move: 5, player: 1 });
// bestMove = mcts.findNextMove(gameState, 2);
// expect(bestMove).toEqual(3);
// });
});
|
17994f380c9d7a8c86015743f2c3c8fba09da956
|
TypeScript
|
fonnesbeck/workbench
|
/ui/src/app/cohort-search/gender-chart/gender-chart.component.ts
| 2.859375
| 3
|
import {ChangeDetectionStrategy, Component, Input} from '@angular/core';
import {List, Map} from 'immutable';
@Component({
selector: 'app-gender-chart',
templateUrl: './gender-chart.component.html',
styleUrls: ['./gender-chart.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GenderChartComponent {
/*
* TODO - this maps gender codes to human readable representations. We
* probably need to either grab that repro from the DB or generate a complete
* list of possible values and include mappings for each one, not just the
* binary basics.
*/
readonly codeMap = {
'M': 'Male',
'F': 'Female',
};
/*
* TODO - see the above note on this.codeMap
*/
readonly defaults = {
Male: 0,
Female: 0,
Unknown: 0
};
readonly axis = {
x: {
show: true,
label: '# Participants',
showLabel: true,
},
y: {
show: true,
label: 'Gender',
showLabel: true,
}
};
private _raw: any;
private _data: any = [];
/**
* Transforms the raw chart data from a List of Maps to a list of {name,
* value} objects suitable for consumption by ngx-charts-bar-horizontal.
* Attaches the raw data to the component for debugging purposes.
*/
@Input() set data(raw) {
this._raw = raw;
this._data = raw
.map(datum => datum.update('gender', code => this.codeMap[code]))
.groupBy(datum => datum.get('gender', 'Unknown'))
.map(data => data.reduce((s, d) => s + d.get('count', 0), 0))
.toMap()
.mergeWith((old, _) => old, this.defaults)
.map((value, name) => ({name, value}))
.valueSeq()
.toArray();
/*
* This is a kind of workaround - the way ngx-charts detects how large it
* should be (to be responsive) only appears to detect changes in the
* parent container on a window resize event
*/
window.dispatchEvent(new Event('resize'));
}
get data() {
return this._data;
}
/**
* Returns the minimum height of the container as a number representing
* pixels. The min height is calculated as 100 * the number of bars with a
* positive value or else just 100.
*/
get minHeight() {
const numberBars = this.data.reduce((count, obj) => {
if (obj.value > 0) { count += 1; }
return count;
}, 0);
return Math.max(numberBars * 100, 200);
}
}
|
2f5bc8db309f217b1ea0edfe8da5c16c5aaf6125
|
TypeScript
|
yume-chan/observe-state
|
/src/scope/action.ts
| 2.5625
| 3
|
import { ScopeManager } from ".";
import { Diff, mergeDiff } from "../diff";
import { Observer, ObserverCallback } from "./observer";
import { ObjectPaths } from "./pathTrie";
interface ActionState {
global: boolean;
diffList: Diff[];
trackUndo: boolean;
undoList: Diff[];
diffPaths: ObjectPaths;
observers: Set<Observer>;
}
function invokeObserversByDependency(
observers: Set<Observer>,
diffPaths: ObjectPaths
) {
let invoked = new Set<ObserverCallback>();
for (const observer of observers) {
if (invoked.has(observer.callback)) {
continue;
}
if (diffPaths.isSameOrAncestorOf(observer.dependencies)) {
observer.callback();
invoked.add(observer.callback);
}
}
}
export class ActionManager {
private scopeManager: ScopeManager;
private stack: ActionState[] = [];
private current: ActionState = {
global: true,
observers: new Set(),
diffList: [],
trackUndo: false,
undoList: [],
diffPaths: new ObjectPaths(),
};
public constructor(scopeManager: ScopeManager) {
this.scopeManager = scopeManager;
}
public begin(trackUndo = false) {
this.stack.push(this.current);
const state: ActionState = {
global: false,
diffList: [],
trackUndo,
undoList: [],
observers: new Set(),
diffPaths: new ObjectPaths(),
};
this.current = state;
return () => {
if (this.current !== state) {
throw new Error('transaction must end in reverse order');
}
this.current = this.stack.pop()!;
if (state.diffPaths.size && this.current.observers.size) {
invokeObserversByDependency(
this.current.observers,
state.diffPaths
);
}
for (const observer of state.observers) {
this.current.observers.add(observer);
}
if (!this.current.global) {
for (const diff of state.diffList) {
this.addDiff(diff);
}
}
if (trackUndo && this.current.global && state.undoList.length) {
this.scopeManager.undoManager.push(state.undoList);
}
};
}
public execute<T>(executor: () => T, trackUndo = false): T {
const end = this.begin(trackUndo);
try {
return executor();
} finally {
end();
}
}
/** @internal */ addObserver(observer: Observer) {
this.current.observers.add(observer);
}
/** @internal */ deleteObserver(observer: Observer) {
this.current.observers.delete(observer);
}
/** @internal */ addDiff(diff: Diff) {
if (this.current.global) {
throw new Error('Can not modify object outside actions');
}
this.current.diffList = mergeDiff(this.current.diffList, diff);
this.current.diffPaths.add(diff.target, diff.path, true);
if (this.current.trackUndo) {
this.current.undoList = mergeDiff(this.current.undoList, diff);
}
const paths = new ObjectPaths();
paths.add(diff.target, diff.path);
invokeObserversByDependency(
this.current.observers,
paths
);
}
/** @internal */ notifyUndoStateChange() {
const paths = new ObjectPaths();
paths.add(this.scopeManager.undoManager, ['canUndo']);
paths.add(this.scopeManager.undoManager, ['canRedo']);
invokeObserversByDependency(
this.current.observers,
paths
);
}
}
|
7de848b801eb8bdb8e5f4aa0ddf2d69cbe5c3f40
|
TypeScript
|
kal93/terminus-ui
|
/src/lib/src/services/validation-message/validation-message.service.ts
| 2.8125
| 3
|
import { Injectable } from '@angular/core';
import { format } from 'date-fns';
import { emailMessage } from './../../utilities/regex/email.regex';
import { creditCardMessage } from './../../utilities/regex/credit-card.regex';
import { passwordMessage } from './../../utilities/regex/password.regex';
// TODO: The consuming app will need a way to pass in the error messages config object so that
// localization is supported. See https://github.com/GetTerminus/terminus-ui/issues/403
/**
* Define a service that offers custom validators
*/
@Injectable()
export class TsValidationMessageService {
/**
* Return the correct error message for a validator
*
* @param validatorName - The name of the validator
* @param validatorValue - The value of the validator
* @return The error message
*/
public getValidatorErrorMessage(validatorName: string, validatorValue?: any): string {
const config = {
// Standard responses:
required: `Required`,
minlength: `Minimum length ${validatorValue.requiredLength}`,
maxlength: `Maximum length ${validatorValue.requiredLength}`,
// Custom responses:
creditCard: creditCardMessage,
email: emailMessage,
password: passwordMessage,
// TODO: Figure out how to abstract pattern messages out so they can be customized per
// pattern. (showing a regex pattern to an end user isn't helpful) and we need the ability to
// support multiple patterns
pattern: `Must contain only letters, numbers or spaces`,
maxDate: '',
minDate: '',
greaterThan: `${validatorValue.actual} is not greater than ${validatorValue.greaterThan}`,
lessThan: `${validatorValue.actual} is not less than ${validatorValue.lessThan}`,
notUnique: `${validatorValue.actual} has already been selected.`,
noResults: `No results found.`,
url: `'${validatorValue.actual}' is not a valid URL.`,
equalToControl: `'${validatorValue.actual}' is not equal to '${validatorValue.compareValue}'`,
};
if (validatorName === 'maxDate') {
const message = `Date must be before`;
config.maxDate = `${message} ${format(validatorValue.maxDate, 'M/D/YYYY')}`;
}
if (validatorName === 'minDate') {
const message = `Date must be after`;
config.minDate = `${message} ${format(validatorValue.minDate, 'M/D/YYYY')}`;
}
return config[validatorName];
}
}
|
38bb9c3cc079c83d649f6784d83517a9c6ea1b24
|
TypeScript
|
Xan0C/curbl-ecs
|
/example/src/systems/velocitySystem.ts
| 2.671875
| 3
|
import { System } from '@curbl/ecs';
import { Components, Position, Velocity } from '../components';
import { ecs } from '../ecs';
const SHAPE_HALF_SIZE = 200;
@ecs.System(Components.POSITION, Components.VELOCITY)
export class VelocitySystem extends System {
constructor(private readonly canvasWidth: number, private readonly canvasHeight: number) {
super();
}
update(delta: number): void {
const entities = this.entities();
for (let i = 0, entity; (entity = entities[i]); i++) {
const velocity = entity.get<Velocity>(Components.VELOCITY);
const position = entity.get<Position>(Components.POSITION);
position.x += velocity.x * delta;
position.y += velocity.y * delta;
if (position.x > this.canvasWidth + SHAPE_HALF_SIZE) position.x = -SHAPE_HALF_SIZE;
if (position.x < -SHAPE_HALF_SIZE) position.x = this.canvasWidth + SHAPE_HALF_SIZE;
if (position.y > this.canvasHeight + SHAPE_HALF_SIZE) position.y = -SHAPE_HALF_SIZE;
if (position.y < -SHAPE_HALF_SIZE) position.y = this.canvasHeight + SHAPE_HALF_SIZE;
}
}
}
|
b15d5df0c4bf4ecb10d05f09015ada95c17a35ab
|
TypeScript
|
radial-color-picker/angular-color-picker
|
/projects/radial-color-picker/src/lib/helpers/constants.ts
| 2.828125
| 3
|
export const Cache = {
sin90: Math.sin(270 * Math.PI / 180),
sin180: Math.sin(180 * Math.PI / 180),
sin270: Math.sin(90 * Math.PI / 180),
cos90: Math.cos(270 * Math.PI / 180),
cos180: Math.cos(180 * Math.PI / 180),
cos270: Math.cos(90 * Math.PI / 180)
};
export const Quadrant = {
I: 'q1',
II: 'q2',
III: 'q3',
IV: 'q4'
};
export const bezierCurves = {
// Standard easing puts subtle attention at the end of an animation,
// by giving more time to deceleration than acceleration.It is the most common form of easing.
standard: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
// Elements exiting a screen use acceleration easing, where they start at rest and end at peak velocity.
acc: 'cubic-bezier(0.4, 0.0, 1, 1)',
// Incoming elements are animated using deceleration easing,
// which starts a transition at peak velocity(the fastest point of an element’s movement) and ends at rest.
dec: 'cubic-bezier(0.0, 0.0, 0.2, 1)'
};
export const timings = {
simpleMicro: '100ms',
simpleEnter: '150ms',
simpleExit: '75ms',
complexEnter: '250ms',
complexExit: '200ms',
largeEnter: '300ms',
largeExit: '250ms'
};
|
07aaffd7e20400d78e8fe1cf0ad3f2f9d598fd6f
|
TypeScript
|
geunheejung/ts_tutorial
|
/src/genericExample/generic1.ts
| 4.3125
| 4
|
// generic 사용 이유 - Type을 동적으로 할당하고 싶을 때 사용
// 같은 형태이지만 Type만 다를 경우 코드가 반복되서 생성됨
// 이럴 때 제네릭을 사용하여 타입을 동적으로 할당받자.
// 장점: any로 하면 any와 관련된 헬퍼, 도우미들이 제대로 작동안하는반면 제네릭은 잘 작동
/*
function hello<T>(message: T): T {
return message;
}
hello<string>('Geuni');
hello<number>(35);
const strArr: string[] = [];
const strArr2: Array<string> = [];
function hi<T>(messages: T[]): T {
return messages[0];
}
hi<string>(["g"]);
type HelloGeneric = <T>(message: T) => T;
const hello1: HelloGeneric = <T>(message: T) => {
return message;
}*/
/*
class Cafe<T> {
private _coffee: T;
constructor(name: T) {
this._coffee = name;
}
}
const cafe = new Cafe<string>('Americano');
*/
/*
class Cafe<T extends string | number> {
private _coffee: T;
constructor(name: T) {
this._coffee = name;
}
}
class Apple<T, K> {
private _name: T;
private _age: K;
constructor(name: T, age: K) {
this._name = name;
this._age = age;
}
}
const apple = new Apple<string, number>(12, 15);
const cafe = new Cafe('');
*/
// enum Color {
// Red = 1,
// Blue = 3,
// Green = 7
// }
// let c: Color = Color.Green;
// console.log(Color[1])
interface Test1 {
name: string;
age: number;
}
/* type lookup
인자로 받은 Object와 인자로 받은 Key가 있고
Object와 Key간의 관계를 알아내기 위해?
type lookup이라는게 생겼다.
오브젝트를 만들 때 타입으로 명시해준 인터페이스를 제네릭에서 key 인자에 명시해줄 부분에 extends 로 타입을 합쳐주는데 여기서 keyof 키워드를 사용해서 interface의 type을 정해주면
오브젝트는 IAinterface 로 만들어졌다면
key는 IAinterface에 명세된 key값만 사용할 수 있기때문에 인자로 받은 key값이 오브젝트에 존재하지 않는다면 에러가 난다.
즉 오브젝트와 키 간의 관계를 알 수 있다.
/*
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
const q: Test1 = {
age: 35,
name: 'geuni',
}
getProperty<string, d>(q, 'name');
setProperty(q, 'age', 'd');
class Stack<T> {
private _data: T[] = [];
push(item: T): void {
this._data.push(item);
}
pop(): T | undefined {
return this._data.pop();
}
}
const stringStack = new Stack<string>();
stringStack.push("d");
function first<T>(arr: T[]): T {
return arr[0];
}
first<string>(["d"]);
interface IType {
age: string,
name: string,
}
*/
interface ITest {
name: string;
age: number;
}
function getPro<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const testObj = {
age: 20,
name: 'geuni'
}
type q = keyof ITest;
/*
1. object의 타입이 명세된 interface를 만들어주고
2. object에 해당 interface를 명시해준다음
3. 함수에 제네릭을 정의해준다음 오브젝트와 매칭되는 제네릭 타입 인자를 keyof 로 해서 key의 제네릭 타입 인자에 extends 시켜주면
4. 타입추론에 의해 오브젝트와 매칭되는 제네릭 인자인 T에는 오브젝트를 만들면서 사용한 인터페이스에 명세된 타입을이 리터럴 타입으로 분리되고
5. 그 타입이 key 제네릭 인자에 extends되면서 인터페이스에 명세된 타입이 아닌 이상 key로 사용할 수 없게된다?
*/
getPro(testObj, 'name');
// extends 는 뜻 그대로 type끼리 상속하는것
|
8487e458aa12a3a5e6844b218196e756edf055da
|
TypeScript
|
m4-used-rollout/pokemon-hud
|
/src-server/rom-reading/tools/gen2lzdecmp.ts
| 2.796875
| 3
|
/**
* Pokemon Gen 2 sprite decompressor Source:
* https://github.com/pret/pokemon-reverse-engineering-tools/blob/master/pokemontools/lz.py
* (and gfx.py for flatten())
* Originally ported to Java by Dabomstew
*
*/
namespace Tools {
const LZ_END = 0xFF;
const INITIAL_BUF_SIZE = 0x1000;
const bit_flipped = new Array<number>(0x100);
for (let b = 0; b < 0x100; b++) {
for (let i = 0; i < 8; i++) {
bit_flipped[b] += ((b >> i) & 1) << (7 - i);
}
}
function flatten(planar: Buffer) {
let strips = new Buffer(planar.length * 4);
for (let j = 0; j < planar.length / 2; j++) {
let bottom = planar[j * 2] & 0xFF;
let top = planar[j * 2 + 1] & 0xFF;
let strip = new Buffer(8);
for (let i = 7; i >= 0; i--) {
strip[7 - i] = (((bottom >>> i) & 1) + ((top * 2 >>> i) & 2));
}
strip.copy(strips, j * 8, 0, 8);
}
return strips;
}
export class Gen2LZDecmp {
public data: Buffer;
public address: number = 0;
private output: Buffer = new Buffer(INITIAL_BUF_SIZE);
private out_idx: number = 0;
private cmd: number = 0;
private len: number = 0;
private offset: number = 0;
constructor(input: Buffer, baseOffset: number, tilesWide: number, tilesHigh: number) {
this.data = input;
this.address = baseOffset;
this.decompress();
this.cutAndTranspose(tilesWide, tilesHigh);
}
public getData() {
return this.output;
}
public getFlattenedData() {
return flatten(this.output);
}
private cutAndTranspose(width: number, height: number) {
if (this.output == null) {
return;
}
let tiles = width * height;
let newData = new Buffer(width * height * 16);
for (let tile = 0; tile < tiles; tile++) {
let oldTileX = tile % width;
let oldTileY = tile / width;
let newTileNum = oldTileX * height + oldTileY;
this.output.copy(newData, newTileNum * 16, tile * 16, (tile + 1) * 16);
}
this.output = newData;
}
private decompress() {
this.output.fill(0);
while (true) {
if (this.peek() == LZ_END) {
this.next();
break;
}
this.cmd = (this.peek() & 0xE0) >> 5;
if (this.cmd == 7) {
// LONG command
this.cmd = (this.peek() & 0x1C) >> 2;
this.len = (this.next() & 0x03) * 0x100 + this.next() + 1;
}
else {
// Normal length
this.len = (this.next() & 0x1F) + 1;
}
while (this.out_idx + this.len > this.output.length) {
this.resizeOutput();
}
switch (this.cmd) {
case 0:
// Literal
this.data.copy(this.output, this.address, this.out_idx, this.address + this.len);
this.out_idx += this.len;
this.address += this.len;
break;
case 1:
// Iterate
let repe = this.next();
for (let i = 0; i < this.len; i++) {
this.output[this.out_idx++] = repe;
}
break;
case 2:
// Alternate
let alts = [this.next(), this.next()];
for (let i = 0; i < this.len; i++) {
this.output[this.out_idx++] = alts[i & 1];
}
break;
case 3:
// Zero-fill
this.out_idx += this.len;
break;
case 4:
// Default repeat
this.repeat();
break;
case 5:
this.repeat(1, bit_flipped);
break;
case 6:
this.repeat(-1);
break;
}
}
this.output = this.output.slice(0, this.out_idx);
}
private repeat(direction = 1, table: number[] = null) {
this.get_offset();
for (let i = 0; i < this.len; i++) {
let value = this.output[this.offset + i * direction] & 0xFF;
this.output[this.out_idx++] = ((table == null) ? value : table[value]);
}
}
private get_offset() {
if (this.peek() >= 0x80) {
// Negative
this.offset = this.next() & 0x7F;
this.offset = this.out_idx - this.offset - 1;
} else {
// Positive, extended
this.offset = this.next() * 0x100 + this.next();
}
}
private resizeOutput() {
let newOut = new Buffer(this.output.length * 2);
newOut.fill(0);
this.output.copy(newOut);//, 0, 0, this.out_idx);
this.output = newOut;
}
public peek() {
return this.data[this.address] & 0xFF;
}
public next() {
return this.data[this.address++] & 0xFF;
}
}
}
|
f2bcf8d2bb220bf4f4c2926a2f8e59170f4fd3c5
|
TypeScript
|
TatsuyaYamamoto/dl-code.web.app
|
/app/domains/AuditLog.ts
| 2.53125
| 3
|
import firebase from "firebase/app";
type FieldValue = firebase.firestore.FieldValue;
export enum LogType {
ACTIVATE_WITH_DOWNLOAD_CODE = "ACTIVATE_WITH_DOWNLOAD_CODE",
DOWNLOAD_PRODUCT_FILE = "DOWNLOAD_PRODUCT_FILE",
PLAY_PRODUCT_FILE = "DOWNLOAD_PRODUCT_FILE",
}
export interface AuditLogDocument {
// who
userId:
| string // login user
| null; // non-login user (ex. download only)
// what
type: LogType;
// when
createdAt: Date | FieldValue;
// where
href: string;
userAgent: string;
// how
params: any;
// results
ok: boolean;
error?: {
name: string;
message: string;
stack?: string;
};
}
export const getColRef = () => {
return firebase.firestore().collection(`auditLogs`);
};
|
ae3ca9d6685d3bedc038db3dbc2b5c71f670988a
|
TypeScript
|
calirvine/restaurant-demo
|
/backend/src/controllers/session.ts
| 2.578125
| 3
|
import { PrismaClient, Profile, User } from '@prisma/client'
import { Request, Response } from 'express'
const prisma = new PrismaClient()
export interface IReqWithSession extends Request {
session: {
userId: string
role: string
} | null
}
export async function getSession(
sessionId?: string,
): Promise<{ userId: string; role: number } | null> {
if (!sessionId) return null
const session = await prisma.session.findOne({ where: { id: sessionId } })
return session ? JSON.parse(session.data) : null
}
export async function createSession(user: User & { profile: Profile | null }) {
const session = await prisma.session.create({
data: {
data: JSON.stringify({ userId: user.id, role: user.profile?.role ?? 0 }),
},
})
return session.id
}
export async function endSession(sessionId: string) {
const res = await prisma.session.delete({ where: { id: sessionId } })
if (res) return true
return false
}
export function purgeSessions() {
prisma.session.deleteMany({})
}
|
890494b21e38dde61b157186fc24e37b8c5926c8
|
TypeScript
|
condottieros/eltex-task
|
/index.ts
| 3.53125
| 4
|
/** Получение случайного числа в диапазоне 0-62 */
const getRandom = () => Math.floor(Math.random() * 62);
/** Преобразование случайного кода в код символов латиницы и цифр */
const randomToCode = (code: number) => {
if (code > 35) return code + 61;
if (code > 9) return code + 55;
return code + 48;
};
const randomToSymbol = (a: number) => String.fromCharCode(randomToCode(a));
const getRandomSymbol = (): string => randomToSymbol(getRandom());
const wait = (ms: number) => new Promise(res => setTimeout(res, ms))
/** main program class and types */
type NumRange = {
position: number,
length: number
}
type SymbolUnit = {
symbol: string,
isNum: boolean
}
class RandomString {
numberCount = 0;
symbolCount = 0;
symbols: Array<SymbolUnit> = []
numberRanges: Array<NumRange> = []
constructor(len: number) {
for (let x = 0; x < len; x++) {
const symbol = getRandomSymbol();
const isNum = !isNaN(parseInt(symbol))
this.symbols.push({
symbol,
isNum
});
isNum ? this.numberCount++ : this.symbolCount++
}
}
replaceSymbols(char: string) {
this.symbols.forEach(x => { if (!x.isNum) x.symbol = char })
}
replaceNums(char: string) {
this.symbols.forEach(x => { if (x.isNum) x.symbol = char })
}
getString(): string {
return this.symbols.map(x => x.symbol).join('')
}
getStrLengt() {
return { symbols: this.symbolCount, nums: this.numberCount }
}
}
const sourceBanner = document.querySelector('.source-string')
const repl1Banner = document.querySelector('.repl-1')
const repl2Banner = document.querySelector('.repl-2')
const numBn = document.querySelector('.num-bn')
const reset = () => [sourceBanner, repl1Banner, repl2Banner, numBn].forEach(el => el!.innerHTML = '')
const start = async () => {
reset()
const len = window.prompt('Введите длину строки')
if (!len || isNaN(parseInt(len))) {
alert('Неверный ввод !')
return
}
const rnd = new RandomString(parseInt(len))
sourceBanner!.innerHTML = rnd.getString()
await wait(1000)
const repl1 = window.prompt('Введите первый символ для замены!')
if (!repl1 || repl1.length > 1) {
alert('Неверный ввод !')
return
}
rnd.replaceSymbols(repl1)
repl1Banner!.innerHTML = rnd.getString()
await wait(1000)
const repl2 = window.prompt('Введите второй символ для замены!')
if (!repl2 || repl2.length > 1) {
alert('Неверный ввод !')
return
}
rnd.replaceNums(repl2)
repl2Banner!.innerHTML = rnd.getString()
await wait(500)
const counters = rnd.getStrLengt()
numBn!.innerHTML = `Количество символов: ${counters.symbols} и ${counters.nums}`
}
const main = () => {
document.querySelector('.start-btn')!.addEventListener('click', start)
}
main()
|
bbc06566f6fffb8b22039ca504d0d8627be248ca
|
TypeScript
|
Subhashsab34/three.ts
|
/src/core/Face3.ts
| 3.046875
| 3
|
import { Color } from '../math/Color';
import { Vector3 } from '../math/Vector3';
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
export class Face3 {
a : number;
b : number;
c : number;
_id : number;
normal : Vector3;
vertexNormals : Array<Vector3>;
color : Color;
vertexColors : Array<Color>;
materialIndex : number;
constructor( a? : number, b? : number, c? : number, normal? : Vector3 | Array<Vector3>, color? : Color | Array<Color>, materialIndex : number = 0 ){
this.a = a;
this.b = b;
this.c = c;
this.normal = ( normal && (normal as Vector3).isVector3 ) ? normal as Vector3 : new Vector3();
this.vertexNormals = Array.isArray( normal ) ? normal : [];
this.color = ( color && (color as Color).isColor ) ? color as Color : new Color();
this.vertexColors = Array.isArray( color ) ? color : [];
this.materialIndex = materialIndex;
}
clone () : Face3 {
return new Face3().copy( this );
}
copy ( source : Face3 ) : Face3 {
this.a = source.a;
this.b = source.b;
this.c = source.c;
this.normal.copy( source.normal );
this.color.copy( source.color );
this.materialIndex = source.materialIndex;
for ( let i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
}
for ( let i = 0, il = source.vertexColors.length; i < il; i ++ ) {
this.vertexColors[ i ] = source.vertexColors[ i ].clone();
}
return this;
}
}
|
2acd31f19a5f7bc7cab4912e161371e4c23c104f
|
TypeScript
|
volsu-infosystem/service-schedule
|
/backend/src/profile/dto/create-profile-base.dto.ts
| 2.609375
| 3
|
import {
IsEmail,
IsNumber,
IsOptional,
IsString,
Length,
} from 'class-validator';
export class CreateProfileBaseDto {
@IsOptional()
@IsString()
@Length(2, 64)
readonly firstName?: string;
@IsOptional()
@IsString()
@Length(2, 64)
readonly lastName?: string;
@IsOptional()
@IsString()
@Length(2, 64)
readonly middleName?: string;
@IsOptional()
@IsEmail()
@Length(0, 256)
readonly email: string;
@IsOptional()
@IsNumber()
readonly userId?: number;
}
|
b576e8ecfaccd5d65f84cb0631e4c247126a91e6
|
TypeScript
|
ebkr/r2modmanPlus
|
/src/providers/generic/zip/ZipProvider.ts
| 2.546875
| 3
|
import ProviderUtils from '../ProviderUtils';
import ZipBuilder from './ZipBuilder';
import ZipEntryInterface from './ZipEntryInterface';
export default abstract class ZipProvider {
private static provider: () => ZipProvider;
static provide(provided: () => ZipProvider): void {
this.provider = provided;
}
public static get instance(): ZipProvider {
if (ZipProvider.provider === undefined) {
ProviderUtils.throwNotProvidedError("ZipProvider");
}
return ZipProvider.provider();
}
public abstract extractAllTo(zip: string | Buffer, outputFolder: string): Promise<void>;
public abstract readFile(zip: string | Buffer, file: string): Promise<Buffer | null>;
public abstract getEntries(zip: string | Buffer): Promise<ZipEntryInterface[]>;
public abstract extractEntryTo(zip: string | Buffer, target: string, outputPath: string): Promise<void>;
public abstract zipBuilder(): ZipBuilder;
}
|
81c1e66edfb89d2871a924696649d3efbd669867
|
TypeScript
|
JordanCervantes/redditclone
|
/src/resolvers/hello.ts
| 2.71875
| 3
|
import { Resolver, Query } from "type-graphql";
@Resolver()
export class HelloResolver{
@Query(() => String)
hello(){
return "hello world"
}
@Query(() => String)
bye(){
return "good bye"
}
@Query(() => String)
shaka(){
let shaka = 'shaka breh';
return shaka;
}
}
|
3ad821833428795f62cd6c559adb9442c09144b4
|
TypeScript
|
scen98/online-ujsag
|
/amp/js/objects/article.ts
| 2.640625
| 3
|
import * as caller from "./caller.js";
import * as ti from "./tokenInstance.js";
export class Article {
id: number;
title: string;
lead: string;
authorId: number;
date: Date;
imgPath: string;
columnId: number;
text: string;
isLocked: boolean;
lockedBy: number;
state: number;
authorName: string;
tokenInstances: ti.TokenInstance[];
constructor(id:number, title:string, lead:string, authorId:number, date:Date, imgPath:string, columnId:number, text?:string, isLocked?:boolean, lockedBy?:number, state?:number, authorName?:string, tokenInstances?: ti.TokenInstance[]){
this.id = id;
this.title = title;
this.lead = lead;
this.authorId = authorId;
this.date = date;
this.imgPath = imgPath;
this.columnId = columnId;
this.text = text;
this.isLocked = isLocked;
this.lockedBy = lockedBy;
this.state = state;
this.authorName = authorName;
this.tokenInstances = tokenInstances;
}
async insert(){
let newIdRaw = await caller.POSTAsynch("../amp/includes/requests/insertarticle.php", this);
this.id = JSON.parse(newIdRaw).newId;
}
async update(): Promise<Boolean>{
let response = await caller.POSTAsynch("../amp/includes/requests/updatearticle.php", this);
return caller.IsSuccessful(response);
}
async delete(): Promise<Boolean>{
let response = await caller.POSTAsynch("../amp/includes/requests/deletearticle.php", this);
return caller.IsSuccessful(response);
}
async switchLock(authorId:number): Promise<Boolean>{
invertLock(this, authorId);
let response: string;
if(this.isLocked){
response = await caller.POSTAsynch("../amp/includes/requests/lockarticle.php", this);
} else {
response = await caller.POSTAsynch("../amp/includes/requests/unlockarticle.php", this);
}
if(JSON.parse(response).msg === "success"){
return true;
} else if(JSON.parse(response).msg === "fail"){
alert("Ezt a cikket már egy másik felhasználó zárolta.")
return false;
} else{
invertLock(this, authorId);
console.log(response);
return false;
}
}
async updateState(){
let data = {
id: this.id,
state: this.state,
columnId: this.columnId
}
let response = await caller.POSTAsynch("../amp/includes/requests/updatearticlestate.php", data);
return caller.IsSuccessful(response);
}
hasTokenInstance(token): Boolean{
if(this.tokenInstances == null){
return false;
}
return this.tokenInstances.some(ti => ti.tokenId === token.id);
}
hasAllTokenInstances(necessaryTokens): Boolean{
return necessaryTokens.every(t=> this.hasTokenInstance(t));
}
}
export function invertLock(article: Article, authorId:number){
if(!article.isLocked){
article.isLocked = true;
article.lockedBy = authorId;
} else {
article.isLocked = false;
}
}
export async function selectArticle(articleId:number): Promise<Article>{
let data = {
id: articleId
}
let response = await caller.POSTAsynch("../amp/includes/requests/selectarticle.php", data);
return constrFromJSON(response);
}
export async function selectArticles(articleIdArray:number[]): Promise<Article[]>{
let data = {
ids: articleIdArray
}
let response = await caller.POSTAsynch("../amp/includes/requests/selectarticles.php", data);
return parseArray(response);
}
export async function selectByAuthorId(authorId: number, keyword:string, state: number, columnId: number, limit:number, offset:number): Promise<Article[]>{
let data = {
authorId: authorId,
keyword: keyword,
limit: limit,
offset: offset,
state: state,
columnId: columnId
}
let response = await caller.POSTAsynch("../amp/includes/requests/selectarticlesbyauthor.php", data);
return parseArray(response);
}
export async function selectArticlesByState(keyword:string, limit:number, offset:number, columnId:number, state:number): Promise<Article[]>{
let data = {
keyword: keyword,
limit: limit,
offset: offset,
columnId: columnId,
state: state
}
let response = await caller.POSTAsynch("../amp/includes/requests/selectarticlesbystate.php", data);
try{
return parseArray(response);
}catch(err){
console.log(err);
console.log(response);
return [];
}
}
function parseArray(json: string):Article[]{
let articleArray = Array();
for (let art of JSON.parse(json).articles) {
let newArticle = new Article(art.id, art.title, art.lead, art.authorId, new Date(art.date), art.imgP,art.columnId, art.text, art.isLocked == 1, art.lockedBy, art.state, art.authorName, ti.constrArray(art.tokenInstances));
articleArray.push(newArticle);
}
return articleArray;
}
export function constrFromJSON(json: string):Article{
let art = JSON.parse(json).article;
let article = new Article(art.id, art.title, art.lead, art.authorId, new Date(art.date), art.imgPath, art.columnId, art.text, art.isLocked == 1, art.lockedBy, art.state, art.authorName);
if(art.state > 0 && art.tokenInstances != null && art.tokenInstances.length > 0){ //asd //???
article.tokenInstances = ti.constrArray(art.tokenInstances);
} else {
article.tokenInstances = [];
}
return article;
}
|
871fdced2add925e229f4e294f9faaecc5180a28
|
TypeScript
|
EnzoDiazDev/discord-interactions
|
/src/interactions/CommandInteractionData.ts
| 2.578125
| 3
|
import ComponentType from "./ComponentType";
export default interface CommandInteractionData {
/** The ID of the invoked command */
id:string;
/** The name of the invoked command */
name:string;
/** Converted users + roles + channels */
resolved?:object;
/** The params + values from the user */
options?:object;
/** For components, the `custom_id` of the component */
custom_id:string;
/** For components, the type of the component */
component_type: ComponentType;
}
|
fec020ffb60774260599e412b196c92dad1b663a
|
TypeScript
|
hyunouknam/congressional-district-generator
|
/frontend/src/models/geometry.ts
| 2.765625
| 3
|
import * as L from 'leaflet';
import * as Topo from 'topojson-client';
// Holds all objects that have unique ids, as well as a few extra mappings
//
// NOTE: this shouldn't be accessed directly outside of geometry.ts, should be accessed from maphandler instead
//
// NOTE: maphandler will initialize this when map data is ready,
// therefore anyone accessing it before then will get errors
export let Repo: {
states: Map<string, MasterState>,
districts: Map<string, MasterDistrict>,
precincts: Map<string, MasterPrecinct>,
//map from layer to the District,precinct, etc, it refers to
layers: Map<L.Layer, GeoRegion>,
} = {} as any;
//TODO TEMP DEBUG
(window as any).R = Repo;
// =================================================================
// A TREATISE ON THE INSTANTIATION OF THE FOLLOWING OBJECTS:
//
// All of the following should only ever be created by the loadFromJson methods
// Furthermore, they should only every be created in the following way:
//
// MasterStates are loaded from initialdata json + corresponding StateTopoJson
// this initializes masterdistricts, masterprecincts, defaultmap, districts4map
// also adds all of them to repo
//
// =========== Define all json formats
//
export type GeoJson = any;
//TODO: outdated?
export type GeoDataJson = {
geometry: GeoJson;
population: number;
average_democrat_votes: number;
}
export type PrecinctTopoEntry = {
id: string;
properties: {
name: string;
population: number;
average_democrat_votes: number;
}
}
export type MasterDistrictJson = {
name: string;
id: string;
}
export type MasterStateJson = {
name: string;
id: string;
districts: MasterDistrictJson[];
default_map: StateMapJson;
}
export type StateMapJson = { [dist_Id:string]: string[]}
export type StateTopoJson = {
type: "Topology";
objects: {
precincts: {
type: "GeometryCollection";
geometries: Array<PrecinctTopoEntry>;
}
}
arcs: any[];
bbox?: any;
transform?: any;
}
// =============== Classes
export interface GeoRegion {
readonly geometry: GeoJson;
readonly layer: L.Polygon;
readonly name: string;
readonly population: number;
readonly average_democrat_votes: number;
}
export class MasterPrecinct implements GeoRegion{
private constructor(
public readonly name: string,
public readonly id: string,
public readonly state: MasterState,
public readonly topoJsonEntry: PrecinctTopoEntry ) {
}
public static loadFromJson(json: PrecinctTopoEntry, state: MasterState){
const mp = new MasterPrecinct(json.properties.name, json.id, state, json);
Repo.precincts.set(mp.id, mp);
//const layer = GeoJsonToPolygon(mp.data.geometry);
//mp.data.layer = layer;
//Repo.layers.set(layer, mp)
return mp;
}
private cache_layer: L.Polygon|null = null;
private cache_geometry: GeoJson|null = null;
get geometry() { this.cache_geometry = this.cache_geometry ||
Topo.feature(this.state.topo as any, this.topoJsonEntry as any);
return this.cache_geometry;}
get layer() {
if(this.cache_layer==null) {
this.cache_layer = GeoJsonToPolygon(this.geometry);
Repo.layers.set(this.cache_layer, this);
}
return this.cache_layer;
}
get population() { return this.topoJsonEntry.properties.population; }
get average_democrat_votes() { return this.topoJsonEntry.properties.average_democrat_votes; }
}
export class MasterDistrict {
private constructor(
public readonly name: string,
public readonly id: string,
public readonly state: MasterState,) {
}
public static loadFromInitialJson(json: MasterDistrictJson, state:MasterState){
const md = new MasterDistrict(json.name, json.id, state);
Repo.districts.set(md.id, md);
return md;
}
}
export class MasterState implements GeoRegion{
public districts: MasterDistrict[] = [];
public precincts: MasterPrecinct[] = [];
public defaultMap: StateMap;
public topo: StateTopoJson;
private constructor(public name: string, public id: string) {
}
public static loadFromInitialJson(json: MasterStateJson, topo: StateTopoJson) {
let ms = new MasterState(json.name, json.id);
ms.topo = topo;
Repo.states.set(ms.id, ms);
//add all districts
json.districts.forEach(distJson => {
let md = MasterDistrict.loadFromInitialJson(distJson, ms);
ms.districts.push(md)
})
//add all precincts
topo.objects.precincts.geometries.forEach(geom => {
const mp = MasterPrecinct.loadFromJson(geom, ms);
ms.precincts.push(mp);
});
//add defaultMap
let map = StateMap.loadFromJson(json.default_map,ms);
ms.defaultMap = map;
return ms;
}
public toString() {
return `<MasterDistrict: ${this.name}, ${this.id}, Districts:
${this.districts.length} of them
>`
}
// ================= GeoRegion implementation
private cache_layer: L.Polygon|null = null;
private cache_geometry: GeoJson|null = null;
get geometry() {
if(this.cache_geometry == null) {
const prec_geoms = this.precincts.map(mp => mp.topoJsonEntry);
this.cache_geometry = Topo.merge(this.topo as any, prec_geoms as any);
}
return this.cache_geometry;
}
get layer() {
if(this.cache_layer==null) {
this.cache_layer = GeoJsonToPolygon(this.geometry);
Repo.layers.set(this.cache_layer, this);
}
return this.cache_layer;
}
get population() {
let sum = 0;
this.precincts.forEach(prec => {
sum += prec.population;
});
return sum;
}
get average_democrat_votes() {
let total = 0;
let totalDem = 0;
this.precincts.forEach(prec => {
totalDem += prec.population * prec.average_democrat_votes;
total += prec.population;
});
return totalDem / total; }
}
export class DistrictForMap implements GeoRegion{
public constructor(
public readonly map: StateMap,
public readonly id: string, ) { //note, masterDistrict data is only initial data
}
get master():MasterDistrict { return Repo.districts.get(this.id)!; }
//discards cached stuff
public dirty() {
throw Error("Dist4Map Dirty() not implemented")
}
// ================= GeoRegion implementation
private cache_layer: L.Polygon|null = null;
private cache_geometry: GeoJson|null = null;
get geometry() {
if(this.cache_geometry == null) {
const prec_geoms: PrecinctTopoEntry[] = [];
this.map.d_p_get(this.id)!.forEach(pId => {
prec_geoms.push(Repo.precincts.get(pId)!.topoJsonEntry);
});
this.cache_geometry = Topo.merge(this.master.state.topo as any, prec_geoms as any);
}
return this.cache_geometry;
}
get layer() {
if(this.cache_layer==null) {
this.cache_layer = GeoJsonToPolygon(this.geometry);
Repo.layers.set(this.cache_layer, this);
}
return this.cache_layer;
}
get name() { return this.master.name}
get population() {
let sum = 0;
this.map.d_p_get(this.id)!.forEach(pId => {
sum += (Repo.precincts.get(pId)!.population);
});
return sum; }
get average_democrat_votes() {
let total = 0;
let totalDem = 0;
this.map.d_p_get(this.id)!.forEach(pId => {
const prec = Repo.precincts.get(pId)!;
totalDem += prec.population * prec.average_democrat_votes;
total += prec.population;
});
return totalDem / total; }
}
//StateMap can only be made
export class StateMap {
//TODO: we should get a null district from the server
//precinctid to districtid
private p_d_map = new Map<string, string>();
//districtid to precinctid[]
private d_p_map = new Map<string, Set<string>>();
//districtid to districtformap
public districts4map = new Map<string, DistrictForMap>();
//constructor starts by setting all precincts to null district
public constructor(public readonly state: MasterState) {
state.precincts.forEach(mp => {
this.p_d_map.set(mp.id, "NULL");
});
state.districts.forEach(md => {
this.d_p_map.set(md.id, new Set());
})
this.d_p_map.set("NULL", new Set(state.precincts.map(mp => mp.id)));
}
public static loadFromJson(json: StateMapJson, state: MasterState){
const map = new StateMap(state);
//Assing precincts from mapping
for(const distId of Object.keys(json)) {
for(const precId of json[distId]) {
map.set_p_d(precId,distId);
} }
//Make district4map objects
for(const distId of Object.keys(json)) {
map.districts4map.set(distId, new DistrictForMap(map, distId));
//this.districts4map.set(md.id, new DistrictForMap(this, md.id, md.data));
}
return map;
}
//assigns prec to specified district
public set_p_d(pId:string, dId: string) {
if(!(this.p_d_map.has(pId) && this.d_p_map.has(dId))){
throw Error(`Invalid precint or district ids: '${pId}', '${dId}'`);
}
const oldD = this.p_d_map.get(pId);
//move precinct from old dist to new
this.d_p_map.get(oldD!)!.delete(pId);
this.d_p_map.get(dId)!.add(pId);
//assign prec to dist
this.p_d_map.set(pId, dId);
//dirty all affected districts TODO, NOT YET IMPLEMENTED SAFELY
const d4m_old = this.districts4map.get(oldD!);
const d4m_new = this.districts4map.get(dId);
d4m_old && d4m_old.dirty();
d4m_new && d4m_new.dirty();
}
public d_p_get(dId: string) { return this.d_p_map.get(dId); }
public p_d_get(pId: string) { return this.p_d_map.get(pId); }
public toString() {
const vals: { [s:string]: string[]} = {};
for (const [dId, precincts] of this.d_p_map.entries()) {
vals[dId] = Array.from(precincts)
}
const s = `Map for ${this.state.id} {` +
JSON.stringify(vals) + "\n}\n";
//test that both mapping match up
for(const [dId, v] of this.d_p_map.entries()) {
for(const pId of v) {
const dId2 = this.p_d_map.get(pId);
if(dId2 != dId){
console.error(s);
throw Error(`StateMap mismatch error: p<${pId}> is in both d<${dId}> and d<${dId2}>`);
} } }
return s;
}
}
//takes a geojson polygon or multipolygon and returns a leaflet polygon layer
function GeoJsonToPolygon(g: any): L.Polygon {
if(g.type == "Polygon"){
g.coordinates.forEach((ring:Array<number[]>) => {
ring.forEach(coord => {
coord.reverse()
});
});
} else if (g.type == "MultiPolygon") {
g.coordinates.forEach((polygon:Array<Array<number[]>>) => {
polygon.forEach(ring => {
ring.forEach(coord => {
coord.reverse()
});
});
});
} else if (g.type == "Feature") {
return GeoJsonToPolygon(g.geometry);
} else {
throw Error("geometry is not polygonal: \n" + JSON.stringify(g));
}
return new L.Polygon(g.coordinates);
}
|
08687b332fa55566d2731798214c7214af8c82b4
|
TypeScript
|
alfie1104/nuber-eats-backend
|
/src/users/users.service.spec.ts
| 2.75
| 3
|
import { Test } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Verification } from 'src/common/entities/verification.entity';
import { JwtService } from 'src/jwt/jwt.service';
import { MailService } from 'src/mail/mail.service';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { UserService } from './users.service';
/*
[Mocking]
UserService에서 사용되는 Repository를 Mock Repository를 이용하여 제공
Mock은 fake implementation of function, class임. 즉 가짜 repository를 생성
이런걸 Mocking이라고 함
jest.fn() : mock function을 생성함 (가짜 함수)
*/
const mockRepository = () => ({
findOne: jest.fn(),
save: jest.fn(),
create: jest.fn(),
findOneOrFail: jest.fn(),
delete: jest.fn(),
});
const mockJwtService = () => ({
sign: jest.fn(() => 'signed-token'),
verify: jest.fn(),
});
const mockMailService = () => ({
sendVerificationEmail: jest.fn(),
});
/*
//Record<K, T> : Construct a type with a set of properties K(Key) of type T(Type). 타입 T를 갖는 요소 K의 집합
//Partial : 모든 속성을 optional로 만듬
//keyof : 모든 key를 가져옴 (typescript에서 사용 가능)
아래 type MockReposoitory는 Repository의 모든 함수를 뜻하는데 각 함수들의 타입을 jest.Mock으로 설정한 것임(가짜 함수)
*/
type MockRepository<T = any> = Partial<
Record<keyof Repository<User>, jest.Mock>
>;
describe('UserService', () => {
let service: UserService;
let usersRepository: MockRepository<User>;
let verificationRepository: MockRepository<Verification>;
let mailService: MailService;
let jwtService: JwtService;
/*
[beforeEach]
일반적으로 unit test를 할 때에는 beforeEach를 쓰고(각 모듈에서 메모리를 공유하는 것 방지)
그래야 검사하려는 로직에서 특정 함수가 몇번 호출되었는지 정확히 파악가능
[beforeAll]
end-to-end test를 할때 사용
*/
beforeEach(async () => {
//테스트를 시작하기 전 UserService를 제공하는 테스팅 모듈 생성
const module = await Test.createTestingModule({
providers: [
UserService,
{
provide: getRepositoryToken(User),
useValue: mockRepository(),
},
{
provide: getRepositoryToken(Verification),
useValue: mockRepository(),
},
{
provide: JwtService,
useValue: mockJwtService(),
},
{
provide: MailService,
useValue: mockMailService(),
},
],
}).compile();
service = module.get<UserService>(UserService);
mailService = module.get<MailService>(MailService);
jwtService = module.get<JwtService>(JwtService);
usersRepository = module.get(getRepositoryToken(User));
verificationRepository = module.get(getRepositoryToken(Verification));
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('createAccount', () => {
const createAccountArgs = {
email: '',
password: '',
role: 0,
};
it('should fail if user exists', async () => {
/*
[mockResolvedValue, mockReturnValue]
원래는 usersRepository의 findOne은 DB를 검색하게 되지만,
jest의 mock을 이용한 가짜함수덕분에 findOne의 반환값을 속일 수 있음.(DB 사용 X)
mock을 사용하면 실제 코드의 특정 부분(본 코드의 경우 usersRepository.findOne 함수)을 mock함수로 대체해서 구동시키게 됨
즉, createAccount 자체의 로직 검사에만 집중가능
(DB 접근과 같이 다른 함수에 의존되는 부분은 모두 mock함수로 대체해서 createAccount를 속이게됨)
*/
usersRepository.findOne.mockResolvedValue({
id: 1,
email: '',
}); //createAccount를 속이기위해 가짜 유저 형태를 생성
const result = await service.createAccount(createAccountArgs);
expect(result).toMatchObject({
ok: false,
error: 'There is a user with that email already',
});
});
it('should create a new user', async () => {
usersRepository.findOne.mockResolvedValue(undefined); //Promise를 return하므로 mockResolvedValue를 이용하여 반환값을 mocking함
usersRepository.create.mockReturnValue(createAccountArgs);
usersRepository.save.mockResolvedValue(createAccountArgs);
verificationRepository.create.mockReturnValue({
user: createAccountArgs,
});
verificationRepository.save.mockResolvedValue({
code: 'code',
});
const result = await service.createAccount(createAccountArgs);
expect(usersRepository.create).toHaveBeenCalledTimes(1);
expect(usersRepository.create).toHaveBeenCalledWith(createAccountArgs);
expect(usersRepository.save).toHaveBeenCalledTimes(1);
expect(usersRepository.save).toHaveBeenCalledWith(createAccountArgs);
expect(verificationRepository.create).toHaveBeenCalledTimes(1);
expect(verificationRepository.create).toHaveBeenCalledWith({
user: createAccountArgs,
});
expect(verificationRepository.save).toHaveBeenCalledTimes(1);
expect(verificationRepository.save).toHaveBeenCalledWith({
user: createAccountArgs,
});
expect(mailService.sendVerificationEmail).toHaveBeenCalledTimes(1);
expect(mailService.sendVerificationEmail).toHaveBeenCalledWith(
expect.any(String),
expect.any(String),
);
expect(result).toEqual({ ok: true });
});
it('should fail on exception', async () => {
usersRepository.findOne.mockRejectedValue(new Error(''));
const result = await service.createAccount(createAccountArgs);
expect(result).toEqual({ ok: false, error: "Couldn't create account" });
});
});
describe('login', () => {
const loginArgs = {
email: 'bs@email.com',
password: 'bs.password',
};
it('should fail if user does not exist', async () => {
usersRepository.findOne.mockResolvedValue(null);
const result = await service.login(loginArgs);
expect(usersRepository.findOne).toHaveBeenCalledTimes(1);
expect(usersRepository.findOne).toHaveBeenCalledWith(
expect.any(Object),
expect.any(Object),
);
expect(result).toEqual({
ok: false,
error: 'User not found',
});
});
it('should fail if the password is wrong', async () => {
//jest.fn(()=> Promise.resolve(false)) : promise를 return하는 mock function이고 해당 promise는 최종적으로 false값을 보냄
// 즉, 패스워드 체크를 틀린것으로 설정
const mockedUser = {
id: 1,
checkPassword: jest.fn(() => Promise.resolve(false)),
};
usersRepository.findOne.mockResolvedValue(mockedUser);
const result = await service.login(loginArgs);
expect(result).toEqual({ ok: false, error: 'Wrong password' });
});
it('should return token if password correct', async () => {
const mockedUser = {
id: 1,
checkPassword: jest.fn(() => Promise.resolve(true)),
};
usersRepository.findOne.mockResolvedValue(mockedUser);
const result = await service.login(loginArgs);
expect(jwtService.sign).toHaveBeenCalledTimes(1);
expect(jwtService.sign).toHaveBeenCalledWith(expect.any(Number));
expect(result).toEqual({ ok: true, token: 'signed-token' });
});
it.todo('shuld fail on error');
});
describe('findById', () => {
const findByArgs = {
id: 1,
};
it('should find an existing user', async () => {
usersRepository.findOneOrFail.mockResolvedValue(findByArgs);
const result = await service.findById(1);
expect(result).toEqual({
ok: true,
user: findByArgs,
});
});
it('should fail if no user is found', async () => {
usersRepository.findOneOrFail.mockRejectedValue(new Error());
const result = await service.findById(1);
expect(result).toEqual({ ok: false, error: 'User Not Found' });
});
});
describe('editProfile', () => {
it('should change email', async () => {
const oldUser = {
email: 'bs@old.com',
verified: true,
};
const editProfileArgs = {
userId: 1,
input: { email: 'bs@new.com' },
};
const newVerification = {
code: 'code',
};
const newUser = {
verified: false,
email: editProfileArgs.input.email,
};
usersRepository.findOne.mockResolvedValue(oldUser);
verificationRepository.create.mockReturnValue(newVerification);
verificationRepository.save.mockResolvedValue(newVerification);
await service.editProfile(editProfileArgs.userId, editProfileArgs.input);
expect(usersRepository.findOne).toHaveBeenCalledTimes(1);
expect(usersRepository.findOne).toHaveBeenCalledWith(
editProfileArgs.userId,
);
expect(verificationRepository.create).toHaveBeenCalledWith({
user: newUser,
});
expect(verificationRepository.save).toHaveBeenCalledWith(newVerification);
expect(mailService.sendVerificationEmail).toHaveBeenCalledWith(
newUser.email,
newVerification.code,
);
});
it('should change password', async () => {
const editProfileArgs = {
userId: 1,
input: { password: 'new.password' },
};
usersRepository.findOne.mockResolvedValue({ password: 'old' });
const result = await service.editProfile(
editProfileArgs.userId,
editProfileArgs.input,
);
expect(usersRepository.save).toHaveBeenCalledTimes(1);
expect(usersRepository.save).toHaveBeenCalledWith(editProfileArgs.input);
expect(result).toEqual({ ok: true });
});
it('should fail on exception', async () => {
usersRepository.findOne.mockRejectedValue(new Error());
const result = await service.editProfile(1, { email: '12' });
expect(result).toEqual({
ok: false,
error: 'Could not update profile.',
});
});
});
describe('verifyEmail', () => {
it('should verify email', async () => {
const mockedVerification = {
user: {
verified: false,
},
id: 1,
};
verificationRepository.findOne.mockResolvedValue(mockedVerification);
const result = await service.verifyEmail('');
expect(verificationRepository.findOne).toHaveBeenCalledTimes(1);
expect(verificationRepository.findOne).toHaveBeenCalledWith(
expect.any(Object),
expect.any(Object),
);
expect(usersRepository.save).toHaveBeenCalledTimes(1);
expect(usersRepository.save).toHaveBeenCalledWith({ verified: true });
expect(verificationRepository.delete).toHaveBeenCalledTimes(1);
expect(verificationRepository.delete).toHaveBeenCalledWith(
mockedVerification.id,
);
expect(result).toEqual({ ok: true });
});
it('should fail on verification not found', async () => {
verificationRepository.findOne.mockResolvedValue(undefined);
const result = await service.verifyEmail('');
expect(result).toEqual({ ok: false, error: 'Verification not found.' });
});
it('should fail on exception', async () => {
verificationRepository.findOne.mockRejectedValue(new Error());
const result = await service.verifyEmail('');
expect(result).toEqual({ ok: false, error: 'Could not verify email' });
});
});
});
|
f95cd2947feee7e4f18a63a7111efdf86104eb9d
|
TypeScript
|
yannduran/tripod
|
/Tripod.Web/app/_common/directives/ModelContrib.ts
| 2.515625
| 3
|
'use strict';
module App.Directives.ModelContrib {
export var directiveName = 'modelContrib';
export class Controller {
hasError = false;
hasSuccess = false;
hasSpinner = false;
error: any = {};
ngModelController: ng.INgModelController;
static $inject = ['$scope'];
constructor(scope: ng.IScope) { }
setValidity(validationErrorKey: string, validationErrorMessage: string): void {
this.ngModelController.$setValidity(validationErrorKey, validationErrorMessage ? false : true);
this.error[validationErrorKey] = validationErrorMessage;
this.hasSpinner = false;
}
spinnerCssClass(): string {
return this.hasSpinner ? 'has-spinner' : null;
}
errorCssClass(): string {
return this.hasError ? 'has-error' : null;
}
successCssClass(): string {
return this.hasSuccess ? 'has-success' : null;
}
hasFeedback(): boolean {
return this.hasError || this.hasSuccess || this.hasSpinner;
}
feedbackCssClass(): string {
if (this.hasSpinner) return this.spinnerCssClass();
if (this.hasError) return this.errorCssClass();
if (this.hasSuccess) return this.successCssClass();
return null;
}
inputGroupCssClass(size?: string): string {
if (!this.hasFeedback()) return null;
var cssClass = 'input-group';
if (size) cssClass += ' input-group-' + size;
return cssClass;
}
}
//#region Directive
var directiveFactory = (): () => ng.IDirective => {
return (): ng.IDirective => {
var d: ng.IDirective = {
name: directiveName,
restrict: 'A', // attribute only
require: [directiveName, 'ngModel', '^formContrib'],
controller: Controller,
compile: (): any => {
return {
pre: (scope: ng.IScope, element: JQuery, attr: ng.IAttributes, ctrls: any[]): void => {
// get the required controllers based on directive order
var modelContribCtrl: Controller = ctrls[0];
var modelCtrl: ng.INgModelController = ctrls[1];
var formContribCtrl: FormContrib.Controller = ctrls[2];
modelContribCtrl.ngModelController = modelCtrl;
// put this contrib controller on the scope
var alias = $.trim(attr['name']);
if (alias) formContribCtrl[alias] = modelContribCtrl;
},
post: (scope: ng.IScope, element: JQuery, attr: ng.IAttributes, ctrls: any[]): void => {
// get the required controllers based on directive order
var modelContribCtrl: Controller = ctrls[0];
var modelCtrl: ng.INgModelController = ctrls[1];
var formContribCtrl: FormContrib.Controller = ctrls[2];
// watch for form submissions, dirtiness, validity, and spinner
scope.$watch(
(): any[]=> {
return [modelCtrl.$valid, modelCtrl.$dirty, formContribCtrl.isSubmitAttempted, modelContribCtrl.hasSpinner];
},
(): void => {
// set error or success on model contrib controller
var isDirtyOrSubmitAttempted = modelCtrl.$dirty || formContribCtrl.isSubmitAttempted;
modelContribCtrl.hasError = !modelContribCtrl.hasSpinner && modelCtrl.$invalid && isDirtyOrSubmitAttempted;
modelContribCtrl.hasSuccess = !modelContribCtrl.hasSpinner && modelCtrl.$valid && isDirtyOrSubmitAttempted;
}, true);
},
};
},
};
return d;
};
};
//#endregion
export var directive = directiveFactory();
}
|
788110f77b086b932d2daf93737b386869e7725e
|
TypeScript
|
dmytrolyn/mmorpg-next-client
|
/store/profile/spenders/spenders.actions.ts
| 2.640625
| 3
|
import { SpenderSchema } from 'utils/contentTypes'
import Types, { SpenderErrorType } from './spenders.types'
interface SetSpendersAction {
type: Types.SET_SPENDERS
data: Array<SpenderSchema>
}
export const setSpendersData = (data: Array<SpenderSchema>): SetSpendersAction => ({
type: Types.SET_SPENDERS,
data
})
interface GetSpenderRewardAction {
readonly type: Types.GET_SPENDER_REWARD
id: number
level: number
}
export const getSpenderReward = (id: number, level: number): GetSpenderRewardAction => ({
type: Types.GET_SPENDER_REWARD,
id,
level
})
interface IncreaseSpenderStatusAction {
readonly type: Types.INCREASE_SPENDERS_STATUS
value: number
}
export const increaseSpendersStatus = (value: number): IncreaseSpenderStatusAction => ({
type: Types.INCREASE_SPENDERS_STATUS,
value
})
interface SpenderLoadingAction {
readonly type: Types.SET_SPENDER_LOADING
SpenderID: number
level: number
status: boolean
}
export const spenderRewardLoading = (SpenderID: number, level: number, status: boolean): SpenderLoadingAction => ({
type: Types.SET_SPENDER_LOADING,
SpenderID,
level,
status
})
interface SpenderErrorAction {
readonly type: Types.SET_SPENDER_ERROR
error: SpenderErrorType
}
export const spenderRewardError = (error: SpenderErrorType): SpenderErrorAction => ({
type: Types.SET_SPENDER_ERROR,
error
})
interface GetSpenderRewardRequestAction {
type: Types.GET_SPENDER_REWARD_REQUEST
SpenderID: number,
Level: number
RowID: number
}
export const getSpenderRewardRequest = (SpenderID: number, Level: number, RowID: number): GetSpenderRewardRequestAction => ({
type: Types.GET_SPENDER_REWARD_REQUEST,
SpenderID,
Level,
RowID
})
type SpenderActionType = GetSpenderRewardAction | IncreaseSpenderStatusAction | SpenderLoadingAction | SpenderErrorAction | SetSpendersAction
export default SpenderActionType
|
50157e1c01538009dee0804a058243e2e70bbd9c
|
TypeScript
|
700software/ts-code-generator
|
/src/tests/testHelpers/methods/class/runClassDefinitionTests.ts
| 2.5625
| 3
|
import * as assert from "assert";
import {ClassTestStructure} from "./../../testStructures";
import {ClassDefinition} from "./../../../../definitions";
import {runBaseDefinitionTests, runNamedDefinitionTests, runExportableDefinitionTests, runDecoratableDefinitionTests, runTypeParameteredDefinitionTests,
runAmbientableDefinitionTests, runAbstractableDefinitionTests, runOrderableDefinitionTests, runDocumentationedDefinitionTests} from "./../base";
import {runClassPropertyDefinitionTests} from "./runClassPropertyDefinitionTests";
import {runClassMethodDefinitionTests} from "./runClassMethodDefinitionTests";
import {runClassStaticPropertyDefinitionTests} from "./runClassStaticPropertyDefinitionTests";
import {runClassStaticMethodDefinitionTests} from "./runClassStaticMethodDefinitionTests";
import {runClassConstructorDefinitionTests} from "./runClassConstructorDefinitionTests";
import {runTypeDefinitionTests} from "./../expression";
import {ensureNotNull} from "./../../ensureNotNull";
export function runClassDefinitionTests(definition: ClassDefinition, structure: ClassTestStructure) {
describe(`class ${structure.name}`, () => {
ensureNotNull(definition, () => {
structure.methods = structure.methods || [];
structure.properties = structure.properties || [];
structure.staticMethods = structure.staticMethods || [];
structure.staticProperties = structure.staticProperties || [];
structure.extendsTypes = structure.extendsTypes || [];
structure.implementsTypes = structure.implementsTypes || [];
runBaseDefinitionTests(definition, structure);
runNamedDefinitionTests(definition, structure);
runExportableDefinitionTests(definition, structure);
runDecoratableDefinitionTests(definition, structure);
runTypeParameteredDefinitionTests(definition, structure);
runAbstractableDefinitionTests(definition, structure);
runAmbientableDefinitionTests(definition, structure);
runClassConstructorDefinitionTests(definition.constructorDef, structure.constructorDef);
runOrderableDefinitionTests(definition, structure);
runDocumentationedDefinitionTests(definition, structure);
it(`should ${structure.isAbstract ? "be" : "not be"} abstract.`, () => {
assert.equal(definition.isAbstract, structure.isAbstract || false);
});
describe("methods", () => {
it("should have the expected number of methods", () => {
assert.equal(definition.methods.length, structure.methods!.length);
});
structure.methods!.forEach((methodTestStructure, i) => {
runClassMethodDefinitionTests(definition.methods[i], methodTestStructure);
});
});
describe("properties", () => {
it("should have the expected number of properties", () => {
assert.equal(definition.properties.length, structure.properties!.length);
});
structure.properties!.forEach((propertyTestStructure, i) => {
runClassPropertyDefinitionTests(definition.properties[i], propertyTestStructure);
});
});
describe("staticMethods", () => {
it("should have the expected number of staticMethods", () => {
assert.equal(definition.staticMethods.length, structure.staticMethods!.length);
});
structure.staticMethods!.forEach((methodTestStructure, i) => {
runClassStaticMethodDefinitionTests(definition.staticMethods[i], methodTestStructure);
});
});
describe("staticProperties", () => {
it("should have the expected number of staticProperties", () => {
assert.equal(definition.staticProperties.length, structure.staticProperties!.length);
});
structure.staticProperties!.forEach((propertyTestStructure, i) => {
runClassStaticPropertyDefinitionTests(definition.staticProperties[i], propertyTestStructure);
});
});
describe("extends", () => {
it("should have the expected number of extends", () => {
assert.equal(definition.extendsTypes.length, structure.extendsTypes!.length);
});
structure.extendsTypes!.forEach((extendTestStructure, i) => {
runTypeDefinitionTests(definition.extendsTypes[i], extendTestStructure);
});
});
describe("implements", () => {
it("should have the expected number of implements", () => {
assert.equal(definition.implementsTypes.length, structure.implementsTypes!.length);
});
structure.implementsTypes!.forEach((implementTestStructure, i) => {
runTypeDefinitionTests(definition.implementsTypes[i], implementTestStructure);
});
});
});
});
}
|
10caa0e0fed2c04c059b1740a536178d02f628da
|
TypeScript
|
nilshartmann/typescript-intro
|
/.material/src_de/_variants/60_z_mapped_types.ts
| 3.5
| 4
|
export default undefined;
type Employee = {
name: string;
salary: number;
age: number;
department: string;
};
// type ValidatedEmployee = {
// [k in keyof Employee]?: boolean
// }
type ValidationResult<TYPE> = {
[k in keyof TYPE]: boolean;
};
type OptionalType<TYPE> = {
[k in keyof TYPE]?: TYPE[k];
};
type ValidatedEmployee = OptionalType<ValidationResult<Employee>>;
const susi: Employee = {
name: "Susi",
age: 32,
salary: 75000,
department: "Software Development"
};
function validateEmployee(emp: Employee): ValidatedEmployee {
console.log(emp);
// ===> what happens if we add "city: 'Hamburg'" to the returned object?
return {
name: emp.name.length > 3,
salary: emp.salary > 70000,
department: emp.name.length > 10
};
}
const validationResult = validateEmployee(susi);
showValidationResult(validationResult);
function showValidationResult(validationResult: ValidatedEmployee) {
//
}
|
f9c97467b2e2139d98951799ed9555497c388e01
|
TypeScript
|
ionic-team/ionic-v3
|
/src/components/infinite-scroll/infinite-scroll.ts
| 2.875
| 3
|
import { Directive, ElementRef, EventEmitter, Input, NgZone, Output } from '@angular/core';
import { Content, ScrollEvent } from '../content/content';
import { DomController } from '../../platform/dom-controller';
import { assert } from '../../util/util';
/**
* @name InfiniteScroll
* @description
* The Infinite Scroll allows you to perform an action when the user
* scrolls a specified distance from the bottom or top of the page.
*
* The expression assigned to the `infinite` event is called when
* the user scrolls to the specified distance. When this expression
* has finished its tasks, it should call the `complete()` method
* on the infinite scroll instance.
*
* @usage
* ```html
* <ion-content>
*
* <ion-list>
* <ion-item *ngFor="let i of items">{% raw %}{{i}}{% endraw %}</ion-item>
* </ion-list>
*
* <ion-infinite-scroll (ionInfinite)="doInfinite($event)">
* <ion-infinite-scroll-content></ion-infinite-scroll-content>
* </ion-infinite-scroll>
*
* </ion-content>
* ```
*
* ```ts
* @Component({...})
* export class NewsFeedPage {
* items = [];
*
* constructor() {
* for (let i = 0; i < 30; i++) {
* this.items.push( this.items.length );
* }
* }
*
* doInfinite(infiniteScroll) {
* console.log('Begin async operation');
*
* setTimeout(() => {
* for (let i = 0; i < 30; i++) {
* this.items.push( this.items.length );
* }
*
* console.log('Async operation has ended');
* infiniteScroll.complete();
* }, 500);
* }
*
* }
* ```
*
* ## `waitFor` method of InfiniteScroll
*
* In case if your async operation returns promise you can utilize
* `waitFor` method inside your template.
*
* ```html
* <ion-content>
*
* <ion-list>
* <ion-item *ngFor="let item of items">{{item}}</ion-item>
* </ion-list>
*
* <ion-infinite-scroll (ionInfinite)="$event.waitFor(doInfinite())">
* <ion-infinite-scroll-content></ion-infinite-scroll-content>
* </ion-infinite-scroll>
*
* </ion-content>
* ```
*
* ```ts
* @Component({...})
* export class NewsFeedPage {
* items = [];
*
* constructor() {
* for (var i = 0; i < 30; i++) {
* this.items.push( this.items.length );
* }
* }
*
* doInfinite(): Promise<any> {
* console.log('Begin async operation');
*
* return new Promise((resolve) => {
* setTimeout(() => {
* for (var i = 0; i < 30; i++) {
* this.items.push( this.items.length );
* }
*
* console.log('Async operation has ended');
* resolve();
* }, 500);
* })
* }
* }
* ```
*
* ## Infinite Scroll Content
*
* By default, Ionic uses the infinite scroll spinner that looks
* best for the platform the user is on. However, you can change the
* default spinner or add text by adding properties to the
* `ion-infinite-scroll-content` component.
*
* ```html
* <ion-content>
*
* <ion-infinite-scroll (ionInfinite)="doInfinite($event)">
* <ion-infinite-scroll-content
* loadingSpinner="bubbles"
* loadingText="Loading more data...">
* </ion-infinite-scroll-content>
* </ion-infinite-scroll>
*
* </ion-content>
* ```
*
*
* ## Further Customizing Infinite Scroll Content
*
* The `ion-infinite-scroll` component holds the infinite scroll logic.
* It requires a child component in order to display the content.
* Ionic uses `ion-infinite-scroll-content` by default. This component
* displays the infinite scroll and changes the look depending
* on the infinite scroll's state. Separating these components allows
* developers to create their own infinite scroll content components.
* You could replace our default content with custom SVG or CSS animations.
*
* @demo /docs/demos/src/infinite-scroll/
*
*/
@Directive({
selector: 'ion-infinite-scroll'
})
export class InfiniteScroll {
_lastCheck: number = 0;
_highestY: number = 0;
_scLsn: any;
_thr: string = '15%';
_thrPx: number = 0;
_thrPc: number = 0.15;
_position: string = POSITION_BOTTOM;
_init: boolean = false;
/**
* @internal
*/
state: string = STATE_ENABLED;
/**
* @input {string} The threshold distance from the bottom
* of the content to call the `infinite` output event when scrolled.
* The threshold value can be either a percent, or
* in pixels. For example, use the value of `10%` for the `infinite`
* output event to get called when the user has scrolled 10%
* from the bottom of the page. Use the value `100px` when the
* scroll is within 100 pixels from the bottom of the page.
* Default is `15%`.
*/
@Input()
get threshold(): string {
return this._thr;
}
set threshold(val: string) {
this._thr = val;
if (val.indexOf('%') > -1) {
this._thrPx = 0;
this._thrPc = (parseFloat(val) / 100);
} else {
this._thrPx = parseFloat(val);
this._thrPc = 0;
}
}
/**
* @input {boolean} If true, Whether or not the infinite scroll should be
* enabled or not. Setting to `false` will remove scroll event listeners
* and hide the display.
*/
@Input()
set enabled(shouldEnable: boolean) {
this.enable(shouldEnable);
}
/**
* @input {string} The position of the infinite scroll element.
* The value can be either `top` or `bottom`.
* Default is `bottom`.
*/
@Input()
get position(): string {
return this._position;
}
set position(val: string) {
if (val === POSITION_TOP || val === POSITION_BOTTOM) {
this._position = val;
} else {
console.error(`Invalid value for ion-infinite-scroll's position input. Its value should be '${POSITION_BOTTOM}' or '${POSITION_TOP}'.`);
}
}
/**
* @output {event} Emitted when the scroll reaches
* the threshold distance. From within your infinite handler,
* you must call the infinite scroll's `complete()` method when
* your async operation has completed.
*/
@Output() ionInfinite: EventEmitter<InfiniteScroll> = new EventEmitter<InfiniteScroll>();
constructor(
private _content: Content,
private _zone: NgZone,
private _elementRef: ElementRef,
private _dom: DomController
) {
_content.setElementClass('has-infinite-scroll', true);
}
_onScroll(ev: ScrollEvent) {
if (this.state === STATE_LOADING || this.state === STATE_DISABLED) {
return 1;
}
if (this._lastCheck + 32 > ev.timeStamp) {
// no need to check less than every XXms
return 2;
}
this._lastCheck = ev.timeStamp;
// ******** DOM READ ****************
const infiniteHeight = this._elementRef.nativeElement.scrollHeight;
if (!infiniteHeight) {
// if there is no height of this element then do nothing
return 3;
}
// ******** DOM READ ****************
const d = this._content.getContentDimensions();
const height = d.contentHeight;
const threshold = this._thrPc ? (height * this._thrPc) : this._thrPx;
// ******** DOM READS ABOVE / DOM WRITES BELOW ****************
let distanceFromInfinite: number;
if (this._position === POSITION_BOTTOM) {
distanceFromInfinite = d.scrollHeight - infiniteHeight - d.scrollTop - height - threshold;
} else {
assert(this._position === POSITION_TOP, '_position should be top');
distanceFromInfinite = d.scrollTop - infiniteHeight - threshold;
}
if (distanceFromInfinite < 0) {
// ******** DOM WRITE ****************
this._dom.write(() => {
this._zone.run(() => {
if (this.state !== STATE_LOADING && this.state !== STATE_DISABLED) {
this.state = STATE_LOADING;
this.ionInfinite.emit(this);
}
});
});
return 5;
}
return 6;
}
/**
* Call `complete()` within the `infinite` output event handler when
* your async operation has completed. For example, the `loading`
* state is while the app is performing an asynchronous operation,
* such as receiving more data from an AJAX request to add more items
* to a data list. Once the data has been received and UI updated, you
* then call this method to signify that the loading has completed.
* This method will change the infinite scroll's state from `loading`
* to `enabled`.
*/
complete() {
if (this.state !== STATE_LOADING) {
return;
}
if (this._position === POSITION_BOTTOM) {
this.state = STATE_ENABLED;
return;
}
assert(this._position === POSITION_TOP, 'position should be top');
/* New content is being added at the top, but the scrollTop position stays the same,
which causes a scroll jump visually. This algorithm makes sure to prevent this.
(Frame 1)
complete() is called, but the UI hasn't had time to update yet.
Save the current content dimensions.
Wait for the next frame using _dom.read, so the UI will be updated.
(Frame 2)
Read the new content dimensions.
Calculate the height difference and the new scroll position.
Delay the scroll position change until other possible dom reads are done using _dom.write to be performant.
(Still frame 2, if I'm correct)
Change the scroll position (= visually maintain the scroll position).
Change the state to re-enable the InfiniteScroll. This should be after changing the scroll position, or it could cause the InfiniteScroll to be triggered again immediately.
(Frame 3)
Done.
*/
// ******** DOM READ ****************
// Save the current content dimensions before the UI updates
const prevDim = this._content.getContentDimensions();
// ******** DOM READ ****************
this._dom.read(() => {
// UI has updated, save the new content dimensions
const newDim = this._content.getContentDimensions();
// New content was added on top, so the scroll position should be changed immediately to prevent it from jumping around
const newScrollTop = newDim.scrollHeight - (prevDim.scrollHeight - prevDim.scrollTop);
// ******** DOM WRITE ****************
this._dom.write(() => {
this._content.scrollTop = newScrollTop;
this.state = STATE_ENABLED;
});
});
}
/**
* Pass a promise inside `waitFor()` within the `infinite` output event handler in order to
* change state of infiniteScroll to "complete"
*/
waitFor(action: Promise<any>) {
const enable = this.complete.bind(this);
action.then(enable, enable);
}
/**
* Call `enable(false)` to disable the infinite scroll from actively
* trying to receive new data while scrolling. This method is useful
* when it is known that there is no more data that can be added, and
* the infinite scroll is no longer needed.
* @param {boolean} shouldEnable If the infinite scroll should be
* enabled or not. Setting to `false` will remove scroll event listeners
* and hide the display.
*/
enable(shouldEnable: boolean) {
this.state = (shouldEnable ? STATE_ENABLED : STATE_DISABLED);
this._setListeners(shouldEnable);
}
/**
* @hidden
*/
_setListeners(shouldListen: boolean) {
if (this._init) {
if (shouldListen) {
if (!this._scLsn) {
this._scLsn = this._content.ionScroll.subscribe(this._onScroll.bind(this));
}
} else {
this._scLsn && this._scLsn.unsubscribe();
this._scLsn = null;
}
}
}
/**
* @hidden
*/
ngAfterContentInit() {
this._init = true;
this._setListeners(this.state !== STATE_DISABLED);
if (this._position === POSITION_TOP) {
this._content.scrollDownOnLoad = true;
}
}
/**
* @hidden
*/
ngOnDestroy() {
this._setListeners(false);
}
}
const STATE_ENABLED = 'enabled';
const STATE_DISABLED = 'disabled';
const STATE_LOADING = 'loading';
const POSITION_TOP = 'top';
const POSITION_BOTTOM = 'bottom';
|
5a1b805177c66139e55b4e9ba76db5d2c266a75b
|
TypeScript
|
pastelmind/stryker
|
/packages/react-mutator/test/unit/mutators/StateMutationMutator.spec.ts
| 2.65625
| 3
|
import { expect } from 'chai';
import ExpectMutation from '@stryker-mutator/mutator-specification/src/ExpectMutation';
import StateMutationMutator from '../../../src/mutators/StateMutationMutator';
import { verifySpecification } from '../../helpers/mutatorAssertions';
function StateMutationMutatorSpec(name: string, expectMutation: ExpectMutation) {
describe('StateMutationMutator', () => {
it('should have name "StateMutation"', () => {
expect(name).eq('StateMutation');
});
it('should mutate a setState() call to direct state mutation', () => {
expectMutation('this.setState({ myValue: 5 });', 'this.state.myValue = 5;');
expectMutation('this.setState({ "myValue": 5 });', 'this.state["myValue"] = 5;');
expectMutation(
'this.setState({ foo: "a", "bar": "b", ["b" + "az"]: 27 });',
'{ this.state.foo = "a"; this.state["bar"] = "b"; this.state["b" + "az"] = 27; }'
);
});
});
}
verifySpecification(StateMutationMutatorSpec, StateMutationMutator);
|
e08e7681096ae3d3f1d1e0f97c7a4c505fa4d310
|
TypeScript
|
digital-thinking/acep
|
/src/test/javascript/spec/app/entities/asset/asset.service.spec.ts
| 2.625
| 3
|
/* tslint:disable max-line-length */
import axios from 'axios';
import sinon from 'sinon'
import AssetService from '@/entities/asset/asset.service';
import {Asset} from '@/shared/model/asset.model';
import {Currency} from '@/shared/model/enumerations/currency.model';
import {AssetType} from '@/shared/model/enumerations/asset-type.model';
import {Source} from '@/shared/model/enumerations/source.model';
const error = {
response: {
status: null,
data: {
type: null
}
}
};
const axiosStub = {
get: sinon.stub(axios, 'get'),
post: sinon.stub(axios, 'post'),
put: sinon.stub(axios, 'put'),
delete: sinon.stub(axios, 'delete'),
};
describe('Service Tests', () => {
describe('Asset Service', () => {
let service: AssetService;
let elemDefault;
beforeEach(() => {
service = new AssetService();
elemDefault = new Asset(
0,
'AAAAAAA',
Currency.AED,
AssetType.Stock,
'AAAAAAA',
Source.AlphaVantage,
);
});
describe('Service methods', () => {
it('should find an element', async () => {
const returnedFromService = Object.assign({}, elemDefault);
axiosStub.get.resolves({data: returnedFromService});
return service
.find(123).then((res) => {
expect(res).toMatchObject(elemDefault);
});
});
it('should not find an element', async () => {
axiosStub.get.rejects(error);
return service.find(123)
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should create a Asset', async () => {
const returnedFromService = Object.assign({
id: 0,
}, elemDefault);
const expected = Object.assign({}, returnedFromService);
axiosStub.post.resolves({data: returnedFromService});
return service.create({}).then((res) => {
expect(res).toMatchObject(expected);
});
});
it('should not create a Asset', async () => {
axiosStub.post.rejects(error);
return service.create({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should update a Asset', async () => {
const returnedFromService = Object.assign({
name: 'BBBBBB',
currency: 'BBBBBB',
assetType: 'BBBBBB',
symbol: 'BBBBBB',
source: 'BBBBBB',
}, elemDefault);
const expected = Object.assign({}, returnedFromService);
axiosStub.put.resolves({data: returnedFromService});
return service.update(expected).then((res) => {
expect(res).toMatchObject(expected);
});
});
it('should not update a Asset', async () => {
axiosStub.put.rejects(error);
return service.update({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should return a list of Asset', async () => {
const returnedFromService = Object.assign({
name: 'BBBBBB',
currency: 'BBBBBB',
assetType: 'BBBBBB',
symbol: 'BBBBBB',
source: 'BBBBBB',
}, elemDefault);
const expected = Object.assign({}, returnedFromService);
axiosStub.get.resolves([returnedFromService]);
return service.retrieve().then((res) => {
expect(res).toContainEqual(expected);
});
});
it('should not return a list of Asset', async () => {
axiosStub.get.rejects(error);
return service.retrieve()
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should delete a Asset', async () => {
axiosStub.delete.resolves({ok: true});
return service.delete(123).then((res) => {
expect(res.ok).toBeTruthy();
});
});
it('should not delete a Asset', async () => {
axiosStub.delete.rejects(error);
return service.delete(123)
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
});
});
});
|
889e9bfe7296651fd8f2c7b0296fba1c708732b0
|
TypeScript
|
dobernike/dobernike.github.io
|
/javascript/pixel-hunter/js/view/stats-view.ts
| 2.84375
| 3
|
/* eslint-disable object-curly-spacing */
import AbstractView from './abstract-view';
import HeaderView from './header-view';
import countLives from '../data/count-lives';
import { statistic } from '../data/data';
import { calcSummaryScores, calcCorrect, calcFast, calcSlow } from '../data/calc-scores';
const header = new HeaderView();
const BONUS = {
CORRECT: 100,
FAST: 50,
LIVES: 50,
SLOW: -50
};
export default class StatsView extends AbstractView {
copyStatsAnswers: any
lives: any
victoryTitle: string = ``;
victoryOrFail: string = ``;
constructor(copyStatsAnswers) {
super();
this.copyStatsAnswers = copyStatsAnswers;
this.lives = countLives(copyStatsAnswers);
}
get template() {
if (this.lives > 0) {
this.victoryTitle = `
<h2 class="result__title">Победа!</h2>
`;
this.victoryOrFail = `
<td class="result__points">× ${BONUS.CORRECT}</td>
<td class="result__total">${calcCorrect(this.copyStatsAnswers) * BONUS.CORRECT}</td>
</tr>
<tr>
<td></td>
<td class="result__extra">Бонус за скорость:</td>
<td class="result__extra">${calcFast(this.copyStatsAnswers)} <span class="stats__result stats__result--fast"></span></td>
<td class="result__points">× ${BONUS.FAST}</td>
<td class="result__total">${calcFast(this.copyStatsAnswers) * BONUS.FAST}</td>
</tr>
<tr>
<td></td>
<td class="result__extra">Бонус за жизни:</td>
<td class="result__extra">${this.lives} <span class="stats__result stats__result--alive"></span></td>
<td class="result__points">× ${BONUS.LIVES}</td>
<td class="result__total">${this.lives * BONUS.LIVES}</td>
</tr>
<tr>
<td></td>
<td class="result__extra">Штраф за медлительность:</td>
<td class="result__extra">${calcSlow(this.copyStatsAnswers)} <span class="stats__result stats__result--slow"></span></td>
<td class="result__points">× ${BONUS.SLOW}</td>
<td class="result__total">${calcSlow(this.copyStatsAnswers) * BONUS.SLOW}</td>
</tr>
<tr>
<td colspan="5" class="result__total result__total--final">${calcSummaryScores(this.copyStatsAnswers, this.lives)}</td>
</tr>
`;
} else {
this.victoryOrFail = `
<td class="result__total"></td>
<td class="result__total result__total--final">fail</td>
</tr>
`;
}
return `
${header.template}
<section class="result">
${this.victoryTitle}
<table class="result__table">
<tr>
<td colspan="2">
${statistic(this.copyStatsAnswers)}
</td>
${this.victoryOrFail}
</table>
</section>
`;
}
bind() {
// Вызывает метод bind класса HeaderView, который по нажатию на кнопку back вызывает метод onClick() этого класса
header.bind(this);
}
onClick() { }
}
|
f216210ce17e048e8a5010998ca1da1396a8cef1
|
TypeScript
|
kennetvu/chakra-ui
|
/packages/styled-system/src/utils/breakpoint.ts
| 2.71875
| 3
|
import { Dict, breakpoints, isArray } from "@chakra-ui/utils"
function normalizeBreakpointObject(bps: Dict) {
let result = [] as any
result = Object.values(bps)
for (const key in bps) {
result[key] = bps[key]
}
return result
}
function normalizeBreakpointArray(bps: any[]) {
const result = bps
for (let index = 0; index < bps.length; index++) {
result[breakpoints[index + 1]] = bps[index]
}
return result
}
export function normalizeBreakpoints(value: any) {
return isArray(value)
? normalizeBreakpointArray(value)
: normalizeBreakpointObject(value)
}
|
cafc48379fdffafddd7e6dc126df906c7587e553
|
TypeScript
|
erickzhao/roller
|
/src/utils/octokit.ts
| 2.59375
| 3
|
import * as GitHub from '@octokit/rest';
let octokit: GitHub;
/**
* Returns an authenticated Octokit.
*
* @returns {Promise<GitHub>}
*/
export async function getOctokit(): Promise<GitHub> {
octokit = octokit || new GitHub({
auth: process.env.GITHUB_TOKEN,
});
return octokit;
}
|
db1dfbd2ddf50e42f6f9d55841565a0e983c3ee6
|
TypeScript
|
jmajurel/cod19GP
|
/src/repositories/doctorRepository.ts
| 2.640625
| 3
|
import IDoctorRepository from "./interfaces/doctorRepoInterface";
import Doctor from "../models/doctor";
import { Db, ObjectId, InsertOneWriteOpResult } from "mongodb";
export default class DoctorRepository implements IDoctorRepository {
private readonly dbClient: Db;
constructor({ dbClient }: { dbClient: Db }) {
this.dbClient = dbClient;
}
async getByEmail(email: string): Promise<Doctor> {
return this.dbClient.collection("doctors").findOne({ email });
}
async getAll(): Promise<Doctor[]> {
return this.dbClient.collection("doctors").find({}).toArray() as Promise<
Doctor[]
>;
}
async getById(id: string): Promise<Doctor> {
return this.dbClient
.collection("doctors")
.findOne({ _id: new ObjectId(id) });
}
async create(newProfile: Doctor): Promise<Doctor> {
return await this.dbClient
.collection("doctors")
.insertOne(newProfile)
.then((result: InsertOneWriteOpResult<Doctor>): Doctor => result.ops[0]);
}
async update(id: string, profile: Doctor): Promise<void> {
delete profile._id;
return await this.dbClient
.collection("doctors")
.updateOne({ _id: new ObjectId(id) }, { $set: { ...profile } })
.then();
}
}
|
a4f7ce11490577048dce78387af91c8b5fa4d688
|
TypeScript
|
MikeHopcroft/PrixFixe
|
/src/core/catalog/schema.ts
| 2.640625
| 3
|
import AJV from 'ajv';
import Debug from 'debug';
import yaml from 'js-yaml';
import { YAMLValidationError } from '../utilities';
import { Catalog } from './catalog';
import {
GenericEntity,
genericEntityFactory,
GenericTypedEntity,
SpecificEntity,
specificEntityFactory,
SpecificTypedEntity,
} from './interfaces';
const debug = Debug('pf:catalogFromYamlString');
interface CatalogDescription {
genericItems: GenericEntity[];
specificItems: SpecificEntity[];
}
// Schema generated with typescript-json-schema:
// typescript-json-schema tsconfig.json CatalogDescription --required
const catalogSchema = {
$schema: 'http://json-schema.org/draft-07/schema#',
definitions: {
GenericEntity: {
properties: {
aliases: {
items: {
type: 'string',
},
type: 'array',
},
cid: {
type: 'number',
},
defaultKey: {
type: 'string',
},
tensor: {
type: 'number',
},
name: {
type: 'string',
},
pid: {
type: 'number',
},
},
required: ['aliases', 'cid', 'defaultKey', 'tensor', 'name', 'pid'],
type: 'object',
},
SpecificEntity: {
properties: {
key: {
type: 'string',
},
name: {
type: 'string',
},
sku: {
type: 'number',
},
},
required: ['key', 'name', 'sku'],
type: 'object',
},
},
properties: {
genericItems: {
items: {
$ref: '#/definitions/GenericEntity',
},
type: 'array',
},
specificItems: {
items: {
$ref: '#/definitions/SpecificEntity',
},
type: 'array',
},
},
required: ['genericItems', 'specificItems'],
type: 'object',
};
const ajv = new AJV();
const catalogValidator = ajv.compile(catalogSchema);
export function catalogFromYamlString(yamlText: string, kind: symbol) {
const yamlRoot = yaml.safeLoad(yamlText) as CatalogDescription;
if (!catalogValidator(yamlRoot)) {
const message =
'catalogFromYamlString: yaml data does not conform to schema.';
debug(message);
debug(catalogValidator.errors);
throw new YAMLValidationError(message, []);
// const output = betterAjvErrors(
// catalogSchema,
// yamlRoot,
// catalogValidator.errors,
// { format: 'cli', indent: 1 }
// );
// throw new YAMLValidationError(message, output || []);
}
const f1 = (entity: GenericEntity): GenericTypedEntity => {
return genericEntityFactory(entity, kind);
};
const genericItems = yamlRoot.genericItems.map(f1);
const f2 = (entity: SpecificEntity): SpecificTypedEntity => {
return specificEntityFactory(entity, kind);
};
const specificItems = yamlRoot.specificItems.map(f2);
return Catalog.fromEntities(genericItems.values(), specificItems.values());
}
|
614caa47b9bae569c2677e34745d10b0634e25f4
|
TypeScript
|
jtenner/assemblyscript
|
/tests/compiler/std/staticarray.ts
| 2.96875
| 3
|
import { OBJECT, TOTAL_OVERHEAD } from "rt/common";
// from contextual type
const arr1: StaticArray<i32> = [1,2,3];
assert(arr1[1] == 2);
assert(arr1.length == 3);
arr1[1] = 4;
assert(arr1[1] == 4);
assert(changetype<OBJECT>(changetype<usize>(arr1) - TOTAL_OVERHEAD).rtId == idof<StaticArray<i32>>());
// from assertion
const arr2 = [1,2,3] as StaticArray<i32>;
assert(arr2[1] == 2);
assert(arr2.length == 3);
arr2[1] = 4;
assert(arr2[1] == 4);
// unique copy
function test(): StaticArray<i32> {
return [5,6,7];
}
var arr3 = test();
assert(arr3[0] == 5);
assert(arr3[1] == 6);
assert(arr3[2] == 7);
assert(arr3.length == 3);
arr3[1] = 8;
assert(arr3[1] == 8);
arr3 = test();
assert(arr3[1] == 6);
// non-static instantiation
class Ref {}
var arr4: StaticArray<Ref> = [ new Ref(), new Ref() ];
arr3 = changetype<StaticArray<i32>>(0); // unleak
arr4 = changetype<StaticArray<Ref>>(0);
__stack_pointer = __heap_base;
__collect();
|
bd8c1c20b2504cc35127124a857cbb1fa13b38c0
|
TypeScript
|
kkenward/mars-rover
|
/src/app/mission-input.component.ts
| 2.65625
| 3
|
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-mission-input',
templateUrl: './mission-input.component.html',
styleUrls: ['./mission-input.component.css']
})
export class MissionInputComponent {
@Output() nextMission: EventEmitter<object> = new EventEmitter<object>();
constructor() { }
addMission(newMission: string) {
if( newMission ) {
try {
const parsed = JSON.parse(newMission);
this.nextMission.emit(parsed);
} catch {
const msg =
'JSON parse error!\n' +
'Enter a mission as a valid JSON object.\n' +
'For example: {"x":3,"y":4,"heading":"S","commands":["f","l","b",r"]}';
window.alert(msg);
}
}
}
}
|
d2a59da0a768880349c706a5a2ad11788d8b6c53
|
TypeScript
|
apple-yagi/nest-general-purpose-app
|
/src/items/items.resolver.ts
| 2.515625
| 3
|
import { UseGuards } from '@nestjs/common';
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { CurrentUser } from 'src/guards/current-user';
import { GqlAuthGuard } from 'src/guards/gql-auth.guard';
import { Item } from './item';
import { ItemsService } from './items.service';
@Resolver('Items')
export class ItemsResolver {
constructor(private readonly itemsService: ItemsService) {}
@Query(returns => [Item])
@UseGuards(GqlAuthGuard)
items() {
return this.itemsService.findAll();
}
@Query(returns => Item)
@UseGuards(GqlAuthGuard)
itemById(@Args('id', { type: () => String }) id: string) {
return this.itemsService.findById(id);
}
@Query(returns => Item)
@UseGuards(GqlAuthGuard)
itemOne(@Args('title', { type: () => String }) title: string) {
return this.itemsService.findOne(title);
}
@Mutation(returns => Item)
@UseGuards(GqlAuthGuard)
createItem(
@CurrentUser() user,
@Args('title', { type: () => String }) title: string,
@Args('description', { type: () => String }) description: string,
) {
return this.itemsService.insert({ title, description }, user);
}
@Mutation(returns => Item)
@UseGuards(GqlAuthGuard)
deleteItem(@Args('id', { type: () => String }) id: string) {
return this.itemsService.remove(id);
}
@Mutation(returns => Item)
@UseGuards(GqlAuthGuard)
updateItem(
@Args('id', { type: () => String }) id: string,
@Args('title', { type: () => String }) title: string,
@Args('description', { type: () => String }) description: string,
) {
return this.itemsService.update(id, { title, description });
}
}
|
cd2100e984eff65d73a758a75d1c895343e19629
|
TypeScript
|
honkit/honkit
|
/packages/@honkit/html/src/dom.ts
| 2.625
| 3
|
import _ from "lodash";
import * as cheerio from "cheerio";
/**
Parse an HTML string and return its content
@param html
@return {cheerio.Root}
*/
export function parse(html: string) {
const $ = cheerio.load(html, { _useHtmlParser2: true });
const $el = $("html, body").first();
return $el.length > 0 ? $el : $;
}
/**
Return main element for a DOM
@param {cheerio.DOM}
@return {cheerio.Node}
*/
export function root($) {
const $el = $("html, body, > div").first();
return $el.length > 0 ? $el : $.root();
}
/**
Return text node of an element
@param {cheerio.Node}
@return {string}
*/
export function textNode($el) {
return _.reduce(
$el.children,
(text, e) => {
if (e.type == "text") text += e.data;
return text;
},
""
);
}
/**
Cleanup a DOM by removing all useless divs
@param {cheerio.Node}
@param {cheerio.DOM}
@return {cheerio.Node}
*/
export function cleanup($el, $) {
$el.find("div").each(function () {
const $div = $(this);
cleanup($div, $);
$div.replaceWith($div.html());
});
return $el;
}
|
6f78587c2cf24f7578ec83febb30d71c2eaef18f
|
TypeScript
|
Aliuihb/guilded.js
|
/packages/common/__tests__/MessageUtil.test.ts
| 2.609375
| 3
|
import { generateMessage, parseMessage, parseToMessage } from '..';
import { Embed } from '../../embeds';
import data from './MessageUtil.test.data.json';
const testingMessage1 = 'TESTING MESSAGE' as const;
const testingMessage2 = 'TESTING MESSAGE 2' as const;
const testingMessage3 = 'TESTING MESSAGE 3' as const;
// taken from https://stackoverflow.com/a/13653180, show them some love.
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
test('convert plain-text content to proper message format', () => {
expect(parseToMessage(testingMessage1)).toStrictEqual(data['plain-message']);
});
test('convert embed content to proper message format', () => {
expect(parseToMessage(new Embed().setTitle(testingMessage1))).toEqual(data['embed-message']);
});
test('convert both plain-text and embed content to proper message format', () => {
expect(parseToMessage(testingMessage2, new Embed().setTitle(testingMessage3))).toEqual(data['mixed-message']);
});
test('generate valid sendable plain-text message structure', () => {
const [id, message] = generateMessage(testingMessage1);
expect(id).toMatch(UUID_REGEX);
expect(message.content).toStrictEqual(data['plain-message']);
});
test('generate valid sendable embed message structure', () => {
const [id, message] = generateMessage(new Embed().setTitle(testingMessage1));
expect(id).toMatch(UUID_REGEX);
expect(message.content).toEqual(data['embed-message']);
});
test('generate valid sendable embed and plain-text message structure', () => {
const [id, message] = generateMessage(testingMessage2, new Embed().setTitle(testingMessage3));
expect(id).toMatch(UUID_REGEX);
expect(message.content).toEqual(data['mixed-message']);
});
test('parse regular message', () => {
expect(parseMessage(data['plain-message'])).toStrictEqual({
embeds: [],
mentions: {
channels: [],
reactions: [],
roles: [],
users: [],
},
parsedArr: [{ content: 'TESTING MESSAGE', type: 'text' }],
parsedText: 'TESTING MESSAGE',
});
});
test('parse embed message', () => {
expect(parseMessage(data['embed-message'])).toStrictEqual({
embeds: [
{
fields: [],
title: 'TESTING MESSAGE',
},
],
mentions: {
channels: [],
reactions: [],
roles: [],
users: [],
},
parsedArr: [],
parsedText: '',
});
});
test('parse multi-line message', () => {
expect(parseMessage(data['multi-line'])).toStrictEqual({
embeds: [],
mentions: {
channels: [],
reactions: [],
roles: [],
users: [],
},
parsedArr: [
{ content: 'MULTILINE', type: 'text' },
{ content: 'STRING', type: 'text' },
{ content: 'TEST', type: 'text' },
],
parsedText: 'MULTILINE\nSTRING\nTEST',
});
});
test('parse message with user mentions', () => {
expect(parseMessage(data['user-mention'])).toStrictEqual({
embeds: [],
mentions: {
channels: [],
reactions: [],
roles: [],
users: ['user-id'],
},
parsedArr: [
{
content: '@nico',
mention: {
avatar: data.avatarURL,
color: '#ececee',
id: 'user-id',
matcher: '@nico',
name: 'nico',
nickname: false,
type: 'person',
},
type: 'user',
},
{ content: ' testing testing!', type: 'text' },
],
parsedText: '@nico testing testing!',
});
});
test('parse message with role mentions', () => {
expect(parseMessage(data['role-mention'])).toStrictEqual({
embeds: [],
mentions: {
channels: [],
reactions: [],
roles: ['10000000'],
users: [],
},
parsedArr: [
{
content: '@Captain',
mention: {
color: '#d9acff',
id: 10000000,
matcher: '@captain',
name: 'Captain',
type: 'role',
},
type: 'role',
},
{ content: ' testing testing 3!', type: 'text' },
],
parsedText: '@Captain testing testing 3!',
});
});
test('parse message with channel mentions', () => {
expect(parseMessage(data['channel-mention'])).toStrictEqual({
embeds: [],
mentions: {
channels: ['channel-id'],
reactions: [],
roles: [],
users: [],
},
parsedArr: [
{
channel: {
id: 'channel-id',
matcher: '#testing',
name: 'testing',
},
content: '#testing',
type: 'channel',
},
{ content: ' testing testing!', type: 'text' },
],
parsedText: '#testing testing testing!',
});
});
test('parse message with mixed mentions', () => {});
|
f787be50049d72b64357409834cde584104c10f6
|
TypeScript
|
Siedlerchr/types-ol-ext
|
/@types/ol-ext/source/GeoImage.d.ts
| 3.09375
| 3
|
import type { Coordinate } from 'ol/coordinate'
import type { Extent } from 'ol/extent'
import type { LineString } from 'ol/geom'
import type { Size } from 'ol/size'
import { ImageCanvas } from 'ol/source'
export interface Options {
url?: string;
image?: any; // TODO: image type
imageCenter?: Coordinate;
imageScale?: Size | number;
imageRotate?: number;
imageCrop?: Extent;
imageMask: Coordinate[];
}
/** Layer source with georeferencement to place it on a map
* @constructor
* @extends {ImageCanvas}
*/
export default class GeoImage extends ImageCanvas {
/**
* @param {Options} options
*/
constructor(options?: Options);
/** calculate image at extent / resolution
* @param {ol/extent/Extent} extent
* @param {number} resolution
* @param {number} pixelRatio
* @param {ol/size/Size} size
* @return {HTMLCanvasElement}
*/
calculateImage(extent: Extent, resolution: number, pixelRatio: number, size: Size): HTMLCanvasElement
/**
* Get coordinate of the image center.
* @return {Coordinate} coordinate of the image center.
* @api stable
*/
getCenter(): Coordinate;
/**
* Set coordinate of the image center.
* @param {Coordinate} coordinate of the image center.
* @api stable
*/
setCenter(coordinate: Coordinate): void;
/**
* Get image scale.
* @return {Size} image scale (along x and y axis).
* @api stable
*/
getScale(): Size;
/**
* Set image scale.
* @param {Size|Number} image scale (along x and y axis or both).
* @api stable
*/
setScale(image: Size | number): void;
/**
* Get image rotation.
* @return {Number} rotation in radian.
* @api stable
*/
getRotation(): number;
/**
* Set image rotation.
* @param {Number} rotation in radian.
* @api stable
*/
setRotation(rotation: number): void;
/**
* Get the image.
* @api stable
*/
getGeoImage(): void;
/**
* Get image crop Extent.
* @return {Extent} image crop Extent.
* @api stable
*/
getCrop(): Extent;
/**
* Set image mask.
* @param {LineString} coords of the mask
* @api stable
*/
setMask(coords: LineString): void;
/**
* Get image mask.
* @return {LineString} coords of the mask
* @api stable
*/
getMask(): LineString;
/**
* Set image crop Extent.
* @param {Extent|Number} image crop Extent or a number to crop from original Size.
* @api stable
*/
setCrop(image: Extent | number): void;
}
|
9d6fa27fbb1f774799af737cda1f9496ce6a6229
|
TypeScript
|
CursedMun/InsomniaBot
|
/commands/Основное/расстаться.ts
| 2.578125
| 3
|
import { Command, Discord, Document } from "discore.js";
import Constants from "../../util/Constants";
export default class extends Command {
get customOptions() {
return {
group: "Основное",
help: "Разорвать текущую пару",
syntax: `${this.client.prefix}расстаться`,
example: `${this.client.prefix}расстаться`,
};
}
async run(message: Discord.Message, args: string[]) {
const Users = this.client.db.getCollection("users")!;
const LoveTaxs = this.client.db.getCollection("LoveTaxs")!;
const LoveRoom = this.client.db.getCollection("voiceconfigs")
const data = {
userId: message.member!.id,
};
const user = await Users.findOne(data);
if (user!.relationship == null)
return message.channel.send(
new Discord.MessageEmbed()
.setColor("#ce2626")
.setDescription(`${message.author}, у вас нет пары.`)
);
const newMsg = await message.author.send(
new Discord.MessageEmbed()
.setColor("#ce2626")
.setDescription(
`${message.author}, уверены?\n\n<:Yes:633712359772389386> - Да\n\n<:No:633712357129977876> - Нет`
)
.setFooter("Поторопись! У тебя есть всего 5 минут на ответ.")
);
await newMsg.react("633712359772389386").catch(console.error);
await newMsg.react("633712357129977876").catch(console.error);
newMsg
.awaitReactions(
(r, u) =>
u.id === message.member!.id &&
["633712359772389386", "633712357129977876"].includes(
r.emoji.id || r.emoji.name
),
{
max: 1,
time: 5 * 1000 * 60,
errors: ["time"],
}
)
.then(async (collected) => {
const reaction = collected.first()!;
if (
(reaction.emoji.id || reaction.emoji.name) === "633712359772389386"
) {
const data1 = {
userId: user!.relationship,
};
const scndperson = await Users.findOne(data1);
const scndusr = message.guild?.members.cache.get(user!.relationship)!;
await LoveTaxs.deleteOne((d: Document) => d.idone == user!.userId || d.idscnd == user!.userId)?.catch(console.error);
await LoveRoom?.deleteOne(((d: Document) => d.id == message.author.id && d.type == 1 || d.idScnd == message.author.id && d.type == 1))?.catch(console.error);
user!.relationship = null;
user!.relationshipRoleID = null;
scndperson!.relationship = null;
scndperson!.relationshipRoleID = null;
await user!.save().catch(console.error);
await scndperson!.save().catch(console.error);
newMsg.delete();
await scndusr.roles.remove(Constants.Ids.Roles.Users.LoveRole).catch(console.error)
await message.member!.roles.remove(Constants.Ids.Roles.Users.LoveRole).catch(console.error)
scndusr.send(
new Discord.MessageEmbed()
.setColor("#ce2626")
.setDescription("Пара разорвана.")
);
return message.author.send(
new Discord.MessageEmbed()
.setColor("#ce2626")
.setDescription("Пара разорвана.")
);
} else {
return message.author
.send(
new Discord.MessageEmbed()
.setColor("#ce2626")
.setDescription(`${message.author}, принято!`)
)
.then((m) => m.delete({ timeout: 15000 }));
}
});
}
}
|
053fbe6299b1c63028f04e4e8d3751ea2c744f9b
|
TypeScript
|
gggfox/amadis
|
/server/src/utils/createPromotorUpdootLoader.ts
| 2.734375
| 3
|
import DataLoader from "dataloader";
import { PromotorUpdoot } from "../entities/PromotorUpdoot";
export const createPromotorUpdootLoader = () =>
new DataLoader<{promotorId: number, userId: number}, PromotorUpdoot | null>(
async (keys) => {
const updoots = await PromotorUpdoot.findByIds(keys as any);
const updootIdToUpdoot: Record<string, PromotorUpdoot> = {};
updoots.forEach((up) => {
updootIdToUpdoot[`${up.userId}|${up.promotorId}`] = up;
});
return keys.map((key) => updootIdToUpdoot[`${key.userId}|${key.promotorId}`]);
}
);
|
ef4fd01e58212254c22fe85fd4ed0e91b2cf5123
|
TypeScript
|
dsignn/library
|
/src/sport/player/PlayerInteface.d.ts
| 2.875
| 3
|
/**
* @interface PlayerInteface
*/
export interface PlayerInteface {
/**
* @return {string}
*/
getFirstName(): string;
/**
* @return {string}
*/
getLastName(): string;
/**
* @return {Date}
*/
getBirthday(): Date;
/**
* @return {string}
*/
getRole(): string;
/**
* @return {string}
*/
getShirtNumber(): string;
}
|
3e794f1349e2b610f064aa4abfdb16f7332117ad
|
TypeScript
|
mitom18/example-server-nodejs
|
/src/model/user.ts
| 2.890625
| 3
|
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
export enum UserRole {
ADMINISTRATOR = "administrator",
USER = "user",
}
@Entity({ name: "users" })
export class User {
@PrimaryGeneratedColumn()
id?: number;
@Column()
email!: string;
@Column()
password!: string;
@Column()
phone!: string;
@Column("varchar", { length: 255 })
role!: UserRole;
}
|
0534b94866db8346f8f7e99b3baebd680056900a
|
TypeScript
|
PavelMCaro/mongoose
|
/app/client/src/view/form/state/form/reducer.ts
| 2.984375
| 3
|
import * as actionTypes from './actionTypes';
interface State {
data: any;
isFetching: boolean;
error: boolean;
errorMessage: string;
}
const initialState: State = {
data: [],
isFetching: false,
error: false,
errorMessage: ''
};
export const form = (state: State = initialState, action): State => {
switch(action.type) {
case actionTypes.FETCH_DATA_REQUEST:
return {
...state,
isFetching: true
}
case actionTypes.FETCH_DATA_SUCCESS:
return {
...state,
isFetching: false,
data: action.data,
error: false
}
case actionTypes.FETCH_DATA_FAILURE:
return {
...state,
isFetching: false,
error: true,
errorMessage: action.msg
}
case actionTypes.SAVE_FORM_DATA_REQUEST:
return {
...state,
isFetching: true
}
case actionTypes.SAVE_FORM_DATA_FAILURE:
return {
...state,
isFetching: false,
error: true,
errorMessage: action.msg
}
default:
return state;
}
}
|
ebd62077a1a7927ebdbf99b05436f49e2271e20c
|
TypeScript
|
zcyemi/Iris
|
/src/core/RenderTexture.ts
| 2.703125
| 3
|
import { GLContext } from "../gl/GLContext";
import { ITexture, TextureCreationDesc, TextureType, TextureDescUtility } from "./Texture";
import { Texture2D } from "./Texture2D";
import { FrameBuffer, FrameBufferTexDesc } from "../gl/FrameBuffer";
export class RenderTexture implements ITexture{
private m_valid:boolean;
private m_fb:FrameBuffer;
private m_desc:TextureCreationDesc;
private m_rawtex:Texture2D;
public getDesc():TextureCreationDesc{
return this.m_desc;
}
public getRawTexture():WebGLTexture{
return this.m_rawtex;;
}
public get internalFB():FrameBuffer{
return this.m_fb;
}
private constructor(){
}
/**
* @TODO this may need trefactoring
* @param glctx
* @param width
* @param height
*/
public resize(glctx:GLContext,width:number,height:number){
if(this.m_fb.resize(glctx,width,height)){
this.m_rawtex = this.internalGetFBtex(TextureDescUtility.getTexFmtType(this.m_desc.internalformat));
}
}
private internalGetFBtex(type:TextureType){
let fb = this.m_fb;
if(type == TextureType.Color){
return fb.coltex;
}
return fb.depthtex;
}
public static create(glctx:GLContext,width:number,height:number,desc:TextureCreationDesc):RenderTexture{
let internalfmt = desc.internalformat;
let texfmt = TextureDescUtility.getTexFmtType(desc.internalformat);
let fbdesc:FrameBufferTexDesc = {};
switch(texfmt){
case TextureType.Color:
fbdesc.colFmt = internalfmt;
break;
case TextureType.Depth:
fbdesc.depthFmt = internalfmt;
break;
case TextureType.DepthStencil:
fbdesc.depthstencilFmt = internalfmt;
break;
}
let fb = FrameBuffer.create(glctx,width,height,fbdesc);
let rt =new RenderTexture();
rt.m_fb = fb;
rt.m_desc = desc;
rt.m_valid = true;
rt.m_rawtex = rt.internalGetFBtex(texfmt);
return rt;
}
public release(glctx:GLContext){
this.m_rawtex = null;
this.m_fb.release(glctx);
this.m_fb= null;
this.m_valid = false;
}
}
|
2014544b501a6eee896786aab235b9a915432bf3
|
TypeScript
|
ilanddev/javascript-sdk
|
/src/sdk/model/o365/__json__/o365-teams-restore-options-request-json.ts
| 2.625
| 3
|
/**
* O365 Teams restore options request JSON properties
*/
export interface O365TeamsRestoreOptionsRequestJson {
user?: string;
password?: string;
device_code?: string;
restore_settings?: boolean;
restore_missing_items?: boolean;
restore_members?: boolean;
restore_changed_items?: boolean;
file_version?: O365TeamsFileVersion;
file_last_version_action?: O365TeamsFileLastVersionAction;
item_ids?: Array<string>;
from?: number;
to?: number;
}
/**
* O365 Teams file version enum
*/
export enum O365TeamsFileVersion {
ALL = 'all',
LAST = 'last'
}
/**
* O365 Teams file last version action enum
*/
export enum O365TeamsFileLastVersionAction {
OVERWRITE = 'overwrite',
MERGE = 'merge'
}
|
bb5e68a570b85ba3417978d20c441d33ca003f1b
|
TypeScript
|
ebi-uniprot/uniprot-website
|
/src/query-builder/utils/fieldInitializer.ts
| 3.078125
| 3
|
import { QueryBit, SearchTermType } from '../types/searchTypes';
const integerRange = /^\[(\*|-?\d+) TO (\*|-?\d+)\]$/;
const dateRange = /^\[(\*|\d{4}-\d{2}-\d{2}) TO (\*|\d{4}-\d{2}-\d{2})\]$/;
const initializer = (
field: SearchTermType,
initialValue?: QueryBit,
isAutoCompleteQueryId = false
): string | [from: string, to: string] => {
// specific case for free text search
if (field.term === 'All') {
return initialValue?.All || '';
}
if (initialValue && field.id === 'go_evidence') {
return initialValue.go_evidence;
}
// The presence of the term indicates user only wants experimental evidence
if (initialValue && field.fieldType === 'experimental_evidence') {
return String(field.term in initialValue);
}
if (initialValue && initialValue[`${field.term}_exp`]) {
return initialValue[`${field.term}_exp`];
}
if (initialValue && initialValue[`${field.autoCompleteQueryTerm}_exp`]) {
return initialValue[`${field.autoCompleteQueryTerm}_exp`];
}
if (field.term === 'xref' && initialValue?.database) {
return '*';
}
// Deal with autocomplete fields as they have two terms with different behavior:
// 1. autoCompleteQueryTerm: for ID searches eg organism_id
// 2. term: for text searches eg organism_name
if (initialValue && field.autoCompleteQueryTerm) {
if (Object.keys(initialValue).includes(field.autoCompleteQueryTerm)) {
// ID search
return initialValue[field.autoCompleteQueryTerm];
}
// Text search
return isAutoCompleteQueryId ? '' : initialValue[field.term];
}
// no value? bail
if (!(initialValue && initialValue[field.term])) {
return '';
}
const value = initialValue[field.term];
// NOTE: is all the following basically just a clause value validator?
// regular expression matching
// regex is present in the field description? try to match extracted value
if (field.regex && field.regex !== undefined) {
const { regex } = field;
const cleanRegex = regex.replace('(?i)', '');
const re = new RegExp(cleanRegex, regex === cleanRegex ? undefined : 'i');
// doesn't match regular expression? bail
if (!re.test(value)) {
return '';
}
}
// possible values are present in the field description? check is included
if (field.values && Array.isArray(field.values)) {
if (!field.values.map(({ value }) => value).includes(value)) {
// isn't included in possible values? bail
return '';
}
}
if (field.fieldType === 'range') {
const [, from = '', to = ''] =
value.match(field.dataType === 'date' ? dateRange : integerRange) || [];
return [from, to];
}
return value;
};
export default initializer;
|
a2b066ee0bec2cdc8550c633f7f2acbd075d79c1
|
TypeScript
|
danmin20/cashbook-14
|
/client/src/Components/atom/PieGraph/index.ts
| 2.71875
| 3
|
import PieGraphConfig from './configType';
import pieGraphDefaultConfig from './defaultConfig';
import './style';
interface PieGraphData {
category: string;
amount: number;
color: string;
}
export default class PieGraph {
data: PieGraphData[];
$wrapper: HTMLElement;
$dom: HTMLElement;
$canvas: HTMLCanvasElement;
cur: number;
end: number;
config: PieGraphConfig;
constructor({ data }: { data: PieGraphData[] }) {
this.data = data;
this.config = pieGraphDefaultConfig;
const {
canvasWidth,
canvasHeight,
animationStartPoint,
animationEndPoint,
} = this.config;
this.$canvas = document.createElement('canvas');
this.$canvas.className = 'pie';
this.$canvas.width = canvasWidth;
this.$canvas.height = canvasHeight;
this.$wrapper = document.createElement('div');
this.$wrapper.className = 'pie-wrapper';
this.$wrapper.appendChild(this.$canvas);
this.$dom = this.$wrapper;
this.cur = animationStartPoint;
this.end = animationEndPoint;
this.render();
}
render() {
const { pieRadius, pieLineWidth, animationCoefficient } = this.config;
const ctx = this.$canvas.getContext('2d') as CanvasRenderingContext2D;
ctx.clearRect(0, 0, this.$canvas.width, this.$canvas.height);
const x = this.$canvas.width / 2;
const y = this.$canvas.height / 2;
const radius = pieRadius / 2 + (pieRadius / 2) * (this.cur / this.end);
let curAngle = Math.PI * 1.5 - Math.PI * 2 * (1 - this.cur / this.end);
let fullAngle = (Math.PI * 2 * this.cur) / this.end;
let totalAmount = 0;
for (const { amount } of this.data) {
totalAmount += amount;
}
this.data.forEach(({ amount, color }) => {
ctx.beginPath();
let deltaAngle = (fullAngle * amount) / totalAmount;
ctx.arc(x, y, radius, curAngle, curAngle + deltaAngle, false);
curAngle += deltaAngle;
ctx.lineWidth =
pieLineWidth / 2 + (pieLineWidth / 2) * (this.cur / this.end);
ctx.strokeStyle = color;
ctx.stroke();
});
this.cur += (this.end - this.cur) / animationCoefficient;
if (this.cur < this.end) {
if (this.cur >= this.end - 0.1) {
this.cur = this.end;
window.requestAnimationFrame(this.render.bind(this));
} else {
window.requestAnimationFrame(this.render.bind(this));
}
}
}
}
|
8297618225ff7acc4dcd8afec6d4a5c4290a1b71
|
TypeScript
|
reecerussell/distro-cms
|
/cms/src/app/store/roles/role.reducer.ts
| 2.828125
| 3
|
import { initializeRoleState, RoleListState, RoleState } from "./role.state";
import * as RoleActions from "./role.action";
import Role from "src/app/models/role.model";
export type Action = RoleActions.All;
const defaultRoleStates: RoleState[] = [
{
...(initializeRoleState() as RoleState),
},
];
const defaultState: RoleListState = {
roles: defaultRoleStates,
loading: false,
pending: 0,
};
const mergeRoles = (existingRoles: RoleState[], newRole: Role) =>
existingRoles
.filter((x) => x.id != newRole.id)
.concat({
...initializeRoleState(),
...newRole,
})
.sort((a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
export const RoleReducer = (state = defaultState, action: Action) => {
switch (action.type) {
case RoleActions.GET_ROLES:
return { ...state, loaded: false, loading: true };
case RoleActions.GET_ROLES_SUCCESS:
return {
...state,
roles: action.payload.map(
(role) =>
({
...initializeRoleState(),
...role,
} as RoleState)
),
loading: false,
loaded: true,
error: null,
};
case RoleActions.GET_ROLES_ERROR:
return {
...state,
loaded: false,
loading: false,
error: action.error,
};
/*
GET ROLE ACTIONS
*/
case RoleActions.GET_ROLE:
return { ...state, loaded: false, loading: true };
case RoleActions.GET_ROLE_SUCCESS:
return {
...state,
roles: mergeRoles(state.roles, action.payload),
loading: false,
loaded: true,
error: null,
};
case RoleActions.GET_ROLE_ERROR:
return {
...state,
loaded: false,
loading: false,
error: action.error,
};
/*
CREATE ROLE ACTIONS
*/
case RoleActions.CREATE_ROLE:
return { ...state, loaded: false, loading: true };
case RoleActions.CREATE_ROLE_SUCCESS:
return {
...state,
roles: mergeRoles(state.roles, action.payload),
loading: false,
loaded: true,
error: null,
};
case RoleActions.CREATE_ROLE_ERROR:
return {
...state,
loaded: false,
loading: false,
error: action.error,
};
/*
UPDATE ROLE ACTIONS
*/
case RoleActions.UPDATE_ROLE:
return { ...state, loaded: false, loading: true };
case RoleActions.UPDATE_ROLE_SUCCESS:
return {
...state,
roles: mergeRoles(state.roles, action.payload),
loading: false,
loaded: true,
error: null,
};
case RoleActions.UPDATE_ROLE_ERROR:
return {
...state,
roles: mergeRoles(state.roles, action.payload),
loaded: false,
loading: false,
error: action.error,
};
/*
DELETE ROLE ACTIONS
*/
case RoleActions.DELETE_ROLE:
return { ...state, loaded: false, loading: true };
case RoleActions.DELETE_ROLE_SUCCESS:
return {
...state,
roles: state.roles.filter((x) => x.id != action.id),
loading: false,
loaded: true,
error: null,
};
case RoleActions.DELETE_ROLE_ERROR:
return {
...state,
loaded: false,
loading: false,
error: action.error,
};
}
};
|
7e4d47fb3273c5b70f9d3cb942ba55bd748719b5
|
TypeScript
|
lotooo/terraforming-mars
|
/src/cards/IceAsteroid.ts
| 2.921875
| 3
|
import { IProjectCard } from "./IProjectCard";
import { Tags } from "./Tags";
import { CardType } from "./CardType";
import { Player } from "../Player";
import { Game } from "../Game";
import { SelectSpace } from "../inputs/SelectSpace";
import { ISpace } from "../ISpace";
export class IceAsteroid implements IProjectCard {
public cost: number = 23;
public tags: Array<Tags> = [Tags.SPACE];
public cardType: CardType = CardType.EVENT;
public name: string = "Ice Asteroid";
public static placeTwoOceans(player: Player, game: Game): SelectSpace | undefined {
let available = game.board.getAvailableSpacesForOcean(player);
if (available.length === 0 || game.noOceansAvailable()) {
return undefined;
}
return new SelectSpace("Select space for first ocean tile", available, (space: ISpace) => {
game.addOceanTile(player, space.id);
available = game.board.getAvailableSpacesForOcean(player);
if (available.length === 0 || game.noOceansAvailable()) {
return undefined;
}
return new SelectSpace("Select space for second ocean tile", available, (space: ISpace) => {
game.addOceanTile(player, space.id);
return undefined;
});
});
}
public play: (player: Player, game: Game) => SelectSpace | undefined = IceAsteroid.placeTwoOceans;
}
|