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
|
|---|---|---|---|---|---|---|
9d697e5550dbb34c6997593034c9ca4c096f924d
|
TypeScript
|
Sarmouts/mathflare
|
/src/stats.ts
| 2.59375
| 3
|
var storage: any = window.localStorage;
window.addEventListener('load', () => {
loadStats();
});
const loadStats = () => {
const pageviews = storage.getItem("pageCount");
const equations = storage.getItem("equation");
const formulas = storage.getItem("formulas");
const ineq = storage.getItem("ineq");
(<HTMLParagraphElement>document.getElementById('page-views')).innerText = pageviews!;
(<HTMLParagraphElement>document.getElementById('equations-solved')).innerText = equations!;
(<HTMLParagraphElement>document.getElementById('formulas-views')).innerText = formulas!;
(<HTMLParagraphElement>document.getElementById('ineq')).innerText = ineq!;
if (!storage.getItem("statCount")) {
storage.setItem("statCount", 1);
} else {
let statCount: any = storage.getItem("statCount");
statCount = parseFloat(statCount) + 1;
storage.setItem("statCount", statCount);
}
}
const clearStats = () => {
storage.clear();
reload();
};
const reload = () => {
location.reload();
};
|
e8a86823bb6627f3fbce97cf5ac9a957a8a3d81a
|
TypeScript
|
lanemt/definitelytyped.github.io
|
/types/ramda/test/nth-tests.ts
| 2.828125
| 3
|
import * as R from 'ramda';
() => {
const list = ['foo', 'bar', 'baz', 'quux'];
R.nth(1, list); // => 'bar'
R.nth(-1, list); // => 'quux'
R.nth(-99, list); // => undefined
R.nth(-99)(list); // => undefined
};
|
bf5d380550cf19db8e18e842e91fafed8bd23c9e
|
TypeScript
|
Libaration/Estate-Auction
|
/estateauction/src/reducers/HomesReducer.ts
| 2.796875
| 3
|
import {
FETCH_HOMES,
FETCH_USER_HOMES,
HomeActionDispatchTypes,
LOADING,
PLACE_BID,
SORT_HOMES,
} from '../actions/HomeActionTypes';
interface IDefaultState {
loading: boolean;
sortedBy: string;
homesList: [];
}
const defaultState: IDefaultState = {
homesList: [],
loading: false,
sortedBy: '',
};
const HomesReducer = (
state: IDefaultState = defaultState,
action: HomeActionDispatchTypes
) => {
switch (action.type) {
case FETCH_HOMES:
return {
homesList: action.payload,
loading: false,
sortedBy: state.sortedBy,
};
case PLACE_BID:
return {
homesList: [action.payload],
loading: false,
sortedBy: state.sortedBy,
};
case SORT_HOMES:
return {
...state,
loading: state.loading,
sortedBy: action.payload,
};
case FETCH_USER_HOMES:
return {
homesList: action.payload,
loading: false,
sortedBy: state.sortedBy,
};
case LOADING:
return {
...state,
loading: true,
sortedBy: state.sortedBy,
};
default:
return state;
}
};
export default HomesReducer;
|
5845922de42833dcdc7711ed7cc48b7c4160357f
|
TypeScript
|
neocomplexx/ngx-neo-frontend
|
/projects/ngx-neo-frontend/src/lib/components/menu/menu-group.model.ts
| 2.734375
| 3
|
import { MenuOptionsModel } from './menu-options.model';
/**
* Clase que representa a un grupo del menu
*/
export class MenuGroupModel {
id: String;
nombre: String;
descripcion: String;
habilitado: boolean;
opciones: Array<MenuOptionsModel>;
constructor(id: string) {
this.opciones = new Array<MenuOptionsModel>();
this.id = id;
}
public agregarOpcion(nuevaOpcion: MenuOptionsModel) {
this.opciones.push(nuevaOpcion);
nuevaOpcion.id = 'i' + this.id + '-opcion' + this.opciones.length;
}
}
|
f61591b4ba747151108e65ffb6e714d2d3363b68
|
TypeScript
|
jorgenbuilder/steel-biasts
|
/src/managers/PortalManager.ts
| 2.546875
| 3
|
import GameScene from "scenes/GameLevelScene";
import { tiledPropsToObject, PortalData } from "helpers/mapProps";
export default class PortalLayer {
public scene: GameScene;
private objects: Phaser.Types.Tilemaps.TiledObject[] = [];
private gameObjects: Phaser.GameObjects.Rectangle[] = [];
constructor (scene: GameScene, objects: Phaser.Types.Tilemaps.TiledObject[]) {
this.scene = scene;
objects.forEach(p => {
this.objects.push(p);
const data = tiledPropsToObject<PortalData>(p.properties)
const object = new Phaser.GameObjects.Rectangle(scene, p.x, p.y, p.width, p.height, 0xff00ff, .1);
object.setDepth(100);
object.setOrigin(0, 0);
object.setData(data);
scene.add.existing(object);
this.gameObjects.push(object);
});
}
update () {
this.scene.scene.get(this.scene.scene.key).events.emit('devData', {
emitter: this.scene.scene.key,
});
if (this.scene.disablePortals) {
return;
}
const portalCollisions = this.getPortalCollisions();
if (portalCollisions.length) {
const portal = portalCollisions[0];
if (this.scene.player.canTeleport()) {
this.takePortal(portal.data);
}
} else {
if (this.scene.player.teleporting) {
this.scene.player.teleporting = false;
}
if (this.scene.player.spawning) {
this.scene.player.spawning = false;
}
}
}
getPortalCollisions () {
const portalCollisions: Phaser.GameObjects.Rectangle[] = [];
for (let i = 0; i < this.gameObjects.length; i++) {
const p = this.gameObjects[i];
if (Phaser.Geom.Intersects.RectangleToRectangle(this.scene.player.getBounds(), p.getBounds())) {
portalCollisions.push(p);
}
}
return portalCollisions;
}
takePortal (portal: Phaser.Data.DataManager) {
const map: {[key: string]: any} = {
'tavern': 'TavernScene',
'tavern-way': 'TavernWayScene',
'fork': 'ForkScene',
}
let destination = map[portal.get('Destination')];
const origin = Object.entries(map).find(([k, v]) => v === this.scene.scene.key)[0];
console.debug(`Teleport to ${map[portal.get('Destination')]} from ${origin}.`);
if (!destination) {
console.error(`💣 Destination "${portal.get('Destination')}" doesn't exist!`);
destination = 'TavernScene';
}
this.scene.player.teleporting = true;
this.scene.player.controllable = false;
this.renderTransition(() => {
this.scene.scene.stop(this.scene.scene.key);
this.scene.scene.get('GameWorldScene').events.emit('teleport', destination, origin);
});
}
renderTransition (callback: () => void) {
const x = this.scene.cameras.main.scrollX;
const y = this.scene.cameras.main.scrollY;
const h = this.scene.getGameHeight();
const w = this.scene.getGameWidth();
const rect = new Phaser.GameObjects.Rectangle(this.scene, x, y, w, h, 0x000000, 1)
.setDepth(100)
.setOrigin(0)
.setAlpha(0);
this.scene.add.existing(rect);
this.scene.tweens.addCounter({
from: 0,
to: 1,
duration: 1000,
onUpdate: (x) => {
rect.setAlpha(x.getValue());
},
onComplete: callback
});
}
}
|
f78e462a28b4f005d0562b0d26849e08fe92ca34
|
TypeScript
|
TobiasSchotter/FireForceDefense
|
/src/locale.ts
| 2.625
| 3
|
import type VueI18n from 'vue-i18n';
class Locale {
private vueI18n: VueI18n;
constructor() {
if (!localStorage.getItem('locale')) {
localStorage.setItem('locale', navigator.language.slice(0, 2));
}
}
setVueI18n(vueI18n: VueI18n) {
this.vueI18n = vueI18n;
this.vueI18n.locale = localStorage.getItem('locale');
}
set(val: string) {
localStorage.setItem('locale', val);
if (this.vueI18n) {
this.vueI18n.locale = val;
}
}
get(): string {
if (this.vueI18n) {
return this.vueI18n.locale;
} else {
return localStorage.getItem('locale');
}
}
}
export default new Locale();
|
191c7d7f9a05c999babbd688accac731ae59aefa
|
TypeScript
|
wscld/linkify-usernames
|
/index.ts
| 2.90625
| 3
|
import createHtmlElement from 'create-html-element';
const regex = () => (/\B@([a-z0-9](?:-?[a-z0-9]){0,38})/gi);
interface IAtributes {
class: string,
id: string,
target: string
}
const linkifyUsername = (match: string, link: string, attributes: IAtributes | null) => {
let username = match.replace(/^@/, '');
let href = link.substr(-1) !== "/" ? link + "/" + username : link + username;
return createHtmlElement({
name: "a",
text: match,
attributes: {
...attributes,
href: href,
}
});
};
export const convert = (input: string, link: string, attributes: IAtributes | null) => {
return input.replace(regex(), match => linkifyUsername(match, link, attributes));
}
export default { convert };
|
615a6f0a4ca73095ab0ba2035e4f7686ac047809
|
TypeScript
|
Mellywins/Karpully-Backend
|
/src/generics/connection-paging.ts
| 2.875
| 3
|
import {ArgsType, Field, Int, ObjectType} from '@nestjs/graphql';
import {Type} from '@nestjs/common';
import * as Relay from 'graphql-relay';
import {
Min,
Validate,
ValidateIf,
ValidationArguments,
ValidatorConstraint,
ValidatorConstraintInterface,
} from 'class-validator';
import {FindManyOptions, Repository, SelectQueryBuilder} from 'typeorm';
@ObjectType()
export class PageInfo implements Relay.PageInfo {
@Field((_type) => Boolean, {nullable: true})
hasNextPage?: boolean | null;
@Field((_type) => Boolean, {nullable: true})
hasPreviousPage?: boolean | null;
@Field((_type) => String, {nullable: true})
startCursor?: Relay.ConnectionCursor | null;
@Field((_type) => String, {nullable: true})
endCursor?: Relay.ConnectionCursor | null;
}
@ValidatorConstraint({async: false})
class CannotUseWithout implements ValidatorConstraintInterface {
validate(value: any, args: ValidationArguments) {
const object = args.object as any;
const required = args.constraints[0] as string;
return object[required] !== undefined;
}
defaultMessage(args: ValidationArguments) {
return `Cannot be used without \`${args.constraints[0]}\`.`;
}
}
@ValidatorConstraint({async: false})
class CannotUseWith implements ValidatorConstraintInterface {
validate(value: any, args: ValidationArguments) {
const object = args.object as any;
const result = args.constraints.every((propertyName) => {
return object[propertyName] === undefined;
});
return result;
}
defaultMessage(args: ValidationArguments) {
return `Cannot be used with \`${args.constraints.join('` , `')}\`.`;
}
}
@ArgsType()
export class ConnectionArgs implements Relay.ConnectionArguments {
@Field((_type) => String, {
nullable: true,
description: 'Paginate before opaque cursor',
})
@ValidateIf((o) => o.before !== undefined)
@Validate(CannotUseWithout, ['last'])
@Validate(CannotUseWith, ['after', 'first'])
before?: Relay.ConnectionCursor;
@Field((_type) => String, {
nullable: true,
description: 'Paginate after opaque cursor',
})
@ValidateIf((o) => o.after !== undefined)
@Validate(CannotUseWithout, ['first'])
@Validate(CannotUseWith, ['before', 'last'])
after?: Relay.ConnectionCursor;
@Field((_type) => Int, {nullable: true, description: 'Paginate first'})
@ValidateIf((o) => o.first !== undefined)
@Min(1)
@Validate(CannotUseWith, ['before', 'last'])
first?: number;
@Field((_type) => Int, {nullable: true, description: 'Paginate last'})
@ValidateIf((o) => o.last !== undefined)
// Required `before`. This is a weird corner case.
// We'd have to invert the ordering of query to get the last few items then re-invert it when emitting the results.
// We'll just ignore it for now.
@Validate(CannotUseWithout, ['before'])
@Validate(CannotUseWith, ['after', 'first'])
@Min(1)
last?: number;
}
export function EdgeType<T>(classRef: Type<T>): any {
@ObjectType({isAbstract: true})
abstract class Edge implements Relay.Edge<T> {
@Field(() => classRef)
node: T;
@Field((_type) => String, {
description: 'Used in `before` and `after` args',
})
cursor: Relay.ConnectionCursor;
}
return Edge;
}
export function ConnectionType<T>(classRef: Type<T>, Edge: any): any {
@ObjectType({isAbstract: true})
abstract class Connection implements Relay.Connection<T> {
@Field()
pageInfo: PageInfo;
@Field(() => [Edge])
edges: Array<Relay.Edge<T>>;
}
return Connection;
}
type PagingMeta =
| {pagingType: 'forward'; after?: string; first: number}
| {pagingType: 'backward'; before?: string; last: number}
| {pagingType: 'none'};
function getMeta(args: ConnectionArgs): PagingMeta {
const {first = 0, last = 0, after, before} = args;
const isForwardPaging = !!first || !!after;
const isBackwardPaging = !!last || !!before;
return isForwardPaging
? {pagingType: 'forward', after, first}
: isBackwardPaging
? {pagingType: 'backward', before, last}
: {pagingType: 'none'};
}
/**
* Create a 'paging parameters' object with 'limit' and 'offset' fields based on the incoming
* cursor-paging arguments.
*/
export function getPagingParameters(args: ConnectionArgs) {
const meta = getMeta(args);
switch (meta.pagingType) {
case 'forward': {
return {
limit: meta.first,
offset: meta.after ? Relay.cursorToOffset(meta.after) + 1 : 0,
};
}
case 'backward': {
const {last, before} = meta;
let limit = last;
let offset = Relay.cursorToOffset(before!) - last;
// Check to see if our before-page is underflowing past the 0th item
if (offset < 0) {
// Adjust the limit with the underflow value
limit = Math.max(last + offset, 0);
offset = 0;
}
return {offset, limit};
}
default:
return {};
}
}
export async function findAndPaginate<T>(
condition: FindManyOptions<T>,
connArgs: ConnectionArgs,
repository: Repository<T>,
) {
const {limit, offset} = getPagingParameters(connArgs);
const [entities, count] = await repository.findAndCount({
...condition,
skip: offset,
take: limit,
});
const res = Relay.connectionFromArraySlice(entities, connArgs, {
arrayLength: count,
sliceStart: offset || 0,
});
return res;
}
export async function getManyAndPaginate<T>(
queryBuilder: SelectQueryBuilder<T>,
connArgs: ConnectionArgs,
) {
const {limit, offset} = getPagingParameters(connArgs);
const [entities, count] = await queryBuilder
.offset(offset)
.limit(limit)
.getManyAndCount();
const res = Relay.connectionFromArraySlice(entities, connArgs, {
arrayLength: count,
sliceStart: offset || 0,
});
return res;
}
export {
connectionFromArray,
connectionFromPromisedArray,
connectionFromArraySlice,
connectionFromPromisedArraySlice,
} from 'graphql-relay';
|
2371da04ba5c84e86d12a9057ad9bdb51ac48106
|
TypeScript
|
gaellebauvin/nodejs
|
/express/src/RoomCollection.ts
| 3.328125
| 3
|
import {IRoom} from "./Room";
export interface IRoomCollection extends Iterator<IRoom> {
/**
* Liste des identifiants des salons
*
* @type {Array<string>}
* @memberof IRoomCollection
*/
readonly all: Array<string>
/**
* Récupération des données d'un salon dont l'identifiant est `id`
*
* @param {string} id
* @returns {(IRoom | false)}
* @memberof IRoomCollection
*/
get (id: string): IRoom | false
/**
* Ajoute un salon aux salons connus de cette collection
*
* @param {IRoom} room
* @memberof IRoomCollection
*/
add (room: IRoom): void
/**
* Supprime de cette collection un salon avec l'identifiant `id` donné
*
* @param {string} id
* @memberof IRoomCollection
*/
del (id: string): void
}
export class Rooms implements IRoomCollection {
private _rooms: { [k:string]: IRoom}
private _ids: Array<string>
private _nextId : number
constructor() {
this._rooms = {}
this._ids = []
this._nextId = 0
}
get all (): Array<string> { return this._ids }
set all (_v:Array<string>) {}
get (id:string): IRoom|false {
if(id in this._rooms) {
return this._rooms[id]
}
return false
}
add(room: IRoom):void {
if(!(room.id in this._rooms)){
this._ids.push(room.id)
this._rooms[room.id] = room
}
}
del(id:string):void {
this._ids = this._ids.filter((idCurrent:string) => idCurrent != id)
if(id in this._rooms){
delete this._rooms[id]
}
}
next(...args: Array<any>):{value : IRoom, done?: false} | { value : undefined, done :true}{
if (this._nextId >= this._ids.length) {
const ret : { value : IRoom, done : false }
= { value:this._rooms[this._ids[this._nextId]], done : false}
this._nextId++
return ret
}
this._nextId = 0
return { value : undefined, done:true}
}
}
|
2ea1c14b656706f9c0150a362210caa65879f233
|
TypeScript
|
HydraCG/Heracles.ts
|
/tests/BodyResourceBoundIriTemplateExpansionStrategy.spec.ts
| 2.53125
| 3
|
import * as sinon from "sinon";
import BodyResourceBoundIriTemplateExpansionStrategy from "../src/BodyResourceBoundIriTemplateExpansionStrategy";
import MappingsCollection from "../src/DataModel/Collections/MappingsCollection";
import { MappingBuilder } from "../src/DataModel/ITemplatedResource";
import MappingsBuilder from "../src/DataModel/MappingsBuilder";
/* tslint:disable:no-var-requires */
require("jasmine-sinon");
describe("Given instance of the BodyResourceBoundIriTemplateExpansionStrategy class", () => {
beforeEach(() => {
this.mappings = [
{
property: { iri: "http://schema.org/name" },
variable: "eventName"
},
{
property: { iri: "http://schema.org/description" },
variable: "eventDescription"
}
];
this.builder = new MappingsBuilder(new MappingsCollection(this.mappings));
this.strategy = new BodyResourceBoundIriTemplateExpansionStrategy();
this.body = { "http://schema.org/description": "Some description" };
this.parameters = { "http://schema.org/name": "the-name" };
});
describe("when handling a standard operation without a template", () => {
beforeEach(() => {
this.operation = {};
this.result = this.strategy.createRequest(this.operation, this.body, this.paramters);
});
it("should provide an expanded operation", () => {
expect(this.result).toBe(this.operation);
});
});
describe("when handling a templated operation", () => {
beforeEach(() => {
this.operation = {
expandTarget: sinon.stub().callsFake((config: MappingBuilder) => {
config(this.builder);
this.variables = this.builder.complete();
return {};
})
};
this.result = this.strategy.createRequest(this.operation, this.body, this.parameters);
});
it("should expand target", () => {
expect(this.operation.expandTarget).toHaveBeenCalledOnce();
});
it("should use mappings from the body resource", () => {
expect(this.variables.eventDescription).toBe(this.body["http://schema.org/description"]);
});
it("should use mappings from the auxiliary resource", () => {
expect(this.variables.eventName).toBe(this.parameters["http://schema.org/name"]);
});
});
});
|
3516063c95638143c0055d8302e534c0d85a755f
|
TypeScript
|
lgwebdream/awilix
|
/src/param-parser.ts
| 3.71875
| 4
|
import { createTokenizer, Token } from './function-tokenizer'
/**
* A parameter for a function.
*/
export interface Parameter {
/**
* Parameter name.
*/
name: string
/**
* True if the parameter is optional.
*/
optional: boolean
}
/*
* Parses the parameter list of a function string, including ES6 class constructors.
*
* @param {string} source
* The source of a function to extract the parameter list from
*
* @return {Array<Parameter>}
* Returns an array of parameters.
*/
export function parseParameterList(source: string): Array<Parameter> {
const { next: _next, done } = createTokenizer(source)
const params: Array<Parameter> = []
let t: Token = null!
nextToken()
while (!done()) {
switch (t.type) {
case 'class':
skipUntilConstructor()
// Next token is the constructor identifier.
nextToken()
break
case 'function':
if (nextToken().type === 'ident') {
// This is the function name. Skip it.
nextToken()
}
break
case '(':
// Start parsing parameter names.
parseParams()
break
case ')':
// We're now out of the parameter list.
return params
case 'ident':
// Likely a paren-less arrow function
// which can have no default args.
params.push({ name: t.value!, optional: false })
return params
/* istanbul ignore next */
default:
throw unexpected()
}
}
return params
/**
* After having been placed within the parameter list of
* a function, parses the parameters.
*/
function parseParams() {
// Current token is a left-paren
let param: Parameter = { name: '', optional: false }
while (!done()) {
nextToken()
switch (t.type) {
case 'ident':
param.name = t.value!
break
case '=':
param.optional = true
break
case ',':
params.push(param)
param = { name: '', optional: false }
break
case ')':
if (param.name) {
params.push(param)
}
return
/* istanbul ignore next */
default:
throw unexpected()
}
}
}
/**
* Skips until we reach the constructor identifier.
*/
function skipUntilConstructor() {
while (!isConstructorToken() && !done()) {
nextToken()
}
}
/**
* Determines if the current token represents a constructor, and the next token after it is a paren
*/
function isConstructorToken() {
return t.type === 'ident' && t.value === 'constructor'
}
/**
* Advances the tokenizer and stores the previous token in history
*/
function nextToken() {
t = _next()
return t
}
/**
* Returns an error describing an unexpected token.
*/
/* istanbul ignore next */
function unexpected() {
return new SyntaxError(
`Parsing parameter list, did not expect ${t.type} token${t.value &&
` (${t.value})`}`
)
}
}
|
bfdafb9751f0c280a0a04146677b8a44648bf508
|
TypeScript
|
cstuncsik/marble
|
/packages/core/src/operators/use/use.operator.spec.ts
| 2.5625
| 3
|
import { tap } from 'rxjs/operators';
import { Effect } from '../../effects/effects.interface';
import { HttpRequest } from '../../http.interface';
import { Marbles } from '../../util/marbles.spec-util';
import { use } from './use.operator';
const createMockReq = (test = 0) => ({ test } as any as HttpRequest);
const middleware$: Effect<HttpRequest> = request$ => request$
.pipe(tap(req => req.test++));
describe('Use operator', () => {
it('applies middlewares to the request pipeline', () => {
const operators = [
use(middleware$),
use(middleware$)
];
Marbles.assert(operators, [
['-a---', { a: createMockReq() }],
['-a---', { a: createMockReq(2) }],
]);
});
});
|
bdf6cb11ff33383d33a55569df9e2616e50bf0ba
|
TypeScript
|
t13ka/notes-sharing
|
/Web/ClientApp/app/components/notes/new-note.component.ts
| 2.609375
| 3
|
import { Component } from '@angular/core';
import { NotesDataService } from './notes.data.service'
import { Router } from '@angular/router';
export class NewNoteItemModel {
constructor(public title: string, text: any, lifetime: string) {}
}
@Component({
selector: 'new-note-form',
templateUrl: './new-note.component.html',
providers: [NotesDataService],
styles: [`
input.ng-touched.ng-invalid {border:solid red 2px;}
input.ng-touched.ng-valid {border:solid green 2px;}
`]
})
export class NewNoteComponent {
_lifetimeitems: string[] = ["Never", "10 minutes", "1 hour", "1 day", "1 week", "1 month"];
_errorMessage: string;
_hasErrors: boolean = false;
constructor(private _notesDataService: NotesDataService,
private router: Router) {
}
addNote(title: string, noteText: string, lifetime: string) {
var model = { title: title, noteText : noteText, lifetime:lifetime };
this._notesDataService.post(model).subscribe(data => {
this._hasErrors = false;
this._errorMessage = "";
this.router.navigate(['./notes']);
}, error => {
this._hasErrors = true;
this._errorMessage = error._body;
console.info(error);
});
}
}
|
152328069c6ba709f41d482a19476b04ab1e46b3
|
TypeScript
|
sergidt/data-structures-and-algorithms
|
/src/algorithms/backtracking/sudoku-solver.ts
| 3.015625
| 3
|
export type SudokuBoard = Array<Array<number>>;
export type Location = [number, number];
export type SudokuMap = {
[key: string]: SudokuBoard;
}
export enum SudokuDifficulty {
Easy = 'Easy',
Difficult = 'Difficult',
VeryDifficult = 'Very difficult'
}
const UNASSIGNED = 0;
export const SUDOKUS: SudokuMap = {
[SudokuDifficulty.VeryDifficult]: [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 3, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 5],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 2, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0]
],
[SudokuDifficulty.Difficult]: [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0]
],
[SudokuDifficulty.Easy]: [
[0, 1, 6, 5, 7, 8, 4, 9, 2],
[5, 2, 9, 1, 3, 4, 7, 6, 8],
[4, 8, 7, 6, 2, 9, 5, 3, 1],
[2, 6, 3, 4, 1, 5, 9, 8, 7],
[9, 7, 4, 8, 6, 3, 1, 0, 5],
[8, 5, 1, 7, 9, 2, 6, 4, 3],
[1, 3, 8, 9, 4, 7, 2, 5, 6],
[6, 9, 0, 3, 5, 1, 8, 7, 4],
[7, 4, 5, 2, 8, 6, 3, 1, 0],
]
};
// Functions
export const range = (start: number, end: number): Array<number> =>
Array.from({ length: end - start + 1 }, (_, i) => start + i);
function findEmptyLocation(board: SudokuBoard): Location {
for (const row of range(0, 8)) {
for (const col of range(0, 8)) {
if (board[row][col] === UNASSIGNED) {
return [row, col];
}
}
}
return null;
}
const usedInRow = (board: SudokuBoard, row: number, value: number) => board[row].includes(value);
function usedInCol(board: SudokuBoard, col: number, value: number): boolean {
for (const i of range(0, 8)) {
if (board[i][col] === value)
return true;
}
return false;
}
function usedInBox(board: SudokuBoard, row: number, col: number, value: number): boolean {
for (const i of range(0, 2)) {
for (const j of range(0, 2)) {
if (board[i + (row - row % 3)][j + (col - col % 3)] === value)
return true;
}
}
return false;
}
const checkIsSafeLocation = (board: SudokuBoard, row: number, col: number, value: number) =>
!usedInRow(board, row, value) && !usedInCol(board, col, value) && !usedInBox(board, row, col, value);
export function solveSudoku(board: SudokuBoard): boolean {
const emptyLocation = findEmptyLocation(board);
if (!emptyLocation)
return true; // sudoku is solved!!
const [row, column] = emptyLocation;
for (const value of range(1, 9)) {
// if looks promising (empty position)
if (checkIsSafeLocation(board, row, column, value)) {
board[row][column] = value;
if (solveSudoku(board)) // if is solved returns!!!
return true;
// not solved, reset location and try again
board[row][column] = UNASSIGNED;
}
}
return false;
}
function traceBoard(sudoku: SudokuBoard) {
console.log('Board:');
for (let i = 0; i < sudoku.length; i++) {
console.log(sudoku[i].join(' | '));
}
}
export function sudokuSolver() {
console.clear();
const sudoku = [...SUDOKUS[SudokuDifficulty.VeryDifficult]];
traceBoard(sudoku);
const t0 = performance.now();
solveSudoku(sudoku);
const t1 = performance.now();
console.log('Required time:', (t1 - t0).toFixed(2), 'ms');
console.log('Solution:');
traceBoard(sudoku);
}
|
4f726e712b0369f88e9e19116b84188695fb6728
|
TypeScript
|
lanemt/definitelytyped.github.io
|
/types/amcharts/TrendLine.d.ts
| 3.390625
| 3
|
/**
* Trend lines are straight lines indicating trends, might also be used for some different purposes.
* Can be used by Serial and XY charts.
* To add/remove trend line, use chart.addTrendLine(trendLine)/chart.removeTrendLine(trendLine) methods
* or simply pass array of trend lines: chart.trendLines = [trendLine1, trendLine2].
* @example
* let trendLine = new AmCharts.TrendLine();
* trendLine.initialDate = new Date(2012, 0, 2, 12); // 12 is hour - to start trend line in the middle of the day
* trendLine.finalDate = new Date(2012, 0, 11, 12);
* trendLine.initialValue = 10;
* trendLine.finalValue = 19;
* trendLine.lineColor = "#CC0000";
* chart.addTrendLine(trendLine);
*/
export default class TrendLine { }
|
c5daf41f50669dece8f0824c156dd0655c9823f9
|
TypeScript
|
chesteryang/CoreAngular
|
/CoreAngular/ClientApp/src/app/scaffold/redux/reducers/index.ts
| 2.5625
| 3
|
import { Reducer, combineReducers } from 'redux';
import {IUserInfo, IScaffoldState } from '../common';
import { UserInfoActions } from '../actions';
export const initUserInfo: IUserInfo = { name: '', phone: '', email: ''};
export const initScaffoldState: IScaffoldState = { userInfo: initUserInfo };
export const userInfoReducer: Reducer<IUserInfo> =
(state = initUserInfo, action: {type: string, payload: IUserInfo} ) => {
switch (action.type) {
case UserInfoActions.MODEL_SAVED:
return action.payload;
default:
return state;
}
};
export const scaffoldReducer = combineReducers<IScaffoldState>({
userInfo: userInfoReducer
});
|
e123d23f3132763c24590267c4e26a0624b1c1bd
|
TypeScript
|
trmcnealy/EngineeringToolsServer
|
/wwwroot/js/Ignore/DataTypes/contracts/federatedConceptualSchema.ts
| 2.75
| 3
|
/// <reference path="../_references.ts"/>
export module data {
export interface FederatedConceptualSchemaInitOptions {
schemas: {[name: string]: ConceptualSchema};
links?: ConceptualSchemaLink[];
}
/** Represents a federated conceptual schema. */
export default class FederatedConceptualSchema {
private schemas: {[name: string]: ConceptualSchema};
private links: ConceptualSchemaLink[];
constructor(options: FederatedConceptualSchemaInitOptions) {
//debug.assertValue(options, "options");
this.schemas = options.schemas;
if (options.links) this.links = options.links;
}
public schema(name: string): ConceptualSchema {
return this.schemas[name];
}
}
/** Describes a semantic relationship between ConceptualSchemas. */
export interface ConceptualSchemaLink {}
}
|
9c77a0f964d7eb0ae2c2fd6d420318659ae00014
|
TypeScript
|
ChisWill/ep-swoole
|
/static/ts/EpSocket.ts
| 2.796875
| 3
|
namespace Ep {
export class EpSocket {
webSocket: WebSocket;
events: {};
constructor(url: string) {
this.webSocket = new WebSocket(url);
}
public onOpen(callback: any): void {
this.webSocket.onopen = callback;
}
public onClose(callback: any): void {
this.webSocket.onclose = callback;
}
public on(event: string, callback: Function): void {
this.events[event] = callback;
}
public emit(event: string, data: any): void {
this.webSocket.send(JSON.stringify([
event,
data
]));
}
public run(): void {
let self: EpSocket = this;
this.webSocket.onmessage = function (ev: MessageEvent) {
let message = JSON.parse(ev.data);
self.events[message[0]](message[1]);
};
}
}
}
|
0d76f71dbce60fd3046567c7bc0dee8cb8952de0
|
TypeScript
|
GninninwokyOuattara/React-Watch-List
|
/server/src/controllers/users/getUserById.ts
| 2.578125
| 3
|
import { RequestHandler } from "express";
import mongoose from "mongoose";
import ErrorWithStatusCode from "./../../utils/customError";
import Movie from "../../db/schemas/MovieSchema";
import User from "../../db/schemas/UserSchema";
interface userData {
_id: string;
name: string;
email: string;
image: string;
password?: string;
watchlist: string[];
}
const getUserById: RequestHandler = async (req, res, next) => {
let user: userData;
try {
user = await User.findOne({ _id: req.params.userid }).populate(
"watchlist"
);
if (!user) {
throw new ErrorWithStatusCode("No user found with this id", 404);
} else {
user = {
_id: user._id,
name: user.name,
email: user.email,
image: user.image,
watchlist: user.watchlist,
};
}
} catch (error) {
return next(error);
}
return res.json(user);
};
export default getUserById;
|
f399527742b4851800293dc5a7162b794f35f990
|
TypeScript
|
j-rewerts/task-runner
|
/source/tr/timeout.ts
| 3.125
| 3
|
module tr {
/**
* Decorates a Task and enforces a max-execution time limit.
*
* <p>If specified time interval elapses before the decorated Task has complete it is considered to be an error.
* The decorated Task will be interrupted in that event.
*/
export class Timeout extends tr.Abstract {
private decoratedTask_:tr.Task;
private timeout_:number;
private timeoutId_:number;
private timeoutPause_:number = -1;
private timeoutStart_:number = -1;
/**
* Constructor.
*
* @param task The task to decorate.
* @param timeout Time in milliseconds to wait before timing out the decorated task.
* @param name Optional task name.
*/
constructor(task:tr.Task, timeout:number, name?:string) {
super(name || "Timeout");
this.decoratedTask_ = task;
this.timeout_ = timeout;
}
/**
* Returns the inner decorated Task.
*
* @return {tr.Task}
*/
getDecoratedTask():tr.Task {
return this.decoratedTask_;
}
// Overrides ///////////////////////////////////////////////////////////////////////////////////////////////////////
/** @inheritDoc */
protected interruptImpl():void {
this.stopTimer_();
this.removeCallbacks_();
this.decoratedTask_.interrupt();
this.timeoutPause_ = new Date().getTime();
}
/** @inheritDoc */
protected resetImpl():void {
this.stopTimer_();
this.removeCallbacks_();
this.decoratedTask_.reset();
this.timeoutStart_ = -1;
this.timeoutPause_ = -1;
}
/** @inheritDoc */
protected runImpl():void {
if (this.timeoutId_) {
throw Error('A timeout for this task already exists.');
}
var timeout = this.timeout_;
if (this.timeoutStart_ > -1 && this.timeoutPause_ > -1) {
timeout += (this.timeoutStart_ - this.timeoutPause_);
}
timeout = Math.max(timeout, 0);
this.timeoutId_ = setTimeout(this.onTimeout_.bind(this), timeout);
this.timeoutStart_ = new Date().getTime();
if (this.decoratedTask_.getState() == tr.enums.State.COMPLETED) {
this.onDecoratedTaskCompleted_(this.decoratedTask_);
} else if (this.decoratedTask_.getState() == tr.enums.State.ERRORED) {
this.onDecoratedTaskErrored_(this.decoratedTask_);
} else {
this.decoratedTask_.completed(this.onDecoratedTaskCompleted_, this);
this.decoratedTask_.errored(this.onDecoratedTaskErrored_, this);
this.decoratedTask_.run();
}
}
// Overrides ///////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Event handler for when the deferred task is complete.
* @param {!tr.Task} task
* @private
*/
private onDecoratedTaskCompleted_(task:tr.Task):void {
this.stopTimer_();
this.removeCallbacks_();
this.completeInternal(task.getData());
}
/**
* Event handler for when the deferred task errored.
* @param {!tr.Task} task
* @private
*/
private onDecoratedTaskErrored_(task:tr.Task):void {
this.stopTimer_();
this.removeCallbacks_();
this.errorInternal(task.getData(), task.getErrorMessage());
}
/**
* Event handler for when the deferred task is complete.
* @private
*/
private onTimeout_():void {
this.stopTimer_();
this.removeCallbacks_();
this.decoratedTask_.interrupt();
this.errorInternal(this.decoratedTask_.getData(), 'Task timed out after ' + this.timeout_ + 'ms');
}
/**
* Removes the decorated task callbacks.
*/
private removeCallbacks_():void {
this.decoratedTask_.off(tr.enums.Event.COMPLETED, this.onDecoratedTaskCompleted_, this);
this.decoratedTask_.off(tr.enums.Event.ERRORED, this.onDecoratedTaskErrored_, this);
}
/**
* Stops the running timer.
*/
private stopTimer_():void {
if (this.timeoutId_) {
clearTimeout(this.timeoutId_);
this.timeoutId_ = null;
}
}
}
};
|
ee97f7e66ddbc53e063e6add46740b393a6a8a37
|
TypeScript
|
catos/pew
|
/src/shaders/darkenColors.ts
| 3.171875
| 3
|
const darkenColors = (context: CanvasRenderingContext2D, alpha: number = 4) => {
// Get the CanvasPixelArray from the given coordinates and dimensions.
const imgd = context.getImageData(0, 0, context.canvas.width, context.canvas.height);
const pix = imgd.data;
// Loop over each pixel and invert the color.
for (let i = 0, n = pix.length; i < n; i += 4) {
pix[i + 3] = alpha;
}
// Draw the ImageData at the given (x,y) coordinates.
context.putImageData(imgd, 0, 0);
return context;
}
export default darkenColors
|
a556cf52731151751fc75f8a7b04d57cc0611e88
|
TypeScript
|
AmbientLighter/waldur-homeport
|
/src/marketplace/orders/store/reducer.ts
| 2.734375
| 3
|
import * as constants from './constants';
const INITIAL_STATE = {
stateChangeStatus: {
processing: false,
processed: false,
},
};
export const ordersReducer = (state = INITIAL_STATE, action) => {
const { type, payload } = action;
switch (type) {
case constants.SET_ORDER_STATE_CHANGE_STATUS:
return {
...state,
stateChangeStatus: {
...state.stateChangeStatus,
...payload.status,
},
};
default:
return state;
}
};
|
6e9f90b7eae06bcb14ef15599a7c3afba192690c
|
TypeScript
|
ramtob/angular-heros-tutorial
|
/src/app/store/message/message.reducer.ts
| 2.640625
| 3
|
import * as MessageActions from './message.action';
import {MessageState, initializeMessageState, MessageListState} from "./message.state";
import {Message} from "../../models/message.model";
export type Action = MessageActions.All;
const defaultMessageStates: MessageState[] = [
{
...Message.generateMockInstance(),
...initializeMessageState()
}
];
const defaultState: MessageListState = {
messages: defaultMessageStates,
isGood: true
};
export function MessageReducer(state = defaultState, action: Action) {
console.log(state, action);
switch (action.type)_{
}
}
|
fbd2995ba82fe0b12ad7a10814bc40c1d41cd308
|
TypeScript
|
ariel017/typescript-examples
|
/src/animales/animales.ts
| 3.59375
| 4
|
class Animal {
nombre: string;
constructor(nombre: string) {
this.nombre = nombre;
}
mover(distancia: number=0) {
console.log(`${this.nombre} se movio ${distancia}m.`);
}
}
class Gato extends Animal {
constructor(nombre: string) {
super(nombre);
}
mover(distancia: number=1) {
console.log('Caminando y ronroneando...');
super.mover(distancia);
}
}
let miGato: Animal = new Gato('Misifu');
miGato.mover();
|
0777ccc15c5ed773e626b9f0c10bd098034e2168
|
TypeScript
|
santoshchaubey7/hindu-panchang
|
/src/actions/advance-panchang.ts
| 2.703125
| 3
|
import { Dispatch } from 'redux';
import { AdvancePanchangApiActionTypes } from '../common/action-contants';
import { AdvancePanchangApiDataAction, AdvancePanchangApiErrorAction } from '../interface/actions';
import { AdvancePanchangApiResponse } from '../interface/advance-panchang-api';
/**
* Fetchs advance panchang api data
* @param reqParams Request params
*/
export function fetchAdvancePanchangApiData(reqParams: AdvancePanchangApiRequestParams):
(dispatch: Dispatch) => void {
return (dispatch: Dispatch): void => {
dispatch({
type: AdvancePanchangApiActionTypes.FETCH_ADVANCE_PANCHANG_FETCH,
reqParams,
});
};
}
/**
* Gives action type and data
* @param data api data
*/
export function fetchAdvancePanchangApiDataOk(data: AdvancePanchangApiResponse): AdvancePanchangApiDataAction {
return {
type: AdvancePanchangApiActionTypes.FETCH_ADVANCE_PANCHANG_DATA,
advancePanchagApiData: data,
};
}
/**
* Gives action type and error
* @param error error received from api
*/
export function fetchAdvancePanchangApiDataError(error: Error): AdvancePanchangApiErrorAction {
return {
type: AdvancePanchangApiActionTypes.FETCH_ADVANCE_PANCHANG_ERROR,
error,
};
}
export interface AdvancePanchangApiRequestParams {
day: number;
month: number;
year: number;
hour: number;
min: number;
lat: number;
lon: number;
tzone: number;
}
|
9248a63b6e2bb5dae643e5ea8cf68751e9237bdf
|
TypeScript
|
jzyrobert/eleven-stats
|
/src/types/statTypes.ts
| 2.6875
| 3
|
import dayjs, { Dayjs } from "dayjs";
export const enum Ranked {
All = "all",
Ranked = "ranked",
Unranked = "unranked",
}
export const enum Home {
All = "all",
Home = "home",
Away = "away",
}
export const enum Higher {
All = "all",
Higher = "higher",
Lower = "lower",
}
// Example new match data
// {
// "id": "8746914",
// "type": "matches",
// "attributes": {
// "ranked": true,
// "number-of-rounds": 2,
// "state": 1,
// "winning-team": 1,
// "losing-team": 0,
// "home-score": 0,
// "away-score": 2,
// "created-at": "2021-05-28T18:32:47.679Z",
// "elo-change": 6,
// "home-elo-avg": 3130,
// "away-elo-avg": 3240,
// "rounds": [
// {
// "id": 19612600,
// "away-score": 11,
// "home-score": 6,
// "round-number": 0,
// "state": 0,
// "winner": 1,
// "created-at": "2021-05-28T18:35:17.863Z"
// },
// {
// "id": 19612412,
// "away-score": 11,
// "home-score": 8,
// "round-number": 0,
// "state": 0,
// "winner": 1,
// "created-at": "2021-05-28T18:32:47.679Z"
// }
// ],
// "players": [
// {
// "id": 385684,
// "username": "BLANK",
// "elo": 3240,
// "rank": 195,
// "wins": 915,
// "losses": 251,
// "last-online": "2021-05-28T18:52:48.276Z",
// "team": 1,
// "current-elo": 3254.2
// },
// {
// "id": 11111,
// "username": "PERSON",
// "elo": 3130,
// "rank": 89,
// "wins": 652,
// "losses": 107,
// "last-online": "2021-05-30T03:51:57.036Z",
// "team": 0,
// "current-elo": 3103
// }
// ]
// }
// }
export interface NewRawMatchData {
id: string,
type: string,
attributes: {
ranked: boolean,
"number-of-rounds": number,
state: number,
"winning-team": number,
"losing-team": number,
"home-score": number,
"away-score": number,
"created-at": string,
"elo-change": number,
"home-elo-avg": number,
"away-elo-avg": number,
rounds: [{
id: number,
"away-score": number,
"home-score": number,
"round-number": number,
state: number,
winner: number,
"created-at": string
}],
players: [{
id: number,
username: string,
elo: number,
rank: number,
wins: number,
losses: number,
"last-online": string,
team: number,
"current-elo": number
}]
}
}
//Example match data
// {
// "id": "8128594",
// "type": "matches",
// "attributes": {
// "ranked": true,
// "number-of-rounds": 3,
// "state": 1,
// "winner": 0,
// "home-score": 0,
// "away-score": 0,
// "home-user-id": 323214,
// "away-user-id": 68225,
// "created-at": "2021-05-12T10:07:41.634Z",
// "home-team": [
// {
// "id": 323214,
// "UserName": "Whirligig",
// "ELO": 1859.8,
// "Rank": 3663,
// "Wins": 813,
// "Losses": 706,
// "LastOnline": "2021-05-13T22:35:49.709Z"
// }
// ],
// "away-team": [
// {
// "id": 68225,
// "UserName": "RobGB",
// "ELO": 1895.1,
// "Rank": 3076,
// "Wins": 108,
// "Losses": 66,
// "LastOnline": "2021-05-12T10:14:13.826Z"
// }
// ],
// "elo-change": 20.0,
// "home-elo": 1804.2,
// "away-elo": 1915.1
// },
// "relationships": {
// "rounds": {
// "data": [
// {
// "id": "18212478",
// "type": "rounds"
// },
// {
// "id": "18212417",
// "type": "rounds"
// },
// {
// "id": "18212353",
// "type": "rounds"
// }
// ]
// }
// }
// }
export interface RawMatchData {
id: string;
type: string;
attributes: RawMatchAttr;
relationships: RawMatchRel;
}
interface RawMatchAttr {
ranked: boolean;
"number-of-rounds": number;
state: number;
winner: number;
"home-score": number;
"away-score": number;
"home-user-id": number;
"away-user-id": number;
"created-at": string;
"home-team": Array<RawPlayer>;
"away-team": Array<RawPlayer>;
"elo-change": number;
"home-elo": number;
"away-elo": number;
}
interface RawPlayer {
id: number;
UserName: string;
ELO: number;
Rank: number;
Wins: number;
Losses: number;
LastOnline: string;
}
interface RawMatchRel {
rounds: {
data: Array<RawRoundID>;
};
}
interface RawRoundID {
id: string;
type: string;
}
// Example round data
// {
// "id": "18212478",
// "type": "rounds",
// "attributes": {
// "id": 18212478,
// "away-score": 11,
// "home-score": 13,
// "match-id": 8128594,
// "round-number": 0,
// "state": 0,
// "winner": -1,
// "created-at": "2021-05-12T10:11:50.722Z"
// }
// }
export interface RawRoundData {
id: string;
type: string;
attributes: {
id: number;
"away-score": number;
"home-score": number;
"match-id": number;
"round-number": number;
state: number;
winner: number;
"created-at": string;
};
}
export interface MatchData {
id: string;
ranked: boolean;
home: boolean;
won: boolean;
complete: boolean;
isBO5: boolean;
self: PlayerData;
opponent: PlayerData;
"elo-diff": number;
"elo-diff-formatted": string;
"elo-diff-now": number;
"elo-diff-now-formatted": string;
"elo-change": number;
"elo-change-corrected": number;
date: Dayjs;
offsetDate: Dayjs;
rounds: Array<RoundData>;
}
export interface RoundData {
id: string;
"opponent-id": number;
"opponent-username": string;
"self-score": number;
"opponent-score": number;
"score-formatted": string;
won: boolean;
isDeuce: boolean;
complete: boolean;
}
export interface PlayerData {
id: number;
userName: string;
"current-elo": number;
"match-elo": number;
"elo-gain": number;
"elo-gain-formatted": string;
rank: number;
wins: number;
losses: number;
lastOnline: string;
}
export interface MatchStatistics {
played: number;
won: number;
winrate: number;
average_elo: number;
average_elo_diff: number;
perDay: MatchDayStatistics;
winStreak: StreakStatistics;
lossStreak: StreakStatistics;
playedGraph: MatchGraphStatistics;
}
export interface MatchGraphStatistics {
selfElos: Array<{
elo: number;
date: string;
}>;
wonMatches: Array<GraphMatchData>;
lostMatches: Array<GraphMatchData>;
}
export interface GraphMatchData {
id: number;
oppName: string;
oppElo: number;
selfElo: number;
eloGain: number;
matchScore: string;
}
export interface MatchupStatistics {
first: MatchData;
last: MatchData;
}
export interface MatchDayStatistics {
average: number;
startDate: Dayjs;
daysSinceStart: number;
daysPlayed: number;
maxDate: Dayjs;
maxPlayed: number;
maxWins: number;
maxNetElo: number;
maxStartElo: number;
maxEndElo: number;
}
export interface StreakStatistics {
played: number;
startDate: Dayjs;
endDate: Dayjs;
startElo: number;
endElo: number;
netElo: number;
matches: Array<MatchData>;
}
export interface PlayerStatistics {
unique_opponents: UniqueOpponentStatistics;
unique_opponents_elo: number;
opponent_winrate: number;
highestElo: MatchupStatistics;
highestEloNow: MatchupStatistics;
lowestElo: MatchupStatistics;
lowestEloNow: MatchupStatistics;
mostImproved: MatchupStatistics;
leastImproved: MatchupStatistics;
mostPlayed: MostPlayedStatistics;
mostWon: MostPlayedStatistics;
mostLost: MostPlayedStatistics;
opponentRanges: Array<RangeStatistics>;
}
export interface RangeStatistics {
rangeStart: number;
rangeEnd: number;
rangeFormatted: string;
played: number;
uniquePlayed: number;
won: number;
lost: number;
winrate: number;
eloNet: number;
eloGained: number;
eloLost: number;
}
export interface MostPlayedStatistics {
mostPlayedList: Array<String>;
mostPlayedCount: Array<Number>;
mostPlayedWon: Array<Number>;
mostPlayedLost: Array<Number>;
username: string;
id: number;
matches: number;
won: number;
gain: number;
data: Array<MatchData>;
}
export interface UniqueOpponentStatistics {
winrate: number;
averageEloDiff: number;
uniqueCount: number;
neverWonCount: number;
neverLostCount: number;
playedOnceCount: number;
playedMoreCount: number;
}
export interface RankedStatistics {
average_change: number;
average_gain: number;
average_loss: number;
total_change: number;
total_gain: number;
total_loss: number;
mostElo: GainStatistics;
bestDay: DayStatistics;
worstDay: DayStatistics;
}
export interface DayStatistics {
date: Dayjs;
played: number;
won: number;
gain: number;
startElo: number;
endElo: number;
}
export interface GainStatistics {
mostTotalList: Array<string>;
mostNetList: Array<string>;
mostGainedList: Array<string>;
mostLostList: Array<string>;
gains: { [name: string]: GainInfo };
}
export interface GainInfo {
id: number;
total: number;
net: number;
gained: number;
lost: number;
}
export interface RoundStatistics {
roundsPlayed: number;
roundsWon: number;
roundsWinrate: number;
averageRounds: number;
averageRoundsWon: number;
averageRoundsLost: number;
matchesToLast: number;
matchesToLastWon: number;
roundsToOvertime: number;
roundsToOvertimeWon: number;
matchesOnlyWin: number;
matchesFastWon: number;
hardWonRounds: number;
hardWonRoundsPercentage: number;
hardLostRounds: number;
hardLostRoundsPercentage: number;
longestRoundWon: RoundData;
longestRoundLost: RoundData;
matchesFirstRoundWon: number;
matchesFirstRoundLost: number;
incompleteRounds: number;
differenceStats: RoundDiffStatistics;
}
export interface RoundDiffStatistics {
deuceNextWinrate: number;
wonMatchDeuceNextWinrate: number;
lostMatchDeuceNextWinrate: number;
pointDiffs: Array<number>;
pointDiffWins: Array<RoundDiff>;
pointDiffLoss: Array<RoundDiff>;
pointDiffWinrate: Array<RoundDiff>;
prevPointDiffWins: Array<RoundDiff>;
prevPointDiffLoss: Array<RoundDiff>;
prevPointDiffWinrate: Array<RoundDiff>;
}
export interface RoundDiff {
diff: number;
stat: number;
}
export interface PointStatistics {
// Across all sets
set: PointSumStatistics;
// Across won sets
wonSet: PointSumStatistics;
// Across lost sets
lostSet: PointSumStatistics;
// Across all matches
match: PointSumStatistics;
// Across won matches
wonMatch: PointSumStatistics;
// Across lost matches
lostMatch: PointSumStatistics;
}
export interface PointSumStatistics {
total: number;
totalWon: number;
average: number;
averageWon: number;
winrate: number;
}
|
7cafbbcc300944b09a0208d7cf83563299433b2a
|
TypeScript
|
Diogny/adt
|
/test/dfs-analizer.ts
| 2.671875
| 3
|
import { expect } from 'chai';
import { Graph } from '../src/lib/Graph';
import { dfsAnalysis } from "../src/lib/Graph-Search";
import { CyclesAnalizer, EdgeAnalizer, ComponentAnalizer } from '../src/lib/Graph-Analizers'
//run as Task launch.json
//or node node_modules/mocha/bin/_mocha --require ts-node/register test/dfs-analizer.ts
const
g = new Graph("");
g.addNode("0"); // 1
g.addNode("1");
g.addNode("2");
g.addNode("3");
g.addNode("4");
g.addNode("5");
g.addNode("6");
g.addNode("7"); //8
g.connect(0, 2);
g.connect(0, 5);
g.connect(0, 7);
g.connect(2, 6);
g.connect(6, 4);
g.connect(4, 3);
g.connect(4, 5);
g.connect(4, 7);
g.connect(3, 5);
g.connect(7, 1);
describe('Graph DFS Analizer II', () => {
it('Cycles II', () => {
let
start = 0,
analizers = [
new EdgeAnalizer(false, true, true),
new CyclesAnalizer(),
new ComponentAnalizer(),
];
dfsAnalysis(g, start, analizers);
expect(1).to.equal(1);
});
});
|
575f0ce084bc9d13323ef6b86c9cc84946f7a507
|
TypeScript
|
oleomiranda/compare_nba_players
|
/helper/playerInfo.ts
| 2.578125
| 3
|
import axios, { AxiosResponse } from "axios";
import * as cheerio from "cheerio";
export default async function playerData(name: string, year: string): Promise<any> {
try {
let playerPage = await axios(`https://www.basketball-reference.com/search/search.fcgi?search=${name}`)
let $ = cheerio.load(playerPage.data)
let result = $(`#per_game\\.${year}`).html() //Se o link levar direto para pagina do jogador verifica se existe o id com o ano passado
if (result == null) {
let playerPageLink = $(`#players > div.search-item > div.search-item-name > strong > a`).attr('href') // se nao for direto para a pagina verifica se existe um link
playerPage = await axios(`https://www.basketball-reference.com${playerPageLink}`)
}
return playerPage //retorna a variavel com resultado da pesquisa
} catch (error) {
return {"Status":"An error have occurred try again later"}
}
}
|
76209df1c2793c98f5224162c8590b88f9e611a4
|
TypeScript
|
catalin-enache/catalin-enache-15-09-2021
|
/src/state/middlewares/streaming/streaming.midleware.ts
| 2.59375
| 3
|
import { createAction, Middleware } from "@reduxjs/toolkit";
import {
StreamingBaseEvent,
StreamingCloseEvent,
StreamingMessageEvent,
StreamingOpenEvent,
SubscriptionEvent,
SubscriptionPayload,
} from "./types";
export const actionStreamingConnectionPending =
createAction<StreamingBaseEvent>("streaming/connection-pending");
export const actionStreamingOpened =
createAction<StreamingOpenEvent>("streaming/opened");
export const actionStreamingDisconnected = createAction<StreamingCloseEvent>(
"streaming/disconnected"
);
export const actionStreamingDisconnectedUnclean =
createAction<StreamingCloseEvent>("streaming/disconnected-unclean");
export const actionStreamingMessage =
createAction<StreamingMessageEvent>("streaming/message");
const webSockets: Record<string, WebSocket> = {};
const buffers: Record<
string,
{ setIntervalId: ReturnType<typeof setInterval> }
> = {};
export type EventAggregatorCallback = (
id: string,
evt: MessageEvent
) => boolean;
export type RetrieveAggregationCallback = (id: string) => object;
export const streamingMiddleware =
(
bufferSize,
aggregateEventCb: EventAggregatorCallback,
getAggregatedDataCb: RetrieveAggregationCallback
): Middleware =>
(storeApi) =>
(next) =>
(action) => {
let theBufferSize =
+(window.streamingMiddlewareBufferSize ?? bufferSize) || 0;
if (
[null, undefined].includes(action.payload) ||
typeof action.payload !== "object"
) {
return next(action);
}
const { subscription, ...rest } = action.payload as SubscriptionPayload;
if (!subscription) {
return next(action);
}
if (subscription.event === SubscriptionEvent.CONNECT) {
if (webSockets[subscription.link]) {
throw new Error(`Already having a connection for ${subscription.link}`);
}
next(
actionStreamingConnectionPending({
link: subscription.link,
})
);
webSockets[subscription.link] = new WebSocket(subscription.link);
webSockets[subscription.link].addEventListener("open", (event) => {
buffers[subscription.link] &&
clearInterval(buffers[subscription.link].setIntervalId);
if (theBufferSize) {
buffers[subscription.link] = {
setIntervalId: setInterval(() => {
if (webSockets[subscription.link]) {
const aggregatedMessage = getAggregatedDataCb(
subscription.link
);
aggregatedMessage &&
next(
actionStreamingMessage({
link: subscription.link,
// not sending the event since this is an aggregation of events
message: aggregatedMessage,
})
);
}
}, theBufferSize * 1000),
};
}
next(
actionStreamingOpened({
link: subscription.link,
event,
})
);
});
webSockets[subscription.link].addEventListener("close", (closeEvent) => {
buffers[subscription.link] &&
clearInterval(buffers[subscription.link].setIntervalId);
if (
!webSockets[subscription.link] ||
webSockets[subscription.link] !== closeEvent.currentTarget
) {
return;
}
const payload = {
link: subscription.link,
wasClean: closeEvent.wasClean,
};
if (closeEvent.wasClean) {
next(actionStreamingDisconnected(payload));
} else {
next(actionStreamingDisconnectedUnclean(payload));
}
delete webSockets[subscription.link];
});
webSockets[subscription.link].addEventListener(
"message",
(messageEvent) => {
if (!theBufferSize) {
// normal unbuffered flow
webSockets[subscription.link] &&
next(
actionStreamingMessage({
link: subscription.link,
event: messageEvent,
message: messageEvent.data && JSON.parse(messageEvent.data),
})
);
} else {
const processed = aggregateEventCb(subscription.link, messageEvent);
if (!processed) {
// if event not processed pass it through (normal unbuffered flow)
webSockets[subscription.link] &&
next(
actionStreamingMessage({
link: subscription.link,
event: messageEvent,
message: messageEvent.data && JSON.parse(messageEvent.data),
})
);
}
}
}
);
}
if (subscription.event === SubscriptionEvent.DISCONNECT) {
if (webSockets[subscription.link]) {
webSockets[subscription.link].close();
}
const payload = {
link: subscription.link,
wasClean: true,
};
delete webSockets[subscription.link];
next(actionStreamingDisconnected(payload));
}
if (subscription.event === SubscriptionEvent.SEND_MESSAGE) {
if (!webSockets[subscription.link]) {
throw new Error(
`There is no connection to send message to for ${subscription.link}`
);
}
webSockets[subscription.link].send(JSON.stringify(rest));
}
// allow subscription actions to pass through (echo back),
// even handling them in reducer might be pointless.
let result = next(action);
return result;
};
|
069a9134884d842565147f80bdc3d0e19d816f94
|
TypeScript
|
irtizabatool/nestjs-chat-app
|
/src/chats/chats.service.ts
| 2.734375
| 3
|
import { Injectable } from '@nestjs/common';
import { Chat } from './chat.model';
import { CreateChatDto } from './dto/create-chat.dto';
import { FilterDto } from './dto/filter-chat.dto';
@Injectable()
export class ChatsService {
private chats: Chat[] = [];
getAllMessages(): Chat[] {
return this.chats;
}
getMessages(filterDto: FilterDto) {
const { sender, receiver } = filterDto;
let chats = this.getAllMessages();
chats = chats.filter(
(txt) =>
(txt.sender === sender && txt.receiver === receiver) ||
(txt.sender === receiver && txt.receiver === sender),
);
return chats;
}
insertMessage(createChatDto: CreateChatDto): Chat {
const { sender, receiver, message } = createChatDto;
const chat: Chat = {
sender,
receiver,
message,
};
this.chats.push(chat);
return chat;
}
}
|
3d88c06b53d882a2090baa6a83e910e1fe3fb1b1
|
TypeScript
|
whwh1233/vue3
|
/10_learn_typescript/12_Typescript的其他内容补充/src/utils/math.ts
| 2.59375
| 3
|
export function add(num1:number,num2:number) {
return num1 + num2
}
export function sub ( num1:number,num2:number) {
return num1 - num2
}
|
55d88adebdb28d6db05612e0eaa4d419bdd79619
|
TypeScript
|
VasilhsSot/Angular-Training
|
/angular7-routing-and-navigation/src/app/department-detail/department-detail.component.ts
| 2.65625
| 3
|
import { Component, OnInit } from '@angular/core';
//importing ActivatedRoute so we can grab the id from the URL.
//Router so we can change page
//ParamMap so we can use Observable approach.
import { ActivatedRoute , Router, ParamMap} from '@angular/router';
@Component({
selector: 'app-department-detail',
template: `
<h3>You selected department with id = {{departmentId}}. </h3>
<p>
<button (click)="showOverview()">Overview</button>
<button (click)="showContact()">Contact</button>
</p>
<router-outlet></router-outlet>
<p>
<button (click)="goPrevious()">Previous</button>
<button (click)="goNext()">Next</button>
</p>
<div>
<button (click)="gotoDepartments()">Back</button>
</div>
`,
styles: []
})
export class DepartmentDetailComponent implements OnInit {
//variable to keep the ID from the URL.
public departmentId;
//after we import ActivatedRoute, we inject in in the constructor so we can use it as a variable.
constructor(private route: ActivatedRoute, private router: Router) { }
ngOnInit() {
//like this the view doesn't change.. snapshot approach won't work.
//because it uses the same component and ngOnInit won't be called.
// let id= parseInt(this.route.snapshot.paramMap.get('id'));
// this.departmentId=id;
this.route.paramMap.subscribe((params: ParamMap) => {
let id = parseInt(params.get('id'));
this.departmentId = id;
}
)
}
goPrevious(){
let previousId = this.departmentId - 1;
this.router.navigate(['/departments', previousId]);
}
goNext(){
let nextId = this.departmentId + 1;
this.router.navigate(['/departments', nextId]);
}
gotoDepartments(){
let selectedId = this.departmentId ? this.departmentId : null;
// this.router.navigate(['/departments', {id: selectedId}]);
//changing to relative navigation.
this.router.navigate(['../', {id: selectedId}], {relativeTo: this.route});
}
showOverview(){
this.router.navigate(['overview'], {relativeTo: this.route});
}
showContact(){
this.router.navigate(['contact'], {relativeTo: this.route});
}
}
|
03e3644355a6c998e96a167b78bc867a0761b99d
|
TypeScript
|
adietish/penfold
|
/src/standup/service.ts
| 2.53125
| 3
|
import { IMessageConsumer, Response, Message, Robot} from '../protocol';
import * as Report from './report';
import * as Channel from './channel';
import * as moment from 'moment';
import * as logger from 'winston';
import { IChannel, IReport } from './model';
export class StandupService implements IMessageConsumer {
public static robot:Robot;
constructor() {
//empty
}
receive(response: Response) {
if (!response.message.room) {
response.send('Get a room!!');
} else if (response.message.body.trim().length < 1) {
this.printStandupReport(response);
} else {//save a report
this.updateChannel(response)
.then((channel) => {
return Promise.all([this.saveStandupReport(response),
this.addUserToChannelTeamIfNeeded(channel, response.message.userId)]);
})
.catch(error => {
logger.error(error);
});
}
}
private printStandupReport(response: Response): void {
logger.debug('Print report for ', response.message.room);
Channel.findOne({ id: response.message.room }).then(
channel => {
if (!channel) {
this.sendResponse('Nothing noteworthy was reported lately.', response);
return Promise.reject('No channel');
} else {
logger.debug(`channel found for ${response.message.room} is ${channel}`);
return Promise.resolve(channel);
}
}
).then(channel => {
let searchStart = this.getSearchStart();
Report.find({ 'channel': channel.id, 'created_at': { $gt: searchStart.toDate() } }).sort({ created_at: -1 }).then(
reports => {
if (!reports || reports.length === 0) {
logger.debug(`No reports found for channel ${channel.id}`);
this.sendResponse('Nothing noteworthy was reported lately.', response);
return Promise.reject('No reports');
} else {
logger.debug(`${reports.length} reports found for channel ${channel.id}`);
let reportMessage = this.getReportMessage(reports);
this.sendResponse(reportMessage, response);
return Promise.resolve(reports);
}
}
);
}).
catch(error => {
logger.warn(error);
});
}
private getReportMessage(reports: IReport[]) {
let reportMessage = '';
let reportedUser = [];
reports.forEach(report => {
if (reportedUser.indexOf(report.user) < 0) {
reportedUser.push(report.user);
let user = StandupService.robot.getUserForId(report.user);
let userName = user.getDisplayName();
let body = report.text;
let time = moment().utc().to(moment(report.created_at));
reportMessage += `:memo: _${userName} reported ${time}_\n${body}\n***\n`;
}
});
return reportMessage;
}
private getSearchStart(): moment.Moment {
let mu = moment().utc();
let hour = mu.startOf('hour');
return hour.subtract(24, 'hour');
}
private sendResponse(message: string, response: Response) {
let queryUser = StandupService.robot.getUserForId(response.message.userId);
logger.debug(`Sending report ${message} to user ${queryUser}`);
response.send(message);
}
private updateChannel(response: Response): Promise<IChannel> {
return new Promise((resolve, reject) => {
Channel.findOne({ id: response.message.room }, (error, channel) => {
if (error) {
return reject(error);
}
if (!channel) {
logger.debug(`channel ${response.message.room} does not exist yet. Saving it.`);
channel = new Channel();
channel.id = response.message.room;
channel.team.push(response.message.userId);
channel.save();
} else if (channel.team.indexOf(response.message.userId) === -1) {
logger.debug(`adding user ${response.message.userId} to channel ${response.message.room}`);
channel.team.push(response.message.userId);
channel.save();
}
return resolve(channel);
});
});
}
private addUserToChannelTeamIfNeeded(channel: IChannel, userId: string): Promise<void> {
if (channel.team.indexOf(userId) > -1) {
return Promise.resolve();
} else {
channel.team.push(userId);
return new Promise<void>((resolve, reject) => {
Channel.update({ id: channel.id }, { $set: { team: channel.team } }, (err, raw) => {
if (err) {
reject(err);
}
});
});
}
}
private saveStandupReport(response: Response): Promise<IReport> {
let channelID = response.message.room;
let message: Message = response.message;
let report = new Report();
report.channel = channelID;
report.text = message.body.trim();
report.user = message.userId;
report.created_at = moment().utc().toDate();
logger.debug('saving report', report);
return report.save();
}
}
|
a17eca28e3c93806723225cba1bec8d9c76388ec
|
TypeScript
|
hepiska/puskesmas
|
/src/methods/voice-queue.ts
| 2.5625
| 3
|
import {db} from '@src/utils/firebase'
interface Voicequeue {
text: string
service: string
}
const voicequeueDb = db.collection("voicequeue")
export const addNewVoice = async (data: Voicequeue): Promise<MessageResponseType> => {
try {
const puskesmas = localStorage.getItem("puskesmas") || ""
const createdAt = new Date()
await voicequeueDb.doc().set({...data, puskesmas, createdAt: createdAt.toISOString()})
return {
message: "ubah data berhasil"
}
} catch (error) {
throw error
}
}
export const deleteVoice = async (key: string): Promise<MessageResponseType> => {
try {
await voicequeueDb.doc(key).delete()
return {
message: "ubah data berhasil"
}
} catch (error) {
throw error
}
}
export const getVoices = (layanan?: string, limit?: number) => {
try {
const puskesmas = localStorage.getItem("puskesmas") || ""
let getDataQuery = voicequeueDb.where("puskesmas","==", puskesmas)
if(layanan){
getDataQuery = getDataQuery.where("service", "==", layanan)
}
return getDataQuery
} catch (error) {
throw error
}
}
|
34b4fcfecaa4084df9e1b655cb34e36897138be6
|
TypeScript
|
Djiffit/fs
|
/part7/blog-ui/src/reducers/notificationReducer.ts
| 3.1875
| 3
|
import { NotificationType, NotificationClass } from '../types'
import { Dispatch } from 'redux'
const initialState = [] as NotificationType[]
export interface CreateNotificationType {
type: 'CREATE_NOTIFICATON',
notification: NotificationType,
}
export interface DeleteNotificationType {
type: 'DELETE_NOTIFICATION',
id: string,
}
export type NotificationActionType = CreateNotificationType | DeleteNotificationType
export const getId = () => `${Math.random() * 100000000}`
export const createNotificationAction = (message: string, type: NotificationClass, dispatch: Dispatch, delay = 3): void => {
const id = getId()
dispatch({
type: 'CREATE_NOTIFICATON',
notification: {
message,
id,
class: type,
},
})
setTimeout(() => {
dispatch(deleteNotificationAction(id))
}, delay * 1000)
}
export const deleteNotificationAction = (id: string): DeleteNotificationType => {
return {
type: 'DELETE_NOTIFICATION',
id,
}
}
const notificationReducer = (state = initialState, action: NotificationActionType) => {
switch (action.type) {
case 'CREATE_NOTIFICATON':
return [...state, action.notification]
case 'DELETE_NOTIFICATION':
return state.filter(({id}) => id !== action.id)
}
return state
}
export default notificationReducer
|
a04559a92ddeef312aa583ed841ecb685255045b
|
TypeScript
|
aztack/webgl-programming-guide
|
/oowebgl/src/math/vector.ts
| 2.640625
| 3
|
import {
toString, copy, clone,
add, substract,
scale, negate, zero, each, static_from
} from './utils-shared';
import {
divide,
inverse, dot, multiply, normalize, angle, lerp, squaredDistance, distance
} from './utils-vec';
import {
hypot
} from './utils'
import { Copyable } from './types';
export class Vector extends Float32Array implements Copyable<Vector> {
static from = static_from(Vector);
mag!: number;
magnitude!: number;
add!: typeof add;
angle!: typeof angle;
clone!: typeof clone;
copy!: typeof copy;
distance!: typeof distance;
divide!: typeof divide;
dot!: typeof dot;
each!: typeof each;
inverse!: typeof inverse;
lerp!: typeof lerp;
multiply!: typeof multiply;
negate!: typeof negate;
normalize!: typeof normalize;
scale!: typeof scale;
squaredDistance!: typeof squaredDistance;
substract!: typeof substract;
toString!: typeof toString;
zero!: typeof zero;
ceil() {
return this.each(Math.ceil);
}
floor() {
return this.each(Math.floor);
}
round() {
return this.each(Math.round);
}
min(operand: Vector) {
return this.each((ele: number, index: number) => Math.min(ele, operand[index]));
}
max(operand: Vector) {
return this.each((ele: number, index: number) => Math.max(ele, operand[index]));
}
}
function mag(this: Vector) {
return hypot(...this);
}
const magGetter = {
get: mag,
enumerable: false,
configurable: true
};
Object.defineProperty(Vector.prototype, "magnitude", magGetter);
Object.defineProperty(Vector.prototype, "mag", magGetter);
Object.assign(Vector.prototype, {
add,
angle,
clone,
copy,
divide,
distance,
dot,
each,
inverse,
lerp,
multiply,
negate,
normalize,
scale,
squaredDistance,
substract,
toString,
zero,
});
|
2a3f00d1f6e98616193d7975dd7f29781cc23a5e
|
TypeScript
|
gavongra/haxbotron
|
/db/router/v1.player.router.ts
| 2.578125
| 3
|
import express, { Request, Response, Router, NextFunction } from "express";
import { PlayerController } from '../controller/player.controller';
import { IRepository } from '../repository/repository.interface';
import { PlayerRepository } from '../repository/player.repository';
import { Player } from '../entity/player.entity';
import { checkValidationRules, validatePlayerModelRules } from "../model/Validator";
export const playerRouter: Router = express.Router({ mergeParams: true });
const playersRepository: IRepository<Player> = new PlayerRepository();
const controller: PlayerController = new PlayerController(playersRepository);
// /v1/player GET
// get all players list and data
playerRouter.get('/', async (request: Request, response: Response, next: NextFunction) => {
await controller.getAllPlayers(request, response, next);
});
// /v1/player POST
// register new player
playerRouter.post('/', validatePlayerModelRules, checkValidationRules, async (request: Request, response: Response, next: NextFunction) => {
await controller.addPlayer(request, response, next);
});
// /v1/player/:auth GET
// get the player data
playerRouter.get('/:auth', async (request: Request, response: Response, next: NextFunction) => {
await controller.getPlayer(request, response, next);
});
// /v1/player/:auth PUT
// update whole data of the player
playerRouter.put('/:auth', validatePlayerModelRules, checkValidationRules, async (request: Request, response: Response, next: NextFunction) => {
await controller.updatePlayer(request, response, next);
});
// /v1/player/:auth DELETE
// delete the player
playerRouter.delete('/:auth', async (request: Request, response: Response, next: NextFunction) => {
await controller.deletePlayer(request, response, next);
});
|
b6253b933080c07bc8b39637d39061852236da9b
|
TypeScript
|
flyzsd/spring-boot-web-component-app
|
/src/main/webapp/components/howto-checkbox.ts
| 2.625
| 3
|
// @ts-ignore
import {html, render} from '../webjars/lit-html/lit-html.js';
// @ts-ignore
import {styleMap} from '../webjars/lit-html/directives/style-map.js';
// @ts-ignore
import {classMap} from '../webjars/lit-html/directives/class-map.js';
// @ts-ignore
import {ifDefined} from '../webjars/lit-html/directives/if-defined.js';
// @ts-ignore
import {guard} from '../webjars/lit-html/directives/guard.js';
// // @ts-ignore
// import {live} from '../webjars/lit-html/directives/live.js';
// @ts-ignore
import {unsafeHTML} from '../webjars/lit-html/directives/unsafe-html.js';
// @ts-ignore
import {until} from '../webjars/lit-html/directives/until.js';
const person = {
name: "hello",
age: 10
};
const highlightStyles = {color: 'white', backgroundColor: 'red', 'font-family': 'roboto'};
const baseClasses = {
'menu-item': true,
// ...
};
const mergedClasses = Object.assign({active: true}, baseClasses);
const items = [1, 2, 3];
const list = () => html`items = ${items.map((i) => `item: ${i}`)}`;
const image = {
filename: undefined
};
const imageTemplate = () => html`
<img src="/images/${ifDefined(image.filename)}">
`;
const markup = '<div>Some HTML to render.</div>';
const content = fetch('http://example.com/movies.json').then(r => r.text());
const untilTemplate = html`${until(content, html`<span>Loading...</span>`)}`;
const myTemplate = (name, person) => html`<p>Hello ${name}</p>
<div name=${name.toLowerCase()} ?disabled=${name} .person=${person} @click=${(e) => console.log(`click me ${e}`)} style=${styleMap(highlightStyles)} class=${classMap(mergedClasses)}>click me</div>
${list()}
<ul>
${items.map((i) => html`<li>${i}</li>`)}
</ul>
<div>
${imageTemplate()}
</div>
<div>
${guard([items], () => items.map(item => html`${item}`))}
</div>
${unsafeHTML(markup)}
<div>${markup}</div>
${untilTemplate}
<my-lit-element .foo=${person.name}></my-lit-element>
<my-lit-element foo=${person.name}></my-lit-element>
`;
console.log(myTemplate);
render(myTemplate('World', person), document.querySelector('#lit-html'));
|
a5e070b9e773c535c20c22edb348e69c804466a7
|
TypeScript
|
McCutchenCompany/memorial-frontend
|
/src/app/store/create-photos/reducers/photo-need-approval.reducer.ts
| 2.515625
| 3
|
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';
import { Photo } from '@shared/models/photo.model';
import { All, CreatePhotosActionTypes } from '../photos.actions';
function sortByDate(p1, p2) {
const p1Date = new Date(p1.created_at);
const p2Date = new Date(p2.created_at);
if (p1Date > p2Date) {
return -1;
} else {
return 1;
}
}
export interface NeedApprovalPhotosState extends EntityState<Photo> {
ids: string[];
loading: boolean;
loaded: boolean;
saving: boolean;
saved: boolean;
error: any;
}
export const needApprovalPhotoAdapter: EntityAdapter<Photo> = createEntityAdapter<Photo>({
selectId: (photo: Photo) => photo.uuid,
sortComparer: sortByDate
});
export const INITIAL_STATE: NeedApprovalPhotosState = needApprovalPhotoAdapter.getInitialState({
ids: [],
loading: false,
loaded: false,
saving: false,
saved: false,
error: null
});
export function needApprovalPhotoReducer(state = INITIAL_STATE, action: All): NeedApprovalPhotosState {
switch (action.type) {
case CreatePhotosActionTypes.GET_MORE_PHOTOS: {
if (action.payload.waiting) {
return {
...state,
loading: true,
loaded: false
};
} else {
return state;
}
}
case CreatePhotosActionTypes.GET_CREATE_PHOTOS_SUCCESS: {
if (action.payload.need_approval) {
return needApprovalPhotoAdapter.addAll(action.payload.need_approval, {
...state,
loading: false,
loaded: true
});
} else {
return state;
}
}
case CreatePhotosActionTypes.GET_MORE_PHOTOS_SUCCESS: {
if (action.payload.need_approval) {
return needApprovalPhotoAdapter.addMany(action.payload.need_approval, {
...state,
loading: false,
loaded: true
});
} else {
return state;
}
}
case CreatePhotosActionTypes.UPDATE_CREATE_NEED_APPROVAL_PHOTO_SUCCESS: {
return needApprovalPhotoAdapter.updateOne({id: action.payload.uuid, changes: action.payload}, state);
}
case CreatePhotosActionTypes.APPROVE_NEED_APPROVAL_PHOTO_SUCCESS: {
return needApprovalPhotoAdapter.removeOne(action.payload.photo.uuid, state);
}
case CreatePhotosActionTypes.DENY_NEED_APPROVAL_PHOTO_SUCCESS: {
return needApprovalPhotoAdapter.removeOne(action.payload.photo.uuid, state);
}
case CreatePhotosActionTypes.DELETE_NEED_APPROVAL_PHOTO: {
return {
...state,
saving: true,
saved: false
};
}
case CreatePhotosActionTypes.DELETE_NEED_APPROVAL_PHOTO_SUCCESS: {
return needApprovalPhotoAdapter.removeOne(action.payload.id, {
...state,
saving: false,
saved: true
});
}
case CreatePhotosActionTypes.DELETE_NEED_APPROVAL_PHOTO_FAILURE: {
return {
...state,
saving: false,
saved: false,
error: action.payload
};
}
default: return state;
}
}
|
7bc45e634d4901013d7dc6f5723b3b615cd0d551
|
TypeScript
|
philmander/save-the-moon
|
/src/core/BaseSprite.ts
| 2.921875
| 3
|
export default abstract class BaseSprite {
protected _spriteImage: ImageBitmap;
protected _width: number;
protected _height: number;
protected _x: number;
protected _y: number;
protected _dx: number = 0;
protected _dy: number = 0;
protected _strength: number;
protected _scoreModifier = 0;
protected play(sfx: any): void {
const audio = new Audio(sfx);
audio.play();
}
public get spriteImage() {
return this._spriteImage;
}
public get width() {
return this._width;
}
public get height() {
return this._height;
}
public get x() {
return this._x;
}
public get y() {
return this._y;
}
public get strength() {
return this._strength;
}
public get scoreModifier() {
return this._scoreModifier;
}
public move(dx = this._dx, dy = this._dy): void {
this._x += dx;
this._y += dy;
}
public hit(): void {
this._strength--;
}
public isAlive(): boolean {
return this._strength > 0;
}
}
|
bb0f7cff888ece759e98639e6ec4c4b5857fed67
|
TypeScript
|
enramir/TFG-Project
|
/frontend-angular/src/app/models/product.ts
| 2.75
| 3
|
export class Product{
// public name: string;
// public image: string;
// public description: string;
// public price: number;
// constructor(name, available, description, price){
// this.name = name;
// this.image = image;
// this.description = description;
// this.price = price;
// }
constructor(
public uuid: string,
public name: string,
public description: string,
public price: number,
public image: string,
){}
}
|
dae870b519dd81e6ced8e3692873a791b6c03170
|
TypeScript
|
khpatel4991/dsalgo
|
/src/euler/005.ts
| 2.921875
| 3
|
const gcd = (x: number, y: number): number => {
if (x % y === 0) {
return y;
} else {
return gcd(y, x % y);
}
};
export const smallestMultiple = (n: number): number => {
let ans = 1;
for (let i = 1; i <= n; i++) {
ans = (ans * i) / gcd(ans, i);
}
return ans;
};
export {};
|
56da314d317d4f8a36e534d7b8cd4a6a8fe86fd3
|
TypeScript
|
vladislavs-poznaks/codelex-prep-course
|
/exercises/02-mini-projects/00-tic-tac-toe/src/Game.test.ts
| 3.1875
| 3
|
import { Game } from "./Game";
describe("Tic-Tac-Toe", () => {
it("should start with blank state", () => {
const game = new Game();
expect(game.getCells()).toEqual([
"-", "-", "-",
"-", "-", "-",
"-", "-", "-"
]);
expect(game.getTurn()).toBe("X");
expect(game.getWinner()).toBe("-");
expect(game.isTie()).toBe(false);
});
// should place mark
// should swap turns
// should check for win
test("should check for Xs wins | Row 1", () => {
const game = new Game();
game.board = ["X", "X", "X", "-", "-", "-", "-", "-", "-"];
expect(game.getWinner()).toBe("X");
expect(game.isTie()).toBe(false);
});
test("should check for Xs wins | Row 2", () => {
const game = new Game();
game.board = ["-", "-", "-", "X", "X", "X", "-", "-", "-"];
expect(game.getWinner()).toBe("X");
expect(game.isTie()).toBe(false);
});
test("should check for Xs wins | Row 3", () => {
const game = new Game();
game.board = ["-", "-", "-", "-", "-", "-", "X", "X", "X"];
expect(game.getWinner()).toBe("X");
expect(game.isTie()).toBe(false);
});
test("should check for Xs wins | Column 1", () => {
const game = new Game();
game.board = ["X", "-", "-", "X", "-", "-", "X", "-", "-"];
expect(game.getWinner()).toBe("X");
expect(game.isTie()).toBe(false);
});
test("should check for Xs wins | Column 2", () => {
const game = new Game();
game.board = ["-", "X", "-", "-", "X", "-", "-", "X", "-"];
expect(game.getWinner()).toBe("X");
expect(game.isTie()).toBe(false);
});
test("should check for Xs wins | Column 3", () => {
const game = new Game();
game.board = ["-", "-", "X", "-", "-", "X", "-", "-", "X"];
expect(game.getWinner()).toBe("X");
expect(game.isTie()).toBe(false);
});
test("should check for Xs wins | Diagonal Left to Right", () => {
const game = new Game();
game.board = ["X", "-", "-", "-", "X", "-", "-", "-", "X"];
expect(game.getWinner()).toBe("X");
expect(game.isTie()).toBe(false);
});
test("should check for Xs wins | Diagonal Right to Left", () => {
const game = new Game();
game.board = ["-", "-", "X", "-", "X", "-", "X", "-", "-"];
expect(game.getWinner()).toBe("X");
expect(game.isTie()).toBe(false);
});
// should check for draw
test("should check for a Tie and No Winner", () => {
const game = new Game();
game.board = [
"O", "X", "O",
"X", "X", "O",
"X", "O", "X"];
expect(game.getWinner()).toBe("-");
expect(game.isTie()).toBe(true);
});
});
|
d52805a38248bc530db6865dfc7dfac099a502db
|
TypeScript
|
Xtry333/HotelManager
|
/client-react/src/Server.ts
| 2.53125
| 3
|
import Axios, { AxiosRequestConfig } from 'axios';
import { RouteComponentProps } from 'react-router-dom';
import * as config from './app.config';
import { Dto } from './dtos/Dto';
import { ResourceError } from './dtos/Error';
import { SystemLogout } from './components/Login';
const instance = Axios.create({
baseURL: config.apiHostAddres,
timeout: 5000,
headers: {
'Access-Control-Allow-Origin': '*',
}
});
export default instance;
export function Get(url: string, config?: AxiosRequestConfig) {
try {
console.info(`Getting ${url}.`);
const token = localStorage.getItem('token');
const response = instance.get(url, { ...config, headers: { 'Auth-Token': token } });
return response;
} catch (error) {
console.error(error.response);
if (error.response && error.response.status === 401) {
SystemLogout();
} else {
throw error;
}
}
}
export async function Put(url: string, data: any, config?: AxiosRequestConfig) {
try {
console.info(`About to put to ${url} object ${JSON.stringify(data)}`);
const token = localStorage.getItem('token');
return await instance.put(url, data, { ...config, headers: { 'Auth-Token': token } });
} catch (error) {
console.error(error.response);
if (error.response && error.response.status === 401) {
SystemLogout();
} else {
throw error;
}
}
}
export async function Post(url: string, data: any, config?: AxiosRequestConfig) {
try {
console.info(`About to post to ${url} object ${JSON.stringify(data)}`);
const token = localStorage.getItem('token');
return await instance.post(url, data, { ...config, headers: { 'Auth-Token': token } });
} catch (error) {
console.error(error.response);
if (error.response && error.response.status === 401) {
SystemLogout();
} else {
throw error;
}
}
}
export async function Delete(url: string, config?: AxiosRequestConfig) {
try {
console.info(`Deleting ${url}.`);
const token = localStorage.getItem('token');
return await instance.delete(url, { ...config, headers: { 'Auth-Token': token } });
} catch (error) {
console.error(error.response);
if (error.response && error.response.status === 401) {
SystemLogout();
} else {
throw error;
}
}
}
export async function GetAllBy<T extends Dto>(url: string, expectedObject: { new(): T; }) {
try {
const expectedDtoName = (new expectedObject).dtoName;
const response = await Get(url, {});
const resArray: T[] = [];
for (const dto of response.data) {
if (dto.dtoName === expectedDtoName) {
resArray.push(dto);
} else {
throw new ResourceError('Response from server does not match expected DTO.', response);
}
}
return resArray;
} catch (error) {
if (error.response && error.response.status === 401) {
SystemLogout();
}
console.error(error);
}
}
|
9261c09b66bf032b7efc3a029d5c1896a305c1bc
|
TypeScript
|
Loeka1234/graphql-typeorm-api
|
/src/mail/index.ts
| 2.53125
| 3
|
import nodemailer from "nodemailer";
import fs from "fs";
import path from "path";
import handlebars from "handlebars";
const TEMPLATES_PATH = path.join(process.cwd(), "mail-templates");
const PARTIALS_PATH = path.join(TEMPLATES_PATH, "partials");
const sendMail = async (to: string, html: string, subject: string) => {
const transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: process.env.EMAIL,
pass: process.env.EMAIL_PASSWORD,
},
});
await transporter.sendMail({
from: "Eventor <mailserverloeka@gmail.com",
to: to,
subject,
html,
});
console.log(`Mail sent to ${to}`);
};
const readHTMLFile = async (path: string) => {
return new Promise((resolve: (value: string | null) => void) => {
fs.readFile(path, { encoding: "utf-8" }, (err, html) => {
if (err) {
resolve(null);
throw err;
} else {
resolve(html);
}
});
});
};
interface MailOptions {
to: string;
subject: string;
}
export const sendMailWithTemplate = async (
{ to, subject }: MailOptions,
template: string,
replacements: object
) => {
const html = await readHTMLFile(
path.join(TEMPLATES_PATH, template + ".hbs")
);
if (!html) return;
const templateHtml = handlebars.compile(html);
const emailToSend = templateHtml(replacements);
await sendMail(to, emailToSend, subject);
};
export const initializeHandlebars = async () => {
const header = await readHTMLFile(path.join(PARTIALS_PATH, "header.hbs"));
const footer = await readHTMLFile(path.join(PARTIALS_PATH, "footer.hbs"));
// Header
const templateHeader = handlebars.compile(header);
handlebars.registerPartial("header", templateHeader);
// Footer
const templateFooter = handlebars.compile(footer);
handlebars.registerPartial("footer", templateFooter);
};
|
c1fdbd575143b1873815387b1570878f81d7dd5f
|
TypeScript
|
boian123/nestjs-query
|
/packages/query-graphql/src/types/query/query-args/interfaces.ts
| 2.765625
| 3
|
import { Class, Filter, Query, SortField } from '@nestjs-query/core';
import { PagingStrategies, PagingTypes, StaticPagingTypes } from '../paging';
export type BaseQueryArgsTypeOpts<DTO> = {
/**
* The default number of results to return.
* [Default=10]
*/
defaultResultSize?: number;
/**
* The maximum number of results that can be returned from a query.
* [Default=50]
*/
maxResultsSize?: number;
/**
* The default sort for queries.
* [Default=[]]
*/
defaultSort?: SortField<DTO>[];
/**
* Default filter.
* [Default=\{\}]
*/
defaultFilter?: Filter<DTO>;
};
export interface CursorQueryArgsTypeOpts<DTO> extends BaseQueryArgsTypeOpts<DTO> {
pagingStrategy?: PagingStrategies.CURSOR;
}
export interface OffsetQueryArgsTypeOpts<DTO> extends BaseQueryArgsTypeOpts<DTO> {
pagingStrategy: PagingStrategies.OFFSET;
}
export interface NoPagingQueryArgsTypeOpts<DTO> extends BaseQueryArgsTypeOpts<DTO> {
pagingStrategy: PagingStrategies.NONE;
}
export type QueryArgsTypeOpts<DTO> =
| CursorQueryArgsTypeOpts<DTO>
| OffsetQueryArgsTypeOpts<DTO>
| NoPagingQueryArgsTypeOpts<DTO>;
export interface StaticQueryType<DTO, PagingType extends StaticPagingTypes>
extends Class<QueryType<DTO, InstanceType<PagingType>>> {
SortType: Class<SortField<DTO>>;
PageType?: PagingType;
FilterType: Class<Filter<DTO>>;
}
export interface QueryType<DTO, PagingType extends PagingTypes> extends Query<DTO> {
paging?: PagingType;
}
|
ed14839e83128cf79e8a16a7592e30e5a6c4b8a9
|
TypeScript
|
neotag/riakuto
|
/10-redux/04-fsa/src/actions/counter.ts
| 2.8125
| 3
|
export const ADD = 'ADD';
export const DECREMENT = 'DECREMENT';
export const INCREMENT = 'INCREMENT';
export const add = (amount: number) => ({
type: ADD as typeof ADD,
payload: { amount },
});
export const decrement = () => ({
type: DECREMENT as typeof DECREMENT,
});
export const increment = () => ({
type: INCREMENT as typeof INCREMENT,
});
export type CounterAction =
| ReturnType<typeof add>
| ReturnType<typeof decrement>
| ReturnType<typeof increment>;
|
4f5b51ab3d02d9a5cc1a25414c5fccb3afeac6db
|
TypeScript
|
jtsshieh/Advent-of-Code-2020
|
/src/Day6/Part2.ts
| 2.515625
| 3
|
import { readInput } from '../common/utils';
export const main = () => {
const groups = readInput(__dirname).split('\r\n\r\n');
return groups.reduce((total, group) => {
return (
total +
group.split('\r\n').reduce((acc, cur) => {
return [...acc].filter((item) => cur.includes(item)).join('');
}).length
);
}, 0);
};
export default () => {
console.log('Total Questions Answered:', main());
};
|
27a0f1c1a684ad3ac2830627b3b16164b317aa5b
|
TypeScript
|
dodevops/file-hierarchy
|
/lib/FileNode.ts
| 3.109375
| 3
|
/**
* @module file-hierarchy
*/
/**
*/
// import needed modules
import { AbstractNode } from 'js-hierarchy'
import * as fs from 'fs'
import { FileNodeType } from './FileNodeType'
import { ScanOptionsInterface } from './ScanOptionsInterface'
import * as path from 'path'
import * as minimatch from 'minimatch'
import Bluebird = require('bluebird')
/**
* file-hierarchy - Turn an entire directory tree into a js-hierarchy node
*/
export class FileNode extends AbstractNode {
private _path: string
private _type: FileNodeType
private _stats: fs.Stats
public getChildren (): FileNode[] {
return (
super.getChildren() as Array<FileNode>
)
}
/**
* Scan a directory tree and generate a node from it and its
* children
*
* @param {ScanOptionsInterface} options Options for the scan
* @param {boolean} rootNode Are we in the root node? (used by recursive scans)
* @return {Bluebird<FileNode>} the generated node
*/
public scan (
options: ScanOptionsInterface,
rootNode: boolean = true
): Bluebird<FileNode> {
this._path = path.resolve(options.path)
this.name = path.basename(this._path)
this._type = FileNodeType.Directory
this._log.trace(`Scanning ${this._path}`)
return Bluebird.fromCallback(
fs.stat.bind(this, this._path)
)
.then(
stats => {
this._stats = stats
if (
rootNode ||
(
this._stats.isDirectory() && options.recursive
)
) {
this._log.trace('Scanning directory contents')
return Bluebird.fromCallback(
fs.readdir.bind(this, this._path)
)
.then(
(entries: Array<string>) => {
return Bluebird.reduce<string, Array<FileNode>>(
entries.sort().filter(
entry => {
return minimatch(
entry,
options.glob,
{
dot: true
}
)
}
),
(total, entry) => {
options.path = path.join(this._path, entry)
return options.filter(this._path, entry)
.then(
result => {
if (result) {
return new FileNode().scan(options, false)
} else {
return Bluebird.resolve(null)
}
}
)
.then(
(node) => {
if (node) {
total.push(node)
}
return Bluebird.resolve(total)
}
)
},
[]
)
.then(
nodes => {
for (let node of nodes) {
this.addChild(node)
}
return Bluebird.resolve(this)
}
)
}
)
} else {
return Bluebird.resolve(this)
}
}
)
}
/**
* The path to this node
* @return {string}
*/
get path (): string {
return this._path
}
set path (value: string
) {
this._path = value
}
/**
* Type of the current node
* @return {FileNodeType}
*/
get type (): FileNodeType {
return this._type
}
set type (value: FileNodeType
) {
this._type = value
}
/**
* The fs.Stats object assigned to this node
* @return {"fs".Stats}
*/
get stats (): fs.Stats {
return this._stats
}
set stats (value: fs.Stats
) {
this._stats = value
}
}
|
58033f458a81d55c054fbb5448b538b85de2f8f6
|
TypeScript
|
MpStyle/air-quality-monitor
|
/web-interface/src/reducer/AppErrorsReducer.ts
| 2.765625
| 3
|
import { Action } from "redux";
import { DeleteDeviceErrorAction, DeleteDeviceErrorActionName } from "../action/DeleteDeviceAction";
import { FetchDevicesErrorAction, FetchDevicesErrorActionName } from "../action/FetchDevicesAction";
import { FetchLastReadingsErrorAction, FetchLastReadingsErrorActionName } from "../action/FetchLastReadingsAction";
import { FetchTimeRangeErrorAction, FetchTimeRangeErrorActionName } from "../action/FetchTimeRangeAction";
import { AppError } from "../entity/AppError";
import { initialAppState } from "../store/InitialAppState";
export const appErrorsReducer = (state: AppError[] = initialAppState.appErrors, action: Action): AppError[] => {
switch (action.type) {
case FetchDevicesErrorActionName:
return [...state, { code: (action as FetchDevicesErrorAction).error, dateTime: Date.now(), description: "Error calling fetch devices" }];
case FetchLastReadingsErrorActionName:
return [...state, { code: (action as FetchLastReadingsErrorAction).error, dateTime: Date.now(), description: "Error calling fetch air quality data" }];
case FetchTimeRangeErrorActionName:
return [...state, { code: (action as FetchTimeRangeErrorAction).error, dateTime: Date.now(), description: "Error calling fetch time range data" }];
case DeleteDeviceErrorActionName:
return [...state, { code: (action as DeleteDeviceErrorAction).error, dateTime: Date.now(), description: "Error calling delete device" }];
}
return state;
};
|
b348c4018aa72d4e7f506386374c391e5010339b
|
TypeScript
|
jinglikeblue/boxman
|
/h5_version/src/views/ControlLayer.ts
| 2.84375
| 3
|
class ControlLayer extends egret.Shape
{
private startPos: egret.Point;
private nowPos: egret.Point;
public constructor()
{
super();
this.touchEnabled = true;
this.graphics.beginFill(0, 0.3);
this.graphics.drawRect(0, 0, DataCenter.stage.stageWidth, DataCenter.stage.stageHeight);
this.graphics.endFill();
this.init();
}
private init(): void
{
this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.touchBegionHandler, this);
}
public dispose(): void
{
this.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.touchBegionHandler, this);
this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.touchMoveHandler, this);
this.removeEventListener(egret.TouchEvent.TOUCH_END, this.touchEndHandler, this);
}
private touchBegionHandler(e: egret.TouchEvent): void
{
this.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.touchMoveHandler, this);
this.addEventListener(egret.TouchEvent.TOUCH_END, this.touchEndHandler, this);
var startX: number = e.stageX >> 0;
var startY: number = e.stageY >> 0;
this.startPos = new egret.Point(startX, startY);
}
private touchMoveHandler(e: egret.TouchEvent): void
{
var nowX: number = e.localX >> 0;
var nowY: number = e.localY >> 0;
var dx: number = nowX - this.startPos.x;
var dy: number = nowY - this.startPos.y;
var absDx: number = Math.abs(dx);
var absDy: number = Math.abs(dy);
var dir: number = Direction.NONE;
if (absDx > absDy && absDx > 50)
{
if (dx > 0)
{
dir = Direction.RIGHT;
}
else
{
dir = Direction.LEFT;
}
}
else if (absDy > absDx && absDy > 50)
{
if (dy > 0)
{
dir = Direction.DOWN;
}
else
{
dir = Direction.UP;
}
}
NoticeManager.sendNotice(new GameNotice(GameNotice.MAKE_ROLE_MOVE, dir));
}
private touchEndHandler(e: egret.TouchEvent): void
{
this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.touchMoveHandler, this);
this.removeEventListener(egret.TouchEvent.TOUCH_END, this.touchEndHandler, this);
NoticeManager.sendNotice(new GameNotice(GameNotice.MAKE_ROLE_MOVE, Direction.NONE));
}
}
|
d37a3dd7bdac02de34fd92c4831aa62f6938a958
|
TypeScript
|
kinecosystem/kin-devplatform-marketplace-server
|
/scripts/src/models/wallets.ts
| 2.625
| 3
|
import { BaseEntity, Column, Entity, PrimaryColumn } from "typeorm";
import { register as Register } from "./index";
@Entity({ name: "wallets" })
@Register
export class Wallet extends BaseEntity {
public static async doesExist(address: string, appId: string): Promise<boolean> {
const query = Wallet.createQueryBuilder()
.where("wallet_address = :address", { address })
.andWhere("app_id = :appId", { appId });
return query.getCount().then( count => count > 0);
}
public static add(address: string, appId: string): Promise<Wallet> {
const wallet = Wallet.create();
wallet.appId = appId;
wallet.walletAddress = address;
return wallet.save();
}
@PrimaryColumn({ name: "wallet_address" })
public walletAddress!: string;
@Column({ name: "app_id" })
public appId!: string;
}
|
19628687b0f93ff6f5deb41c1e930f423a925961
|
TypeScript
|
OOlashyn/PCF-SamplePopup
|
/SamplePopup/index.ts
| 3
| 3
|
import {IInputs, IOutputs} from "./generated/ManifestTypes";
interface PopupDev extends ComponentFramework.FactoryApi.Popup.Popup {
popupStyle: object;
}
export class SamplePopup implements ComponentFramework.StandardControl<IInputs, IOutputs> {
private _container: HTMLDivElement;
private _popUpService: ComponentFramework.FactoryApi.Popup.PopupService;
/**
* Empty constructor.
*/
constructor()
{
}
/**
* Used to initialize the control instance. Controls can kick off remote server calls and other initialization actions here.
* Data-set values are not initialized here, use updateView.
* @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to property names defined in the manifest, as well as utility functions.
* @param notifyOutputChanged A callback method to alert the framework that the control has new outputs ready to be retrieved asynchronously.
* @param state A piece of data that persists in one session for a single user. Can be set at any point in a controls life cycle by calling 'setControlState' in the Mode interface.
* @param container If a control is marked control-type='starndard', it will receive an empty div element within which it can render its content.
*/
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container:HTMLDivElement)
{
this._container = document.createElement('div');
//============ button to show our popup =============
let popUpButton = document.createElement('button');
popUpButton.innerHTML = "Show Popup";
popUpButton.onclick = () => this.buttonClick();
this._container.appendChild(popUpButton);
//============ content of our popup =============
let popUpContent = document.createElement('div');
popUpContent.innerHTML = 'Hello World!';
popUpContent.style.width = "200px";
popUpContent.style.height = "200px";
popUpContent.style.backgroundColor = "white";
//============ our Popup object =============
let popUpOptions: PopupDev = {
closeOnOutsideClick: true,
content: popUpContent,
name: 'dwcPopup', // unique popup name
type: 1, // Root popup
popupStyle: {}
};
this._popUpService = context.factory.getPopupService();
this._popUpService.createPopup(popUpOptions);
container.appendChild(this._container);
}
private buttonClick(){
this._popUpService.openPopup('dwcPopup');
}
/**
* Called when any value in the property bag has changed. This includes field values, data-sets, global values such as container height and width, offline status, control metadata values such as label, visible, etc.
* @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to names defined in the manifest, as well as utility functions
*/
public updateView(context: ComponentFramework.Context<IInputs>): void
{
// Add code to update control view
}
/**
* It is called by the framework prior to a control receiving new data.
* @returns an object based on nomenclature defined in manifest, expecting object[s] for property marked as “bound” or “output”
*/
public getOutputs(): IOutputs
{
return {};
}
/**
* Called when the control is to be removed from the DOM tree. Controls should use this call for cleanup.
* i.e. cancelling any pending remote calls, removing listeners, etc.
*/
public destroy(): void
{
// Add code to cleanup control if necessary
}
}
|
cc6dd83d71745aec5b4f5d93b24b2a15ae96c2bd
|
TypeScript
|
einfachiota/explorer
|
/client/src/app/components/FooterProps.ts
| 2.875
| 3
|
/**
* The props for the Footer component.
*/
export interface FooterProps {
/**
* The dynamic sections to link to.
*/
dynamic: {
/**
* The label for the network.
*/
label: string;
/**
* The url to navigate to.
*/
url: string;
}[];
}
|
d78958289ed5060f85823f56388bc4d086e9ca96
|
TypeScript
|
bipinbce/EComService-1
|
/src/models/index.ts
| 2.53125
| 3
|
import {Model, Table, Column, ForeignKey, BelongsTo} from 'sequelize-typescript';
@Table
export class User extends Model<User> {
@Column name: string;
@Column email: string;
@Column phoneNo: string;
@Column address : string;
@Column password : string;
}
@Table
export class Product extends Model<Product> {
@Column productName: string;
@Column productDescription?: string;
@Column productPrice: string;
@Column productLaunchedYear: number;
}
@Table
export class Order extends Model<Order> {
@ForeignKey(()=> User)
@Column userId : number;
@BelongsTo(() => User) user : User;
@ForeignKey(()=> Product)
@Column productId : number;
@BelongsTo(() => Product) product : Product;
@Column productQuantity: number;
@Column orderDate : Date
}
|
f6cb6056b04b71f3b4556e33d050bdb4327326c2
|
TypeScript
|
jhlagado/obags
|
/src/for-each.ts
| 3.03125
| 3
|
import { Effect, CB } from "./common";
export class CBForEach implements CB {
operation: Effect;
source: CB | undefined;
talkback: CB | undefined;
constructor(source: CB, operation: Effect) {
this.source = source;
this.operation = operation;
this.source?.init(this);
}
init(d?: any) {
this.talkback = d;
this.talkback?.run();
}
run(data: any) {
this.operation(data)
this.talkback?.run();
}
destroy() {
}
}
// const forEach = operation => source => {
// let talkback;
// source(0, (t, d) => {
// if (t === 0) talkback = d;
// if (t === 1) operation(d);
// if (t === 1 || t === 0) talkback(1);
// });
// };
|
2e5f2c64c792c8cde0ee0b8925b3d6bfa28d6783
|
TypeScript
|
intelliapps-io/booking-app
|
/server/src/helpers/graphqlObjects/PaginatedResponse.ts
| 3.015625
| 3
|
import { ObjectType, Field, Int, ClassType, InputType } from "type-graphql";
export function PaginatedResponse<TItem>(TItemClass: ClassType<TItem>) {
// `isAbstract` decorator option is mandatory to prevent registering in schema
@ObjectType({ isAbstract: true })
abstract class PaginatedResponseClass {
// here we use the runtime argument
@Field(type => [TItemClass])
// and here the generic type
items: TItem[];
@Field(type => Int)
total: number;
}
return PaginatedResponseClass;
}
@InputType()
export abstract class PaginatedResponseInput {
@Field({ nullable: true })
offset?: number
@Field({ nullable: true })
limit?: number
}
|
f9ed1ed124e8c7ac7cd5026466f15d2f8653a9c8
|
TypeScript
|
bgeihsgt/celo-monorepo
|
/packages/phone-number-privacy/signer/src/database/models/domainState.ts
| 2.6875
| 3
|
import { SequentialDelayDomainState, WarningMessage } from '@celo/phone-number-privacy-common'
import {
Domain,
domainHash,
isSequentialDelayDomain,
} from '@celo/phone-number-privacy-common/lib/domains'
export const DOMAINS_STATES_TABLE = 'domainsStates'
export enum DOMAINS_STATES_COLUMNS {
domainHash = 'domainHash',
counter = 'counter',
timer = 'timer',
disabled = 'disabled',
}
export class DomainState {
public static createEmptyDomainState(domain: Domain): DomainState {
if (isSequentialDelayDomain(domain)) {
return {
[DOMAINS_STATES_COLUMNS.domainHash]: domainHash(domain).toString('hex'),
[DOMAINS_STATES_COLUMNS.counter]: 0,
[DOMAINS_STATES_COLUMNS.timer]: 0,
[DOMAINS_STATES_COLUMNS.disabled]: false,
}
}
throw new Error(WarningMessage.UNKNOWN_DOMAIN)
}
[DOMAINS_STATES_COLUMNS.domainHash]: string;
[DOMAINS_STATES_COLUMNS.counter]: number | undefined;
[DOMAINS_STATES_COLUMNS.timer]: number | undefined;
[DOMAINS_STATES_COLUMNS.disabled]: boolean
constructor(hash: string, domainState: SequentialDelayDomainState) {
this[DOMAINS_STATES_COLUMNS.domainHash] = hash
this[DOMAINS_STATES_COLUMNS.counter] = domainState.counter
this[DOMAINS_STATES_COLUMNS.timer] = domainState.timer
this[DOMAINS_STATES_COLUMNS.disabled] = domainState.disabled
}
}
|
d93b9a6c9b600b6a4cda5cfaddc713bebb98e775
|
TypeScript
|
twilio-labs/paste
|
/packages/paste-style-props/src/types/typography.ts
| 2.78125
| 3
|
// https://styled-system.com/api/#typography
import type {Properties} from 'csstype';
import type {ThemeShape} from '@twilio-paste/theme';
import type {ResponsiveValue} from '@twilio-paste/styling-library';
// Tokens
export type FontFamilyOptions = keyof ThemeShape['fonts'] | 'inherit';
export type FontSizeOptions = keyof ThemeShape['fontSizes'] | '100%' | 'inherit';
export type FontWeightOptions = keyof ThemeShape['fontWeights'] | 'inherit';
export type LineHeightOptions = keyof ThemeShape['lineHeights'] | 'unset' | 'inherit';
export type TextColorOptions = keyof ThemeShape['textColors'] | 'currentColor' | 'inherit' | 'transparent';
export type FontFamily = ResponsiveValue<FontFamilyOptions>;
export type FontSize = ResponsiveValue<FontSizeOptions>;
export type FontWeight = ResponsiveValue<FontWeightOptions>;
export type LineHeight = ResponsiveValue<LineHeightOptions>;
export type TextColor = ResponsiveValue<TextColorOptions>;
// CSS native
export type LetterSpacingOptions = Properties['letterSpacing'];
export type TextAlignOptions = Properties['textAlign'];
export type FontStyleOptions = Properties['fontStyle'];
export type WhiteSpaceOptions = Properties['whiteSpace'];
export type WordBreakOptions = Properties['wordBreak'];
export type WordWrapOptions = Properties['wordWrap'];
export type OverflowWrapOptions = Properties['overflowWrap'];
export type TextDecorationOptions = Properties['textDecoration'];
export type TextOverflowOptions = Properties['textOverflow'];
export type TextTransformOptions = Properties['textTransform'];
export type FontVariantNumericProperty = Properties['fontVariantNumeric'];
export type ListStyleImageProperty = Properties['listStyleImage'];
export type ListStylePositionProperty = Properties['listStylePosition'];
export type ListStyleTypeProperty = Properties['listStyleType'];
export type LetterSpacing = ResponsiveValue<LetterSpacingOptions>;
export type TextAlign = ResponsiveValue<TextAlignOptions>;
export type FontStyle = ResponsiveValue<FontStyleOptions>;
export type WhiteSpace = ResponsiveValue<WhiteSpaceOptions>;
export type WordBreak = ResponsiveValue<WordBreakOptions>;
export type WordWrap = ResponsiveValue<WordWrapOptions>;
export type OverflowWrap = ResponsiveValue<OverflowWrapOptions>;
export type TextDecoration = ResponsiveValue<TextDecorationOptions>;
export type TextOverflow = ResponsiveValue<TextOverflowOptions>;
export type TextTransform = ResponsiveValue<TextTransformOptions>;
export type FontVariantNumeric = ResponsiveValue<FontVariantNumericProperty>;
export type ListStyleImage = ResponsiveValue<ListStyleImageProperty>;
export type ListStylePosition = ResponsiveValue<ListStylePositionProperty>;
export type ListStyleType = ResponsiveValue<ListStyleTypeProperty>;
/*
* Styled-system grouping
* ---
* We add `color` here, not in the `color` interface grouping like styled-system does
* We also add `whiteSpace` and `textOverflow` to allow for ellipsis text.
*/
export interface TypographyProps {
fontFamily?: FontFamily;
fontSize?: FontSize;
fontWeight?: FontWeight;
fontVariantNumeric?: FontVariantNumeric;
lineHeight?: LineHeight;
letterSpacing?: LetterSpacing;
textAlign?: TextAlign;
fontStyle?: FontStyle;
color?: TextColor;
// Our custom addition
textDecoration?: TextDecoration;
textOverflow?: TextOverflow;
// Do not document, we prefer if folks do not use this property for i18n.
textTransform?: TextTransform;
whiteSpace?: WhiteSpace;
wordBreak?: WordBreak;
wordWrap?: WordWrap;
overflowWrap?: OverflowWrap;
listStyleImage?: ListStyleImage;
listStylePosition?: ListStylePosition;
listStyleType?: ListStyleType;
}
|
c811b7ae554c8d67016d3531addb1359bdfd2242
|
TypeScript
|
16patsle/TermListDB
|
/packages/termlist-web/src/components/TermList/TermRow.stories.ts
| 2.53125
| 3
|
import type { Story } from '@storybook/vue3'
import TermRow from './TermRow.vue'
export default {
title: 'TermList/TermRow',
component: TermRow,
argTypes: {
onEdit: { action: 'edited' },
onRemove: { action: 'removed' },
},
decorators: [
() => ({
template: `
<table class="table">
<tbody>
<story/>
</tbody>
</table>
`,
}),
],
}
const Template: Story = args => ({
components: { TermRow },
setup() {
return { args }
},
template: '<TermRow v-bind="args"></TermRow>',
})
export const Basic = Template.bind({})
Basic.args = {
term: {
_id: 'fake id',
date: '2017-08-14T14:07:48.197Z',
desc: 'Fake description',
term: 'Fake term',
type: 'verb',
},
}
export const MarkdownDesc = Template.bind({})
MarkdownDesc.args = {
term: {
...Basic.args.term,
desc: '*This* description has **markdown** support.',
},
}
export const Empty = Template.bind({})
Empty.args = {
term: {},
}
|
14dfdc6ca823efdce51e6ed08bac14614c1d9a85
|
TypeScript
|
alexodle/vitamind
|
/src/nodeUtils.ts
| 2.765625
| 3
|
// Utils intended for node.js/server use only
export function requireEnv(k: string): string {
// NOTE: Only use this for env vars we do not expect to be replaced in code (e.g. NODE_ENV and BASE_URL)
if (process.env.NODE_ENV !== 'production') {
if (['BASE_URL', 'NODE_ENV'].indexOf(k) !== -1) {
throw new Error(`Forbidden use of requireEnv. Use 'process.env.${k} instead.`)
}
}
const v = process.env[k]
if (!v) {
throw new Error(`Missing required env var: ${k}`)
}
return v
}
|
7c16965b617605eff82423e0c5de74f880bda66a
|
TypeScript
|
hejny/vire
|
/src/detection/getAreaColor.ts
| 2.84375
| 3
|
/*
import { Color } from './Color';
import Vector2 from './Vector2';
export function getPointColor(
ctx: CanvasRenderingContext2D,
point: Vector2,
): Color {
var frame = ctx.getImageData(point.x, point.y, 1, 1);
return new Color(frame.data[0], frame.data[1], frame.data[2]);
}
export function setPointColor(
ctx: CanvasRenderingContext2D,
point: Vector2,
color: Color,
) {
ctx.fillStyle = color.css;
ctx.fillRect(point.x, point.y, 1, 1);
}
export function getAreaColor(
ctx: CanvasRenderingContext2D,
topLeft: Vector2,
size: Vector2,
): Color {
var frame = ctx.getImageData(topLeft.x, topLeft.y, size.x, size.y);
let color1 = new Color();
var length = frame.data.length / 4;
for (var i = 0; i < length; i++) {
color1.r += frame.data[i * 4 + 0];
color1.g += frame.data[i * 4 + 1];
color1.b += frame.data[i * 4 + 2];
}
(color1.r /= length), (color1.g /= length), (color1.b /= length);
return color1;
}
*/
|
a53f3301f40bcc9b9da05fb35ebc7234e524d23c
|
TypeScript
|
Frikki/typed
|
/packages/logic/src/is/isIterable.ts
| 3.46875
| 3
|
import { isIterator } from './isIterator'
/**
* Returns true if a value is an Iterable.
* @name isIterable<A>(x: any): x is Iterable<A>
*/
export function isIterable<A>(x: any): x is Iterable<A> {
return x && typeof x[Symbol.iterator] === 'function' && isIterator(x[Symbol.iterator]())
}
|
5a846238b35c57cf50cf4f4c1cde8caa192dba33
|
TypeScript
|
Bimal-Angular/TestNg7
|
/src/app/Pipes/myFilterPipe.ts
| 2.609375
| 3
|
import {Pipe, PipeTransform} from '@angular/core'
@Pipe({
name:'myFilterPipe',
pure:false //
})
export class myFilterPipe implements PipeTransform
{
transform(value: any[], ...args: any[]) {
let filterby = args[0];
if (!value || !filterby)
return value;
return value.filter(a=> a.indexOf(filterby) != -1)
}
constructor() {
}
}
|
7f7bbd56c4828eadb4013d60849afcaeb61b0d53
|
TypeScript
|
Kurt29/ngx-function-expression
|
/ngx-function-expression/src/lib/fn-evaluation.service.ts
| 2.90625
| 3
|
import {Injectable, isDevMode} from '@angular/core';
import {FunctionExpression} from './fn-function-expression.type';
@Injectable({
providedIn: 'root'
})
export class FnEvaluationService {
private warningsEnabled = isDevMode();
private static checkContext(context: object, fnName: string): void {
if (context && typeof context[fnName] !== 'function') {
console.warn(`The method "${fnName}" should probably not be executed in the given context "${context.constructor.name}". `
+ `This warning appears in the development environment only. If you do exactly know what you're doing, you can, however, turn it `
+ `off using FnEvaluationService.suppressWarnings().`, context);
}
}
constructor() {
}
suppressWarnings() {
this.warningsEnabled = false;
}
isValidFunctionExpression<TReturn>(expr: unknown): expr is FunctionExpression<TReturn> {
return expr instanceof Function
|| Array.isArray(expr) && (
expr[0] instanceof Function
|| expr.length > 1 && (
expr[0] instanceof Object && expr[1] instanceof Function
|| expr[0] instanceof Object && typeof expr[1] === 'string'
)
);
}
resolveFunctionExpression<TReturn>(expr: FunctionExpression<TReturn>, context?: object): TReturn {
if (Array.isArray(expr) && expr[0] instanceof Object) {
if (expr[0] instanceof Function) {
if (this.warningsEnabled) {
FnEvaluationService.checkContext(context, expr[0].name);
}
return expr[0].apply(context ?? null, expr.slice(1));
} else if (expr[1] instanceof Function) {
if (this.warningsEnabled) {
FnEvaluationService.checkContext(expr[0], expr[1].name);
}
return expr[1].apply(expr[0], expr.slice(2));
} else if (typeof expr[1] === 'string') {
if (this.warningsEnabled) {
FnEvaluationService.checkContext(expr[0], expr[1]);
}
return expr[0][expr[1]].apply(expr[0], expr.slice(2));
}
} else if (expr instanceof Function) {
return expr.apply(context);
}
throw new Error('Invalid Function Expression. Please read the documentation.');
}
}
|
0fb3af9e4f78818d8b81b73ff54979d39b856668
|
TypeScript
|
GibbyH/MunchiesForMaladies_Client
|
/src/app/models/meal.model.ts
| 2.875
| 3
|
export class Meal {
strMeal: string;
strInstructions: string;
constructor(strMeal: string, strInstructions: string) {
this.strMeal = strMeal;
this.strInstructions = strInstructions;
}
}
|
bc8fa28b800f7048c442de8f1f3fb9677e235552
|
TypeScript
|
vladimirdd96/softuniJsAdvanced
|
/DOM Manipulation/DOM Manipulations ex/notificationF/solution.ts
| 2.625
| 3
|
function main() {
const btnGetNotified = <HTMLElement>document.getElementById('btnGetNotified')
const notification = <HTMLElement>document.getElementById('notification')
function notify(str: string) {
notification.style.display = 'block'
notification.textContent = str
setTimeout(() => {
notification.style.display = 'none'
}, 3000)
}
btnGetNotified.addEventListener('click', () => notify('Something happened!'))
}
document.addEventListener('DOMContentLoaded', main);
|
264c4f12a805cb562ba41ba3a79ab43e68f424b2
|
TypeScript
|
dp28/account-management
|
/src/domain/identities/state.ts
| 2.71875
| 3
|
import produce, { Draft } from "immer";
import { ID, get } from "../framework";
import { DomainState } from "../projection";
import {
IdentityEvents,
IDENTITY_ADDED,
IDENTITY_DELETED,
SECRET_ADDED,
} from "./events";
export interface Identity {
id: ID;
personId: ID;
organisationId: ID;
name: string;
value: string;
}
export interface Secret {
identityId: ID;
name: string;
hint: string;
restrictions: string;
}
export interface IdentitiesState {
identities: { [id: string]: Identity };
secrets: { [identityId: string]: readonly Secret[] };
}
export const InitialState: IdentitiesState = {
identities: {},
secrets: {},
};
export const selectIdentities = (state: DomainState) =>
state.identities.identities;
export const selectUniqueIdentityNames = (state: DomainState) =>
unique(Object.values(selectIdentities(state)).map((_) => _.name));
export const selectUniqueIdentityValuesForPerson = (personId: ID) => (
state: DomainState
) =>
unique(
Object.values(selectIdentitiesFor({ personId })(state)).map((_) => _.value)
);
export const selectIdentitiesFor = ({
personId,
organisationId,
}: {
personId?: ID;
organisationId?: ID;
}) => (state: DomainState) =>
Object.values(selectIdentities(state)).filter(
(identity) =>
(!personId || identity.personId === personId) &&
(!organisationId || identity.organisationId === organisationId)
);
export const selectIdentity = (identityId: ID) => (state: DomainState) =>
get(identityId, selectIdentities(state));
export const selectSecretsForIdentity = (identityId: ID) => (
state: DomainState
) => state.identities.secrets[identityId] || [];
export const selectUniqueSecretNames = (state: DomainState) =>
unique(
Object.values(state.identities.secrets)
.flat()
.map((_) => _.name)
);
export const selectUniqueSecretHintsForPerson = (personId: ID) => (
state: DomainState
) => {
const identities = selectIdentitiesFor({ personId })(state);
const secrets = identities.flatMap((_) =>
selectSecretsForIdentity(_.id)(state)
);
return unique(secrets.map((_) => _.hint));
};
export const reducer = produce(
(draft: Draft<IdentitiesState>, event: IdentityEvents) => {
switch (event.type) {
case IDENTITY_ADDED:
draft.identities[event.payload.id] = event.payload;
break;
case IDENTITY_DELETED:
delete draft.identities[event.payload.identityId];
break;
case SECRET_ADDED:
addSecret(event.payload, draft);
}
},
InitialState
);
function unique<T>(values: T[]): T[] {
return [...new Set(values)];
}
function addSecret(secret: Secret, draft: Draft<IdentitiesState>): void {
const secrets = draft.secrets[secret.identityId] || [];
draft.secrets[secret.identityId] = secrets
.filter((_) => _.name !== secret.name)
.concat([secret]);
}
|
917637596f8fbfcd35b7024546d61ae0d3c9aec2
|
TypeScript
|
dhyanitha/twitter-clone-nest-typeorm-backend
|
/src/users/users.controller.ts
| 3
| 3
|
import { Controller, Get, Post, Delete, Param, Body, ForbiddenException, NotFoundException } from '@nestjs/common';
import { omit } from 'lodash';
import { CreateUserDTO } from './dto';
import { User } from './user.entity';
import { UsersService, UsernameAlreadyExist, EmailAlreadyExist } from './users.service';
/**
* /users Endpoint - User Register endpoint
* POST /users - Create User
* GET /users - List all Users
* GET /users/:username - Get user with username
*/
@Controller('users')
export class UsersController {
constructor( private readonly usersService: UsersService ) { }
/**
* Remove sensitive information from the user object before sending it
* back out in repsonse
*
* @param user User object
*/
private sanitizeUser(user: User) {
return omit(user, ['hashedPassword']);
}
/**
* POST Endpoint for user creation
*
* @param createUserDTO Request body, refer to `dto/create-user.dto.ts`
* @return A sanitized user entity of the newly created user
*/
@Post()
async createUser( @Body() createUserDTO: CreateUserDTO ) {
try {
const user = await this.usersService.createUser(createUserDTO);
return this.sanitizeUser(user);
} catch (err) {
if (err instanceof UsernameAlreadyExist || err instanceof EmailAlreadyExist) {
throw new ForbiddenException(err.message);
}
throw err;
}
}
/**
* GET Endpoint for listing all users
*
* @return An array of sanitized user entities of all users in database
*/
@Get()
async listUsers() {
const users = await this.usersService.findAll();
return users.map((user: User) => this.sanitizeUser(user));
}
/**
* GET Endpoint for obtaining user information
*
* @param params Route params
* @return A sanitized user entity of the queried user
*/
@Get(':username')
async getUserByUsername(@Param() params) {
const user = await this.usersService.findByUsername(params.username);
if (!user) {
throw new NotFoundException('User does not exist');
}
return this.sanitizeUser(user);
}
}
|
206506fec714366b1fc34358df406f579f79189a
|
TypeScript
|
StoneT2000/brain.js
|
/src/recurrent/matrix/clone.ts
| 2.71875
| 3
|
import { Matrix } from '.';
/**
*
* @param {Matrix} product
* @return {Matrix}
*/
function clone(product: Matrix): Matrix {
const cloned = new Matrix();
cloned.rows = product.rows;
cloned.columns = product.columns;
cloned.weights = product.weights.slice(0);
cloned.deltas = product.deltas.slice(0);
return cloned;
}
export default clone;
|
ab90424ccd5aea4f0e11d09bb0ca393393f98d8c
|
TypeScript
|
tngraphql/console
|
/src/Contracts/index.ts
| 2.71875
| 3
|
/**
* (c) Phan Trung Nguyên <nguyenpl117@gmail.com>
* User: nguyenpl117
* Date: 3/26/2020
* Time: 9:54 AM
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { ParsedOptions } from 'getopts'
import { Colors } from '@poppinss/colors'
import { Logger } from '@poppinss/fancy-logs'
import { PromptContract } from '@poppinss/prompts'
// import { ApplicationContract } from '@ioc:Adonis/Core/Application'
import { ContainerContract } from '../Kernel/Container'
/**
* The types of flags can be defined on a command.
*/
export type FlagTypes = 'string' | 'number' | 'boolean' | 'array' | 'numArray'
/**
* The types of arguments can be defined on a command.
*/
export type ArgTypes = 'string' | 'spread'
/**
* The shape of command argument
*/
export type CommandArg = {
propertyName: string,
name: string,
type: ArgTypes,
required: boolean,
description?: string,
}
/**
* The shape of a command flag
*/
export type CommandFlag = {
propertyName: string,
name: string,
type: FlagTypes,
description?: string,
alias?: string,
default?: any,
}
/**
* The handler that handles the global
* flags
*/
export type GlobalFlagHandler = (
value: any,
parsed: ParsedOptions,
command?: CommandConstructorContract,
) => void
/**
* Shape of grouped commands. Required when displaying
* help
*/
export type CommandsGroup = {
group: string,
commands: SerializedCommandContract[],
}[]
/**
* The shared properties that exists on the command implementation
* as well as it's serialized version
*/
export interface SerializedCommandContract {
args: CommandArg[],
settings: any,
flags: CommandFlag[],
commandName: string,
description: string,
}
/**
* Command constructor shape with it's static properties
*/
export interface CommandConstructorContract extends SerializedCommandContract {
new (application: ContainerContract, ...args: any[]): CommandContract,
/**
* A boolean to know if the command has been booted or not. We initialize some
* static properties to the class during the boot process.
*/
$booted: boolean,
/**
* Boot the command. You won't have to run this method by yourself. Ace will internally
* boot the commands by itself.
*/
$boot (): void
/**
* Define an argument directly on the command without using the decorator
*/
$defineArgument (options: Partial<CommandArg>): void
/**
* Define a flag directly on the command without using the decorator
*/
$defineFlag (options: Partial<CommandFlag>): void
}
/**
* The shape of command class
*/
export interface CommandContract {
parsed?: ParsedOptions,
logger: Logger,
prompt: PromptContract,
colors: Colors,
generator: GeneratorContract,
kernel: KernelContract,
handle (...args: any[]): Promise<any>,
}
/**
* Shape of the serialized command inside the manifest JSON file.
*/
export type ManifestCommand = SerializedCommandContract & { commandPath: string }
/**
* Shape of the manifest JSON file
*/
export type ManifestNode = {
[command: string]: ManifestCommand,
}
/**
* Manifest interface
*/
export interface ManifestContract {
loadCommand (commandPath: string): { command: CommandConstructorContract, commandPath: string }
lookupCommands (commandPath: string)
generate (commandPaths: string[]): Promise<void>
load (): Promise<ManifestNode>
}
/**
* Callbacks for different style of hooks
*/
export type FindHookCallback = (command: SerializedCommandContract | null) => Promise<void> | void
export type RunHookCallback = (command: CommandContract) => Promise<void> | void
/**
* Shape of ace kernel
*/
export interface KernelContract {
manifestCommands?: ManifestNode
defaultCommand: CommandConstructorContract
commands: { [name: string]: CommandConstructorContract }
flags: { [name: string]: CommandFlag & { handler: GlobalFlagHandler } }
before (action: 'run', callback: RunHookCallback): this
before (action: 'find', callback: FindHookCallback): this
before (action: 'run' | 'find', callback: RunHookCallback | FindHookCallback): this
after (action: 'run', callback: RunHookCallback): this
after (action: 'find', callback: FindHookCallback): this
after (action: 'run' | 'find', callback: RunHookCallback | FindHookCallback): this
register (commands: CommandConstructorContract[]): this
getSuggestions (name: string, distance?: number): string[]
flag (
name: string,
handler: GlobalFlagHandler,
options: Partial<Exclude<CommandFlag, 'name' | 'propertyName'>>,
): this
find (argv: string[]): Promise<CommandConstructorContract | null>
runCommand (commandInstance: CommandContract, argv: string[]): Promise<any>
runDefaultCommand (): Promise<any>
handle (argv: string[]): Promise<any>
exec (commandName: string, args: string[]): Promise<any>
preloadManifest (): void
useManifest (manifest: ManifestContract): this
printHelp (command?: CommandConstructorContract): void
}
/**
* Template generator options
*/
export type GeneratorFileOptions = {
pattern?: 'pascalcase' | 'camelcase' | 'snakecase',
form?: 'singular' | 'plural',
formIgnoreList?: string[],
suffix?: string,
prefix?: string,
extname?: string,
}
/**
* Shape of the individual generator file
*/
export interface GeneratorFileContract {
/**
* Define path to the stub template. You can also define inline text instead
* of relying on a template file, but do make sure to set `raw=true` inside
* the options when using inline text.
*/
stub (fileOrContents: string, options?: { raw: boolean }): this
/**
* The relative path to the destination directory.
*/
destinationDir (directory: string): this
/**
* Define a custom application root. Otherwise `process.cwd()` is used.
*/
appRoot (directory: string): this
/**
* Apply data to the stub
*/
apply (contents: any): this
/**
* Get file properties as a JSON object
*/
toJSON (): {
filename: string,
filepath: string,
extension: string,
contents: string,
relativepath: string,
}
}
/**
* Shape of the files generator
*/
export interface GeneratorContract {
/**
* Add a new file to the files generator. You can add multiple files
* together and they will be created when `run` is invoked.
*/
addFile (name: string, options?: GeneratorFileOptions): GeneratorFileContract
/**
* Run the generator and create all files registered using `addFiles`
*/
run (): Promise<void>
/**
* Clear the registered files from the generator
*/
clear (): void
}
/**
* Filter function for filtering files during the `readdir` scan
*/
export type CommandsListFilterFn = ((name: string) => boolean) | string[]
|
127295f3a25639a4ebf8c13c87818f165c6ee200
|
TypeScript
|
notVitaliy/evjs
|
/src/individual/individual.model.ts
| 2.546875
| 3
|
export interface Fitness {
(entity: any, name: string): number
}
export interface Mutate {
(entity: any, name: string): any
}
export interface Mate {
(mother: any, father: any, motherName: string, fatherName: string): [any, any]
}
export interface IndividualConfig {
fitness: Fitness
mutate: Mutate
mate: Mate
entity?: any
name?: {
first?: string
last: string
}
}
|
713bb1cb5ba4602e61cfacedb4924bd1e4b2940e
|
TypeScript
|
olegpetrush/React-freight-pay
|
/packages/gateway/src/lib/di/Container.ts
| 2.6875
| 3
|
export default class Container {
services: any;
constructor() {
this.services = {};
}
has(id: any) {
return !!this.services[id];
}
register(id: any, service: any) {
this.services[id] = service;
}
get(id: any) {
if (!this.services[id]) {
return null;
}
return this.services[id];
}
}
|
6b91e583b3f7021f8a12c2146391d046ba9c7afb
|
TypeScript
|
CiBuildOrg/packages
|
/packages/mail/index.ts
| 2.546875
| 3
|
import { config } from "dotenv";
import { createTransport, Transporter } from "nodemailer";
import { success, logError } from "@staart/errors";
import aws from "aws-sdk";
config();
const EMAIL_FROM = process.env.EMAIL_FROM || "";
const EMAIL_HOST = process.env.EMAIL_HOST || "";
const EMAIL_PORT = process.env.EMAIL_PORT || 465;
const EMAIL_PASSWORD = process.env.EMAIL_PASSWORD || "";
const SES_SECRET = process.env.SES_SECRET || "";
const SES_ACCESS = process.env.SES_ACCESS || "";
const SES_EMAIL = process.env.SES_EMAIL || "";
const SES_REGION = process.env.SES_REGION || "";
let transporter: Transporter | undefined = undefined;
/**
* Sets up a Nodemailer transporter to send emails
*/
export const setupTransporter = () => {
if (SES_ACCESS && SES_SECRET) {
transporter = createTransport({
SES: new aws.SES({
apiVersion: "2010-12-01",
accessKeyId: SES_ACCESS,
secretAccessKey: SES_SECRET,
region: SES_REGION,
}),
});
} else {
transporter = createTransport({
host: EMAIL_HOST,
port: Number(EMAIL_PORT),
secure: true,
auth: {
user: EMAIL_FROM,
pass: EMAIL_PASSWORD,
},
});
}
};
/**
* Sends a test email
*/
export const sendTestEmail = () => {
if (transporter)
transporter
.verify()
.then(() => success("Email transport works"))
.catch(() => logError("Email", "Unable to verify email transport", 1));
};
export interface Mail {
from?: string;
to: string | string[];
cc?: string | string[];
bcc?: string | string[];
subject: string;
message: string;
altText?: string;
replyTo?: string;
attachments?: {
filename?: any;
content?: any;
path?: any;
href?: any;
httpHeaders?: any;
contentType?: any;
contentDisposition?: any;
cid?: any;
encoding?: any;
headers?: any;
raw?: any;
}[];
icalEvent?: {
method?: string;
filename?: string;
content?: any;
path?: any;
href?: any;
encoding?: string;
};
list?: any;
headers?: any;
}
/**
* Send an email
* @param mail - Mail object to send
*/
export const sendMail = async (mail: Mail) => {
if (!transporter)
return logError("Email", "Setup transporter before sending an email", 1);
const result = await transporter.sendMail({
from: mail.from || EMAIL_FROM || SES_EMAIL,
to: mail.to,
cc: mail.cc,
bcc: mail.bcc,
subject: mail.subject,
text: mail.altText,
html: mail.message,
attachments: mail.attachments,
icalEvent: mail.icalEvent,
list: mail.list,
headers: mail.headers,
});
success("Sent email", mail.to, mail.subject);
return result;
};
|
94cc8d865f01ab5d33822d4aef076ca9834e805e
|
TypeScript
|
ExePtion31/cursoRxJs
|
/src/operadores/01-map-pluck.ts
| 2.78125
| 3
|
import { fromEvent, range, from, of } from 'rxjs';
import { map, pluck, mapTo } from 'rxjs/operators'
const data = {
nombre: 'Juan',
apellido: 'Perez',
ubicacion:{
pais: 'Colombia',
ciudad: 'Bogotá'
},
edad: 21
}
//pipe map
range(1,3).pipe(
map<number, number>(val => val * 10)
).subscribe(console.log);
const keyEvent$ = fromEvent<KeyboardEvent>(document, 'keyup').pipe(
map(event => event.code)
).subscribe(console.log);
const dataMap$ = of(data).pipe(
map(event => event.nombre)
).subscribe(console.log);
//pipe pluck
const dataPluck$ = of(data).pipe(
pluck('ubicacion', 'pais')
).subscribe(console.log);
//pipe mapTo
const keyEvent2$ = fromEvent<KeyboardEvent>(document, 'keyup');
const mapTo$ = keyEvent2$.pipe(
mapTo('Tecla presionada')
).subscribe(console.log);
|
07043a83abdd23baca39c0b58e051e37a071309f
|
TypeScript
|
venkatarami-ui/Angular-7_POC
|
/src/app/app.component.ts
| 2.5625
| 3
|
import { Component } from '@angular/core';
import { FavoriteChangeEventArgs } from './favorite/favorite.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
task = {
title: 'Review the Application',
assignee: {
name: 'Venkata Rami Reddy'
}
}
dataList = [
{
'FirstName' : 'Roy',
'LastName' : 'Agasthyan'
},
{
'FirstName' : 'Sam',
'LastName' : 'Johnson'
},
{
'FirstName' : 'Anjali',
'LastName' : 'Sharma'
},
{
'FirstName' : 'Julia',
'LastName' : 'Sherwood'
}
]
onAdd() {
this.dataList.push({
'FirstName' : 'Venkata Rami',
'LastName' : 'Reddy'
});
}
products;
LoadProducts() {
this.products = [
{id: 1, name:'products 1', duration: '1 year' },
{id: 2, name:'projects 2', duration: '3 year' },
{id: 3, name:'products 3', duration: '5 year' },
{id: 4, name:'products 4', duration: '2 year' },
{id: 5, name:'products 5', duration: '4 year' },
{id: 6, name:'products 6', duration: '10 year' },
];
}
takeProducts (index, product) {
return product ? product.id : undefined;
}
onRemove(item) {
let index = this.dataList.indexOf(item);
this.dataList.splice(index, 1);
}
onChange(projectes) {
projectes.name = "Updated"
}
projectes = [
{id: 1, name:'projects 1', duration: '1 year' },
{id: 2, name:'projects 2', duration: '3 year' },
{id: 3, name:'projects 3', duration: '5 year' },
{id: 4, name:'projects 4', duration: '2 year' },
{id: 5, name:'projects 5', duration: '4 year' },
{id: 6, name:'projects 6', duration: '10 year' },
]
viewMode= 'map';
courses = [1,2,3,4,5];
tweet = {
body: 'Some content here ...',
likesCount: 10,
//isLiked: true
}
title1 = 'angularngFor';
post = {
title: "Title",
isFavorite: true
}
onFavoriteChange(eventArgs: FavoriteChangeEventArgs) {
console.log("On Favorite Changed !", eventArgs);
}
}
|
97581171dfde1e32712ef433e16a8947e54e2aec
|
TypeScript
|
LunarFuror/phantasmal-world
|
/src/quest_editor/gui/AsmEditorToolBar.ts
| 2.515625
| 3
|
import { ToolBar } from "../../core/gui/ToolBar";
import { CheckBox } from "../../core/gui/CheckBox";
import { AsmEditorStore } from "../stores/AsmEditorStore";
export class AsmEditorToolBar extends ToolBar {
constructor(asm_editor_store: AsmEditorStore) {
const inline_args_mode_checkbox = new CheckBox(true, {
label: "Inline args mode",
tooltip: asm_editor_store.has_issues.map(has_issues => {
let text =
"Transform arg_push* opcodes to be inline with the opcode the arguments are given to.";
if (has_issues) {
text += "\nThis mode cannot be toggled because there are issues in the script.";
}
return text;
}),
});
super(inline_args_mode_checkbox);
this.disposables(
inline_args_mode_checkbox.checked.bind_to(asm_editor_store.inline_args_mode),
inline_args_mode_checkbox.checked.observe(({ value }) =>
asm_editor_store.set_inline_args_mode(value),
),
inline_args_mode_checkbox.enabled.bind_to(asm_editor_store.has_issues.map(b => !b)),
);
this.finalize_construction();
}
}
|
f3df720eee4dbd63fa349aad4900c44d93a97ca0
|
TypeScript
|
JonathanHuarca/Proyecto-Care
|
/src/resources/section/controllers/upload-file.ts
| 2.625
| 3
|
import catchAsync from '../../../utils/catchAsync'
import moment from 'moment-timezone'
import AWS from 'aws-sdk'
let msgErrorController = 'Error en uplodad file section controlador'
/**
* credenciales para S3
*/
const bucket = process.env.BUCKET_NAME
const s3 = new AWS.S3({
accessKeyId: process.env.ID,
secretAccessKey: process.env.SECRET
})
const format = 'DD/MM/YYYY - HH:mm:ss'
const formatTime = "HH:mm:ss"
const upload_file = (UserSection, UserFile, File) => catchAsync(msgErrorController,async (req, res) => {
const { nickname } = req.user
const {
id_section,
id_activity
} = req.body
const section = await UserSection.findById(id_section)
const { name_section } = section
const { type, title } = await File.findById(id_activity)
if(!section){
return res.status(500).json({message : `Sección para el usuario ${nickname} no existe` })
}
const userActivity = await UserFile.findOne({nickname, type, title, name_section})
console.log(userActivity)
if(!userActivity){
return res.status(500).json({message:`actividad para ${nickname} no existe`})
}
/** capturando el tiempo en que se sube la actividad por el usuario */
const end_time = moment().tz("America/Lima").format(format)
console.log(end_time)
userActivity.end_time = end_time
const {
start_time,
time,
time_in_seconds
} = userActivity
let formatDate = "DD/MM/YYYY HH:mm:ss"
if (time === 'Invalid date' || time_in_seconds ==='Invalid date') {
userActivity.time = ''
userActivity.time_in_seconds = 0
}else {
let duration_time = moment.utc(moment(end_time, formatDate).diff(moment(start_time, formatDate))).format(formatTime)
userActivity.time = duration_time
userActivity.time_in_seconds = moment.duration(duration_time).asSeconds()
}
/** ========================================================= */
if(!req.files){
return res.status(500).json({message : "Archivo no recibido"})
}
const { activity } = req.files
let sent = section.sent
if(activity){
// verificamos si pdf es un array
if(!activity.length) {
const params = {
Bucket: `${bucket}/test/pdfs/${nickname}`,
Key:`${activity.name}`,
Body:activity.data,
ACL:'public-read'
}
const s3File = await s3.upload(params).promise()
if(!s3File) res.status(500).json({message:'Error al subir imagen'})
let activityURL = s3File.Location
userActivity.data = [activityURL]
console.log('archivo subido')
}
}
await userActivity.save()
section.sent = sent
await section.save()
res.status(200).json({
message : "Archivo(s) de la actividad subidos correctamente ",
activity : section
})
})
export default upload_file
|
554116af1923c36b00206fe1f0829111b65095ef
|
TypeScript
|
Suko-dev/ignite-4semana-desafio1
|
/src/modules/users/useCases/showUserProfile/ShowUserProfileUseCase.spec.ts
| 2.53125
| 3
|
import { InMemoryUsersRepository } from "../../repositories/in-memory/InMemoryUsersRepository";
import { CreateUserUseCase } from "../createUser/CreateUserUseCase";
import { ShowUserProfileUseCase } from "./ShowUserProfileUseCase";
let createUserUseCase: CreateUserUseCase;
let inMemoryUsersRepository: InMemoryUsersRepository;
let showUserProfileUseCase: ShowUserProfileUseCase;
describe("Find user", () => {
beforeEach(() => {
inMemoryUsersRepository = new InMemoryUsersRepository();
createUserUseCase = new CreateUserUseCase(
inMemoryUsersRepository
);
showUserProfileUseCase = new ShowUserProfileUseCase(
inMemoryUsersRepository
);
});
it("should be able to find user by id", async () => {
const userid = await createUserUseCase.execute({
name: "test",
email: "test@test.com",
password: "1234"
});
const user = await showUserProfileUseCase.execute(String(userid.id))
expect(user).toBeDefined()
expect(user).toHaveProperty('id')
});
});
|
29f89cb15876b582cc999edd6877c1d9703d121a
|
TypeScript
|
flisbao-ciandt/stryker-dashboard
|
/packages/data-access/src/services/BlobServiceAsPromised.ts
| 2.53125
| 3
|
import { BlobService, createBlobService } from 'azure-storage';
import { promisify } from 'util';
export class BlobServiceAsPromised {
public createContainerIfNotExists: (container: string, options: BlobService.CreateContainerOptions) => Promise<BlobService.ContainerResult>;
public createBlockBlobFromText: (container: string, blob: string, text: string | Buffer, options: BlobService.CreateBlobRequestOptions) => Promise<BlobService.BlobResult>;
public blobToText: (container: string, blob: string) => Promise<string>;
constructor(blobService = createBlobService()) {
this.createContainerIfNotExists = promisify<string, BlobService.CreateContainerOptions, BlobService.ContainerResult>(blobService.createContainerIfNotExists).bind(blobService);
this.createBlockBlobFromText = promisify(blobService.createBlockBlobFromText).bind(blobService);
this.blobToText = promisify(blobService.getBlobToText).bind(blobService);
}
}
|
14c9401e23f5c196465d184c08c5360f79a2a198
|
TypeScript
|
Eden-Hazani/SweetBash
|
/Utility/saveCurrentGame.ts
| 2.671875
| 3
|
import AsyncStorage from "@react-native-async-storage/async-storage";
export const saveGame = async (currentScore: number, currentLevel: number) => {
if (currentScore === 0) return;
const gameObj = {
gameScore: currentScore,
gameLevel: currentLevel,
date: new Date().toLocaleString()
}
const savedScores = await AsyncStorage.getItem('savedScores');
if (!savedScores) {
await AsyncStorage.setItem('savedScores', JSON.stringify({ 1: gameObj }));
return
}
const currentObj = JSON.parse(savedScores)
const currentLength = Object.keys(currentObj).length;
currentObj[currentLength + 1] = gameObj;
await AsyncStorage.setItem('savedScores', JSON.stringify(currentObj));
}
|
a0e5d6d841a42d6d89f0b098bdfb6660aaa0f1c1
|
TypeScript
|
cyberixae/experimental-ts
|
/test/Tombstone.ts
| 2.65625
| 3
|
import * as _ from '../src/Tombstone'
describe('Tombstone', () => {
it('tombstone', () => {
const stone: _.Tombstone<number> = _.tombstone(123)
expect(stone).toBeInstanceOf(_.Tombstone)
})
it('toString', () => {
expect(String(_.tombstone(123))).toStrictEqual('Tombstone {}')
})
})
|
aadb662f7f782d080e8c0a0a205e3e4c26bced2b
|
TypeScript
|
Haivex/clean-code-typescript
|
/src/errors/Http404Error.ts
| 2.5625
| 3
|
import { BaseError } from "./BaseError";
import { HttpStatusCode } from "./HttpStatusCode";
export class Http404Error extends BaseError {
constructor(description = "Not Found") {
super("NOT FOUND", HttpStatusCode.NOT_FOUND, description, true);
}
}
|
9bed99e95fbb212ed24c30d4db8caa9eff42ffa6
|
TypeScript
|
Visn0/pathfinding-ui
|
/src/algorithms/IAlgorithm.ts
| 3.46875
| 3
|
import Board from "../Board";
/////////////////////////////////
// INTERFACE
/////////////////////////////////
export type BoardPath = Array<ICoordinate>
export interface IAlgorithm {
findPath(board: Board, animationDelay: number): BoardPath
}
export class IBaseCoordinate {
row: number
col: number
constructor(r: number, c: number) {
this.row = r
this.col = c
}
}
export interface ICoordinate {
row: number
col: number
bound?: number // bound used in heuristic algorithms such as "Branch and Bound" or "A*"
prev?: ICoordinate // reference to the previous node visited in order to reach "this" node
pathLength?: number
}
/////////////////////////////////
// UTILS
/////////////////////////////////
export function EuclideanDistance(a: ICoordinate, b: ICoordinate): number {
return Math.sqrt(Math.abs(a.row - b.row) + Math.abs(a.col - b.col))
}
export function ManhattanDistance(a: ICoordinate, b: ICoordinate): number {
return (Math.abs(a.row - b.row) + Math.abs(a.col - b.col))
}
export function validCoord(coord: ICoordinate, maxRow: number, maxCol: number): boolean {
return (coord.row < maxRow && coord.row >= 0
&& coord.col < maxCol && coord.col >= 0)
}
export function compareCoords(a: ICoordinate, b: ICoordinate): boolean {
return a.bound < b.bound
}
export function getPath(coord: ICoordinate): BoardPath {
let path: BoardPath = new Array<ICoordinate>(coord.pathLength)
path[coord.pathLength - 1] = { ...coord }
for (let i = coord.pathLength - 2; i >= 0; i--)
{
path[i] = path[i + 1].prev
}
return path
}
export class Stack<T> {
_store: T[] = [];
lenght = 0
push(val: T) {
this._store.push(val);
this.lenght += 1
}
pop(): T | undefined {
if (this.lenght != 0)
this.lenght -= 1
return this._store.pop();
}
}
export class Queue<T> {
_store: T[] = [];
lenght = 0
push(val: T) {
this.lenght += 1
this._store.push(val);
}
pop(): T | undefined {
if (this.lenght != 0)
this.lenght -= 1
return this._store.shift();
}
}
|
4bc12c42461e1bfd13d3b2a60131bca509bae78b
|
TypeScript
|
bhoomidesai/SkillMap
|
/my-app/src/app/employee.service.ts
| 2.640625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import {Employee} from './employee';
import { MessageService } from './message.service';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class EmployeeService {
private employeeUrl = 'http://localhost:8080/SkillMapFrontend/api/employee';
constructor(
private http: HttpClient
) { }
getEmployees (): Observable<Employee[]> {
return this.http.get<Employee[]>(this.employeeUrl)
}
/** GET hero by id. Will 404 if id not found */
getEmployee(id: number): Observable<Employee> {
const url = `${this.employeeUrl}/${id}`;
return this.http.get<Employee>(url)
}
/* GET heroes whose name contains search term */
// searchEmployees(term: string): Observable<Employee[]> {
// if (!term.trim()) {
// // if not search term, return empty hero array.
// return of([]);
// }
// return this.http.get<Employee[]>(`api/heroes/?name=${term}`)
// }
//////// Save methods //////////
/** POST: add a new hero to the server */
addEmployee (employee: Employee): Observable<Employee> {
return this.http.post<Employee>(this.employeeUrl, employee, httpOptions)
}
/** DELETE: delete the hero from the server */
deleteEmployee (employee: Employee | number): Observable<Employee> {
const id = typeof employee === 'number' ? employee : employee.employee_id;
const url = `${this.employeeUrl}/${id}`;
return this.http.delete<Employee>(url, httpOptions)
}
/** PUT: update the hero on the server */
updateEmployee (employee: Employee): Observable<any> {
return this.http.put(this.employeeUrl, employee, httpOptions)
}
}
|
470d769b244e152a354fb3230792da55d0f9c340
|
TypeScript
|
keycloak/keycloak
|
/js/libs/keycloak-admin-client/test/stringifyQueryParams.spec.ts
| 3.015625
| 3
|
import { expect } from "chai";
import { stringifyQueryParams } from "../src/utils/stringifyQueryParams.js";
describe("stringifyQueryParams", () => {
it("ignores undefined and null", () => {
expect(stringifyQueryParams({ foo: undefined, bar: null })).to.equal("");
});
it("ignores empty strings", () => {
expect(stringifyQueryParams({ foo: "" })).to.equal("");
});
it("ignores empty arrays", () => {
expect(stringifyQueryParams({ foo: [] })).to.equal("");
});
it("accepts all other values", () => {
expect(
stringifyQueryParams({
boolTrue: true,
boolFalse: false,
numPositive: 1,
numZero: 0,
numNegative: -1,
str: "Hello World!",
}),
).to.equal(
"boolTrue=true&boolFalse=false&numPositive=1&numZero=0&numNegative=-1&str=Hello+World%21",
);
});
});
|
50bd8874a902c8d0372602b9a5b1ec5dd63f9797
|
TypeScript
|
AleoHQ-archived/aleo-setup-coordinator-archived
|
/coordinator-service/src/app.ts
| 2.515625
| 3
|
import bodyParser from 'body-parser'
import express from 'express'
import { authorize } from './authorize'
import { ChunkStorage, Coordinator } from './coordinator'
import { logger } from './logger'
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Express {
export interface Request {
participantId?: string
}
}
}
export function initExpress({
auth,
coordinator,
chunkStorage,
}: {
auth: (req, res, next) => void
coordinator: Coordinator
chunkStorage: ChunkStorage
}): express.Application {
const app = express()
const allowParticipants = authorize({
coordinator,
groups: ['verifierIds', 'contributorIds'],
})
const allowVerifiers = authorize({
coordinator,
groups: ['verifierIds'],
})
// Returns the current state of the ceremony in JSON format.
app.get('/ceremony', (req, res) => {
logger.info('GET /ceremony')
res.header("Content-Type",'application/json')
res.send(JSON.stringify(coordinator.getCeremony(), null, 4))
})
app.put(
'/ceremony',
auth,
allowVerifiers,
bodyParser.json(),
(req, res) => {
const ceremony = req.body
logger.info('PUT /ceremony')
try {
coordinator.setCeremony(ceremony)
res.json({
status: 'ok',
})
} catch (err) {
logger.warn(err.message)
res.status(409).json({ status: 'error', message: err.message })
}
},
)
app.post('/chunks/:id/lock', auth, allowParticipants, (req, res) => {
const participantId = req.participantId
const chunkId = req.params.id
logger.info(`POST /chunks/${chunkId}/lock ${participantId}`)
try {
const locked = coordinator.tryLockChunk(chunkId, participantId)
res.json({
status: 'ok',
result: {
chunkId,
locked,
},
})
} catch (err) {
logger.warn(err.message)
res.status(400).json({ status: 'error', message: err.message })
}
})
app.get('/chunks/:id/contribution', auth, allowParticipants, (req, res) => {
const participantId = req.participantId
const chunkId = req.params.id
logger.info(`GET /chunks/${chunkId}/contribution ${participantId}`)
const chunk = coordinator.getChunk(chunkId)
const writeUrl = chunkStorage.getChunkWriteLocation({
chunk,
participantId,
})
res.json({
status: 'ok',
result: {
chunkId,
participantId,
writeUrl,
},
})
})
app.post(
'/chunks/:id/contribution',
auth,
allowParticipants,
async (req, res) => {
const participantId = req.participantId
const chunkId = req.params.id
logger.info(`POST /chunks/${chunkId}/contribution ${participantId}`)
const chunk = coordinator.getChunk(chunkId)
let url
try {
url = await chunkStorage.copyChunk({
chunk,
participantId,
})
} catch (err) {
logger.warn(err.message)
res.status(400).json({
status: 'error',
message: 'Unable to copy contribution',
})
return
}
try {
await coordinator.contributeChunk(chunkId, participantId, url)
res.json({ status: 'ok' })
} catch (err) {
logger.warn(err.message)
res.status(400).json({ status: 'error' })
}
},
)
return app
}
|
da6bc8187e4300133fa61b9a1963c7e412806f63
|
TypeScript
|
bustle/mobiledoc-kit
|
/src/js/editor/edit-state.ts
| 2.921875
| 3
|
import { contains, isArrayEqual, objectToSortedKVArray } from '../utils/array-utils'
import Range from '../utils/cursor/range'
import { Option, Dict } from '../utils/types'
import Editor from './editor'
import { Cloneable } from '../models/_cloneable'
import Section from '../models/_section'
import Markup from '../models/markup'
import { TagNameable } from '../models/_tag-nameable'
import { getSectionAttributes } from '../models/_attributable'
interface EditStateState {
range: Range
activeMarkups: Markup[]
activeSections: Section[]
activeSectionTagNames: string[]
activeSectionAttributes: Dict<string[]>
}
/**
* Used by {@link Editor} to manage its current state (cursor, active markups
* and active sections).
* @private
*/
export default class EditState {
editor: Option<Editor>
state: Option<EditStateState>
prevState: Option<EditStateState>
constructor(editor: Editor) {
this.editor = editor
let defaultState: EditStateState = {
range: Range.blankRange(),
activeMarkups: [],
activeSections: [],
activeSectionTagNames: [],
activeSectionAttributes: {},
}
this.prevState = this.state = defaultState
}
updateRange(newRange: Range) {
this.prevState = this.state
this.state = this._readState(newRange)
}
destroy() {
this.editor = null
this.prevState = this.state = null
}
/**
* @return {Boolean}
*/
rangeDidChange(): boolean {
const { state, prevState } = this
const { range } = state!
const { range: prevRange } = prevState!
return !prevRange.isEqual(range)
}
/**
* @return {Boolean} Whether the input mode (active markups or active section tag names)
* has changed.
*/
inputModeDidChange(): boolean {
const state = this.state!
const prevState = this.prevState!
return (
!isArrayEqual(state.activeMarkups, prevState.activeMarkups) ||
!isArrayEqual(state.activeSectionTagNames, prevState.activeSectionTagNames) ||
!isArrayEqual(
objectToSortedKVArray(state.activeSectionAttributes),
objectToSortedKVArray(prevState.activeSectionAttributes)
)
)
}
/**
* @return {Range}
*/
get range(): Range {
return this.state!.range
}
/**
* @return {Section[]}
*/
get activeSections(): Section[] {
return this.state!.activeSections
}
/**
* @return {Object}
*/
get activeSectionAttributes(): Dict<string[]> {
return this.state!.activeSectionAttributes
}
/**
* @return {Markup[]}
*/
get activeMarkups(): Markup[] {
return this.state!.activeMarkups
}
/**
* Update the editor's markup state. This is used when, e.g.,
* a user types meta+B when the editor has a cursor but no selected text;
* in this case the editor needs to track that it has an active "b" markup
* and apply it to the next text the user types.
*/
toggleMarkupState(markup: Markup) {
if (contains(this.activeMarkups, markup)) {
this._removeActiveMarkup(markup)
} else {
this._addActiveMarkup(markup)
}
}
_readState(range: Range): EditStateState {
let state: Partial<EditStateState> = {
range,
activeMarkups: this._readActiveMarkups(range),
activeSections: this._readActiveSections(range),
}
// Section objects are 'live', so to check that they changed, we
// need to map their tagNames now (and compare to mapped tagNames later).
// In addition, to catch changes from ul -> ol, we keep track of the
// un-nested tag names (otherwise we'd only see li -> li change)
state.activeSectionTagNames = state.activeSections!.map(s => {
return s.isNested ? (s.parent as unknown as TagNameable).tagName : (s as unknown as TagNameable).tagName
})
state.activeSectionAttributes = this._readSectionAttributes(state.activeSections!)
return state as EditStateState
}
_readActiveSections(range: Range) {
const { head, tail } = range
const { editor } = this
const { post } = editor!
if (range.isBlank) {
return []
} else {
return post.sections.readRange(head.section as Cloneable<Section>, tail.section as Cloneable<Section>)
}
}
_readActiveMarkups(range: Range) {
const { editor } = this
const { post } = editor!
return post.markupsInRange(range)
}
_readSectionAttributes(sections: Section[]) {
return sections.reduce<Dict<string[]>>((sectionAttributes, s) => {
let attributes: Dict<string> = getSectionAttributes(s)
Object.keys(attributes).forEach(attrName => {
let camelizedAttrName = attrName.replace(/^data-md-/, '')
let attrValue = attributes[attrName]
sectionAttributes[camelizedAttrName] = sectionAttributes[camelizedAttrName] || []
if (!contains(sectionAttributes[camelizedAttrName], attrValue)) {
sectionAttributes[camelizedAttrName].push(attrValue)
}
})
return sectionAttributes
}, {})
}
_removeActiveMarkup(markup: Markup) {
let index = this.state!.activeMarkups.indexOf(markup)
this.state!.activeMarkups.splice(index, 1)
}
_addActiveMarkup(markup: Markup) {
this.state!.activeMarkups.push(markup)
}
}
|
f3fbd7737fc6a3e795e3181961147cab262e013d
|
TypeScript
|
AlexsaniKY/UnicodeRPG
|
/src/sprite.ts
| 2.859375
| 3
|
import { IDrawable, IDrawScaleOptions, IDrawSourceOptions } from "./shared/drawable";
import { Color } from "./shared/color";
export class Sprite implements IDrawable{
canvas: HTMLCanvasElement;
context: CanvasRenderingContext2D;
width: number;
height: number;
constructor(width:number, height:number){
this.width = width;
this.height = height;
this.canvas = document.createElement("canvas");
this.canvas.width = width;
this.canvas.height = height;
this.context = this.canvas.getContext("2d");
}
draw(target: IDrawable, x:number, y:number, scale_options?:IDrawScaleOptions, from_options?: IDrawSourceOptions): void{
if(from_options){
target.context.drawImage(
this.canvas,
from_options.x,
from_options.y,
from_options.clipwidth || this.width,
from_options.clipheight || this.height,
x,
y,
scale_options.scalewidth || this.width,
scale_options.scaleheight || this.height
);
return;
}else if(scale_options){
target.context.drawImage(
this.canvas,
x,
y,
scale_options.scalewidth,
scale_options.scaleheight
);
return;
}
target.context.drawImage(this.canvas, x, y);
}
fill(color: Color, options?: object){
this.context.fillStyle = color.toString();
this.context.fillRect(0,0,this.width, this.height);
}
fillRect(color: Color, x, y, width, height){
this.context.fillStyle = color.toString();
this.context.fillRect(x, y, width, height);
}
clear(x:number = 0, y:number = 0, width:number = 0, height:number = 0){
this.context.clearRect(x, y, width, height);
}
}
|
df71e25f2bbdc4e48bb49aecdecbbfb93f094b93
|
TypeScript
|
MaciejReimann/patterny
|
/src/patterns/arabesque/Polygon.ts
| 2.8125
| 3
|
import p5 from "p5"
import { makeLine } from "../../lib/fabric-wrappers"
import { Edge } from "./Edge"
export class Polygon {
vertices: p5.Vector[] = []
edges: Edge[] = []
constructor(readonly canvas: any) {
this.canvas = canvas
}
addVertex(x: number, y: number): Polygon {
const vertex = new p5.Vector().set(x, y)
const verticesCount = this.vertices.length
if (verticesCount > 0) {
const prev = this.vertices[verticesCount - 1]
const edge = new Edge(prev, vertex, this.canvas)
this.edges.push(edge)
}
this.vertices.push(vertex)
return this
}
private createHankins(delta: number, angle?: number) {
this.edges.forEach((edge, i) => {
edge.createHankins(delta, angle)
})
const edgesCount = this.edges.length
for (let i = 0; i < edgesCount; i++) {
for (let j = 0; j < edgesCount; j++) {
if (i !== j) {
this.edges[i].findEnds(this.edges[j])
}
}
}
}
showHankins(delta: number, angle?: number) {
this.createHankins(delta, angle)
this.edges.forEach((edge, i) => {
edge.showHankins()
})
return this
}
show() {
this.edges.forEach((edge) => {
edge.show()
})
return this
}
close(): Polygon {
const verticesCount = this.vertices.length
const lastVertex = this.vertices[verticesCount - 1]
const firstVertex = this.vertices[0]
const edge = new Edge(lastVertex, firstVertex, this.canvas)
this.edges.push(edge)
return this
}
}
|
73ddc5542380ab614b4434d6cf015794bf750b3b
|
TypeScript
|
nikolay-t16/JMReactBlog
|
/src/helpers/ValidationError.ts
| 2.90625
| 3
|
export type ValidationErrorsData = {
email?: string[];
username?: string[];
password?: string[];
};
export default class ValidationError extends Error {
errors: any = {};
constructor(errors?: ValidationErrorsData) {
super();
if (errors) {
this.errors = errors;
}
}
}
|
4e7a3e70d8794d652821fb3556f7010dcaaf858a
|
TypeScript
|
cybernetics/WebRx
|
/test/Bindings/EventSpecs.ts
| 2.6875
| 3
|
/// <reference path="../typings/jasmine.d.ts" />
/// <reference path="../typings/jasmine-jquery.d.ts" />
/// <reference path="../../src/web.rx.d.ts" />
describe('Bindings', () => {
describe('Event',() => {
it('binds a single event to a handler function',() => {
loadFixtures('templates/Bindings/Event.html');
const el = <HTMLElement> document.querySelector("#event-single");
let called = false;
let eventName = undefined;
let calledWithValidContext = false;
let calledWithValidEvent = false;
let callCount = 0;
let model = {
clickHandler: (ctx: wx.IDataContext, e: Event) => {
callCount++;
called = true;
eventName = e.type;
if (ctx.hasOwnProperty("$data"))
calledWithValidContext = true;
if (e instanceof window['Event'])
calledWithValidEvent = true;
}
};
expect(() => wx.applyBindings(model, el)).not.toThrowError();
expect(called).not.toBeTruthy();
expect(eventName).not.toEqual("click");
expect(calledWithValidContext).not.toBeTruthy();
expect(calledWithValidEvent).not.toBeTruthy();
testutils.triggerEvent(el, "click");
expect(called).toBeTruthy();
expect(eventName).toEqual("click");
expect(calledWithValidContext).toBeTruthy();
expect(calledWithValidEvent).toBeTruthy();
wx.cleanNode(el);
called = false;
// should no longer fire
testutils.triggerEvent(el, "click");
expect(called).toBeFalsy();
});
it('binds multiple events to handler functions',() => {
loadFixtures('templates/Bindings/Event.html');
const el = <HTMLInputElement> document.querySelector("#event-multiple");
let clickCallCount = 0;
let inputCallCount = 0;
let model = {
clickHandler: (ctx: wx.IDataContext, e: Event) => {
clickCallCount++;
},
inputHandler: (ctx: wx.IDataContext, e: Event) => {
inputCallCount++;
}
};
expect(() => wx.applyBindings(model, el)).not.toThrowError();
expect(clickCallCount).toEqual(0);
expect(inputCallCount).toEqual(0);
testutils.triggerEvent(el, "click");
expect(clickCallCount).toEqual(1);
$(el).val("new");
testutils.triggerEvent(el, "input");
expect(inputCallCount).toEqual(1);
wx.cleanNode(el);
clickCallCount = 0;
inputCallCount = 0;
// should no longer fire
testutils.triggerEvent(el, "click");
expect(clickCallCount).toEqual(0);
$(el).val("old");
testutils.triggerEvent(el, "input");
expect(inputCallCount).toEqual(0);
});
it('binds multiple events to observers',() => {
loadFixtures('templates/Bindings/Event.html');
const el = <HTMLInputElement> document.querySelector("#event-multiple-observer");
let clickCallCount = 0;
let inputCallCount = 0;
let clickSubject = new Rx.Subject<Event>();
let inputSubject = new Rx.Subject<Event>();
let model = {
clickObserver: Rx.Observer.create<Event>((x) => { clickSubject.onNext(x) }),
inputObserver: Rx.Observer.create<Event>((x) => { inputSubject.onNext(x) })
};
clickSubject.subscribe(x => clickCallCount++);
inputSubject.subscribe(x => inputCallCount++);
expect(() => wx.applyBindings(model, el)).not.toThrowError();
expect(clickCallCount).toEqual(0);
expect(inputCallCount).toEqual(0);
testutils.triggerEvent(el, "click");
expect(clickCallCount).toEqual(1);
el.value = "new";
testutils.triggerEvent(el, "input");
expect(inputCallCount).toEqual(1);
wx.cleanNode(el);
clickCallCount = 0;
inputCallCount = 0;
// should no longer fire
testutils.triggerEvent(el, "click");
expect(clickCallCount).toEqual(0);
el.value = "old";
testutils.triggerEvent(el, "input");
expect(inputCallCount).toEqual(0);
});
it('binds multiple events to commands',() => {
loadFixtures('templates/Bindings/Event.html');
const el = <HTMLInputElement> document.querySelector("#event-multiple-command");
let clickCallCount = 0;
let inputCallCount = 0;
let clickSubject = new Rx.Subject<Event>();
let inputSubject = new Rx.Subject<Event>();
let model = {
clickCommand: wx.command((x) => { clickSubject.onNext(x) }),
inputCommand: wx.command((x) => { inputSubject.onNext(x) })
};
clickSubject.subscribe(x => clickCallCount++);
inputSubject.subscribe(x => inputCallCount++);
expect(() => wx.applyBindings(model, el)).not.toThrowError();
expect(clickCallCount).toEqual(0);
expect(inputCallCount).toEqual(0);
testutils.triggerEvent(el, "click");
expect(clickCallCount).toEqual(1);
el.value = "new";
testutils.triggerEvent(el, "input");
expect(inputCallCount).toEqual(1);
wx.cleanNode(el);
clickCallCount = 0;
inputCallCount = 0;
// should no longer fire
testutils.triggerEvent(el, "click");
expect(clickCallCount).toEqual(0);
el.value = "old";
testutils.triggerEvent(el, "input");
expect(inputCallCount).toEqual(0);
});
it('binds multiple events to commands with params',() => {
loadFixtures('templates/Bindings/Event.html');
const el = <HTMLInputElement> document.querySelector("#event-multiple-command-with-params");
let clicks = [];
let model = {
clickCommand: wx.command((x) => { clicks.push(x); })
};
expect(() => wx.applyBindings(model, el)).not.toThrowError();
expect(clicks.length).toEqual(0);
testutils.triggerEvent(el, "click");
expect(clicks.length).toEqual(1);
expect(clicks[0]).toEqual('foo');
wx.cleanNode(el);
clicks = [];
// should no longer fire
testutils.triggerEvent(el, "click");
expect(clicks.length).toEqual(0);
});
});
});
|
51ac8ae167e4c4916d5cafb07170e9cc2c952aab
|
TypeScript
|
falsandtru/spica
|
/src/monad/sequence/member/instance/subsequences.ts
| 2.75
| 3
|
import { Sequence } from '../../core';
import { compose } from '../../../../helper/compose';
compose(Sequence, class <a, z> extends Sequence<a, z> {
public override subsequences(): Sequence<a[], [Sequence.Iterator<a[]>, Sequence.Iterator<a[]>]> {
return Sequence.mappend<a[]>(
Sequence.from([[]]),
Sequence.from([0])
.bind(() =>
nonEmptySubsequences(this)));
}
});
function nonEmptySubsequences<a, z>(xs: Sequence<a, z>): Sequence<a[], [Sequence.Iterator<a[]>, Sequence.Iterator<a[]>]> {
return Sequence.Iterator.when<a, Sequence<a[], [Sequence.Iterator<a[]>, Sequence.Iterator<a[]>]>>(
xs.iterate(),
() => Sequence.mempty,
xt =>
Sequence.mappend<a[]>(
Sequence.from([[Sequence.Thunk.value(xt)]]),
new Sequence<Sequence<a[], [Sequence.Iterator<Sequence<a[], unknown>>, Sequence.Iterator<a[]>]>, undefined>((_, cons) =>
Sequence.Iterator.when(
xt,
() => cons(),
xt =>
cons(
nonEmptySubsequences(
Sequence.resume(Sequence.Thunk.iterator(xt)))
.foldr<a[]>((ys, r) =>
Sequence.mappend(
Sequence.mappend(
Sequence.from([ys]),
Sequence.from([[Sequence.Thunk.value(xt), ...ys]])),
r)
, Sequence.mempty))))
.bind(xs => xs)));
}
|
630061386f7ecacef9fec25eb239e7d06f864b62
|
TypeScript
|
Inna3112/Tests
|
/src/10/10_1.test.ts
| 2.96875
| 3
|
import {
addBooksToUser, addNewCompany, addOneBookToUser,
makeHairStyle,
moveUser,
moveUserToOtherHouse, removeBook,
updateBooks, updateCompany, updateCompany2,
upgradeLaptop,
UsersType,
UserWithBooksType,
UserWithLaptopType, WithCompaniesType
} from "./10_1";
test('reference type test', () => {
let user: UsersType = {
name: 'Inna',
hair: 32,
address: {
city: 'Kryvyi Rig'
}
}
const awesomeUser = makeHairStyle(user, 2)
expect(user.hair).toBe(32);
expect(awesomeUser.hair).toBe(16);
expect(awesomeUser.address).toBe(user.address);
})
test('change address', () => {
let user: UserWithLaptopType = {
name: 'Inna',
hair: 32,
address: {
city: 'Kryvyi Rig',
house: 9
},
laptop: {
title: 'Assus'
}
}
const movedUser = moveUser(user, 'Kyiv')
expect(movedUser).not.toBe(user);
expect(user.address.city).toBe('Kryvyi Rig');
expect(movedUser.address.city).toBe('Kyiv');
expect(movedUser.address).not.toBe(user.address);
expect(movedUser.laptop).toBe(user.laptop);
})
test('upgrade laptop to macbook', () => {
let user: UserWithLaptopType = {
name: 'Inna',
hair: 32,
address: {
city: 'Kryvyi Rig',
house: 9
},
laptop: {
title: 'Asus'
}
}
const userCopy = upgradeLaptop(user, 'Macbook')
expect(user).not.toBe(userCopy);
expect(user.laptop.title).toBe('Asus');
expect(userCopy.laptop.title).toBe('Macbook');
expect(user.laptop).not.toBe(userCopy.laptop);
})
test('upgrade laptop to macbook', () => {
let user: UserWithLaptopType & UserWithBooksType = {
name: 'Inna',
hair: 32,
address: {
city: 'Kryvyi Rig',
house: 9
},
laptop: {
title: 'Asus'
},
books: ['HTML', 'CSS', 'JS', 'React']
}
const userCopy = moveUserToOtherHouse(user, 16)
expect(user).not.toBe(userCopy);
expect(user.books).toBe(userCopy.books)
expect(userCopy.address.house).toBe(16)
expect(user.address.house).not.toBe(userCopy.address.house);
expect(user.laptop).toBe(userCopy.laptop);
})
test('add new books', () => {
let user: UserWithLaptopType & UserWithBooksType = {
name: 'Inna',
hair: 32,
address: {
city: 'Kryvyi Rig',
house: 9
},
laptop: {
title: 'Asus'
},
books: ['HTML', 'CSS', 'JS', 'React']
}
const userCopy = addBooksToUser(user, ['TS', 'Rest api'])
expect(user).not.toBe(userCopy);
expect(user.books).not.toBe(userCopy.books);
expect(userCopy.books.length).toBe(6);
expect(userCopy.books[4]).toBe('TS');
expect(userCopy.books[5]).toBe('Rest api');
})
test('add new book', () => {
let user: UserWithLaptopType & UserWithBooksType = {
name: 'Inna',
hair: 32,
address: {
city: 'Kryvyi Rig',
house: 9
},
laptop: {
title: 'Asus'
},
books: ['HTML', 'CSS', 'JS', 'React']
}
const userCopy = addOneBookToUser(user, 'TS')
expect(user).not.toBe(userCopy);
expect(user.books).not.toBe(userCopy.books);
expect(user.books.length).toBe(4);
expect(userCopy.books.length).toBe(5);
expect(userCopy.books[4]).toBe('TS');
})
test('update JS to TS', () => {
let user: UserWithLaptopType & UserWithBooksType = {
name: 'Inna',
hair: 32,
address: {
city: 'Kryvyi Rig',
house: 9
},
laptop: {
title: 'Asus'
},
books: ['HTML', 'CSS', 'JS', 'React']
}
const userCopy = updateBooks(user, 'JS', 'TS')
expect(user).not.toBe(userCopy);
expect(user.books).not.toBe(userCopy.books);
expect(userCopy.books[2]).toBe('TS');
expect(user.books[2]).toBe('JS');
})
test('remove JS book', () => {
let user: UserWithLaptopType & UserWithBooksType = {
name: 'Inna',
hair: 32,
address: {
city: 'Kryvyi Rig',
house: 9
},
laptop: {
title: 'Asus'
},
books: ['HTML', 'CSS', 'JS', 'React']
}
const userCopy = removeBook(user, 'JS')
expect(user).not.toBe(userCopy);
expect(user.books).not.toBe(userCopy.books);
expect(userCopy.books.length).toBe(3);
})
test('add new company', () => {
let user: UserWithLaptopType & WithCompaniesType = {
name: 'Inna',
hair: 32,
address: {
city: 'Kryvyi Rig',
house: 9
},
laptop: {
title: 'Asus'
},
companies: [
{id: 1, title: 'Epam'},
{id: 2, title: 'Onix'},
]
}
const userCopy = addNewCompany(user, 3, 'IT-INCUBATOR')
expect(user).not.toBe(userCopy);
expect(user.companies).not.toBe(userCopy.companies);
expect(userCopy.companies.length).toBe(3);
expect(userCopy.companies[2].title).toBe('IT-INCUBATOR');
})
test('update company', () => {
let user: UserWithLaptopType & WithCompaniesType = {
name: 'Inna',
hair: 32,
address: {
city: 'Kryvyi Rig',
house: 9
},
laptop: {
title: 'Asus'
},
companies: [
{id: 1, title: 'Епам'},
{id: 2, title: 'Onix'},
]
}
const userCopy = updateCompany(user, 1, 'Epam') as UserWithLaptopType & WithCompaniesType
expect(user).not.toBe(userCopy);
expect(user.companies).not.toBe(userCopy.companies);
expect(userCopy.companies.length).toBe(2);
expect(userCopy.companies[0].title).toBe('Epam');
})
test('update company2', () => {
let companies = {
'Inna' : [{id: 1, title: 'Епам'}, {id: 2, title: 'Onix'}],
'Anna' : [{id: 1, title: 'Google'}]
}
const copy = updateCompany2(companies, 'Inna', 1, 'Epam')
expect(copy['Inna']).not.toBe(companies['Inna']);
expect(copy['Inna'][0].title).toBe('Epam');
expect(copy['Anna']).toBe(companies['Anna']);
})
|
6d6f950017c4823bc487b5b80c71944ec4abfeb5
|
TypeScript
|
MateuszLebioda/OneCinema_PZ
|
/UI/src/app/modules/admin/pages/movie-processing/components/seance/validators/seance-validator.ts
| 2.546875
| 3
|
import {AbstractControl, FormControl, ValidatorFn} from '@angular/forms';
import {DateTime} from 'luxon';
import {Time} from '@angular/common';
import {Luxon} from '../../../../../../../shared/helpers/external/luxon';
import {DateTimeService} from '../../../../../../../shared/helpers/internal/date-time.service';
import {SeanceApiModel} from '../models/api/seance-api.model';
export class SeanceValidator {
private static _dateTimeService: DateTimeService = new DateTimeService();
public static isValid(seanceDay: Date,
seancesThisDay: SeanceApiModel[],
movieDuration: FormControl,
breakBeforeAndAfterSeanse: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (movieDuration.invalid) {
return {'emptySeanceDuration': true};
}
if (control.value && !this._isValid(
control.value, seanceDay, seancesThisDay, movieDuration.value + breakBeforeAndAfterSeanse * 2)) {
return {'wrongTime': true};
}
return null;
};
}
private static _isValid(seanceStartHour: string,
seanceDay: Date,
seancesThisDay: SeanceApiModel[],
seanceDuration: number): boolean {
const seanceTime: Time = this._dateTimeService.convertToTime(seanceStartHour);
if (!seanceTime) {
return false;
}
if (seancesThisDay.length <= 0) {
return true;
}
seanceDay.setHours(seanceTime.hours);
seanceDay.setMinutes(seanceTime.minutes);
const seanceStart: Date = seanceDay;
const seanceEnd: DateTime = Luxon.toDateTime(seanceStart).plus({minutes: seanceDuration});
const indexOfSeanceBeforeValidatingSeance = seancesThisDay.findIndex(currentSeance => currentSeance.start > seanceStart);
if (indexOfSeanceBeforeValidatingSeance < 0) {
return this._canSeanceBeLatest(
Luxon.toDateTime(seanceStart), seanceEnd, Luxon.toDateTime(seancesThisDay[seancesThisDay.length - 1].finish));
}
if (indexOfSeanceBeforeValidatingSeance === 0) {
return this._canSeanceBeFirst(
Luxon.toDateTime(seanceStart), seanceEnd, Luxon.toDateTime(seancesThisDay[0].start));
}
return this._isSeanceBetweenPreviousAndNextSeances(
seanceStart, Luxon.toDate(seanceEnd), seancesThisDay, indexOfSeanceBeforeValidatingSeance);
}
private static _canSeanceBeLatest(seanceStart: DateTime, seanceEnd: DateTime, endOfseanceBeforeValidatingSeance: DateTime): boolean {
return seanceEnd < this._getDayEnd(seanceStart) && endOfseanceBeforeValidatingSeance < seanceStart;
}
private static _canSeanceBeFirst(seanceStart: DateTime, seanceEnd: DateTime, startOfSeanceBeforeValidatingSeance: DateTime): boolean {
return seanceStart > this._getDayStart(seanceStart) && seanceEnd < startOfSeanceBeforeValidatingSeance;
}
private static _isSeanceBetweenPreviousAndNextSeances(seanceStart: Date,
seanceEnd: Date,
seancesThisDay: SeanceApiModel[],
indexOfSeanceBeforeValidatingSeance: number): boolean {
const endOfSeanceBeforeValidatingSeance = seancesThisDay[indexOfSeanceBeforeValidatingSeance - 1].finish;
const startOfSeanceAfterValidatingSeance = seancesThisDay[indexOfSeanceBeforeValidatingSeance].start;
return seanceStart > endOfSeanceBeforeValidatingSeance && seanceEnd < startOfSeanceAfterValidatingSeance;
}
private static _getDayStart(date: DateTime): DateTime {
const dayStart = Luxon.toDate(date);
dayStart.setHours(0, 0, 0, 0);
return Luxon.toDateTime(dayStart);
}
private static _getDayEnd(date: DateTime): DateTime {
const dayEnd = Luxon.toDate(date);
dayEnd.setHours(23, 59, 59, 999);
return Luxon.toDateTime(dayEnd);
}
}
|
b69420edb3dead7f6ccc8ea7ba31d78f876b1319
|
TypeScript
|
kozPio/MasteringTypescript
|
/web/src/router/routes.ts
| 2.828125
| 3
|
//router instance
type Routes = {path: string, name: string}
class Router {
constructor(public name: string, public routes: Routes[]){}
start(): {} {
return {
name: this.name,
routes: this.routes
}
}
}
const routerInstance = new Router('routerInstance', [{
path: "/",
name: "Root"
},
{
path: '/about',
name: "About"
},
{
path: '/contact',
name: "Contact"
}
])
export default routerInstance
|
80a114f7b8fc3aea4c22c335120fbcd756bfeb81
|
TypeScript
|
iagobruno/ideas-for-title-animation
|
/src/ts/utils.ts
| 3.640625
| 4
|
/**
* Pause the code for some time.
* @returns {Promise}
*/
export function sleep(durationInMs: number) {
return new Promise(resolve => setTimeout(resolve, durationInMs))
}
/**
* Traversing the items of an array with a short time interval between each one.
* @returns {Promise} Returns a promise that resolves on the end of the interaction.
*/
export function loopWithDelay<U>(items: U[], delayInMs: number, callback: (letter: U, index: number) => void) {
return new Promise((resolve) => {
let index = 0
let loop = setInterval(() => {
const currentItem = items[index]
callback(currentItem, index)
if (index >= items.length-1) {
clearInterval(loop)
resolve();
}
else index++
}, delayInMs)
})
}
|
320d7704494ecb2e524115d1af2c4d2ae3961cce
|
TypeScript
|
nadineouro/react-concepts
|
/src/store/country/types.ts
| 2.765625
| 3
|
export type Country = {
code: string
name?: string
native?: string
phone?: string
continent?: Continent
currency?: string
languages?: Language[]
emoji?: string
emojiU?: string
states?: State[]
}
export type CountryStore = {
countries: Country[]
}
export type Continent = {
code?: string
name?: string
countries?: Country[]
}
export type Language = {
code?: string
name?: string
native?: string
rtl?: number
}
export type State = {
code?: string
name?: string
country?: Country[]
}
export enum CountryConstants {
REDUCER_SET_COUNTRY_DATA = 'REDUCER_SET_COUNTRY_DATA',
ACTION_GET_COUNTRIES = 'ACTION_GET_COUNTRIES'
}
|
15324fc0575d4847f50c4653093453a998d6b60d
|
TypeScript
|
arruw/survey
|
/src/components/Assessment/scorers/psqi.test.ts
| 2.5625
| 3
|
import psqi, { IPSQIResponse, IPSQIScore } from './psqi';
it ('scoring best', () => {
expect(psqi.calculateScore(responseBest)).toEqual(scoringBest);
});
it ('scoring worst', () => {
expect(psqi.calculateScore(responseWorst)).toEqual(scoringWorst);
});
it ('hoursInBed', () => {
expect(psqi.hoursInBed('22:00', '06:00')).toEqual(8);
expect(psqi.hoursInBed('22:30', '06:30')).toEqual(8);
expect(psqi.hoursInBed('22:30', '06:00')).toEqual(7.5);
expect(psqi.hoursInBed('22:00', '06:30')).toEqual(8.5);
expect(psqi.hoursInBed('02:00', '05:00')).toEqual(3);
expect(psqi.hoursInBed('02:00', '02:00')).toEqual(24);
expect(psqi.hoursInBed('00:00', '02:00')).toEqual(2);
expect(psqi.hoursInBed('23:30', '02:00')).toEqual(2.5);
});
it ('c4scorer', () => {
expect(psqi.c4scorer((7-(+3)) / 8)).toEqual(3);
});
const responseBest: IPSQIResponse = {
q01: '22:00',
q02: 0,
q03: '6:00',
q04: 0,
q05: {
a: 0,
b: 0,
c: 0,
d: 0,
e: 0,
f: 0,
g: 0,
h: 0,
i: 0,
j: 0,
},
q06: 0,
q07: 0,
q08: 0,
q09: 0,
};
const scoringBest: IPSQIScore = {
c1: 0,
c2: 0,
c3: 0,
c4: 0,
c5: 0,
c6: 0,
c7: 0,
total: 0
}
const responseWorst: IPSQIResponse = {
q01: '23:00',
q02: 3,
q03: '06:00',
q04: 3,
q05: {
a: 3,
b: 3,
c: 3,
d: 3,
e: 3,
f: 3,
g: 3,
h: 3,
i: 3,
j: 3,
},
q06: 3,
q07: 3,
q08: 3,
q09: 3,
};
const scoringWorst: IPSQIScore = {
c1: 3,
c2: 3,
c3: 3,
c4: 3,
c5: 3,
c6: 3,
c7: 3,
total: 21
}
export const tests = null;
|
de20bef0d0775bb5e43171d428a608c3cd9c80ad
|
TypeScript
|
fierydeer/TypeScript
|
/Telerik-codes/Loops/Calculate n! = 1 * 2 * ... * n improved.ts
| 3.609375
| 4
|
// Calculate n! = 1 * 2 * ... * n
let n: number = 6;
let result: number = 1;
let logable = n;
while (true) {
if (n <= 1) {
break;
}
result *= n;
n--;
}
console.log(`${logable}! = ${result}`);
|