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
|
|---|---|---|---|---|---|---|
a33e0acb9140175f57f4b964bdae0795e7a28d0f
|
TypeScript
|
whiterook6/webgl
|
/src/cameras/PerspectiveLens.ts
| 2.578125
| 3
|
import {Lens} from "./Lens";
import {mat4} from "gl-matrix";
export class PerspectiveLens extends Lens {
public fieldOfView: number = (45 * Math.PI) / 180;
public aspect: number = 1;
public zNear: number = 0.1;
public zFar: number = 100.0;
public getProjection() {
const matrix = mat4.create();
mat4.perspective(matrix, this.fieldOfView, this.aspect, this.zNear, this.zFar);
return matrix;
}
}
|
020fd896f76e8606cf12a57462008a237c8afef3
|
TypeScript
|
mrwhale-io/mrwhale
|
/packages/mrwhale-commands/src/commands/fun/ascii.ts
| 2.796875
| 3
|
import { codeBlock, CommandOptions } from "@mrwhale-io/core";
import * as figlet from "figlet";
import * as util from "util";
const figletAsync = util.promisify(figlet);
export const data: CommandOptions = {
name: "ascii",
description: "Generate ascii.",
type: "fun",
usage: "<prefix>ascii <text>",
examples: ["<prefix>ascii Mr. Whale"],
cooldown: 5000,
};
export async function action(text: string): Promise<unknown> {
if (!text) {
return "Please provide some text.";
}
const result = (await figletAsync(text)) as string;
if (!result) {
return "Could not parse input."
}
return codeBlock(result);
}
|
da8ef040d2842a41e426dd2418b0e2bb7119730c
|
TypeScript
|
arturdedela/cryptography-lab-1
|
/src/components/Encryption/Encrypt/types.ts
| 2.59375
| 3
|
import { AlgorithmNames } from "../algorithms";
import { Mode } from "../Encryption";
export interface IEventData {
action: string;
}
export interface IEncryptData extends IEventData {
file: ArrayBuffer;
mode: Mode;
algorithmName: AlgorithmNames;
encryptionKey: string;
options: any;
}
export interface IProgressData extends IEventData{
progress: number;
}
export interface IFinishData extends IEventData {
encryptedFile: ArrayBuffer;
decryptionKey: string;
encryptTime: number;
}
export function isEncryptMessage(data: IEventData): data is IEncryptData {
return data.action === "encrypt";
}
export function isProgressMessage(data: IEventData): data is IProgressData {
return data.action === "progress";
}
export function isFinishMessage(data: IEventData): data is IFinishData {
return data.action === "finish";
}
export type EncryptTimings = Array<{ size: number, time: number }>;
|
84009f77d38c66fdd1e7d49f7a30062a8c94df79
|
TypeScript
|
Arsenalist/twitter-video-uploader
|
/src/fileDetectedHandler.ts
| 2.625
| 3
|
import {getVideoDurationInSeconds} from 'get-video-duration'
import {SocketServerWrapper} from "./socketServerWrapper";
import {createThumbnailPath, createThumbnailPathFromWebRoot} from "./videoFilePaths";
import {videoInfoRequest} from "./socketMessage";
const fs = require('fs');
function isFileNewEnough(newDetectedFile: string) {
const stat = fs.statSync(newDetectedFile);
const thirtySeconds = 30 * 1000;
return new Date().getTime() - stat.mtime <= thirtySeconds;
}
export const fileDetectedHandler = async (newDetectedFile: string, wrapper: SocketServerWrapper, web_client_dir: string) => {
console.log("new file found", newDetectedFile);
let completeFile = false
try {
// this call fails if the file is being written to which is what we want as we don't want
// to process incomplete files
await getVideoDurationInSeconds(newDetectedFile);
completeFile = true
} catch (e) {
console.log("incomplete file found, skipping", newDetectedFile);
}
const newEnough = isFileNewEnough(newDetectedFile);
if (!completeFile || !newEnough) {
return;
}
try {
let thumb = createThumbnailPath(web_client_dir, newDetectedFile);
fs.copyFileSync(newDetectedFile, thumb)
wrapper.send(videoInfoRequest(newDetectedFile, createThumbnailPathFromWebRoot(thumb)))
console.log("processed", newDetectedFile);
} catch (e) {
console.log("encountered an error processing file", newDetectedFile, e);
}
}
|
08343ea2b5b6a1f59c7509bb9c6b6fe3ed80f9ba
|
TypeScript
|
Bingsta/Angular-async-routes-loading-test
|
/src/app/services/page.service.ts
| 2.59375
| 3
|
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { PageType } from '../types/PageType.type';
import { delay, map } from 'rxjs/operators';
import { GenericHTMLComponent } from '../generic-html/generic-html.component';
import { ModuleItem } from './module-item';
import { PropertyModuleComponent } from '../property-module/property-module.component';
import { TestamonialModuleComponent } from '../testamonial-module/testamonial-module.component';
import Module from '../types/Module.type';
import Page from '../types/Page.type';
import { ModuleType } from '../types/ModuleType.type';
export interface PageConfig {
id: number;
name: string;
type: PageType;
title: string;
strapline: string;
coverImage: string;
modules: ModuleItem[];
}
@Injectable({
providedIn: 'root'
})
export class PageService {
pageConfig: PageConfig;
constructor() { }
getPage(id: number): Observable<PageConfig> {
console.log(ModuleType);
return this.mockApiCall(id)
.pipe(
map((page) => {
const modules: ModuleItem[] = [];
this.pageConfig = {
id: page.id,
name: page.name,
type: page.type,
title: page.title,
strapline: page.strapline,
coverImage: page.coverImage,
modules: page.modules.map(this.ModuleItemFactory())
};
return this.pageConfig;
})
);
}
private ModuleItemFactory(): (value: Module, index: number, array: Module[]) => ModuleItem {
return (module: Module) => {
switch (module.type) {
case ModuleType.GenericHTML:
return new ModuleItem(GenericHTMLComponent, module.config);
case ModuleType.Property:
return new ModuleItem(PropertyModuleComponent, module.config);
case ModuleType.Testamonial:
return new ModuleItem(TestamonialModuleComponent, module.config);
default:
throw Error('Unknown module type');
}
};
}
mockApiCall(id: number): Observable<Page> {
console.log(ModuleType.GenericHTML);
const pages: Page[] = [
{
id: 0,
name: 'Home',
type: PageType.HOME,
title: 'Home page',
strapline: 'Home page strapline',
coverImage: 'dasd',
modules: [
{
type: ModuleType.GenericHTML,
config: {
title: 'Generic HTML test',
html: '<div class="nonsense">My content</div>'
}
},
{
type: ModuleType.Property,
config: {
title: 'Latest properties',
properties: [
{
address: 'property 1'
},
{
address: 'property 2'
},
{
address: 'property 3'
}
]
}
},
{
type: ModuleType.GenericHTML,
config: {
title: 'Another html component',
html: '<div class="nonsense"><ul><li>asdasd</li><li>dasdas</li></div>'
}
}
]
},
{
id: 1,
name: 'Property search',
type: PageType.PROPERTYSEARCH,
title: 'Property search',
strapline: 'Do a search please',
coverImage: 'dasd',
modules: [
{
type: ModuleType.GenericHTML,
config: {
title: 'Generic test',
html: '<div class="nonsense">My content</div>'
}
}
]
},
{
id: 3,
name: 'Some bollocks',
type: PageType.PROPERTYSEARCH,
title: 'Some bollocks',
strapline: 'Blah blah blah',
coverImage: 'dasd',
modules: [
{
type: ModuleType.GenericHTML,
config: {
title: 'Generic test',
html: '<div class="nonsense">My content</div>'
}
}
]
}
];
const page = pages.find((p: Page) => p.id === id);
return of(page)
.pipe(
delay(1000)
);
}
}
|
ceaeb24ad84f205996dd7c6ee76b66bdeb76e190
|
TypeScript
|
Perseus101/lonely-journey
|
/src/stars.ts
| 2.859375
| 3
|
import * as PIXI from 'pixi.js';
import Camera from './camera';
function wrap(val: number, by: number): number {
val = val % by;
if (val < 0) {
return val + by;
} else {
return val;
}
}
function randomGauss(): number {
let randA = Math.random();
let randB = Math.random();
return Math.sqrt(-2 * Math.log(randA)) * Math.cos(2 * Math.PI * randB);
}
// unique random number generation from
// https://stackoverflow.com/questions/11808804/generate-unique-number-within-range-0-x-keeping-a-history-to-prevent-duplic/11809348#11809348
function makeRandomRange(x: number): any {
var range = new Array(x),
pointer = x;
return function getRandom() {
pointer = (pointer - 1 + x) % x;
var random = Math.floor(Math.random() * pointer);
var num = (random in range) ? range[random] : random;
range[random] = (pointer in range) ? range[pointer] : pointer;
return range[pointer] = num;
};
}
function randSign(): number {
return 2 * Math.round(Math.random()) - 1;
}
export class Stars {
app: PIXI.Application;
container: PIXI.Container;
starGraphic: any;
stars: any[] = [];
bufferStars: any[] = [];
lastCamera: Camera;
parallaxAmount = 0.1;
starSettings = {
numParticles: 150,
alphaMin: 0.1,
alphaMax: 0.7,
sizeChangeSpeed: 0.02,
};
constructor(app: PIXI.Application) {
this.app = app;
this.container = new PIXI.Container();
for (let i = 0; i < this.starSettings.numParticles; ++i) {
this.newStar();
}
this.app.stage.addChild(this.container);
}
tick(delta: number, camera: Camera) {
if (this.lastCamera) {
//update scaling
if (camera.scale != this.lastCamera.scale) {
let ratio = camera.scale / this.lastCamera.scale;
for (let star of this.stars) {
star.position.x = ratio * (star.position.x - this.app.renderer.width / 2) + this.app.renderer.width / 2;
star.position.y = ratio * (star.position.y - this.app.renderer.height / 2) + this.app.renderer.height / 2;
}
//correct for zooming in
if (camera.scale > this.lastCamera.scale) {
for (let star of this.stars) {
if (star.position.x < 0 || star.position.x >= this.app.renderer.width || star.position.y < 0 || star.position.y >= this.app.renderer.height) {
star.pX = Math.random();
star.pY = Math.random();
star.position.x = this.app.renderer.width * star.pX;
star.position.y = this.app.renderer.height * star.pY;
star.isSpawning = true;
star.isDespawning = false;
star.scale.x = 0;
star.scale.y = 0;
}
//update spawning
if (star.isSpawning) {
star.scale.x += this.starSettings.sizeChangeSpeed;
star.scale.y += this.starSettings.sizeChangeSpeed;
if (star.scale.x >= star.ogScale || star.scale.y >= star.ogScale) {
star.scale.x = star.ogScale;
star.scale.y = star.ogScale;
star.isSpawning = false;
}
}
}
} else {
let p = 1 - ratio*ratio;
let n = this.starSettings.numParticles;
let numToRespawn = 1.4*Math.min(Math.max(Math.round(randomGauss() * Math.sqrt(n * p * (1 - p)) + p*n), 0), n);
let fun = makeRandomRange(this.stars.length);
let misses = 0;
for (let i = 0; i < numToRespawn; i++) {
//mark a random star to despawn to balance it out
let despawnStar = this.stars[fun()];
while (despawnStar.isInBuffer || despawnStar.isDespawning) {
despawnStar = this.stars[fun()];
misses += 1;
}
despawnStar.isDespawning = true;
despawnStar.isSpawning = false;
//now get an unused star, or make one
let star: any;
if (this.bufferStars.length > 0) {
star = this.bufferStars.pop();
this.newProperties(star);
} else {
star = this.newStar();
}
let range = (1 - ratio) / 2;
let offset = ratio / 2;
let dim1 = randSign() * (range * Math.random() + offset) + 0.5;
let dim2 = Math.random();
if (Math.random() > 0.5) {
star.pX = dim1;
star.pY = dim2;
} else {
star.pX = dim2;
star.pY = dim1;
}
star.position.x = this.app.renderer.width * star.pX;
star.position.y = this.app.renderer.height * star.pY;
}
}
for (let star of this.stars) {
//update despawning
if (star.isDespawning) {
star.scale.x -= this.starSettings.sizeChangeSpeed;
star.scale.y -= this.starSettings.sizeChangeSpeed;
if (star.scale.x <= 0 || star.scale.y <= 0) {
star.scale.x = 0;
star.scale.y = 0;
star.position.x = -1;
star.position.y = -1;
star.isSpawning = false;
star.isDespawning = false;
star.isInBuffer = true;
star.visible = false;
star.alpha = 0;
this.bufferStars.push(star);
}
}
}
}
//update position
for (let star of this.stars) {
if (!star.isInBuffer) {
star.position.x += camera.scale * (this.lastCamera.x - camera.x) * this.parallaxAmount;
star.position.y += camera.scale * (this.lastCamera.y - camera.y) * this.parallaxAmount;
if (star.position.x < 0 || star.position.x >= this.app.renderer.width) {
star.position.x = wrap(star.position.x, this.app.renderer.width);
star.pY = Math.random();
star.position.y = this.app.renderer.height * star.pY;
}
if (star.position.y < 0 || star.position.y >= this.app.renderer.height) {
star.position.y = wrap(star.position.y, this.app.renderer.height);
star.pX = Math.random();
star.position.x = this.app.renderer.width * star.pX;
}
}
}
//update last camera store
camera.clone_into(this.lastCamera);
} else {
//set initial positions
for (let star of this.stars) {
star.position.x = this.app.renderer.width * star.pX;
star.position.y = this.app.renderer.height * star.pY;
}
this.lastCamera = camera.clone();
}
}
newStar() {
var texture = PIXI.Texture.fromCanvas(this.getStarGraphic());
var star: any = new PIXI.Sprite(texture);
this.newProperties(star);
this.container.addChild(star);
this.stars.push(star);
return star;
}
newProperties(star: any) {
var settings = this.starSettings;
var scale = 0.3 + Math.random() * 0.5;
star.anchor.x = 0.5;
star.anchor.y = 0.5;
star.ogScale = scale;
star.scale.x = scale;
star.scale.y = scale;
star.alpha = (settings.alphaMax - settings.alphaMin) * Math.random() + settings.alphaMin;
star.rad = 180 * Math.random();
star.pX = Math.random();
star.pY = Math.random();
star.position.x = this.app.renderer.width * star.pX;
star.position.y = this.app.renderer.height * star.pY;
star.visible = true;
star.isInBuffer = false;
star.isDespawning = false;
star.isSpawning = false;
}
getStarGraphic() {
var starCanvas;
if (!this.starGraphic) {
starCanvas = document.createElement('canvas');
starCanvas.setAttribute("width", "20");
starCanvas.setAttribute("height", "20");
let starCTX = starCanvas.getContext("2d");
starCTX.beginPath();
starCTX.arc(10, 10, 3, 0, 2 * Math.PI, true);
starCTX.fillStyle = '#FFFFFF';
starCTX.fill();
this.starGraphic = starCanvas;
} else {
starCanvas = this.starGraphic;
}
return starCanvas;
}
}
export default Stars;
|
65735323df0631b3d9ebb9132e7f76a0eb59e65c
|
TypeScript
|
loglife-dev/transporte-biologico_v3
|
/src/modules/city/useCases/create/CityUseCase.ts
| 2.5625
| 3
|
import { inject, injectable } from "tsyringe";
import { AppError } from "../../../../shared/errors/AppError";
import { ICityDTO } from "../../dtos/ICityDTO";
import { City } from "../../infra/entities/City";
import { ICityRepository } from "../../repositories/ICityRepository";
@injectable()
class CreateCityUseCase {
constructor(
@inject("CityRepository")
private readonly cityRepository: ICityRepository) { }
async execute({
name,
state,
hub_id,
schedule_deadline,
observation,
}: ICityDTO): Promise<City> {
if ( name ==="" || state ===""){
throw new AppError("fill in all fields")
}
const cityAlreadyExists = await this.cityRepository.findByName(name);
if (cityAlreadyExists) {
throw new AppError("There is already a registered user with this City!!", 400)
}
const city = new City();
Object.assign(city, {
name,
state,
hub_id,
schedule_deadline,
observation,
});
const createCity = await this.cityRepository.Create(city)
return createCity;
}
}
export { CreateCityUseCase };
|
0e8f4a36deb1c89e04fca167e30678a077153ce7
|
TypeScript
|
mothepro/signaling-lobby
|
/util/stringSantizer.ts
| 2.9375
| 3
|
const zeroWidthCharCodes = new Set<number>()
.add(0x200B) // Zero Width Space
.add(0x200C) // Zero Width non - joiner Unicode code point
.add(0x200D) // Zero Width joiner Unicode code point
.add(0xFEFF) // Zero Width no -break space Unicode code point
.add(0) // Null
.add(7) // Bell
.add(8) // Backspace
.add(9) // Horizontal Tab
.add(10) // Line Feed
.add(11) // Vertical Tab
.add(12) // Form Feed
.add(13) // Carriage Return
.add(26) // Control Z
.add(27) // Escape
/** Removes any bad characters from a user's string. */
export default function (input: unknown, maxLen?: number): string {
if (typeof input == 'string')
return input
.replace(new RegExp(`[${String.fromCharCode(...zeroWidthCharCodes)}]`, 'g'), '')
.trim()
.substr(0, maxLen)
return ''
}
|
cf2a7e8acc79e54a10892a48bc44ae82f45aeb03
|
TypeScript
|
cordeno/cordeno
|
/src/client/constructors/RESUMED.ts
| 2.546875
| 3
|
import { Client } from "../Client.ts";
export class RESUMED {
public reconnectRequested: boolean = false;
public resumeTime: Date | null = null;
constructor(private client: Client, private payload: any) {
if (this.payload.reconnectRequested) {
this.reconnectRequested = this.payload.reconnectRequested;
} else {
this.resumeTime = new Date();
}
}
}
|
3532fd9a5eef0dac052ca4c8ac86911d513e0656
|
TypeScript
|
BryanWilhite/songhay-ng-workspace
|
/songhay/projects/songhay/core/src/lib/services/app-tabular-data.store.ts
| 2.609375
| 3
|
import { Observable, Subscription, BehaviorSubject } from 'rxjs';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpClientOptions } from '../models/http-client-options';
import { SendMethods } from '../models/send-methods.type';
import { AppDataStore } from './app-data.store';
/**
* defines a tabular data store
* for the application domain
*
* @export
*/
@Injectable()
export class AppTabularDataStore<TDomain, TError> extends AppDataStore<
TDomain,
TError
> {
/**
* gets the tabular data
* of the internal data store
*/
get rows(): Observable<TDomain[]> {
return this.tabularDomainSubject.asObservable();
}
private tabularDomainSubject: BehaviorSubject<TDomain[]>;
private dataStore: { rows: TDomain[] };
/**
*Creates an instance of AppDataStore.
*/
constructor(private tabularClient: HttpClient) {
super(tabularClient);
}
/**
* loads tabular data into the rows
* of the internal data store
*
* @tutorial https://coryrylan.com/blog/angular-observable-data-services
*/
loadRows(uri: string, options: HttpClientOptions = {}) {
const sub = this.tabularClient.get(uri, options).subscribe(data => {
this.doNextTabularDomainSubject(data, 'get');
});
this.subscriptions.push(sub);
}
/**
* gets/reloads domain datum
* with the specified strategy @param {onNext}
* for the rows of the internal data store
*/
sendToChangeRows(
method: SendMethods,
uri: string,
onNext: (data: object, rows: TDomain[]) => void,
body: {} | null = null,
options: HttpClientOptions = {}
): void {
const defaultNext = (data: object) => {
onNext(data, this.dataStore.rows);
this.doNextTabularDomainSubject(data, method);
};
const defaultError = (error: any) => this.indicateError(uri, error);
let sub: Subscription;
switch (method) {
case 'delete':
sub = this.tabularClient
.delete(uri, options)
.subscribe(defaultNext, defaultError);
break;
case 'get':
sub = this.tabularClient
.get(uri, options)
.subscribe(defaultNext, defaultError);
break;
case 'patch':
sub = this.tabularClient
.patch(uri, body, options)
.subscribe(defaultNext, defaultError);
break;
case 'post':
sub = this.tabularClient
.post(uri, body, options)
.subscribe(defaultNext, defaultError);
break;
case 'put':
sub = this.tabularClient
.put(uri, body, options)
.subscribe(defaultNext, defaultError);
break;
}
this.subscriptions.push(sub);
}
private doNextTabularDomainSubject(
data: object,
method: SendMethods
): void {
const domainData = this.getTabularDomainData(data, method);
this.dataStore.rows = domainData;
this.tabularDomainSubject.next(Object.assign({}, this.dataStore).rows);
}
private getTabularDomainData(data: object, method: SendMethods): TDomain[] {
const domainData =
this.options && this.options.domainConverter
? (this.options.domainConverter(
method,
data
) as TDomain[])
: ((data as unknown) as TDomain[]);
return domainData;
}
}
|
ff8d0a80e13722a2c494eec5f21d25a4bbc9b15f
|
TypeScript
|
russell-mason/clocks
|
/src/app/game/game.component.ts
| 2.75
| 3
|
import { Component, OnDestroy, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { GameStage } from '../shared/game/game-stage.enum';
import { GameService } from '../shared/game/game.service';
/**
* Component that coordinates what's shown to the user at any given time.
* Responds to changes in the game and selects different components.
*/
@Component({
selector: 'app-game',
templateUrl: './game.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class GameComponent implements OnInit, OnDestroy {
/**
* Creates an instance of GameComponent.
*/
constructor(private gameService: GameService) {}
/**
* Type alias for template binding.
*/
public readonly GameStage = GameStage;
/**
* Gets a stream emitting the current stage of the game.
* As the game progresses different screens are automatically displayed.
*/
public readonly currentGameStage$ = this.gameService.currentGameStage$;
/**
* Initializes the game so it always starts from a known state.
*/
public ngOnInit(): void {
this.gameService.reset();
}
/**
* Clean up reactive subscriptions.
*/
public ngOnDestroy(): void {
this.gameService.reset();
}
/**
* Indicates the user is ready to play and times should be displayed for them to memorize.
*/
public startCommitToMemoryCountdown(): void {
this.gameService.startCommitToMemoryCountdown();
}
/**
* Indicates the user has finished memorizing the times and is ready to recall them.
*/
public startRecallCountdown(): void {
this.gameService.startRecallCountdown();
}
/**
* Indicates the user has finished recalling the times and is ready for them to be scored.
*/
public score(): void {
this.gameService.score();
}
}
|
4a3817df8fb3cd7c94d83e018f6e6d1c9e76a868
|
TypeScript
|
SnowHeight/App
|
/src/services/bridge.service.ts
| 2.578125
| 3
|
import { Injectable } from '@angular/core';
import * as _ from 'lodash';
import { BluetoothSerial } from '@ionic-native/bluetooth-serial';
import { GeneralDataEntry } from './model';
import moment from 'moment';
import Chance from 'chance';
export enum Commands {
SETTINGS = 'settings',
SAVE_SETTINGS = 'savesettings',
GDATA_NEXT = 'gdata:next',
GDATA = 'gdata',
SET_DATE = 'setdate'
}
const chance = new Chance();
@Injectable()
export class BridgeService {
constructor(private bluetooth: BluetoothSerial) {}
parseConfig(s) {
let regex = /([^\[\];]+)=([^\[\];]+)/gm;
let obj = {};
let match;
while ((match = regex.exec(s))) {
obj[match[1]] = match[2];
}
return obj;
}
configObjectToString(obj) {
let data = null;
_.each(obj, (value, key) => {
if(typeof value === 'boolean') {
value = value.toString();
}
if (data === null) {
data = `${key}=${value}`;
} else {
data = `${data};${key}=${value}`;
}
});
return data;
}
textToUint8Array(text) {
let arr = new Uint8Array(text.length);
for (let i = 0; i < text.length; i++) {
arr[i] = text.charCodeAt(i);
}
return arr;
}
calculateChecksum(string) {
let sum = 0;
for (let i = 0; i < string.length; i++) {
sum += string.charCodeAt(i);
}
return sum % 100;
}
rowsValid(rows) {
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
let checksumDelimiterIndex = row.lastIndexOf('@');
if (checksumDelimiterIndex > -1) {
//split string at the last @ into string and checksum
let string = row.substring(0, checksumDelimiterIndex);
let checksum = row.substring(checksumDelimiterIndex + 1);
if (!isNaN(checksum)) {
checksum = parseInt(checksum);
let calculatedChecksum = this.calculateChecksum(string);
if (checksum !== calculatedChecksum) {
console.log(
'row not valid. checksum does not match',
`${calculatedChecksum} !== ${checksum}`
);
return false;
}
} else {
console.log('row not valid. checksum not a number');
return false;
}
} else {
console.log('row not valid. checksum separator missing');
return false;
}
}
return true;
}
executeCommand(_command: string, data?: string) {
let timeout;
return new Promise(async (resolve, reject) => {
let finished = false;
let command;
if (data) {
command = `[${_command}]${data}[/${_command}]\n`;
} else {
command = `[${_command}]\n`;
}
console.log('executing', command);
let subscriber = this.bluetooth
.subscribe(`[${_command}]`)
.subscribe(async rawData => {
clearTimeout(timeout);
finished = true;
subscriber.unsubscribe();
resolve();
});
await this.bluetooth.write(this.textToUint8Array(command));
timeout = setTimeout(() => {
if (!finished) {
console.log('timeout exceeded');
subscriber.unsubscribe();
reject(new Error('timeout exceeded'));
} else {
console.log(
'timeout finished but command also did. everything is ok'
);
}
}, 15000);
});
}
executeCommandWithReturnValue(_command: string, data?: string) {
let timeout;
return new Promise<string>(async (resolve, reject) => {
let finished = false;
let command: string;
if (data) {
command = `[${_command}]${data}[/${_command}]\n`;
} else {
command = `[${_command}]\n`;
}
console.log('executing', command);
let subscriber = this.bluetooth
.subscribe(`[/${_command}]`)
.subscribe(async rawData => {
clearTimeout(timeout);
finished = true;
rawData = rawData
.substring(rawData.lastIndexOf(`[${_command}]`))
.replace(`[${_command}]`, '')
.replace(`[/${_command}]`, '');
subscriber.unsubscribe();
resolve(rawData);
});
await this.bluetooth.write(this.textToUint8Array(command));
timeout = setTimeout(() => {
if (!finished) {
console.log('timeout exceeded');
subscriber.unsubscribe();
reject(new Error('timeout exceeded'));
} else {
console.log(
'timeout finished but command also did. everything is ok'
);
}
}, 15000);
});
}
parseGeneralDataEntry(s: string): GeneralDataEntry {
let parts = _.map(s.split(';'), s => s.trim());
let date = moment(parts[1], 'YYYYMMDDHHmm');
return {
id: parts[0],
date: date.unix() * 1000,
temperature: +parts[2],
pressure: +parts[3],
floorDistance: +parts[4],
humidity: +parts[5],
year: date.year().toString(),
month: date.format('YYYY-MM'),
day: date.format('YYYY-MM-DD')
};
}
async generateGeneralData(amount: number) {
let items = [];
let date = moment();
for (let i = 0; i < amount; i++) {
date.subtract(10, 'minutes');
let string = `${amount - i - 1};${date.format(
'YYYYMMDDHHmm'
)};${chance.integer({ max: 35, min: -20 })};${chance.integer({
min: 990,
max: 1020
})};${chance.integer({ min: 115, max: 130 })};${chance.integer({
min: 10,
max: 50
})}`;
items.push(`${string}@${this.calculateChecksum(string)}`);
}
items.reverse();
return items;
}
}
|
44ddcca2b68f8f83a5ac993237a9d5115515c090
|
TypeScript
|
DmitryDorofeev/vk-bridge
|
/src/applyMiddleware.ts
| 3.15625
| 3
|
import { VKBridge, VKBridgeSend } from './types/bridge';
import { Middleware, MiddlewareAPI } from './types/middleware';
/**
* Creates the VK Bridge enhancer that applies middleware to the `send`
* method. This is handy for a variety of task such as logging every sent
* event.
*
* @param middlewares The middleware chain to be applied.
* @returns The VK Bridge enhancer applying the middleware.
*/
export function applyMiddleware(...middlewares: Array<Middleware | undefined | null>): (bridge: VKBridge) => VKBridge {
if (middlewares.includes(undefined) || middlewares.includes(null)) {
return applyMiddleware(...middlewares.filter((item): item is Middleware => typeof item === 'function'));
}
return (bridge) => {
if (middlewares.length === 0) {
return bridge;
}
let send: VKBridgeSend = () => {
throw new Error(
'Sending events while constructing your middleware is not allowed. ' +
'Other middleware would not be applied to this send.'
);
};
const middlewareAPI: MiddlewareAPI = {
subscribe: bridge.subscribe,
send: (...args) => bridge.send(...args),
};
const chain = middlewares
.filter((item): item is Middleware => typeof item === 'function')
.map((middleware) => middleware(middlewareAPI)) //
.reduce((a, b) => (send) => a(b(send)));
send = chain(bridge.send);
return {
...bridge,
send,
};
};
}
|
cb934d9d4795b221288e36fbfc565bd9f966e5b3
|
TypeScript
|
brudil/timothy
|
/src/parser.ts
| 2.734375
| 3
|
export enum Token {
Character = 'character',
TitlePage = 'titlePage',
SceneHeading = 'sceneHeading',
SceneNumber = 'sceneNumber',
Transition = 'transition',
Dialogue = 'dialogue',
Parenthetical = 'parenthetical',
Action = 'action',
Centered = 'centered',
Section = 'section',
Synopsis = 'synopsis',
Note = 'note',
NoteInline = 'noteInline',
Boneyard = 'boneyard',
PageBreak = 'pageBreak',
LineBreak = 'lineBreak',
Emphasis = 'emphasis',
FX = 'fx',
BoldItalicUnderline = 'boldItalicUnderline',
BoldUnderline = 'boldUnderline',
ItalicUnderline = 'italicUnderline',
BoldItalic = 'boldItalic',
Bold = 'bold',
Italic = 'italic',
Underline = 'underline',
Splitter = 'splitter',
Cleaner = 'cleaner',
Standardizer = 'standardizer',
Whitespacer = 'whitespacer',
}
export interface TokenData {
type: Token | string;
text: string;
}
const regexMap: { [token: string]: RegExp } = {
[Token.TitlePage]: /^((?:title|credit|author[s]?|format|source|notes|draft|draft date|date|contact|series|copyright)\:)/gim,
[Token.SceneHeading]: /^((?:\*{0,3}_?)?(?:(?:int|ext|est|i\/e)[. ]).+)|^(?:\.(?!\.+))(.+)/i,
[Token.SceneHeading]: /( *#(.+)# *)/,
[Token.Transition]: /^((?:FADE (?:TO BLACK|OUT)|CUT TO BLACK)\.|.+ TO\:)|^(?:> *)(.+)/,
[Token.FX]: /^((F\/X|ATMOS|GRAMS). (.+))/,
[Token.Dialogue]: /^([A-Z*_]+[0-9A-Z (._\-')]*)(\^?)?(?:\n(?!\n+))([\s\S]+)/,
[Token.Parenthetical]: /^(\(.+\))$/,
[Token.Action]: /^(.+)/g,
[Token.Centered]: /^(?:> *)(.+)(?: *<)(\n.+)*/g,
[Token.Section]: /^(#+)(?: *)(.*)/,
[Token.Synopsis]: /^(?:\=(?!\=+) *)(.*)/,
[Token.Note]: /^(?:\[{2}(?!\[+))(.+)(?:\]{2}(?!\[+))$/,
[Token.NoteInline]: /(?:\[{2}(?!\[+))([\s\S]+?)(?:\]{2}(?!\[+))/g,
[Token.Boneyard]: /(^\/\*|^\*\/)$/g,
[Token.PageBreak]: /^\={3,}$/,
[Token.LineBreak]: /^ {2}$/,
[Token.Emphasis]: /(_|\*{1,3}|_\*{1,3}|\*{1,3}_)(.+)(_|\*{1,3}|_\*{1,3}|\*{1,3}_)/g,
[Token.BoldItalicUnderline]: /(_{1}\*{3}(?=.+\*{3}_{1})|\*{3}_{1}(?=.+_{1}\*{3}))(.+?)(\*{3}_{1}|_{1}\*{3})/g,
[Token.BoldUnderline]: /(_{1}\*{2}(?=.+\*{2}_{1})|\*{2}_{1}(?=.+_{1}\*{2}))(.+?)(\*{2}_{1}|_{1}\*{2})/g,
[Token.ItalicUnderline]: /(?:_{1}\*{1}(?=.+\*{1}_{1})|\*{1}_{1}(?=.+_{1}\*{1}))(.+?)(\*{1}_{1}|_{1}\*{1})/g,
[Token.BoldItalic]: /(\*{3}(?=.+\*{3}))(.+?)(\*{3})/g,
[Token.Bold]: /(\*{2}(?=.+\*{2}))(.+?)(\*{2})/g,
[Token.Italic]: /(\*{1}(?=.+\*{1}))(.+?)(\*{1})/g,
[Token.Underline]: /(_{1}(?=.+_{1}))(.+?)(_{1})/g,
[Token.Splitter]: /\n{2,}/g,
[Token.Cleaner]: /^\n+|\n+$/,
[Token.Standardizer]: /\r\n|\r/g,
[Token.Whitespacer]: /^\t+|^ {3,}/gm,
};
function lexer(script: string) {
return script
.replace(regexMap.boneyard, '\n$1\n')
.replace(regexMap.standardizer, '\n')
.replace(regexMap[Token.Cleaner], '')
.replace(regexMap.whitespacer, '');
}
function tokenize(script: string): { tokens: any; metadata: any } {
var src = lexer(script).split(regexMap.splitter),
i = src.length,
line,
match,
parts,
text,
meta,
x,
xlen,
dual,
tokens = [];
const metadata: {
[key: string]: string;
} = {};
while (i--) {
line = src[i];
// title page
if (regexMap[Token.TitlePage].test(line)) {
match = line
.replace(regexMap[Token.TitlePage], '\n$1')
.split(regexMap.splitter)
.reverse();
for (x = 0, xlen = match.length; x < xlen; x++) {
parts = match[x].replace(regexMap.cleaner, '').split(/\:\n*/);
const key = parts[0]
.trim()
.toLowerCase()
.replace(' ', '_');
if (key) {
metadata[key] = parts[1].trim();
}
}
continue;
}
// scene headings
if ((match = line.match(regexMap[Token.SceneHeading]))) {
text = match[1] || match[2];
if (text.indexOf(' ') !== text.length - 2) {
if ((meta = text.match(regexMap.scene_number))) {
meta = meta[2];
text = text.replace(regexMap.scene_number, '');
}
tokens.push({
type: 'scene_heading',
text: text,
scene_number: meta || undefined,
});
}
continue;
}
// centered
if ((match = line.match(regexMap.centered))) {
tokens.push({ type: 'centered', text: match[0].replace(/>|</g, '') });
continue;
}
// transitions
if ((match = line.match(regexMap.transition))) {
tokens.push({ type: 'transition', text: match[1] || match[2] });
continue;
}
// dialogue blocks - characters, parentheticals and dialogue
if ((match = line.match(regexMap.dialogue))) {
if (match[1].indexOf(' ') !== match[1].length - 2) {
// we're iterating from the bottom up, so we need to push these backwards
if (match[2]) {
tokens.push({ type: 'dual_dialogue_end' });
}
tokens.push({ type: 'dialogue_end' });
parts = match[3].split(/(\(.+\))(?:\n+)/).reverse();
for (x = 0, xlen = parts.length; x < xlen; x++) {
text = parts[x];
if (text.length > 0) {
tokens.push({
type: regexMap.parenthetical.test(text)
? 'parenthetical'
: 'dialogue',
text: text,
});
}
}
tokens.push({ type: 'character', text: match[1].trim() });
tokens.push({
type: 'dialogue_begin',
dual: match[2] ? 'right' : dual ? 'left' : undefined,
});
if (dual) {
tokens.push({ type: 'dual_dialogue_begin' });
}
dual = match[2] ? true : false;
continue;
}
}
// section
if ((match = line.match(regexMap.section))) {
tokens.push({
type: Token.Section,
text: match[2],
depth: match[1].length,
});
continue;
}
// fx
if ((match = line.match(regexMap[Token.FX]))) {
tokens.push({ type: Token.FX, style: match[2], text: match[3] });
continue;
}
// synopsis
if ((match = line.match(regexMap.synopsis))) {
tokens.push({ type: Token.Synopsis, text: match[1] });
continue;
}
// notes
if ((match = line.match(regexMap.note))) {
tokens.push({ type: Token.Note, text: match[1] });
continue;
}
// boneyard
if ((match = line.match(regexMap.boneyard))) {
tokens.push({
type: match[0][0] === '/' ? 'boneyard_begin' : 'boneyard_end',
});
continue;
}
// page breaks
if (regexMap[Token.PageBreak].test(line)) {
tokens.push({ type: Token.PageBreak });
continue;
}
// line breaks
if (regexMap[Token.LineBreak].test(line)) {
tokens.push({ type: Token.LineBreak });
continue;
}
tokens.push({ type: Token.Action, text: line });
}
return { tokens: tokens.reverse(), metadata };
}
function parse(
script: string,
): {
tokens: TokenData[];
metadata: { title: string; credit: string; authors: string };
} {
return tokenize(script);
}
export { parse };
|
29e44a7d67d9dcff20736538ca2b14d169060065
|
TypeScript
|
grimace/ngx-form-builder
|
/src/app/utils/formatTime.ts
| 3.203125
| 3
|
/**
* format time to string
* @param time
*/
export function formatTime(time) {
var digits = [time.getHours(), time.getMinutes(), time.getSeconds()];
var timeStr = '';
for (var i = 0, len = digits.length; i < len; ++i) {
timeStr += (digits[i] < 10 ? '0' : '') + digits[i];
if (i < len - 1) {
timeStr += ':';
}
}
return time.getFullYear() + '/' + (time.getMonth() + 1) + '/' + time.getDate() + ' ' + timeStr;
}
|
f6100b61658d162e1c8b94a98d0d9f44fc6bc0c7
|
TypeScript
|
future4code/Yan-Sabino
|
/semana19/backend-template-ts/src/business/entities/post.ts
| 3.34375
| 3
|
export class Post {
constructor(
private postId: string,
private picture: string,
private description: string,
private creationDate: Date,
private postType: PostType,
private userId: string
) {}
public getPostId(): string {
return this.postId;
}
public getPicture(): string {
return this.picture;
}
public getDescription(): string {
return this.description;
}
public getCreationDate(): Date {
return this.creationDate;
}
public getUserId(): string {
return this.userId;
}
public getPostType(): PostType {
return this.postType;
}
public static mapStringsToPostType(postType: string): PostType {
switch (postType) {
case "NORMAL":
return PostType.NORMAL;
case "EVENT":
return PostType.EVENT;
default:
throw new Error("Invalid Post Type");
}
}
}
export enum PostType {
NORMAL = "NORMAL",
EVENT = "EVENT"
}
|
6f97d18ba6b38a36a5b4994a5a6167c763fe4306
|
TypeScript
|
ruslanguns/rusgunx-blog
|
/src/shared/dto/response-error.dto.ts
| 2.8125
| 3
|
// success: false => errorMessage, error
import { IResponse } from '../interfaces/response.interface';
export class ResponseError implements IResponse {
constructor(infoMessage: string, data?: any) {
this.success = false;
this.message = infoMessage;
this.data = data;
console.warn(new Date().toString() + ' - [Response]: ' + infoMessage + (data ? ' - ' + JSON.stringify(data) : ''));
}
message: string;
data: any[];
errorMessage: any;
error: any;
success: boolean;
}
|
f27b9a589356554ffbbda65cc08801001d608cc0
|
TypeScript
|
abdulmoiz2245/angular_laravel
|
/common/shared/charts/chartist/chartist-line.ts
| 2.546875
| 3
|
import * as Chartist from 'chartist';
import {IChartistLineChart, ILineChartOptions} from 'chartist';
import {BaseChart} from '@common/shared/charts/base-chart';
export class ChartistLine extends BaseChart {
protected lineConfig: ILineChartOptions = {
showArea: true,
lineSmooth: true,
low: 0,
fullWidth: true,
chartPadding: {
left: 15,
right: 30,
},
axisY: {
// 0,454 => 0,4 when displaying chart with no data
labelInterpolationFnc: (val) => Math.floor(val)
}
};
protected chart: IChartistLineChart;
protected generate() {
const lineConfig = {
...this.lineConfig,
high: this.getHigh(),
};
this.chart = new Chartist.Line(
this.config.selector,
this.transformChartData(),
lineConfig,
);
}
protected transformChartData() {
return {
labels: this.config.labels,
series: this.config.data,
};
}
protected getHigh() {
// if chart data is empty, show 0-100 in Y axis
return this.getMaxValue() ? null : 100;
}
public destroy() {
if (this.chart) {
this.chart.detach();
}
}
}
|
ca8fe3a8706285f9ff222482ee375444583ce877
|
TypeScript
|
FynnGrandke/interview-preparation
|
/src/index.ts
| 2.8125
| 3
|
// You can write your code here.
// Add console.log(`${myVariable}`) to see your output.
// Don't forget to run 'npm start' in the console!
const myVariable = 'World'
console.log(`Hello ${myVariable}`)
|
511ae6ce77466793261a8de4b52098fef2a187db
|
TypeScript
|
peterhchen/800_Angular
|
/21_22/ch21-http-fetch-data-src/src/app/employee.service.ts
| 2.578125
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IEmployee } from './employee';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class EmployeeService {
//private _url: string ="src/assets/data/employees.json"
private _url: string ="/assets/data/employees.json";
//private _url: string= "https://jsonplaceholder.typicode.com/todos";
currentURL = '';
constructor(private http: HttpClient) {
this.currentURL = window.location.href;
}
getEmployee (): Observable<IEmployee[]> {
console.log ('this.currentURL: ', this.currentURL);
console.log ('this.http.get(this._url): ', this.http.get(this._url));
return this.http.get<IEmployee[]>(this._url);
// getEmployee ():
// return [
// {"id": 1, "name": "Andrew", "age": 30},
// {"id": 2, "name": "Brandon", "age": 25},
// {"id": 3, "name": "Christina", "age": 26},
// {"id": 4, "name": "Elena", "age": 28}
// ];
}
}
|
07f8c385f39034da7f383628e401aa0c1ceac0f9
|
TypeScript
|
TeamBerry/cranberry
|
/src/redux/reducers/user.reducer.ts
| 2.625
| 3
|
/* eslint-disable import/prefer-default-export */
import AsyncStorage from '@react-native-community/async-storage';
import axios from 'axios';
import { AuthSubject } from '../../models/session.model';
import {
RESTORE_TOKEN, SIGN_IN, SIGN_OUT, UPDATE_USER,
} from '../actionTypes';
export type StoreType = {
userToken: string,
user: AuthSubject
}
const initialState: StoreType = {
userToken: null,
user: null,
};
export const createAnonymousSession = (): AuthSubject => {
const values = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let anonymousToken = '';
// eslint-disable-next-line no-plusplus
for (let i = 20; i > 0; --i) {
anonymousToken += values[Math.round(Math.random() * (values.length - 1))];
}
const session: AuthSubject = {
_id: `user-${anonymousToken}`,
name: null,
mail: null,
settings: {
theme: 'dark',
picture: null,
color: '#DF62A9',
isColorblind: false,
},
};
AsyncStorage.setItem('BBOX-user', JSON.stringify(session));
return session;
};
export const userReducer = (state = initialState, action): StoreType => {
switch (action.type) {
case UPDATE_USER:
return {
...state,
user: action.payload.user,
};
case RESTORE_TOKEN:
return {
...state,
userToken: action.payload.userToken ?? null,
user: action.payload.user ?? createAnonymousSession(),
};
case SIGN_IN:
return {
...state,
userToken: action.payload.userToken,
user: action.payload.user,
};
case SIGN_OUT:
return {
...state,
user: createAnonymousSession(),
userToken: null,
};
default:
return state;
}
};
|
3fb5ed53d2bf68b5fd82e6ac43196e94c447f933
|
TypeScript
|
armmroorm/vending-machine-backednd
|
/src/machine/dto/create-machine.dto.ts
| 2.515625
| 3
|
import { IsNotEmpty, Length } from 'class-validator';
export class CreateMachineDto {
@IsNotEmpty()
@Length(0)
machineName: string;
@IsNotEmpty()
@Length(0)
location: string;
@IsNotEmpty()
@Length(0)
address: string;
}
|
ecfdb10ccb8a446b2ee73725fe5258e0b21465f9
|
TypeScript
|
GennadySX/race-scheduler-app
|
/src/store/reducers/Race.ts
| 2.734375
| 3
|
import {
RACE_GET_START,
RACE_SET,
RACE_GET_END,
RACE_GET_ERR,
} from '../actions/Races';
const initialState = {
races: [],
max: 0,
current: 1,
loading: false,
err: false,
};
const reducer = (state: any = initialState, action: any) => {
switch (action.type) {
case RACE_SET:
//console.log('race set reducer ', action)
const {offset, RaceTable, total} = action.data;
return {
...state,
races: RaceTable.Races,
max: total / 10,
current: offset && offset > 10 ? offset / 10 : 1,
loading: false,
err: false,
};
case RACE_GET_START:
return {
...state,
loading: true,
err: false,
};
case RACE_GET_END:
return {
...state,
loading: false,
err: false,
};
case RACE_GET_ERR:
return {
...state,
loading: false,
err: true,
};
default:
return state;
}
};
export default reducer;
|
772fed559fbd5b42597bb2e1385f1a6e60d0aef4
|
TypeScript
|
duki994/nrwl-nx-workshop
|
/tools/generators/util-lib/index.ts
| 2.53125
| 3
|
import { Tree, formatFiles, installPackagesTask } from '@nrwl/devkit';
import { libraryGenerator } from '@nrwl/workspace/generators';
interface Schema {
name: string;
tags?: string;
directory: 'api' | 'store' | 'shared';
}
const checkNameHasUtil = (name: string) => name?.includes('util') ?? false;
const mergeTags = (
existingTags?: string,
newTags?: string
): string | undefined => {
const trimmed = existingTags?.trim();
if (trimmed && newTags) {
return `${trimmed},${newTags}`.trim();
}
return newTags;
};
const sanitizeName = (name?: string): string | undefined | null =>
name?.charAt(0) === '-' ? name.substr(1) : name;
export default async function (host: Tree, schema: Schema) {
const name = checkNameHasUtil(schema.name)
? schema.name
: `util-${sanitizeName(schema.name)}`;
const libScheme: Schema = {
...schema,
name,
tags: mergeTags(schema.tags, `scope:${schema.directory},type:util`),
};
await libraryGenerator(host, libScheme);
await formatFiles(host);
return () => {
installPackagesTask(host);
};
}
|
069b2a421dd1fc6bd48bf0251c40fa8e569ba739
|
TypeScript
|
cnbrkkaya/typescript-basics
|
/src/index.ts
| 4.25
| 4
|
//Basic Types
let id: number = 5
let company: string = "CK"
let isValid: boolean = true
let x: any = "Hello"
let ids: number[] = [1, 2, 3, 4, 5]
let arr: any[] = [1, 2, "ck", false]
//Tuple
let person: [number, string, boolean] = [1, "ck", true]
//Tuple Array
let employee: [number, string][]
employee = [
[1, "CK"],
[2, "AA"],
]
//Union
let pid: string | number
pid = "5"
//Enum
enum Direction1 {
Up,
Down,
Left,
Right,
}
enum Direction2 {
Up = "Up",
Down = "Down",
Left = "Left",
Right = "Right",
}
//Objects
type User = {
id: number
name: string
}
const user: User = {
id: 1,
name: "CK",
}
//Type Assertion
let cid: any = 1
//1
let customerId = <number>cid
//2
let customerID = cid as number
//Functions
function addNum(x: number, y: number): number {
return x + y
}
//Void
function log(message: string | number): void {
console.log(message)
}
//Interfaces
interface UserInterface {
readonly id: number
name: string
age?: number
}
const newUser: UserInterface = {
id: 1,
name: "CK",
}
//Optional = ? && readonly
//Interface with function
interface MathFunc {
(x: number, y: number): number
}
const add: MathFunc = (x: number, y: number): number => x + y
const sub: MathFunc = (x: number, y: number): number => x - y
//Classes
// public private protected
//Classes with interface
interface PersonInterface {
id: number
name: string
register(): string
}
class Person implements PersonInterface {
id: number
name: string
constructor(id: number, name: string) {
this.id = id
this.name = name
}
register(): string {
return `${this.name} is registered`
}
}
const ck = new Person(11, "CK")
console.log(ck.register())
//Subclass
class Employee extends Person {
position: string
constructor(id: number, name: string, position: string) {
super(id, name)
this.position = position
}
}
const newEmp = new Employee(111, "CKE", "Dev")
console.log(newEmp.register())
//Generics
function getArray<T>(items: T[]): T[] {
return new Array().concat(items)
}
let numArray = getArray<number>([1, 2, 3, 4, 5])
let strArray = getArray<string>(["sdfsdf", "sdfsdf", "sdfsdf"])
strArray.push("dfgdf")
const a: number = 4
|
2346cc358ab7a1819df537ecd3b48661626ac09b
|
TypeScript
|
johancc/Apollo
|
/packages/server/src/models/Numbers.ts
| 2.84375
| 3
|
import {
getModelForClass,
post,
pre,
prop,
ReturnModelType,
} from "@typegoose/typegoose";
export interface INum {
value: number;
}
@pre<Num>("save", function () {
console.log(`Saving ${this.value}`);
})
@post<Num>("save", function (num) {
console.log(`Created Document ${num.id}`);
})
export class Num implements INum {
@prop({ required: true })
public value: number;
public static async getLargestNumber(this: ReturnModelType<typeof Num>) {
return this.find({}).sort("-value").exec();
}
}
const NumberModel = getModelForClass(Num);
export default NumberModel;
|
0ea27d773f65b6a107b56b43d974c0f8f0eab683
|
TypeScript
|
glimmerjs/glimmer-vm
|
/packages/@glimmer/reference/test/utils/platform.ts
| 2.859375
| 3
|
export default function objectValues(obj: any) {
if (typeof Object.values === 'function') {
return Object.values(obj);
} else {
return Object.keys(obj).map((k) => obj[k]);
}
}
|
206e88f3d647b43590bb391b438187a4f7107943
|
TypeScript
|
jthogsett/fam-element
|
/test/observe-property.test.ts
| 3.015625
| 3
|
import { observeProperty } from '../src/observe-property'
describe('observeProperty', () => {
it('calls the callback when the observed property is updated', () => {
const callback = jest.fn()
class Foo {
@observeProperty(callback)
bar?: string
}
const instance = new Foo()
instance.bar = 'value'
expect(callback).toBeCalledWith(instance, undefined, 'value')
callback.mockClear()
instance.bar = 'value2'
expect(callback).toBeCalledWith(instance, 'value', 'value2')
})
it('inherits existings property descriptors', () => {
const callback = jest.fn()
class Foo {
internalBar?: string
@observeProperty(callback)
get bar() {
return this.internalBar
}
set bar(value) {
this.internalBar = value
}
}
const instance = new Foo()
instance.bar = 'value'
expect(callback).toBeCalled()
expect(instance.bar).toEqual(instance.internalBar)
})
})
|
83b030f3cfb2f1c61b5587e5518287d8a2207c3d
|
TypeScript
|
Pfoerd/advent_of_code_2018
|
/src/day_12/day_12_1.ts
| 3.109375
| 3
|
import * as os from 'os';
export function day12_part1(rawFileData: string) {
const inputData: string[] = rawFileData.split(os.EOL);
let pots: string = inputData.splice(0, 2)[0].substr(15);
// we only need to know one side of the rules
const spreadRules = inputData.filter(v => v.indexOf('=> #') !== -1).map(v => v.substr(0, 5));
// calculates the sum of indices needed for the result
const currentSum: () => number = () => {
return [...pots].reduce((a, v, i) => a + (v === '#' ? i - zeroPotPosition : 0), 0);
};
let zeroPotPosition = 0;
for (let generation = 1; generation <= 20; generation++) {
// insert missing pots. We always want to start with a min of 5 empty
// pots at the beginning and at the end to always cover the '.....' rule
const missingPotsCountBeginning = Math.max(0, 5 - pots.indexOf('#'));
const missingPotsCountEnd = Math.max(0, 5 - (pots.length - 1 - pots.lastIndexOf('#')));
zeroPotPosition += missingPotsCountBeginning;
pots = Array.from(Array(missingPotsCountBeginning), () => '.').reduce((a, v) => a + v, '')
+ pots
+ Array.from(Array(missingPotsCountEnd), () => '.').reduce((a, v) => a + v, '');
let newGeneration = '';
for (let pot = 2; pot < pots.length - 2; pot++) {
const nearbyPots = pots.slice(pot - 2, pot + 3);
const newPotValue = spreadRules.indexOf(nearbyPots) !== -1 ? '#' : '.';
newGeneration += newPotValue;
}
zeroPotPosition -= 2;
pots = newGeneration;
}
return currentSum();
}
|
7b0f39139e7795fce926cb9f334bda771b6330cf
|
TypeScript
|
DevSeto/awesome-typescript-loader
|
/issues/product-designer/src/stores/UIStore-spec.ts
| 2.515625
| 3
|
import { iocContainer } from '../utils/ioc/index';
import { UIStore } from './UIStore';
const wnd = window as any;
describe('UI Store', function () {
let store: UIStore;
beforeEach(() => store = iocContainer.get(UIStore));
afterEach(() => {
wnd.innerWidth = 1024;
wnd.innerHeight = 768;
});
it('should have window dimensions', function () {
expect(store.windowDimensions.width).to.eq(1024);
expect(store.windowDimensions.height).to.eq(768);
});
it('should update window dimensions on resize', function () {
wnd.innerWidth = 1920;
wnd.innerHeight = 1080;
$(window).trigger('resize');
expect(store.windowDimensions.width).to.eq(1920);
expect(store.windowDimensions.height).to.eq(1080);
});
describe('Pane resizing', function () {
it('should fallback to min value if below bounds', function () {
store.paneResizing.setSplit(0);
expect(store.paneResizing.split).to.equal(store.paneResizing.MIN_PANE_SPLIT);
});
it('should fallback to min value if NaN', function () {
store.paneResizing.setSplit(NaN);
expect(store.paneResizing.split).to.equal(store.paneResizing.MIN_PANE_SPLIT);
});
it('should fallback to max value if over bounds', function () {
store.paneResizing.setSplit(999);
expect(store.paneResizing.split).to.equal(store.paneResizing.MAX_PANE_SPLIT);
});
});
});
|
ed622d4261ad035e07c87481c74b34bbb0b1b471
|
TypeScript
|
Esri/hub.js
|
/packages/search/test/ago/helpers/aggs/collection.test.ts
| 2.546875
| 3
|
import { collectionAgg } from "../../../../src/ago/helpers/aggs/collection";
describe("collection aggs test", () => {
it("calculates collection raw aggs correctly", () => {
const agoAggs = {
counts: [
{
fieldName: "type",
fieldValues: [
{
value: "Feature Layer",
count: 12
},
{
value: "PDF",
count: 10
},
{
value: "unknown type",
count: 10
}
]
}
]
};
const actual = collectionAgg(agoAggs);
const expected = { collection: { Dataset: 12, Document: 10, Other: 10 } };
expect(actual).toEqual(expected);
});
it("should handle undefined agoAggregations", () => {
const actual = collectionAgg();
const expected = { collection: {} };
expect(actual).toEqual(expected);
});
it("should handle blank agoAggregations", () => {
const actual = collectionAgg({});
const expected = { collection: {} };
expect(actual).toEqual(expected);
});
});
|
97a568854bb4549f69b098e3ead2f0a9da1d7625
|
TypeScript
|
Egg4/crop-app
|
/src/app/lib/array.prototype.ts
| 3.375
| 3
|
import './object.prototype';
interface Array<T> {
deepEqual(array1: T[], array2: T[]): boolean;
}
Array.deepEqual = function (array1: [], array2: []): boolean {
if (!array1 || !array2) return false;
if (array1.length !== array2.length) return false;
for (var i = 0, l=this.length; i < l; i++) {
const val1 = array1[i];
const val2 = array2[i];
const areArrays = Array.isArray(val1) && Array.isArray(val2);
if (areArrays && !Array.deepEqual(val1, val2)) return false;
const areObjects = Object.isObject(val1) && Object.isObject(val2);
if (areObjects && !Object.deepEqual(val1, val2)) return false;
if (!areArrays && !areObjects && val1 !== val2) return false;
}
return true;
}
|
c5af1f851cfd31bb2350489416112c037ae4d4b5
|
TypeScript
|
qcjxberin/backgroundSystem
|
/src/filters/index.ts
| 2.78125
| 3
|
import Vue from 'vue'
function sex ( str: string ) {
if (str === 'MALE') {
return '男'
} else if (str === 'FEMALE') {
return '女'
} else if (str === 'UNKNOW') {
return '未知'
}
}
Vue.filter('sex', sex)
|
4870e072b8ade314ad8a9e5c2ff47328bdddbe8f
|
TypeScript
|
MonchiLin/modern-magic
|
/projects/Data-Structure-and-Algorithms/DataStructure/Queue/__tests__/回文检查.spec.ts
| 3.78125
| 4
|
/**
*
回文是正反都能读通的单词、词组、数或一系列字符的序列,例如 madam或 racecar。
*
*/
import {DQueue} from "../Queue";
/**
* 计算过程 "madam"
* 1. m
* 2. ma
* 3. mad
* 4. mada
* 5. madam
*
*
* @param word
*/
function palindromeChecker(word: string): boolean {
const queue = new DQueue();
word.split("")
.forEach(w => {
queue.addBack(w)
});
let newStr = "";
while (queue.size() !== 0) {
newStr += queue.removeBack()
}
return newStr === word
}
describe('回文检查', function () {
it('should ', function () {
expect.assertions(2);
expect(palindromeChecker("madam")).toBe(true);
expect(palindromeChecker("test")).toBe(false)
});
});
|
e781cf735e1af4151434c88dedb8ad0c7f61184b
|
TypeScript
|
cynt4k/prepaid-list
|
/backend/src/core/express/response.ts
| 2.609375
| 3
|
import { HttpCodes } from './codes';
import { IResponse } from '../../types/express';
import { Response, NextFunction } from 'express';
export let response = (res: Response, code: HttpCodes, msg?: string, data?: any) => {
let responseMessage: IResponse<any> = <IResponse<any>>{};
if (code >= 400) {
responseMessage.status = 'error';
responseMessage.code = code;
} else {
responseMessage.status = 'success';
responseMessage.code = code;
}
(data === undefined) ? responseMessage.data = '' : responseMessage.data = data;
(msg === undefined) ? responseMessage.message = '' : responseMessage.message = msg;
res.setHeader('Content-Type', 'application/json');
res.status(code).send(JSON.stringify(responseMessage));
};
export default response;
|
00799fde8995a60b3ab8b897f6109626378d47d9
|
TypeScript
|
ytechie/SimpleTrackingV3
|
/src/providers/fedex/FedexTracker.ts
| 2.59375
| 3
|
import * as fs from 'fs';
import * as path from 'path';
import * as request from 'request-promise';
import * as xml2js from 'xml2js-es6-promise';
import { TrackingData } from '../TrackingData';
import { ITracker } from '../ITracker';
import { ActivityData } from '../ActivityData';
export class FedexTracker implements ITracker {
FEDEX_API_URL = "https://wsbeta.fedex.com:443/web-services/track";
trackRequestTemplate:string = '';
key:string;
password:string;
accountNumber:string;
meterNumber:string;
constructor(key:string, password:string, accountNumber:string, meterNumber:string) {
this.key = key;
this.password = password;
this.accountNumber = accountNumber;
this.meterNumber = meterNumber;
}
private buildRequest(trackingNumber:string) {
if(this.trackRequestTemplate.length === 0) {
let templatePath = path.join(__dirname, 'RequestTemplate.xml');
this.trackRequestTemplate = fs.readFileSync(templatePath).toString();
}
return this.trackRequestTemplate
.replace('{key}', this.key)
.replace('{password}', this.password)
.replace('{accountNumber}', this.accountNumber)
.replace('{meterNumber}', this.meterNumber)
.replace('{trackingNumber}', trackingNumber);
}
async Track(trackingNumber:string) {
if(!FedexTracker.IsValidTrackingNumber(trackingNumber)) {
console.log('Not a FedEx Tracking Number');
return null;
}
let req = this.buildRequest(trackingNumber);
let options = {
body:req,
headers:
{
//'Host': 'wsbeta.fedex.com:443',
}
};
let body = await request.post(this.FEDEX_API_URL, options);
let json = await xml2js(body, {explicitArray: false});
//Unwrap the SOAP envelope
json = json['SOAP-ENV:Envelope']['SOAP-ENV:Body'];
let td = FedexTracker.ConvertJsonToStandardFormat(json);
td.lastHardFetch = new Date();
return td;
}
public static IsValidTrackingNumber(trackingNumber:string) {
return trackingNumber.length === 12
|| trackingNumber.length === 15
|| trackingNumber.length === 22;
}
public static ConvertJsonToStandardFormat(results:any):TrackingData {
if(results["v3:TrackReply"] && results["v3:TrackReply"]["v3:HighestSeverity"] === "ERROR") {
console.error('Got a non-expected error from fedex');
return null;
}
//Check for invalid tracking number code
if(results.TrackReply.CompletedTrackDetails.TrackDetails.Notification.Code === "9040") {
console.log('Fedex says they have no data for the package');
return null;
}
let td = new TrackingData();
td.trackerName = "FedEx";
td.activity = new Array<ActivityData>();
let a = results.TrackReply.CompletedTrackDetails.TrackDetails;
let trackDetail = results.TrackReply.CompletedTrackDetails.TrackDetails;
td.trackingNumber = trackDetail.TrackingNumber;
if(trackDetail.PackageWeight) {
td.weight = trackDetail.PackageWeight.Value + trackDetail.PackageWeight.Units;
}
if(trackDetail.ActualDeliveryTimestamp) {
td.estimatedDelivery = new Date(Date.parse(trackDetail.ActualDeliveryTimestamp));
}
if(trackDetail.Events instanceof Array) {
trackDetail.Events.forEach((event) => {
var ad = new ActivityData();
ad.timestamp = new Date(Date.parse(event.Timestamp));
ad.location.city = event.Address.City;
ad.location.state = event.Address.StateOrProvinceCode;
ad.location.zip = event.Address.PostalCode;
ad.location.countryCode = event.Address.CountryCode;
ad.shortDescription = event.EventDescription;
td.activity.push(ad);
});
} else {
var ad = new ActivityData();
ad.timestamp = new Date(Date.parse(trackDetail.Events.Timestamp));
ad.location.city = trackDetail.Events.Address.City;
ad.location.state = trackDetail.Events.Address.StateOrProvinceCode;
ad.location.zip = trackDetail.Events.Address.PostalCode;
ad.location.countryCode = trackDetail.Events.Address.CountryCode;
td.activity.push(ad);
}
td.usageRequirements = "NOTICE: FedEx authorizes you to use FedEx tracking"
+ " systems solely to track shipments tendered by"
+ " or for you to FedEx for delivery and for no other"
+ " purpose. Any other use of FedEx tracking systems and"
+ " information is strictly prohibited.";
return td;
}
}
|
8b0f6dc99ca737f8460ab7f69f375dd09b7fdda1
|
TypeScript
|
yubowenok/coda
|
/server/src/util/integrity.ts
| 2.515625
| 3
|
import * as paths from '../constants/path';
import {
JudgeMode,
ProblemsetConfig
} from '../constants';
const checkProblemsetIntegrity = (problemset: ProblemsetConfig): void => {
if (problemset.judgeMode === JudgeMode.BLIND && problemset.freebies) {
console.error(`problemset ${problemset.id} has blind judge but non-zero freebies`);
}
};
/**
* Checks the integrity of all problemsets.
*/
export const checkProblemsetsIntegrity = (): void => {
console.log('TODO: checkProblemsetsIntegrity');
};
/**
* Checks the integrity of all problems.
*/
export const checkProblemsIntegrity = (): void => {
console.log('TODO: checkProblemsIntegrity');
};
|
171887270c2c4c8513544f67e105df3099f0e9ba
|
TypeScript
|
a1967629423/d_language
|
/executor.ts
| 2.8125
| 3
|
import type { AST } from "./d_language_lib";
import { createInterface } from "readline";
export class Context {
/** 流程控制状态,在return时此值会被设置为return值 */
exit: Value | undefined = undefined;
break: Value | undefined = undefined;
continue: Value | undefined = undefined;
get NormalExit() {
if (this.exit !== undefined) return this.exit;
if (this.break !== undefined) return this.break;
if (this.continue !== undefined) return this.continue;
return undefined;
}
constructor(
public paramMap: Map<string, Value> = new Map(),
public parent?: Context,
public children: Context[] = []
) {}
resetControlFlow() {
this.exit = undefined;
this.break = undefined;
this.continue = undefined;
}
searchInContext(name: string): [Value, Context] {
if (this.paramMap.has(name)) {
return [this.paramMap.get(name)!, this];
}
if (this.parent) {
return this.parent.searchInContext(name);
}
throw new Error(`can't find identity: ${name}`);
}
declareParam(name: string, value: Value) {
this.paramMap.set(name, value);
}
setValue(name: string, value: Value) {
this.paramMap.set(name, value);
}
makeChild() {
const newChild = new Context();
this.children.push(newChild);
newChild.parent = this;
return newChild;
}
}
class FunctionExecutor {
constructor(public ctx: Context) {}
call(params: Value[]): Value {
return null;
}
}
class DynamicFunctionExecutor extends FunctionExecutor {
constructor(
public ast: AST | null | undefined,
public argNames: string[],
public ctx: Context
) {
super(ctx);
}
call(params: Value[]): Value {
if (!this.ast) return null;
for (let i = 0; i < this.argNames.length; i++) {
if (i > params.length) {
this.ctx.declareParam(this.argNames[i], null);
} else {
this.ctx.declareParam(this.argNames[i], params[i]);
}
}
this.ctx.resetControlFlow();
return executeAST(this.ast, this.ctx);
}
}
class InternalFunctionExecutor extends FunctionExecutor {
constructor(public func: (...args: Value[]) => Value) {
super(new Context());
}
override call(params: Value[]): Value {
return this.func(...params);
}
}
function wrapperValue(v: any): Value {
if (v instanceof Function) {
new InternalWrapperFunction(v);
}
return v;
}
function unWrapperValue(v: Value) {
if (v instanceof FunctionExecutor) {
if (v instanceof InternalFunctionExecutor) {
return v.func;
}
if (v instanceof InternalWrapperFunction) {
return v.getBindFunc();
}
return null;
}
return v;
}
class InternalWrapperFunction extends FunctionExecutor {
constructor(public func: (...args: any[]) => any, public target?: any) {
super(new Context());
}
getBindFunc() {
if (this.target) {
return this.func.bind(this.target);
}
return this.func;
}
override call(params: Value[]): Value {
if (this.target) {
return wrapperValue(
this.func.apply(this.target, params.map(unWrapperValue))
);
} else {
return wrapperValue(this.func(params.map(unWrapperValue)));
}
}
}
type Value =
| number
| string
| boolean
| null
| object
| Map<string, Value>
| Value[]
| FunctionExecutor;
const InternalFunctionMap: Map<string, FunctionExecutor> = new Map([
[
"print",
new InternalFunctionExecutor((...args: Value[]) => {
console.log(...args);
return null;
}),
],
[
"time",
new InternalFunctionExecutor(() => {
return Date.now();
}),
],
[
"input",
new InternalFunctionExecutor((...args: Value[]) => {
const question = (args[0] as string) ?? "";
const callback = args[1] as FunctionExecutor;
if (!callback) {
throw new Error(`input require callback`);
}
const readlineInterface = createInterface({
input: process.stdin,
output: process.stdout,
});
readlineInterface.question(question, (answer) => {
callback.call([answer]);
readlineInterface.close();
});
return null;
}),
],
[
"rand",
new InternalFunctionExecutor(() => {
return Math.random();
}),
],
[
"setTimeout",
new InternalFunctionExecutor((...args: Value[]) => {
const time = args[0] as number;
const cb =args[1] as FunctionExecutor;
if (typeof time !== "number") throw new Error(`time must be a number`);
if(!(cb instanceof FunctionExecutor)){
throw new Error(`cb must be a function`);
}
setTimeout(()=>{
cb.call([]);
}, time)
return null;
}),
],
[
"len",
new InternalFunctionExecutor((value:Value)=>{
if(value instanceof Array) {
return value.length;
}
if(value instanceof Map) {
return value.size;
}
if(value instanceof Object) {
return Object.keys(value).length;
}
return 0;
})
],
[
"append",
new InternalFunctionExecutor((array:Value,value:Value)=>{
if(array instanceof Array) {
array.push(value);
return value;
}
throw new Error(`append target must be a array`);
})
]
]);
function executeAdd(ast: AST, context: Context): Value {
const left = executeAST(ast.param2, context) as any;
const right = executeAST(ast.param3!, context) as any;
return left + right;
}
function executeSub(ast: AST, context: Context): Value {
const left = executeAST(ast.param2!, context) as any;
const right = executeAST(ast.param3!, context) as any;
return left - right;
}
function executeMultiply(ast: AST, context: Context): Value {
const left = executeAST(ast.param2!, context) as any;
const right = executeAST(ast.param3!, context) as any;
return left * right;
}
function executeDivision(ast: AST, context: Context): Value {
const left = executeAST(ast.param2!, context) as any;
const right = executeAST(ast.param3!, context) as any;
return left / right;
}
function executeFunctionParam(
ast: AST | null,
context: Context,
arr: Value[] = []
): Value[] {
if (!ast) {
return arr;
}
const currentValue = executeAST(ast.param2!, context);
arr.push(currentValue);
executeFunctionParam(ast.param3!, context, arr);
return arr;
}
function executeFunctionCall(ast: AST, context: Context) {
const identity = ast.param2! as string;
const params = executeFunctionParam(ast.param3!, context);
if (InternalFunctionMap.has(identity)) {
return InternalFunctionMap.get(identity)!.call(params);
}
const [func] = context.searchInContext(identity);
if (func instanceof FunctionExecutor) {
return func.call(params);
} else {
throw new Error(`${identity} can't to call`);
}
}
function resolveFunctionParams(
ast: AST | null | undefined,
arr: string[] = []
): string[] {
if (!ast) {
return arr;
}
arr.push(ast.param2!);
resolveFunctionParams(ast.param3, arr);
return arr;
}
function executeString(ast: AST): Value {
return ast.param2 as string;
}
function executeNumber(ast: AST): Value {
return ast.param2 as number;
}
function executeBool(ast: AST): Value {
return ast.param2 as boolean;
}
function executeArrayList(
ast: AST,
context: Context,
arr: Value[] = []
): Value[] {
if (!ast) {
return arr;
}
const value = executeAST(ast.param2!, context);
arr.push(value);
executeArrayList(ast.param3!, context, arr);
return arr;
}
function executeArray(ast: AST, context: Context): Value {
return executeArrayList(ast.param2, context);
}
function executeDeclare(ast: AST, context: Context): Value {
context.declareParam(ast.param2!, null);
return null;
}
function executeDeclareInitial(ast: AST, context: Context): Value {
const value = executeAST(ast.param3!, context);
context.declareParam(ast.param2!, value);
return value;
}
function executeSetValue(ast: AST, context: Context): Value {
const name = ast.param2 as string;
const value = executeAST(ast.param3!, context);
context.setValue(name, value);
return value;
}
function executeIdentify(ast: AST, context: Context): Value {
const name = ast.param2 as string;
return context.searchInContext(name)[0];
}
function executeDeclareFunction(ast: AST, context: Context): Value {
const name = ast.param2 as string;
const params = resolveFunctionParams(ast.param3);
const func = new DynamicFunctionExecutor(
ast.param4,
params,
context.makeChild()
);
context.declareParam(name, func);
return func;
}
function executeEqual(ast: AST, context: Context): Value {
const left = executeAST(ast.param2!, context);
const right = executeAST(ast.param3!, context);
return left === right;
}
function executeNotEqual(ast: AST, context: Context): Value {
const left = executeAST(ast.param2!, context);
const right = executeAST(ast.param3!, context);
return left !== right;
}
function executeGreatThan(ast: AST, context: Context): Value {
const left = executeAST(ast.param2!, context) as any;
const right = executeAST(ast.param3!, context) as any;
return left > right;
}
function executeLessThan(ast: AST, context: Context): Value {
const left = executeAST(ast.param2!, context) as any;
const right = executeAST(ast.param3!, context) as any;
return left < right;
}
function executeGreatThanOrEqual(ast: AST, context: Context): Value {
const left = executeAST(ast.param2!, context) as any;
const right = executeAST(ast.param3!, context) as any;
return left >= right;
}
function executeLessThanOrEqual(ast: AST, context: Context): Value {
const left = executeAST(ast.param2!, context) as any;
const right = executeAST(ast.param3!, context) as any;
return left <= right;
}
function executeAddAndAssign(ast: AST, context: Context): Value {
const name = ast.param2 as string;
const [value, ctx] = context.searchInContext(name);
const rightValue = executeAST(ast.param3!, context) as any;
const res = value + rightValue;
ctx.setValue(name, res);
return res;
}
function executeSubAndAssign(ast: AST, context: Context): Value {
const name = ast.param2 as string;
const [value, ctx] = context.searchInContext(name);
const rightValue = executeAST(ast.param3!, context) as any;
const res = (value as any) - rightValue;
ctx.setValue(name, res);
return res;
}
function executeSMulAndAssign(ast: AST, context: Context): Value {
const name = ast.param2 as string;
const [value, ctx] = context.searchInContext(name);
const rightValue = executeAST(ast.param3!, context) as any;
const res = (value as any) * rightValue;
ctx.setValue(name, res);
return res;
}
function executeDivAndAssign(ast: AST, context: Context): Value {
const name = ast.param2 as string;
const [value, ctx] = context.searchInContext(name);
const rightValue = executeAST(ast.param3!, context) as any;
const res = (value as any) / rightValue;
ctx.setValue(name, res);
return res;
}
function executeIf(ast: AST, context: Context): Value {
const condition = executeAST(ast.param2!, context);
const childContext = context.makeChild();
if (condition) {
if (ast.param3) {
executeAST(ast.param3, childContext);
if (childContext.exit !== undefined) {
context.exit = childContext.exit;
}
}
} else {
if (ast.param4) {
executeAST(ast.param4, childContext);
}
}
// 如果子上下文return了,根据流程控制if应该传递return状态
if (childContext.exit !== undefined) {
context.exit = childContext.exit;
}
if (childContext.break !== undefined) {
context.break = childContext.break;
}
if (childContext.continue !== undefined) {
context.continue = childContext.continue;
}
return null;
}
function executeWhile(ast: AST, context: Context): Value {
const childContext = context.makeChild();
while (true) {
const condition = executeAST(ast.param2!, context);
if (!condition) break;
if (ast.param3) {
executeAST(ast.param3, childContext);
}
// 如果子上下文return了,根据流程控制while应该传递return状态
if (childContext.exit !== undefined) {
context.exit = childContext.exit;
return null;
}
if (childContext.break !== undefined) {
console.log("break");
childContext.break = undefined;
return null;
}
if (childContext.continue !== undefined) {
childContext.continue = undefined;
}
}
return null;
}
function executeReturn(ast: AST, context: Context): Value {
if (!ast.param2) {
context.exit = null;
return null;
}
const res = executeAST(ast.param2!, context);
context.exit = res;
return res;
}
function executeBreak(ast: AST, context: Context): Value {
if (!ast.param2) {
context.break = null;
return null;
}
const res = executeAST(ast.param2!, context);
context.break = res;
return res;
}
function executeContinue(ast: AST, context: Context): Value {
if (!ast.param2) {
context.continue = null;
return null;
}
const res = executeAST(ast.param2!, context);
context.continue = res;
return res;
}
function executeArrayGet(ast: AST, context: Context) {
const name = ast.param2 as string;
const idx = executeAST(ast.param3!, context);
const [value] = context.searchInContext(name);
if (typeof value !== "object") {
throw new Error(`the ${name} can't use array get`);
}
return ((value as any)[idx as any] ?? null) as Value;
}
function executeNegative(ast: AST, context: Context): Value {
const value = executeAST(ast.param2!, context);
return !value;
}
function executePoint(ast: AST, context: Context): Value {
const left = executeAST(ast.param2, context) as any;
const right = ast.param3!.param2 as string;
if (!left) {
throw new Error(`left value is empty`);
}
if (!right) {
throw new Error(`right value is empty`);
}
return wrapperValue(left[right]);
}
function executeSetArrayValue(ast:AST,context:Context):Value {
const name = ast.param2 as string;
const [target] = context.searchInContext(name);
if(!target) {
throw new Error(`can't set value in to null`);
}
const index = executeAST(ast.param3!,context) as string|number;
const value = executeAST(ast.param4!,context);
if(target instanceof Map) {
target.set(String(index),value);
return value;
}
if(target instanceof Array) {
target[Number(index)] = value
return value;
}
if(target instanceof Object) {
(target as any)[index] = value;
return value;
}
throw new Error(`target can't set value`);
}
export function executeAST(ast: AST, context: Context): Value {
if (context.NormalExit !== undefined) {
return context.NormalExit;
}
switch (ast.param1) {
case "+":
return executeAdd(ast, context);
case "-":
return executeSub(ast, context);
case "*":
return executeMultiply(ast, context);
case "/":
return executeDivision(ast, context);
case "!":
return executeNegative(ast, context);
case ".":
return executePoint(ast, context);
case "==":
return executeEqual(ast, context);
case "!=":
return executeNotEqual(ast, context);
case ">":
return executeGreatThan(ast, context);
case "<":
return executeLessThan(ast, context);
case ">=":
return executeGreatThanOrEqual(ast, context);
case "<=":
return executeLessThanOrEqual(ast, context);
case "+=":
return executeAddAndAssign(ast, context);
case "-=":
return executeSubAndAssign(ast, context);
case "*=":
return executeSMulAndAssign(ast, context);
case "/=":
return executeDivAndAssign(ast, context);
case "STRING":
return executeString(ast);
case "NUMBER":
return executeNumber(ast);
case "BOOL":
return executeBool(ast);
case "ARRAY":
return executeArray(ast, context);
case "ARRAY_GET":
return executeArrayGet(ast, context);
case "NULL":
return null;
case "IDENTIFY":
return executeIdentify(ast, context);
case "IF":
return executeIf(ast, context);
case "WHILE":
return executeWhile(ast, context);
case "DECLARE_VAR":
return executeDeclare(ast, context);
case "DECLARE_VAR_INITIAL":
return executeDeclareInitial(ast, context);
case "SET_VALUE":
return executeSetValue(ast, context);
case "SET_ARRAY_VALUE":
return executeSetArrayValue(ast,context);
case "FUNCTION_CALL":
return executeFunctionCall(ast, context);
case "FUNCTION_DECLARE":
return executeDeclareFunction(ast, context);
case "RETURN":
return executeReturn(ast, context);
case "BREAK":
return executeBreak(ast, context);
case "CONTINUE":
return executeContinue(ast, context);
case "EXPRESSION_SEQ":
executeAST(ast.param2!, context);
if (context.NormalExit !== undefined) {
return context.NormalExit;
}
return executeAST(ast.param3!, context);
default:
return null;
}
}
export function evalAST(ast: AST, context?: Context) {
const ctx = context ?? new Context();
}
|
cd44d3205c6ec1d828aceffdb9a59488825a6943
|
TypeScript
|
RizwanMurtaza/MultiTenant
|
/src/app/forms/Login/LoginForm.ts
| 2.609375
| 3
|
import { required, minLength, email } from "@rxweb/reactive-form-validators";
export class LoginForm {
@required({ message: "email is required field" })
@email({ message: "user name must be a email" })
username: string;
@required({ message: "password is required" })
@minLength({ value: 6, message: "invalid password" })
password: string;
}
|
673cf17c8c9a3304111cd5c5de8738dc290021ad
|
TypeScript
|
ygorkayan/estruturas-de-dados
|
/src/estruturas-de-dados/deque.ts
| 3.546875
| 4
|
export default class Deque<T> {
private count: number;
private lowestCount: number;
private items: Record<number, T>;
constructor() {
this.count = 0;
this.lowestCount = 0;
this.items = {};
}
private moveForRight() {
const itemsTemp: Record<number, T> = {};
for (let i = 0; i < this.count; i++) {
const value = this.items[i];
itemsTemp[i + 1] = value;
}
this.items = itemsTemp;
this.count++;
}
addFront(element: T): void {
this.moveForRight();
this.items[this.lowestCount] = element;
}
addBack(element: T): void {
this.items[this.count++] = element;
}
removeFront(): T {
const value: T = this.items[this.lowestCount];
delete this.items[this.lowestCount++];
return value;
}
removeBack(): T {
const value: T = this.items[this.count];
delete this.items[--this.count];
return value;
}
peekFront(): T {
return this.items[this.lowestCount];
}
peekBack(): T {
return this.items[this.count - 1];
}
isEmpty(): boolean {
return this.size() === 0;
}
clear(): void {
this.items = {};
}
size(): number {
return this.count - this.lowestCount;
}
}
|
f428bcdfd2505b2d52ca3dd2c2b7319b9c164b9c
|
TypeScript
|
andruxacomm/nakukopTest
|
/store/modules/BaseStore.ts
| 2.6875
| 3
|
import { types } from 'mobx-state-tree';
export const BaseStore = types
.model({
isFetching: false,
error: types.maybeNull(types.string),
})
.actions(self => {
const setFetching = (value: boolean): void => {
self.isFetching = value;
};
const setError = (e: Error): void => {
self.error = e.message;
};
const clearError = (): void => {
self.error = null;
};
return {
setFetching,
clearError,
setError,
};
});
|
e27a99f1657570144c82877a24fd5025cd2d2020
|
TypeScript
|
bantyK/Payment-Billing-System
|
/Frontend/frontend/src/app/model/admin.ts
| 2.8125
| 3
|
export class Admin {
private id: number;
private username: string;
private password: string;
private dateOfJoining: Date;
private salary: number;
constructor(id: number, username: string, password: string, dateofJoining: Date, salary: number) {
this.id = id;
this.username = username;
this.password = password;
this.dateOfJoining = dateofJoining;
this.salary = salary;
}
getId() {
return this.id;
}
}
|
2dcd18f5b7f334c70eff30df179764873cebc69a
|
TypeScript
|
gurundoro/100AlgorithmChallenge
|
/100AlgorithmsChallenge/largestNumber/largestNumber.ts
| 3.203125
| 3
|
function largestNumber(n: number): number {
let str = ''
for(let i = 0; i < n; i++){
str += 9
}
return Number(str)
}
console.log(largestNumber(2));
|
7213bd1786eb13ef79f386cc28963c864293f1a9
|
TypeScript
|
nerder/typescript-rest-api
|
/src/controllers/BalanceController.ts
| 2.59375
| 3
|
import { Inject } from "typescript-ioc";
import { FormParam, Path, PathParam, PUT } from "typescript-rest";
import { BalanceService } from "../services/BalanceService";
@Path("/balance/")
export class BalanceController {
@Inject
private balanceService!: BalanceService;
@Path(":userId/deposit")
@PUT
public async deposit(
@PathParam("userId") userId: string,
@FormParam("amount") amount: number,
): Promise<boolean> {
return this.balanceService.deposit(userId, amount);
}
@Path(":fromUserId/to/:toUserId")
@PUT
public async transfer(
@PathParam("fromUserId") fromUserId: string,
@PathParam("toUserId") toUserId: string,
@FormParam("amount") amount: number,
): Promise<boolean> {
return this.balanceService.transfer(fromUserId, toUserId, amount);
}
}
|
1aa5c8b128ba7468376f687ae4d91485510329e3
|
TypeScript
|
rocketseat-creators-program/angular-http-requests-2021-10-13
|
/src/app/features/students/student.ts
| 3.03125
| 3
|
export interface Student {
id: number;
name: string;
email: string;
birthday: string;
createdAt: Date;
}
export class Student {
name: string;
email: string;
birthday: string;
constructor(name?: string, email?: string, birthday?: string) {
this.name = name || '';
this.email = email || '';
this.birthday = birthday || '';
}
}
|
9a45726f2892ba411c25aadb59e5ce41f3401e56
|
TypeScript
|
hkfd/hkfd
|
/packages/angular/src/app/shared/pipes/helpers.ts
| 2.78125
| 3
|
import { ApiPipeInput } from './api.pipe';
import { PrismicPipeInput } from './prismic.pipe';
import {
Image as GenericImage,
Video as GenericVideo,
Audio as GenericAudio
} from 'generic';
import {
ImageBlockData as ApiImageBlockData,
VideoBlockData as ApiVideoBlockData,
AudioBlockData as ApiAudioBlockData
} from 'api';
import {
ImageBlockData as PrismicImageBlockData,
VideoBlockData as PrismicVideoBlockData
} from 'prismic';
export type PipeReturn<T> = T extends ApiImageBlockData | PrismicImageBlockData
? GenericImage
: T extends ApiVideoBlockData | PrismicVideoBlockData
? GenericVideo
: T extends ApiAudioBlockData
? GenericAudio
: T extends ApiImageBlockData[] | PrismicImageBlockData[]
? GenericImage[]
: never;
export const isImageInput = <
T extends ApiImageBlockData | PrismicImageBlockData
>(
val: ApiPipeInput | PrismicPipeInput
): val is T => val.hasOwnProperty('image');
export const isVideoInput = <
T extends ApiVideoBlockData | PrismicVideoBlockData
>(
val: ApiPipeInput | PrismicPipeInput
): val is T => val.hasOwnProperty('video');
export const isAudioInput = <T extends ApiAudioBlockData>(
val: ApiPipeInput
): val is T => val.hasOwnProperty('audio');
export const isArrayInput = <
T extends ApiImageBlockData[] | PrismicImageBlockData[]
>(
val: ApiPipeInput | PrismicPipeInput
): val is T => Array.isArray(val);
|
3f733b9fd92f8c9303a6b50acb897ee311c081bb
|
TypeScript
|
jobjava00/typescript
|
/basic/ch3/src/enum.ts
| 3.640625
| 4
|
enum WeekDay { Mon, Tue, Wed, Thu }
enum WeekDay2 { Mon = 10, Tue, Wed = 10 << 2, Thu = 13 } // 초기값 지정
enum WeekDay3 { Mon = "Monday", Tue = "Tuesday" } // 문자열 지정
let day: WeekDay = WeekDay.Mon;
console.log(day);
console.log(WeekDay2.Wed);
console.log(WeekDay3.Mon);
|
d76e033f4d6e121ce98543c2731222b6c08e7382
|
TypeScript
|
manooog/noreact
|
/src/react.ts
| 2.671875
| 3
|
import { VNode } from './VNode';
import { MVVM } from './MVVM';
const isInBrowser = new Function(
'try {return this===window;}catch(e){ return false;}'
);
class NoReact {
private mode: 'deep' | 'shallow' = 'deep';
public target: MVVM;
createElement(
Elem: string | (typeof MVVM) | (typeof Fragment) | ((props: any) => any),
attrs: { [key: string]: any },
...children: (VNode | VNode[] | string)[]
): VNode {
let allchildren: VNode[] = [];
this.flatten('$', children, allchildren);
if (typeof Elem == 'string') {
let vnode: VNode = new VNode('standard');
vnode.SetTag(Elem);
vnode.isMulti = false;
if (attrs != null) {
Object.keys(attrs).forEach(key => {
vnode.SetAttr(key, attrs[key]);
})
}
vnode.SetChildren(allchildren);
return vnode;
}
if (Elem == Fragment) {
let vnode: VNode = new VNode('fragment');
vnode.isMulti = true;
vnode.SetChildren(allchildren);
if (attrs != null) {
Object.keys(attrs).forEach(key => {
vnode.SetAttr(key, attrs[key]);
})
}
return vnode;
}
if ((Elem as Function).prototype instanceof MVVM) {
let vnode = new VNode('custom');
let mvvm = new (Elem as any)(attrs) as MVVM;
vnode.SetMvvm(mvvm);
mvvm.$SetChildren(allchildren);
mvvm.$AttachVNode(vnode);
if (this.mode == 'deep') {
let root = mvvm.$DoRender();
vnode.isMulti = root.isMulti;
}
if (attrs != null) {
Object.keys(attrs).forEach(key => {
vnode.SetAttr(key, attrs[key]);
})
}
return vnode;
}
if (typeof Elem == "function") {
let vnode = (Elem as Function)(attrs);
return vnode;
}
}
private flatten(prefix: string, children: any[], res: VNode[]) {
children.forEach((child, index) => {
if (child == null) return;
if (child instanceof Array) {
this.flatten(prefix + index + '_', child, res);
} else {
if (child instanceof VNode) {
let key = child.GetAttr('key');
if (key != null) {
res.push(child);
} else {
child.SetAttr('key', prefix + index);
res.push(child);
}
} else {
let textnode = new VNode('text');
textnode.SetText(child + '');
textnode.SetAttr('key', prefix + index);
res.push(textnode);
}
}
});
}
ChangeMode(mode: 'shallow' | 'deep') {
this.mode = mode;
}
}
export class Fragment {
}
export class Ref<T> {
current: T;
}
export const React = new NoReact();
let counter = 0;
export function GetId() {
return counter++;
}
|
4e46510d78fe62a18cfb293f9f75d99aa15e2117
|
TypeScript
|
phongluudn1997/react-piano
|
/src/utils/useMount.ts
| 2.53125
| 3
|
import * as React from "react";
const useEffectOnce = (effect: React.EffectCallback) => {
//eslint-disable-next-line react-hooks/exhaustive-deps
React.useEffect(effect, []);
};
type Effect = (...args: unknown[]) => void;
export const useMount = (fn: Effect) => {
useEffectOnce(() => {
fn();
});
};
|
7ad348edeac8d316565fded08379975b46246103
|
TypeScript
|
brycejech/socket-server
|
/src/index.ts
| 2.546875
| 3
|
import * as http from 'http';
import { SocketServer } from './socket-server';
import { ISocketMessage } from './socket-server/interfaces';
const httpServer = http.createServer(requestHandler),
socketServer = new SocketServer(httpServer);
function requestHandler(req: http.IncomingMessage, res: http.ServerResponse){
let body: string = '';
req.on('data', (chunk: any) => {
body += chunk;
});
req.on('end', () => {
let data: any;
try{
data = JSON.parse(body);
}
catch(e){
return clientError('Error deserializing request', res);
}
const { channel, message }: { channel: string, message: any } = data;
if(!(channel && message)){
return clientError('Missing channel or message props', res);
}
socketServer.messageClients(channel, 'test', message);
res.writeHead(200, {"Content-Type": "application/json"});
res.write(`{"message": "OK", "received": ${ JSON.stringify(data) }}`);
res.end();
});
}
function clientError(msg: string, res: http.ServerResponse){
res.writeHead(400, {"Content-Type": "application/json"});
res.write(`{"message": "${ msg }"}`);
res.end();
}
httpServer.listen(9999, () => console.log('Node HTTP server listening on 9999'));
|
633bbce61423b4f9231a126fe42f82210195f516
|
TypeScript
|
upgundecha/cucumber
|
/gherkin/javascript/src/types.ts
| 2.515625
| 3
|
export interface IGherkinOptions {
defaultDialect?: string
includeSource?: boolean
includeGherkinDocument?: boolean
includePickles?: boolean
}
const defaultOptions: IGherkinOptions = {
defaultDialect: 'en',
includeSource: true,
includeGherkinDocument: true,
includePickles: true,
}
export function gherkinOptions(options: IGherkinOptions) {
return { ...defaultOptions, ...options }
}
|
cde7744dacca16b4ed3da613cb5e2cb2c54c226a
|
TypeScript
|
1241962119/superV-node-end
|
/model/enums/activity.ts
| 2.796875
| 3
|
/**
* @description
* 活动状态
* @export
* @enum {number}
*/
export enum ActivityStatus {
/**
* 待发布
*/
PENDING = 0,
/**
* 上架
*/
SHOW = 1,
/**
* 下架
*/
HIDE = 2,
/**
* 删除
*/
DELETE = 3
}
|
21e85d997aab734545eea193036f7b94d995b3bd
|
TypeScript
|
gurhann/typescript-samples
|
/js/looping.ts
| 3.15625
| 3
|
var randArray = [3,4,5,6];
for(var i in randArray) {
document.write(i + "<br />");
}
var strArray = randArray.map(String);
for(var i of strArray) {
document.write(i + "<br />");
}
document.write("type of randArray:" + typeof randArray + "<br />");
document.write("type of strArray:" + typeof strArray);
|
308eb04147a3bc2534a3c81b9208b0914dfde2fa
|
TypeScript
|
firebase/firebase-tools
|
/src/fsutils.ts
| 2.953125
| 3
|
import { readFileSync, statSync } from "fs";
import { FirebaseError } from "./error";
export function fileExistsSync(path: string): boolean {
try {
return statSync(path).isFile();
} catch (e: any) {
return false;
}
}
export function dirExistsSync(path: string): boolean {
try {
return statSync(path).isDirectory();
} catch (e: any) {
return false;
}
}
export function readFile(path: string): string {
try {
return readFileSync(path).toString();
} catch (e: unknown) {
if ((e as NodeJS.ErrnoException).code === "ENOENT") {
throw new FirebaseError(`File not found: ${path}`);
}
throw e;
}
}
|
5d1d955288e6999bf51c3b64621c01d4f5718101
|
TypeScript
|
Isur/isomorphic-react-app
|
/src/Client/Services/Base/request.service.ts
| 2.828125
| 3
|
import axios from "axios";
import { Cookies } from "react-cookie";
import { RequestService } from "./request.interface";
import config from "@client/config";
type methods = "GET" | "POST" | "PATCH" | "DELETE";
export class Request implements RequestService {
private _basePath: string;
public constructor(basePath: string) {
this._basePath = basePath;
}
public async request<Res, Req = null>(url: string, method: methods, data?: Req): Promise<Res> {
let res: Res;
const access_token = new Cookies().get("access_token");
try {
const response = await axios({
method,
url: `${this._basePath}/${url}`,
baseURL: config.backend,
data,
headers: { access_token },
});
res = response.data;
} catch(error) {
console.error(error);
if(error.message === "Network Error") {
// TODO: Handle no internet connection.
}
throw {
code: error.response.status,
data: error.response.data,
message: error.message,
};
}
return res;
}
public async get<Res>(url: string): Promise<Res> {
return await this.request<Res>(url, "GET");
}
public async post<Res, Req>(url: string, data: Req): Promise<Res> {
return await this.request<Res, Req>(url, "POST", data);
}
public async patch<Res, Req>(url: string, data: Req): Promise<Res> {
return await this.request<Res, Req>(url, "PATCH", data);
}
public async delete<Res>(url: string): Promise<Res> {
return await this.request<Res>(url, "DELETE");
}
}
|
c2cbede132cbfe9edf31d872a3e58f0fc0f4c096
|
TypeScript
|
NCElegacy/WebGLStudyNote
|
/ThreeJsStudyNote/material/texture/texture3/src/main.ts
| 2.703125
| 3
|
import * as THREE from "three"
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap";
import "./main.css";
import { Mesh } from "three";
window.addEventListener("DOMContentLoaded", () => {
// レンダラーの設定。
const RENDER = new THREE.WebGLRenderer();
/// レンダラーのサイズを決める(画面の大きさ)
/// 必ずしも画面いっぱいである必要はない。
const WIDTH = window.innerWidth;
const HEIGHT = window.innerHeight;
/// レンダラーにサイズを設定。
RENDER.setSize(WIDTH, HEIGHT);
/// canvasをbodyに追加する。
document.body.appendChild(RENDER.domElement);
// シーンの追加
const SCENE = new THREE.Scene();
// カメラの設定
const CAMERA = new THREE.PerspectiveCamera(45, WIDTH / HEIGHT, 1, 10000);
/// カメラの位置を設定
CAMERA.position.set(0, 0, 1000);
// ジオメトリの作成(球体やボックスの作成など)
const GEOMETRY = new THREE.SphereGeometry(100, 60, 60);
// マテリアル設定 テクスチャを使う場合
/// テクスチャに使う画像の読み込み
const LOADER = new THREE.TextureLoader();
const TEXTURE = LOADER.load("imgs/texture1.png");
/// マテリアルの作成(テクスチャを使った)
const MATERIAL = new THREE.MeshStandardMaterial({
map: TEXTURE
});
// メッシュの設定
/// メッシュの作成
/// メッシュはジオメトリとマテリアルを組み合わせたもの。
const MESH = new THREE.Mesh(GEOMETRY, MATERIAL);
/// メッシュをシーンに追加
SCENE.add(MESH);
// 光源設定
/// 平行光源の作成(光源の色を決める)
/// 光源がないと画面が真っ暗になり良くわからなくなる。
const LIGHT = new THREE.DirectionalLight(0xffffff);
/// 平行光源の位置を設定
LIGHT.position.set(1, 1, 1);
/// シーンにライトを追加
SCENE.add(LIGHT);
let time = 0;
const draw = (): void => {
requestAnimationFrame(draw);
// メッシュの回転
MESH.rotation.x += 0.005;
MESH.rotation.y += 0.005;
// メッシュの拡大
time += 0.005;
MESH.scale.x = Math.sin(time) * 2;
MESH.scale.y = Math.sin(time) * 2;
MESH.scale.z = Math.sin(time) * 2;
// シーンとカメラを表示
RENDER.render(SCENE, CAMERA);
}
draw();
})
|
ade8881a38eee8e0923e37119cddd0df3449e725
|
TypeScript
|
gzuidhof/WebMetaverse
|
/src/ds/circularbuffer.ts
| 3.40625
| 3
|
/**
* Author Guido Zuidhof / http://guido.io
*/
module DS {
/**
* Circular buffer
* Data structure that uses a single, fixed-size buffer.
* A new entry overwrites the oldest entry when the buffer is full.
*/
export class CircularBuffer<T> {
buffer: T[];
/**
* Index of the newest entry
*/
pointer: number;
// [ 5, 6, 7, 1, 2, 3, 4]
// |
// pointer = 2
constructor(length: number) {
this.buffer = [];
this.buffer.length = length;
this.pointer = 0;
}
push(element: T) {
this.pointer = (this.pointer + 1) % this.buffer.length;
this.buffer[this.pointer] = element;
}
get(index): T {
return this.buffer[index];
}
getNewest(): T {
return this.buffer[this.pointer];
}
clear(): void {
var length = this.buffer.length;
this.buffer = [];
this.buffer.length = length;
}
}
}
|
6e63d9f277a5629c800c33529f67df4296a6f819
|
TypeScript
|
maryb14/BusBoard
|
/workspace/busStop.ts
| 2.71875
| 3
|
import * as request from 'request'
import * as _ from "lodash"
import {Bus} from './bus'
export class BusStop {
constructor(public id: string, public name: string) { }
getBuses(): Promise <Bus[]> {
let promiseLatAndLong: Promise <string> = new Promise((resolve) => {
var requestString = "https://api.tfl.gov.uk/StopPoint/" +
this.id + "/Arrivals?app_id=ef0cca24&app_key=281fde5472478ee61c2d8a63c5e4f554";
request(requestString, (error, response, body) => {
resolve(body);
});
});
return promiseLatAndLong.then((bodyString: string) => {
return this.getBusesArray(bodyString);
});
}
private getBusesArray(bodyString: string): Bus[] {
var latLongArray = JSON.parse(bodyString);
var busesArrayFromJSON = [];
busesArrayFromJSON = JSON.parse(bodyString);
busesArrayFromJSON = _.sortBy(busesArrayFromJSON, (bus) => {
return bus.timeToStation;
});
var shortenedBusesArrayFromJSON = busesArrayFromJSON.slice(0, 5);
var busesArray = _.map(shortenedBusesArrayFromJSON,(busFromJson) => {
return new Bus(busFromJson.lineId, busFromJson.timeToStation, busFromJson.destinationName);
});
return busesArray;
}
}
|
567a16a31eff3d006762817584715a9cabc191a9
|
TypeScript
|
eternalconcert/suitescript-types-tools-and-frameworks
|
/src/nstypes.ts
| 2.578125
| 3
|
export type NSBoolean = 'T'|'F'// perhaps the api support native boolean accorting to typings
export type NSDate = string // perhaps the api support native Dates accorting to typings
export type NSRecordType = string // but could be a enum or ored type
export interface NativeError { name?: string, message?: string, stack?: string[], type?: string }
|
1a91819bf6e057e78630013f156d603ed0694eb0
|
TypeScript
|
qdraw/starsky
|
/starsky/starsky/clientapp/src/shared/validate-login-form.ts
| 3.171875
| 3
|
/**
* Handle form validation for the login form
* false is no email or password
* null is non valid email adres
* true is continue
* @param email - user's auth email
* @param password - user's auth password
*/
export const validateLoginForm = (
email: string,
password: string
): boolean | null => {
// Check for undefined or empty input fields
if (!email || !password) {
return false;
}
if (!validateEmail(email)) {
return null;
}
return true;
};
function validateEmail(email: string) {
// before feb'22: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
// NOSONAR
const re =
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
|
8ea022f0cd9d0f6a040522cb57bd6503d8a9e63f
|
TypeScript
|
rafaelgalle/rabbitmq-requeue
|
/consumer/server.ts
| 2.75
| 3
|
import * as amqplib from 'amqplib'
var exWork = 'e.work';
var queueWork = 'q.work';
var bindKeyWork = '';
var exWait = 'e.wait';
var queueWait = 'q.wait';
var bindKeyWait = '';
amqplib.connect('amqp://guest:guest@localhost')
.then(conn => {
conn.createChannel()
.then(ch => {
// Criando exchanges
ch.assertExchange(exWait, 'topic', { durable: true });
ch.assertExchange(exWork, 'topic', { durable: true });
// Criando fila de espera com DLX configurada.
ch.assertQueue(queueWait, { durable: true, deadLetterExchange: exWork })
.then(q => {
// Criando ligação entre fila de espera e exchange de espera.
ch.bindQueue(q.queue, exWait, bindKeyWait);
// Observer que criamos a fila mas não iniciamos um consumidor para ela,
// fazendo com que a mensagem publicada seja expirada de acordo com seu TTL
// e redirecionada para a DLX configurada, retornando para a exchange de trabalho
});
// Criando fila de trabalho
ch.assertQueue(queueWork, { durable: true })
.then(q => {
// Criando ligação entre fila e exchange
ch.bindQueue(q.queue, exWork, bindKeyWork);
// Iniciando um consumidor para a fila, ele irá consumir e processar cada nova
// mensagem que a fila receber
ch.consume(q.queue, function (msg: any) {
console.log('## CONSUMINDO MENSAGEM ## ')
console.log('## FILA: ' + q.queue)
Process(ch, msg)
}, { noAck: true });
});
})
})
function Process(ch: any, msg: any){
// Buscando quantas vezes essa mensagem foi processada
let count = msg.properties.headers.count ? msg.properties.headers.count : 1
// Setando options da mensagem com ttl de 5 segundos e header contendo o contador
let options = { expiration: 5000, headers: { 'count': ++count }}
if (count > 5) return console.log('## Escapando por exceder limite de tentativas')
// Publicando mensagem em exchange de espera com TTL definido
ch.publish(exWait, bindKeyWait, Buffer.from(msg.content.toString()), options)
console.log('## Simulando erro - Publicando em fila de espera')
}
|
f23c65d7b7349930a12f5c9e78d35aa4a6677f79
|
TypeScript
|
tafm/PG-projeto2
|
/projeto.ts
| 2.75
| 3
|
import * as $ from 'jquery'
import { Bezier } from './classes/bezier'
import { Camera } from './classes/camera'
import { FuncoesAux } from './classes/funcoesAux'
import { Iluminacao } from './classes/iluminacao'
let camera : Camera
let iluminacao : Iluminacao
let bezier : Bezier
let size = { width: 800, height: 600 }
let canvas = $('#canvas')[0]
let frames = 0
let intervalo = 0
function leituraEntradas () {
camera = FuncoesAux.entrada.loadCamera($('#camera')[0].value)
iluminacao = FuncoesAux.entrada.loadIluminacao(($('#iluminacao')[0].value))
FuncoesAux.entrada.loadObject($('#objeto')[0].value)
frames = parseInt($('#bezier')[0].value.split('\n')[1])
intervalo = parseInt($('#bezier')[0].value.split('\n')[0])
bezier = new Bezier($('#bezier')[0].value)
$('#entradas').css('display', 'none')
canvas.width = size.width
canvas.height = size.height
$('#canvas').css('display', 'block')
}
function sleep (ms) {
return new Promise ((resolve) => setTimeout(resolve, ms))
}
async function iniciaCamera () {
let t = 0
let fator = 1.0 / frames
let ctx = canvas.getContext('2d')
while (t <= 1) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
camera.p = bezier.getPonto(t)
t += fator
let canvasFunc = camera.takeFrame(size, iluminacao)
ctx.drawImage(canvasFunc, 0, 0)
await sleep (intervalo)
}
// console.log('Taking a break...');
// await sleep(2000);
// console.log('Two second later');
}
$('#botao').click(() => {
leituraEntradas()
iniciaCamera()
// let canvasFunc = camera.takeFrame(size, iluminacao) // pega um frame da câmera e desenha na tela
// let ctx = canvas.getContext('2d')
// ctx.drawImage(canvasFunc, 0, 0)
})
// fake entradas
// $('#camera')[0].value = '-200 -50 300\n0.667 0.172 -1\n0 3 0\n65 0.5 0.6'
// $('#iluminacao')[0].value = '-200 -50 300\n1\n2 2 2\n1\n1 1 1\n0.5\n0 255 0\n2'
// $('#objeto')[0].value = '3 1\n50.0000 0.0000 0.000\n0 50 0\n0 0 50\n1 2 3'
// $('#bezier')[0].value = '1\n-200 -50 300'
// $('#tempo')[0].value = '1'
// $('#frames')[0].value = '1'
// leituraEntradas()
// let canvasFunc = camera.takeFrame(size, iluminacao) // pega um frame da câmera e desenha na tela
// let ctx = canvas.getContext('2d')
// ctx.drawImage(canvasFunc, 0, 0)
// loadCamera('-200 -50 300\n0.667 0.172 -1\n0 3 0\n65 0.5 0.6')
// loadIluminacao('-200 -50 300\n1\n2 2 2\n1\n1 1 1\n0.5\n0 255 0\n2')
// loadObject('3 1\n50.0000 0.0000 0.000\n0 50 0\n0 0 50\n1 2 3')
// console.log(new Ponto2d(1, 2))
// console.log($('#teste'))
// fake entradas
// $('#camera')[0].value = '50 -50 300\n0 0 -1\n1 -100 10\n10 -2 -3'
// // $('#iluminacao')[0].value = '-200 -50 300\n1\n2 2 2\n1\n1 1 1\n0.5\n0 255 0\n2'
// $('#iluminacao')[0].value = '-220 -150 700\n1\n40 20 20\n1\n0.7 0.7 0.7\n0.5\n220 220 220\n2'
// $('#objeto')[0].value = '4 4\n1 1 1\n1 30 1\n30 30 1\n1 1 30\n1 2 3\n1 2 4\n2 3 4\n1 3 4'
// $('#bezier')[0].value = '200\n50\n4\n30 -100 500\n0 -100 500\n10 -120 500\n10 -80 500'
// leituraEntradas()
// let canvasFunc = camera.takeFrame(size, iluminacao) // pega um frame da câmera e desenha na tela
// let ctx = canvas.getContext('2d')
// ctx.drawImage(canvasFunc, 0, 0)
// iniciaCamera()
|
e734df90d317fcb48dbeb97ae0ee3cc781009d85
|
TypeScript
|
jgretz/schwankie
|
/site/app/services/util/colorForTag.ts
| 2.59375
| 3
|
import * as R from 'ramda';
const FOOD_TAGS = [
'food',
'recipe',
'baking',
'coffee',
'chicken',
'cookies',
'bread',
'soup',
'instantpot',
'breakfast',
];
const TECH_TAGS = [
'tech',
'react',
'javascript',
'programming',
'ai',
'ml',
'software',
'technology',
'development',
];
const BUSINESS_TAGS = ['business', 'career', 'interview', 'life', 'startup'];
const SPORTS_TAGS = ['sports', 'running', 'basketball', 'football', 'soccer', 'races', 'shoes'];
const tagBgColorMap = {
food: 'accent_salmon',
tech: 'accent_dark_green',
business: 'accent_light_green',
sports: 'accent_blue',
};
const DEFAULT_COLOR = 'slate-300';
export function colorForTag(tag: string) {
return colorForTags([tag]);
}
export function colorForTags(tags: string[]) {
if (R.intersection(tags, FOOD_TAGS).length > 0) {
return tagBgColorMap.food;
}
if (R.intersection(tags, TECH_TAGS).length > 0) {
return tagBgColorMap.tech;
}
if (R.intersection(tags, BUSINESS_TAGS).length > 0) {
return tagBgColorMap.business;
}
if (R.intersection(tags, SPORTS_TAGS).length > 0) {
return tagBgColorMap.sports;
}
return DEFAULT_COLOR;
}
|
10444357a2b3721e2d9c78ad8e18fa4bbf1e937c
|
TypeScript
|
almcaffee/mock-repo
|
/src/app/pipes/sensitive-info.pipe.ts
| 2.65625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sensitiveInfo'
})
export class SensitiveInfoPipe implements PipeTransform {
transform(value: string, format?: string): any {
if(value) {
let hiddenInfo: string = '';
let valArr: any[] = [];
let mask: string = '*';
let maskAll = format && format === 'all' ? true : false;
let length = maskAll ? value.length : 1;
if(value && format && format === 'date') {
return 'XX/XX/XXXX';
} else if(value && format && format === 'all') {
for(let i = 0; i < length; i++) hiddenInfo += mask;
return hiddenInfo;
} else if(value && format && format === 'long') {
for(let i = 0; i < value.length - 4; i++) hiddenInfo += mask;
hiddenInfo += value.substr(value.length - 4);
return hiddenInfo;
} else {
hiddenInfo = '*'+value.substr(value.length - 4);
return hiddenInfo;
}
} else {
return 'N/A';
}
}
}
|
9ece640a21c8101edb25882400f2579d27c16c2a
|
TypeScript
|
devank-hub/weirdtrex
|
/src/commands/music/radio.ts
| 2.6875
| 3
|
import * as Discord from "discord.js";
import * as path from "path";
import { IBotCommand } from "../../api";
const RadioBrowser = require('radio-browser');
const { Utils } = require("erela.js");
const ms = require("ms");
export default class radio implements IBotCommand {
public readonly _command = "radio";
public readonly aliases : string[] = ["rd"];
public readonly category : string = path.basename(__dirname);
public readonly display : boolean = true;
help(): string {
return "this command plays online radio stations on **radio voice-channel** depending upon your searching terma and then selection from 1 to 7,if first time plays nothing then try again it sometime fails to load the link";
}
isThisCommand(command: string): boolean {
return command === this._command;
}
usage(): string {
return "?radio <station_name>"
}
async runCommand(args: string[], msgObject: Discord.Message, client: Discord.Client): Promise<any> {
if (!args[0])
{
msgObject.channel.send("Please provide a radio name to search.")
.then(msg=>{msg.delete({timeout: 3000})});
msgObject.delete();
return;
}
const query = args.join(" ");
const voiceChannel = msgObject.guild.channels.cache.find(c=> c.name.toLowerCase() === "📻radio") as Discord.VoiceChannel;
//console.log(voiceChannel)
if (!voiceChannel)
{
//console.log(voiceChannel)
msgObject.channel.send("You need to be in a voice channel to play radio.").then(msg=>{msg.delete({timeout: 3000})});
msgObject.delete();
return;
}
//@ts-ignore
const player = client.music.players.get(msgObject.guild.id);
//@ts-ignore
if (!player) client.music.players.spawn({
guild: msgObject.guild,
textChannel: msgObject.channel,
voiceChannel
});
//@ts-ignore
const plays = client.music.players.get(msgObject.guild.id);
let filter = {
limit: 7, // list max 5 items
by: 'name', // search in tag
searchterm: query, // term in tag
}
let str = "";
let i = 0;
let embed = new Discord.MessageEmbed();
embed.setTitle('**Search Results for 📻**');
embed.setFooter("Your response time closes within the next 30 seconds. Type 'cancel' to cancel the selection",msgObject.guild.iconURL());
let data = await RadioBrowser.getStations(filter)
embed.setDescription(data.map((obj: any, i:number) => `**${i+1}.🎶 [${obj.name} ${obj.language}](${obj.url_resolved})**`).join('\n\n'))//idk if url property exists
msgObject.channel.send(embed).then(msg=>{msg.delete({timeout: 10000})});
const collector = msgObject.channel.createMessageCollector(m => {
return m.author.id === msgObject.author.id && new RegExp(`^([1-7]|cancel)$`, "i").test(m.content)
}, {
time: 30000,
max: 1
});
collector.on("collect", async m => {
if (/cancel/i.test(m.content)) return collector.stop("cancelled")
m.delete();
const track = [Number(m.content) - 1];
collector.on("end", (_, reason) => {
if (["time", "cancelled"].includes(reason)) {
//@ts-ignore
if (player.queue.empty == true) client.music.players.destroy(player.guild.id)
return msgObject.channel.send("Cancelled selection.").then(msg => {msg.delete({timeout: 3000})});
}
});
//@ts-ignore
str = data[track].url;
if (!str) return msgObject.channel.send('Cannot play this Radio Station').then(msg => {msg.delete({timeout: 3000})});
await play(str)
})
async function play(str: any) {
if (str.length === 0) return msgObject.channel.send(new Discord.MessageEmbed().setDescription(`Invalid Radio item`).setColor("GREEN")).then(msg => {msg.delete({timeout: 3000})});
//@ts-ignore
await client.music.search(str, msgObject.author).then(async (res: any) => {
switch (res.loadType) {
case "TRACK_LOADED":
plays.queue.add(res.tracks[0]);
msgObject.channel.send(`Adding \`${res.tracks[0].title}\` \`${Utils.formatTime(res.tracks[0].duration, true)}\``).then(msg => {msg.delete({timeout: 4000})});
if (!plays.playing) {
plays.play();
plays.setTrackRepeat(false);
plays.setQueueRepeat(false);
}
break;
case "LOAD_FAILED":
msgObject.channel.send("Unable to add this station try other options !!").then(msg => {msg.delete({timeout: 3000})});
break;
}
})
.catch((error: any) => console.error(error))
}
msgObject.delete();
}
}
|
287ae408c03da986ffa48df8196069b397665e20
|
TypeScript
|
sajadparacha/angularjs-learning
|
/favoriteusingngclass.component.ts
| 2.875
| 3
|
import {Component,Input,Output,EventEmitter} from 'angular2/core'
@Component({
selector : "favoriteusingngclass",
/*
Don't delete below lines , these are to be used to define inline templates
Inline templates are good if small.
However if the HTML code grows it's better to create a new HTML file like favorite.template.html for better sepration of concerns
*/
// template:`
// <h2>Favorite Component 3453456</h2>
// <i class="glyphicon"
// [class.glyphicon-star-empty]="!isFavorite"
// [class.glyphicon-star]="isFavorite"
// (click)="onClick()"
// ></i>
// `
template:`
<h2>Favorite Component using ngclass</h2>
<i class="glyphicon"
[ngClass]="{
'glyphicon-star-empty':!isFavorite,
'glyphicon-star':isFavorite
}"
(click)="onClick()"
></i>
<h2>Favorite Component using ngclass</h2>
`
})
export class FavoriteUsingNgClass{
//**declaring a variable as input property which is visible to the any object of this component
//**Declaring an input paramete with a different name to outer world
@Input('is_favorite') isFavorite =true;
//**Publish an output event
@Output() change=new EventEmitter();
//**Declaring an input parameter as it is
//@Input('is_favorite') isFavorite =false;
onClick(){
this.isFavorite=!this.isFavorite;
//**Call the change event when the favorite is cicked
this.change.emit({newValue:this.isFavorite});
}
}
|
878d76070f3bd6a9314e907aea520ad0aec936c5
|
TypeScript
|
future4code/Luan-Campos
|
/BackEnd/Semana 20/Logic Exercises/ex3b.ts
| 3.34375
| 3
|
function compare(text: string, text2: string): Boolean {
if (text.toLowerCase() === text2.toLowerCase()) {
return true;
}
return false;
}
console.log(compare("luan", "luAn"));
|
ba4451d88823304dc4987529f08b73692e87d1bf
|
TypeScript
|
hapijs/ammo
|
/test/index.ts
| 2.875
| 3
|
import * as Stream from 'stream';
import * as Ammo from '..';
import * as Code from '@hapi/code';
import * as Lab from '@hapi/lab';
import * as Wreck from '@hapi/wreck';
const { expect } = Lab.types;
const TestStream = class extends Stream.Readable {
_count: number;
constructor() {
super();
this._count = -1;
}
_read() {
this._count++;
if (this._count < 10) {
this.push(this._count.toString());
return;
}
this.push(null);
}
};
const range = Ammo.header('bytes=2-9', 10) as Ammo.Range[];
const stream = new Ammo.Clip(range[0]);
const source = new TestStream();
const buffer = await Wreck.read(source.pipe(stream));
Code.expect(buffer.toString()).to.equal('23456789');
// header()
Ammo.header('bytes=2-9', 10);
expect.type<Ammo.Range[] | null>(Ammo.header('bytes=2-9', 10));
expect.error(Ammo.header());
expect.error(Ammo.header({}, 45));
expect.error(Ammo.header('x'));
|
6d8e7979572576c6298855826a890cd5b5afeb9a
|
TypeScript
|
alanshaw/it-pushable
|
/src/fifo.ts
| 3.328125
| 3
|
// ported from https://www.npmjs.com/package/fast-fifo
export interface Next<T> {
done?: boolean
error?: Error
value?: T
}
class FixedFIFO<T> {
public buffer: Array<Next<T> | undefined>
private readonly mask: number
private top: number
private btm: number
public next: FixedFIFO<T> | null
constructor (hwm: number) {
if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {
throw new Error('Max size for a FixedFIFO should be a power of two')
}
this.buffer = new Array(hwm)
this.mask = hwm - 1
this.top = 0
this.btm = 0
this.next = null
}
push (data: Next<T>): boolean {
if (this.buffer[this.top] !== undefined) {
return false
}
this.buffer[this.top] = data
this.top = (this.top + 1) & this.mask
return true
}
shift (): Next<T> | undefined {
const last = this.buffer[this.btm]
if (last === undefined) {
return undefined
}
this.buffer[this.btm] = undefined
this.btm = (this.btm + 1) & this.mask
return last
}
isEmpty (): boolean {
return this.buffer[this.btm] === undefined
}
}
export interface FIFOOptions {
/**
* When the queue reaches this size, it will be split into head/tail parts
*/
splitLimit?: number
}
export class FIFO<T> {
public size: number
private readonly hwm: number
private head: FixedFIFO<T>
private tail: FixedFIFO<T>
constructor (options: FIFOOptions = {}) {
this.hwm = options.splitLimit ?? 16
this.head = new FixedFIFO<T>(this.hwm)
this.tail = this.head
this.size = 0
}
calculateSize (obj: any): number {
if (obj?.byteLength != null) {
return obj.byteLength
}
return 1
}
push (val: Next<T>): void {
if (val?.value != null) {
this.size += this.calculateSize(val.value)
}
if (!this.head.push(val)) {
const prev = this.head
this.head = prev.next = new FixedFIFO<T>(2 * this.head.buffer.length)
this.head.push(val)
}
}
shift (): Next<T> | undefined {
let val = this.tail.shift()
if (val === undefined && (this.tail.next != null)) {
const next = this.tail.next
this.tail.next = null
this.tail = next
val = this.tail.shift()
}
if (val?.value != null) {
this.size -= this.calculateSize(val.value)
}
return val
}
isEmpty (): boolean {
return this.head.isEmpty()
}
}
|
9ed5c05f4c238e4c520a0d73514ef67eaf904815
|
TypeScript
|
chriskrycho/v5.chriskrycho.com
|
/eleventy/utils.ts
| 2.71875
| 3
|
import { env } from 'process';
interface ToString {
toString(): string;
}
export const toString = (a: ToString): string => a.toString();
export const logErr = (err: unknown): void => {
if (env['DEBUG']) {
console.error(err);
}
};
|
6a5276aa2465820cf0e425a6fef124c292a94500
|
TypeScript
|
tokyosheep/ExportImages
|
/src/js/fileSystem/basicSystem.ts
| 2.578125
| 3
|
import * as fs from "fs";
import * as path from "path";
const readFile = (path:string):Promise<string|Error> =>{
return new Promise((resolve,reject)=>{
fs.readFile(path,"utf-8",(err,data)=>{
if(err)reject(err);
resolve(data);
});
})
};
const writeFile = (path:string,data:object):Promise<boolean|Error> =>{
return new Promise((resolve,reject)=>{
fs.writeFile(path,JSON.stringify(data),(err)=>{
if(err)reject(err);
resolve(true);
})
});
}
export default {readFile:readFile,writeFile:writeFile};
|
eaf55c3d288f6d2ac55248087dee5d68e6ce2bdd
|
TypeScript
|
Mayness/multi-events
|
/types/event.d.ts
| 2.78125
| 3
|
interface EventSub {
id: symbol;
fnArray: Function[];
size: number;
constructor(id: symbol, fnArray: Function[], realSize?: number): void;
applyFunction(value: any[]): void;
}
interface _events {
[propName: string]: EventSub[];
}
interface EventCache {
[propName: string]: symbol;
}
declare class MultiEvents {
_events: _events;
_eventsCount: number;
constructor();
on(eventName: string | string[], callback: Function | Function[]): EventCache;
emit(eventName: string | string[], params: any): void;
once(eventName: string | string[], callback: Function | Function[]): EventCache;
removeEvent(eventArray: string | string[]): boolean[] | boolean;
removeEventFunction(id: symbol | symbol[]): boolean[] | boolean;
}
export default MultiEvents;
|
35b0f7382047d0225b5977f075523a491de817be
|
TypeScript
|
Y-shu/ReCap-Angular
|
/myspace/class.ts
| 3.375
| 3
|
class Bakery{
name:string;
type:string;
color:string;
constructor(name:string,type:string,color:string){
this.name = name;
this.type = type;
this.color = color
}
display():void{
console.log("Welcome to " +this.name+ " we serve food of type " +this.type) ;
}
}
var bakery = new Bakery("MyBakery","Cakes","Red");
bakery.display();
|
06f49c2d8864ae9c5719bb03d0857362f7e3a973
|
TypeScript
|
sygic-travel/js-sdk
|
/src/Alerts/Mapper.ts
| 2.5625
| 3
|
import { Alert, DetailedAlert } from './Alert';
export const mapAlertApiResponseToAlert = (alert: any): Alert => ({
id: alert.id,
type: alert.type,
severity: alert.severity,
affectedArea: alert.affected_area as GeoJSON.GeoJsonObject,
perex: alert.perex,
name: alert.name,
state: alert.state,
origin: alert.origin,
provider: alert.provider,
providerUrl: alert.provider_url,
validFrom: alert.valid_from,
validTo: alert.valid_to,
updatedAt: alert.updated_at
} as Alert);
export const mapAlertsApiResponseToAlerts = (alerts: any[]): Alert[] => alerts.map(mapAlertApiResponseToAlert);
export const mapDetailedAlertApiResponseToDetailedAlert = (detailedAlert: any): DetailedAlert => {
const mappedAlert: Alert = mapAlertApiResponseToAlert(detailedAlert);
return {
...mappedAlert,
description: detailedAlert.description,
externalId: detailedAlert.external_id,
webUrl: detailedAlert.web_url,
geometry: detailedAlert.geometry
} as DetailedAlert;
};
|
d900bd38376e988033ad26f42b110e2919ac290a
|
TypeScript
|
vikram-gsu/twitter-search
|
/src/api/format-data.ts
| 2.734375
| 3
|
import searchResult from "../types/search-result";
const getUTCSecondsSinceEpoch = (date: Date) =>
Math.round((date.getTime() + date.getTimezoneOffset() * 60 * 1000) / 1000);
function formatData(statuses: any): searchResult[] {
return statuses
.map((status: any) => ({
created_at: new Date(status.created_at),
id: status.id_str,
text:
status.full_text.lastIndexOf("http") === -1
? status.full_text
: status.full_text.slice(0, status.full_text.lastIndexOf("http")),
hash_tags: status.entities.hashtags.map((hashTag: any) => hashTag.text),
user_screen_name: status.user.screen_name,
image_url: status.user.profile_image_url,
tweet_url: status.full_text.slice(
status.full_text.lastIndexOf("http"),
status.full_text.length
),
}))
.sort((result1: searchResult, result2: searchResult) => {
return (
getUTCSecondsSinceEpoch(result2.created_at) -
getUTCSecondsSinceEpoch(result1.created_at)
);
});
}
function getAllHashTags(statuses: any): Set<string> {
return new Set(
statuses.reduce(
(hashTags: string[], status: any) => [...hashTags, ...status.hash_tags],
[]
)
);
}
export { formatData, getAllHashTags };
|
8d417d8ad11d19f28f5297695b564cc921ec4053
|
TypeScript
|
kiekk/study-typescript
|
/control/src/loop/while-loop.ts
| 2.53125
| 3
|
let count: number = 1
let sum: number = 0
while (count <= 100) {
sum += count
count++
}
console.log(sum)
|
de1b986b8f6aace123c85d0f1765e73ef7d00198
|
TypeScript
|
ischoolinc/coregadget
|
/c391ef32-f3b7-406a-8cd2-b8a1e4cfe77d/src/app/merge-helper.ts
| 2.875
| 3
|
import { CourseCodeInfo, FileInfo } from './form/model-subject';
export class MergeHelper {
constructor() {}
/**
* 歷程產生的大表
*/
tempCourseTable: Map<string, CourseCodeInfo> = new Map();
/**
* 每一份FileIno的暫存
*/
tempCourseMap: Map<string, CourseCodeInfo> = new Map();
/**
*
* @param fileInfo 要加入合併的檔案
*/
mergeFile(fileInfo: FileInfo): void {
this.tempCourseMap.clear();
// 複製到暫存區
fileInfo.mapSubjectCodes.forEach((value, key) => {
value.clearActionHistory(); // 每次判斷前先清空歷史資料
this.tempCourseMap.set(key, value.clone());
});
// 將原本大表中刪除的物件做移除
this.tempCourseTable.forEach((value) => {
if (value.isDelete) {
this.tempCourseTable.delete(value.key);
}
});
// 使用暫存區資料搬移到大表中
this.tempCourseMap.forEach((newCourseValue) => {
// 有沒有相對應大表的key值
if (this.tempCourseTable.has(newCourseValue.key)) {
if ((newCourseValue.action === '新增或不變')) {
newCourseValue.action = '不變';
this.tempCourseTable.set(newCourseValue.key, newCourseValue) ;
}
else if (newCourseValue.action === '修改') {
newCourseValue.setActionHistory(this.tempCourseTable.get(newCourseValue.key));
this.tempCourseTable.delete(newCourseValue.key);
newCourseValue.key = newCourseValue.courseCode;
newCourseValue.addHistoryRecord(fileInfo.md5Code, String(fileInfo.approvedDate), newCourseValue);
this.tempCourseTable.set(newCourseValue.key, newCourseValue) ;
}
else if (newCourseValue.action === '刪除') {
newCourseValue.isDelete = true;
this.tempCourseTable.delete(newCourseValue.key);
newCourseValue.addHistoryRecord(fileInfo.md5Code, String(fileInfo.approvedDate), newCourseValue);
this.tempCourseTable.set(newCourseValue.key, newCourseValue);
}
}
// 沒有相對應大表的key值
else {
if (newCourseValue.action === '新增或不變') {
newCourseValue.action = '新增';
newCourseValue.addHistoryRecord(fileInfo.md5Code, String(fileInfo.approvedDate), newCourseValue);
this.tempCourseTable.set(newCourseValue.key, newCourseValue);
}
else if (newCourseValue.action === '修改') {
newCourseValue.addHistoryRecord(fileInfo.md5Code, String(fileInfo.approvedDate), newCourseValue);
newCourseValue.key = newCourseValue.courseCode;
this.tempCourseTable.set(newCourseValue.key, newCourseValue);
}
else if (newCourseValue.action === '刪除') {
newCourseValue.isDelete = true;
newCourseValue.addHistoryRecord(fileInfo.md5Code, String(fileInfo.approvedDate), newCourseValue);
this.tempCourseTable.set(newCourseValue.key, newCourseValue);
}
}
});
}
/**
* 取得歷程加匯入檔的大表
*/
getFinalCourseCodes(): Map<string, CourseCodeInfo> {
return this.tempCourseTable;
}
}
|
721d00638bea9277ec84b06b2fe2c1997aa1c418
|
TypeScript
|
drunken-lemur/core2d
|
/src/game/rayCasting/entity/map.ts
| 2.765625
| 3
|
import {
Bounds,
Color,
Entity,
IBrush,
IBrushStyle,
IViews,
Size,
styledView,
translatedView
} from "core";
const mapData =
"#########......." +
"#..............." +
"#.......########" +
"#..............#" +
"#......##......#" +
"#......##......#" +
"#..............#" +
"###............#" +
"##.............#" +
"#......####..###" +
"#......#.......#" +
"#......#.......#" +
"#..............#" +
"#......#########" +
"#..............#" +
"################";
export class Map extends Entity {
private static readonly Wall = "#";
private static readonly Width = 16;
private static readonly Height = 16;
private static readonly CellSize = Size.valueOf(30);
style: IBrushStyle = { fillStyle: Color.Red, strokeStyle: Color.Black };
views: IViews<this> = [
styledView,
translatedView,
(map, brush) => {
const {
Wall,
Width,
Height,
CellSize: { w, h }
} = Map;
const { data } = map;
for (let y = 0; y < Height; y++) {
for (let x = 0; x < Width; x++) {
const offset = y * Width + x;
if (data[offset] === Wall) {
brush.fillRect(x * w, y * w, w, h).strokeRect(x * w, y * w, w, h);
}
}
}
}
];
private data: string;
constructor(data: string = mapData) {
super();
this.data = data;
}
private static Draw(map: Map, brush: IBrush) {}
}
|
3e06e1a92d4dcd0b7b337c8706f22cec5e7574fa
|
TypeScript
|
backstagePro/playground-api
|
/src/model/base/IWrite.ts
| 3.203125
| 3
|
export interface IWrite<T> {
/**
* Create a new document and return its id
*
* @param item
*/
create(item: T): Promise<string>;
/**
* Update a single item.
*
* If the item is modified in result of this operation - true will be returned
* from this function
*
* @param id
* @param item
*/
update(id: string, item: T): Promise<boolean>;
/**
* Delete a item by id.
*
* If deletion was succesfull, 'true' will be returned
*
* @param id
*/
delete(id: string): Promise<boolean>;
}
|
63c87eb7d4269665fd233f94e18b4f060baffbf3
|
TypeScript
|
BYazdaani/Stacks-Editor
|
/src/rich-text/plugins/spoiler-toggle.ts
| 2.828125
| 3
|
import { EditorState, Plugin, Transaction } from "prosemirror-state";
import { docChanged } from "../../shared/utils";
/**
* Updates all spoiler nodes within the state's selection
* @param tr The transaction to modify
* @param state The state whose selection to check for spoiler nodes (does not have to be the current state!)
* @param shouldReveal Whether to force the spoiler to be revealed or not
* @param transactions The array of transactions to map node positions through (if the state is not current)
*/
function updateSpoilers(
tr: Transaction,
state: EditorState,
shouldReveal: boolean,
transactions?: Transaction[]
) {
const { from, to } = state.selection;
state.doc.nodesBetween(from, to, (node, pos) => {
// if spoiler node, set revealed attribute
if (node.type.name === "spoiler") {
// inherit whatever attributes are already on the node,
// but do NOT update the node directly (or else the view will not register as changed)
const attrs = { ...node.attrs };
attrs.revealed = shouldReveal;
let wasDeleted = false;
if (transactions?.length) {
// map the position through each transaction to make sure the node we're altering still exists
transactions.forEach((t) => {
const result = t.mapping.mapResult(pos);
// if the node was outright deleted, skip it!
if (result.deleted) {
wasDeleted = true;
return false;
}
// set pos to the current position of the node
pos = result.pos;
});
}
// if the node was deleted, then there's nothing to do
if (wasDeleted) {
return false;
}
tr = tr.setNodeMarkup(pos, null, attrs);
// don't recurse into this node's children
return false;
}
});
return tr;
}
/** Plugin that forces the `revealed` attr on "spoiler" nodes on selection and removes it on de-selection */
export const spoilerToggle = new Plugin({
appendTransaction(transactions, oldState, newState) {
// if the doc / selection has not changed, nothing to do
if (!docChanged(oldState, newState)) {
return null;
}
let tr = newState.tr;
// un-reveal all spoilers from the old state/selection
tr = updateSpoilers(tr, oldState, false, transactions);
// reveal all spoilers in the new selection
tr = updateSpoilers(tr, newState, true);
// no nodes changed, just return
if (!tr.steps.length) {
return null;
}
// make sure this doesn't get added to the history
tr = tr.setMeta("addToHistory", false);
return tr;
},
});
|
dab0c9cd26a7ef727bff6a687dfa026e3e236b39
|
TypeScript
|
vraptor75011/ST_Risk
|
/graphqlServer/utils/scripts/createMigrationsIndex.ts
| 2.546875
| 3
|
import * as fg from 'fast-glob';
import * as fs from 'fs';
import * as path from 'path';
/**
* All paths relative to root dir
*
*/
interface migrationsParams {
migrationsSrc: string;
migrationsGlobPattern: string;
migrationsOut: string;
migrationsOutFileName: string;
}
export { migrationsParams };
function createMigrationsIndex(params: migrationsParams): void {
const rootDir = path.resolve(__dirname, './../..');
console.log('Creating migrations index');
const src = path.resolve(rootDir, params.migrationsSrc);
if (!fs.existsSync(src)) {
console.log(`App api cannot be found. Path not exist: ${src}`);
process.exit(1);
}
const outDir = path.resolve(rootDir, params.migrationsOut);
const tmpFile = path.resolve(outDir, 'tmp.' + params.migrationsOutFileName);
const outFile = path.resolve(outDir, params.migrationsOutFileName);
if (!fs.existsSync(outDir)) {
fs.mkdirSync(outDir);
}
for (const item of fg.sync(`${src}/**/migrations/*.ts`)) {
const filePath = path.relative(outDir, item).replace(/\.ts$/, '');
const data = `export * from '${filePath}'\n`;
fs.writeFileSync(tmpFile, data, { flag: 'a+' });
}
if (fs.existsSync(outFile) && fs.existsSync(tmpFile)) {
fs.unlinkSync(outFile);
console.log(`Old file '${outFile}' removed`);
}
if (fs.existsSync(tmpFile)) {
fs.renameSync(tmpFile, outFile);
console.log(`New file ${outFile} saved`);
}
}
export default createMigrationsIndex;
|
73fb6c95cbd261d216a5c973c522bbe2cd03ae1c
|
TypeScript
|
AWolan/febs
|
/client/services/assignment.service.ts
| 2.609375
| 3
|
import axios, { AxiosResponse } from 'axios';
import {
AssignmentTO,
Assignment,
} from '../interfaces/assignment/interfaces';
import { Status } from '../enums/common.enums';
import { parseDate } from '../utils/date.utils';
export const fetchAllAssignments = () =>
axios.get('/api/assignment')
.then((response: AxiosResponse<AssignmentTO[]>): Assignment[] => response.data.map((assignment: AssignmentTO) => ({
...assignment,
startDate: parseDate(assignment.startDate),
endDate: parseDate(assignment.endDate),
status: Status[assignment.status],
})));
|
4efe463b075c6bc99a7e06e1c6db77cc33a32630
|
TypeScript
|
capturely/capturely-js
|
/src/structures/cookies.ts
| 2.640625
| 3
|
///<reference path="abstractStructure.ts"/>
import AbstractStructure from "./abstractStructure";
class Cookies extends AbstractStructure {
protected cookies: object[] = [];
public make(
name: string,
value: string,
url: string | null = null,
domain: string | null = null,
path: string | null = null,
expires: string | null = null,
httpOnly: boolean | null = null,
secure: boolean | null = null,
sameSite: string | null = 'Lax'
) {
this.cookies.push({name, value, url, domain, path, expires, httpOnly, secure, sameSite});
return this;
}
}
export default Cookies;
|
e24bef4251e3fdd10f1a47e8bd9a46faaf2f267f
|
TypeScript
|
hubol/pissant
|
/src/stopwatch.ts
| 2.828125
| 3
|
export class Stopwatch
{
public readonly startedMilliseconds = new Date().getTime();
public get elapsedMilliseconds()
{
return new Date().getTime() - this.startedMilliseconds;
}
public get elapsedMillisecondsText()
{
return `${this.elapsedMilliseconds}ms`;
}
}
|
c6b122d228aa93d0bc7e209c9ab6caa90c8b44fd
|
TypeScript
|
reach2amitdeb/TypeScript
|
/Interfaces/FunctionalInterfaces.ts
| 3.5625
| 4
|
interface Add{
(x:number, y:number):void
}
interface Sub{
(x:number, y:number):number
}
var add:Add;
var sub:Sub;
add = function(x:number, y:number):void{
console.log(x+y);
}
sub = function(x:number, y:number):number{
return x-y;
}
|
70ccfaf1ef040c145c56565aaab334471dbecdbf
|
TypeScript
|
Paxxi/Vim
|
/src/configuration/commandKeyMap.ts
| 2.671875
| 3
|
import * as vscode from 'vscode';
export enum Command {
// Enter insert mode
InsertAtCursor = 1,
InsertAtLineBegin,
InsertAfterCursor,
InsertAtLineEnd,
InsertNewLineBelow,
InsertNewLineAbove,
// Movement
MoveUp,
MoveDown,
MoveLeft,
MoveRight,
MoveLineBegin,
MoveLineEnd,
MoveWordBegin,
MoveWordEnd,
MoveFullWordBegin,
MoveFullWordEnd,
MoveLastWord,
MoveLastFullWord,
MoveLastWordEnd,
MoveLastFullWordEnd,
// MoveHalfPageUp,
// MoveHalfPageDown,
MoveFullPageUp,
MoveFullPageDown,
// MoveFirstLine,
// MoveLastLine,
MoveParagraphBegin,
MoveParagraphEnd,
MoveNonBlank,
MoveNonBlankFirst,
MoveNonBlankLast,
MoveMatchingBracket,
// Find
Find,
// Folding
Fold,
Unfold,
FoldAll,
UnfoldAll,
// Text Modification
Undo,
Redo,
Copy,
Paste,
ChangeWord,
ChangeFullWord,
ChangeCurrentWord,
ChangeCurrentWordToNext,
ChangeToLineEnd,
DeleteLine,
DeleteToNextWord,
DeleteToFullNextWord,
DeleteToWordEnd,
DeleteToFullWordEnd,
DeleteToWordBegin,
DeleteToFullWordBegin,
DeleteToLineEnd,
DeleteChar,
DeleteLastChar,
Indent,
Outdent,
// Misc
EnterVisualMode,
EnterCommand,
ExitMessages,
}
export type CommandKeyHandler = {[key: string]: Command};
export class CommandKeyMap {
public normalModeKeyMap : CommandKeyHandler;
public insertModeKeyMap : CommandKeyHandler;
public visualModeKeyMap : CommandKeyHandler;
constructor(
normalModeKeyMap : CommandKeyHandler,
insertModeKeyMap : CommandKeyHandler,
visualModeKeyMap : CommandKeyHandler) {
this.normalModeKeyMap = normalModeKeyMap;
this.insertModeKeyMap = insertModeKeyMap;
this.visualModeKeyMap = visualModeKeyMap;
}
static fromUserConfiguration(): CommandKeyMap {
let getConfig = function(keyHandlers: CommandKeyHandler, configName: string): CommandKeyHandler {
let overrides = vscode.workspace.getConfiguration("vim")
.get(configName, keyHandlers);
// merge
for (let key in overrides) {
if (overrides.hasOwnProperty(key)) {
keyHandlers[key] = overrides[key];
}
}
return keyHandlers;
};
let normalMode = getConfig(CommandKeyMap.DefaultNormalKeyMap(), "normalModeKeyBindings");
let insertMode = getConfig(CommandKeyMap.DefaultInsertKeyMap(), "insertModeKeyBindings");
let visualMode = getConfig(CommandKeyMap.DefaultVisualKeyMap(), "visualModeKeyBindings");
return new CommandKeyMap(normalMode, insertMode, visualMode);
}
static DefaultNormalKeyMap() : CommandKeyHandler {
return {
"h": Command.MoveLeft,
"j": Command.MoveDown,
"k": Command.MoveUp,
"l": Command.MoveRight,
"0": Command.MoveLineBegin,
"$": Command.MoveLineEnd,
"^": Command.MoveNonBlank,
"gg": Command.MoveNonBlankFirst,
"G": Command.MoveNonBlankLast,
"w": Command.MoveWordBegin,
"W": Command.MoveFullWordBegin,
"e": Command.MoveWordEnd,
"E": Command.MoveLastFullWordEnd,
"ge": Command.MoveLastWordEnd,
"gE": Command.MoveLastFullWordEnd,
"b": Command.MoveLastWord,
"B": Command.MoveLastFullWord,
"{": Command.MoveParagraphBegin,
"}": Command.MoveParagraphEnd,
"%": Command.MoveMatchingBracket,
">>": Command.Indent,
"<<": Command.Outdent,
"u": Command.Undo,
"ctrl+r": Command.Redo,
"yy": Command.Copy,
"p": Command.Paste,
"cw": Command.ChangeWord,
"cW": Command.ChangeFullWord,
"ciw": Command.ChangeCurrentWord,
"caw": Command.ChangeCurrentWordToNext,
"C": Command.ChangeToLineEnd,
"dd": Command.DeleteLine,
"dw": Command.DeleteToNextWord,
"dW": Command.DeleteToFullNextWord,
"db": Command.DeleteToWordBegin,
"dB": Command.DeleteToFullWordBegin,
"de": Command.DeleteToWordEnd,
"dE": Command.DeleteToFullWordEnd,
"D" : Command.DeleteToLineEnd,
"x": Command.DeleteChar,
"X": Command.DeleteLastChar,
"/": Command.Find,
"zc": Command.Fold,
"zo": Command.Unfold,
"zC": Command.FoldAll,
"zO": Command.UnfoldAll,
":": Command.EnterCommand,
"v": Command.EnterVisualMode,
"esc": Command.ExitMessages
};
}
static DefaultInsertKeyMap() : CommandKeyHandler {
return {
"i": Command.InsertAtCursor,
"I": Command.InsertAtLineBegin,
"a": Command.InsertAfterCursor,
"A": Command.InsertAtLineEnd,
"o": Command.InsertNewLineBelow,
"O": Command.InsertNewLineAbove,
};
}
static DefaultVisualKeyMap() : CommandKeyHandler {
return {
"v": Command.EnterVisualMode
};
}
}
|
ce5d18735cd9feb86774e654549cae7bcfbecc51
|
TypeScript
|
Platekun/bare-ui
|
/src/common/custom-breakpoints.ts
| 3.0625
| 3
|
import keys from './keys';
import isObject from './isObject';
import isNull from './isNull';
import EMPTY_STRING from './empty-string';
/**
* Stolen from Material UI.
*/
export const bps: Record<string, number> = {
xs: 0,
sm: 600,
md: 960,
lg: 1280,
xl: 1920,
};
type IBreakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl';
export function from(key: IBreakpoint) {
return `@media (min-width: ${bps[key]}px)`;
}
export type IResponsiveProp<TProp> =
| TProp
| Partial<{
xs: TProp;
sm: TProp;
md: TProp;
lg: TProp;
xl: TProp;
}>;
type IProp = Record<string, any>;
type ICustomStyleFunction = {
prop: string;
props: IProp;
transform: (props: any) => string;
};
function customBreakpoints(opts: ICustomStyleFunction) {
const { prop, props, transform } = opts;
const propValue = props[prop];
if (!isObject(propValue) && !isNull(propValue)) {
return transform(props);
} else if (isNull(propValue)) {
return EMPTY_STRING;
}
// Force the order the responsive values are written
const breakpointsForProp = keys({
...(propValue.xs ? { xs: propValue.xs } : {}),
...(propValue.sm ? { sm: propValue.sm } : {}),
...(propValue.md ? { md: propValue.md } : {}),
...(propValue.lg ? { lg: propValue.lg } : {}),
...(propValue.xl ? { xl: propValue.xl } : {}),
});
const responsiveStyles = breakpointsForProp.reduce((acc, breakpoint) => {
const propValueForBreakpoint = (propValue as IProp)[breakpoint];
const mediaQueryForBreakpoint = breakpoint !== 'xs' ? from(breakpoint as IBreakpoint) : undefined;
const stylesForBreakpoint = transform({
...props,
[prop]: propValueForBreakpoint,
});
if (!mediaQueryForBreakpoint) {
return `
${stylesForBreakpoint}
${acc}
`;
}
return `
${acc}
${mediaQueryForBreakpoint} {
${stylesForBreakpoint}
}
`;
}, EMPTY_STRING);
return responsiveStyles;
}
export default customBreakpoints;
export type ITransformResponsiveProps<TProps, TResponsivePropName extends string, TProp> = Omit<
TProps,
TResponsivePropName
> &
TProp;
|
f1837ac6882c283fbf9079df44949a11c4cb7194
|
TypeScript
|
baisheng/picker
|
/src/modules/jobs/number.service.ts
| 2.6875
| 3
|
import { Injectable } from '@nestjs/common';
@Injectable()
export class NumberService {
twice(x: number) {
return x * 2;
}
thrice(x: number) {
return x * 3;
}
}
|
aaf45ae8e8fe73c1360830a13a0d4a52e019f9dd
|
TypeScript
|
AkshayPilane/zeldaPlay
|
/apps/api/src/app/validators/isEmail.ts
| 2.53125
| 3
|
import { PropertyValidator, PropertyValidatorError } from '@deepkit/type';
import { emailError } from './messages';
export class IsEmail implements PropertyValidator {
validate(value: string): PropertyValidatorError | void {
if (!value.includes('@')) {
return new PropertyValidatorError('bad_email', emailError(value));
}
}
}
|
1e1c98652f4d3a48cbb02dc9f12fd687cd6e2a95
|
TypeScript
|
gengjian1203/YikanBox
|
/client/src/redux/reducers/avatarShowInfo.ts
| 2.75
| 3
|
import { produce } from 'immer'
import { deepClone } from '@/utils/index'
import {
INIT_AVATAR_INFO,
SET_AVATAR_SHOW_LIST_POINT,
SET_AVATAR_IMAGE,
SET_SELECT_TYPE,
SET_SELECT_JEWELRY,
ADD_AVATAR_JEWELRY,
REMOVE_AVATAR_JEWELRY,
UPDATE_AVATAR_JEWELRY,
} from '@/redux/constants/avatarShowInfo'
const LIMIE_AVATAR_SHOW_LIST = 10
const INITIAL_STATE = {
nAvatarShowListPoint: 0, // 操作指针
arrAvatarShowList: [
{
strAvatarImage: '', // 头像底图
arrAvatarJewelry: [], // 饰品列表(有序)
strSelectType: '', // 操作状态 // 'BTN_FLIP'-翻转 'BTN_DELETE'-删除 'BTN_ADD'-复制 'BTN_RESIZE'-调整尺寸 'MOVE'-拖动
objSelectJewelry: {}, // 选中饰品对象
},
], // 操作记录列表
}
const getNewAvatarShow = draft => {
return draft.arrAvatarShowList[draft.nAvatarShowListPoint]
}
// 新建操作记录
const newAvatarShow = draft => {
// 清除废弃分支操作
draft.arrAvatarShowList.splice(draft.nAvatarShowListPoint + 1, 999)
// 新建操作记录
const objAvatarShowNew = deepClone(
draft.arrAvatarShowList[draft.nAvatarShowListPoint]
)
draft.arrAvatarShowList.push(objAvatarShowNew)
draft.nAvatarShowListPoint++
// 超出列表最大限制则弹出最古老操作记录
if (draft.arrAvatarShowList.length > LIMIE_AVATAR_SHOW_LIST) {
draft.arrAvatarShowList.shift()
draft.nAvatarShowListPoint--
}
}
// 清除头像为空的脏数据操作记录
const cleanAvatarShow = draft => {
if (draft.arrAvatarShowList.length >= 2) {
if (draft.arrAvatarShowList[0].strAvatarImage === '') {
draft.arrAvatarShowList.shift()
draft.nAvatarShowListPoint--
}
}
}
export default function avatarShowInfoReducer(state = INITIAL_STATE, action) {
const { type, payload } = action
return produce(state, draft => {
switch (type) {
// 初始化头像秀的信息
case INIT_AVATAR_INFO:
draft = INITIAL_STATE
return draft
// 设置操作记录指针
case SET_AVATAR_SHOW_LIST_POINT:
draft.nAvatarShowListPoint = payload
return draft
// 设置头像秀的背景图片
case SET_AVATAR_IMAGE:
newAvatarShow(draft)
getNewAvatarShow(draft).strAvatarImage = payload
getNewAvatarShow(draft).arrAvatarJewelry = []
getNewAvatarShow(draft).strSelectType = ''
getNewAvatarShow(draft).objSelectJewelry = {}
cleanAvatarShow(draft)
return draft
// 设置操作的类型
case SET_SELECT_TYPE:
getNewAvatarShow(draft).strSelectType = payload
return draft
// 设置选中的饰品信息
case SET_SELECT_JEWELRY:
getNewAvatarShow(draft).objSelectJewelry = payload
return draft
// 新增头像秀的饰品信息
case ADD_AVATAR_JEWELRY:
newAvatarShow(draft)
getNewAvatarShow(draft).arrAvatarJewelry.push(payload)
return draft
// 移除头像秀的饰品信息
case REMOVE_AVATAR_JEWELRY:
{
newAvatarShow(draft)
const objNewAvatarShow = getNewAvatarShow(draft)
const nIndex = objNewAvatarShow.arrAvatarJewelry.findIndex(item => {
return item.id === payload.id
})
if (nIndex >= 0) {
objNewAvatarShow.strSelectType = ''
objNewAvatarShow.objSelectJewelry = {}
objNewAvatarShow.arrAvatarJewelry.splice(nIndex, 1)
}
}
return draft
// 更新头像秀的饰品信息
case UPDATE_AVATAR_JEWELRY:
{
newAvatarShow(draft)
const objNewAvatarShow = getNewAvatarShow(draft)
const nIndex = objNewAvatarShow.arrAvatarJewelry.findIndex(item => {
return item.id === payload.id
})
if (nIndex >= 0) {
objNewAvatarShow.strSelectType = ''
objNewAvatarShow.objSelectJewelry = payload
objNewAvatarShow.arrAvatarJewelry[nIndex] = payload
}
}
return draft
default:
return draft
}
})
}
|
9f6f0aba88ba9e60ec6b10aad2e8bf113e3cbcc3
|
TypeScript
|
offlinehacker/justmodel
|
/test/justmodel.test.ts
| 3.140625
| 3
|
import Joi from "joi"
import { Model } from "../src/justmodel"
type User = {
username: string
password: string
meta?: {
abcd: string
metaObject: {
key: string
}
}
}
class UserModel extends Model<User> {
get schema() {
return super.schema.keys({
username: Joi.string()
.required()
.min(4),
password: Joi.string()
.required()
.min(8),
meta: Joi.object({
abcd: Joi.string(),
metaObject: Joi.object({
key: Joi.string()
}).default({})
}).default({ metaObject: {} })
})
}
}
/**
* Model test
*/
describe("Model test", () => {
it("Model is instantiable", () => {
expect(new Model()).toBeInstanceOf(Model)
})
describe("model creation", () => {
it("should create valid model", () => {
new UserModel().create({
username: "user",
password: "password"
})
})
it("should throw ValidationError if creating invalid model", () => {
expect(() => {
new UserModel().create({
username: "abc",
password: "abc"
})
}).toThrow(/child "username" fails/)
})
})
describe("model loading", () => {
it("should load model", () => {
new UserModel().load({
username: "user",
password: "password",
meta: {}
})
})
it("should apply defaults", () => {
const user = new UserModel().load({
username: "user",
password: "password"
})
expect(user.meta).toEqual({ metaObject: {} })
})
})
describe("model properties", () => {
it("should get property using get method", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
expect(model.get("username")).toBe("user")
})
it("should get deep property using get method", () => {
const model = new UserModel().load({
username: "user",
password: "password",
metaObject: {
key: "value"
}
})
expect(model.get("metaObject.key")).toBe("value")
})
it("should get property value by object key", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
expect(model.username).toBe("user")
expect(model.password).toBe("password")
})
it("should get deep object properties", () => {
const model = new UserModel().load({
username: "user",
password: "password",
meta: {
abcd: "test"
}
})
expect(model.meta.abcd).toBe("test")
})
it("should throw error on get if property is not set", () => {
const model = new UserModel().load({ username: "user" })
expect(() => model.get("password")).toThrow(ReferenceError)
})
it("should check if model has property set", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
expect(model.has("username")).toBeTruthy()
})
it("should check if model has old property set", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
expect(model.hasOld("username")).toBeTruthy()
})
it("should check if model has any value", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
expect(model.has()).toBeTruthy()
expect(model.hasOld()).toBeTruthy()
})
it("should set value using object key", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
model.username = "newuser"
expect(model.username).toBe("newuser")
})
it("should set deep value using object key", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
model.meta.abcd = "defgh"
model.meta.metaObject.key = "value"
expect(model.meta.abcd).toBe("defgh")
expect(model.meta.metaObject.key).toBe("value")
})
it("should update using update method", () => {
let model = new UserModel().load({
username: "user",
password: "password"
})
model = model.update({ username: "newuser" })
expect(model.get("username")).toBe("newuser")
})
it("should update in place using updateInPlace method", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
model.updateInPlace({ username: "newuser" })
expect(model.get("username")).toBe("newuser")
})
})
describe("model changes", () => {
it("should have no changes on loading", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
expect(model.hasChanged()).toBeFalsy()
})
it("should have changes when creating model", () => {
const model = new UserModel().create({
username: "user",
password: "password"
})
expect(model.hasChanged()).toBeTruthy()
})
it("should detect changes when updating model using object keys", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
model.username = "newuser"
expect(model.hasChanged()).toBeTruthy()
expect(model.hasChanged("username")).toBeTruthy()
})
it("should update immutably when using update method", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
const newModel = model.update({ username: "newuser" })
expect(model.hasChanged()).toBeFalsy()
expect(newModel.hasChanged()).toBeTruthy()
})
it("should update in place when using updateInPlace method", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
const newModel = model.updateInPlace({ username: "newuser" })
expect(model.hasChanged()).toBeTruthy()
expect(newModel.hasChanged()).toBeTruthy()
})
it("should get old value using getOld method", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
model.username = "newuser"
expect(model.getOld("username")).toBe("user")
})
it("should commit changes", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
expect(
model
.update({ username: "newuser" })
.commit()
.hasChanged()
).toBeFalsy()
expect(
model
.updateInPlace({ username: "newuser" })
.commitInPlace()
.hasChanged()
).toBeFalsy()
})
it("should check if models are equal", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
expect(model.equals(model)).toBeTruthy()
})
})
describe("model misc methods", () => {
it("should get value", () => {
const data = {
username: "user",
password: "password",
meta: { metaObject: {} }
}
const model = new UserModel().load(data)
expect(model.value()).toEqual(data)
})
it("should clone model", () => {
const model = new UserModel().load({
username: "user",
password: "password"
})
expect(model.clone()).not.toBe(model)
})
})
})
|
3cfa63c9da7fb06758ea9de1d66d37d31e3840bb
|
TypeScript
|
ibzakharov/angular_project_template
|
/Client/app/js/entities/operationResult.ts
| 2.96875
| 3
|
class OperationResult {
public Succeeded: boolean;
public Message: string;
constructor(succeeded: boolean, message?: string) {
this.Succeeded = succeeded;
this.Message = message;
}
}
|
5de477bc1d9c4c06d10131b61357d5596b23aeb9
|
TypeScript
|
l3043Y/nestjs-iot-server
|
/src/cluster.ts
| 2.578125
| 3
|
// cluster.ts
// import cluster from 'cluster';
const cluster = require('cluster')
import * as os from 'os';
export class Cluster {
static register(workers: Number | 'auto', callback: Function): void {
if (cluster.isMaster) {
console.log(`Master server started on ${process.pid}`);
//ensure workers exit cleanly
process.on('SIGINT', function () {
console.log('Cluster shutting down...');
for (var id in cluster.workers) {
cluster.workers[id].kill();
}
// exit the master process
process.exit(0);
});
var cpus = os.cpus().length;
if (workers > cpus || workers === 'auto')
workers = cpus;
for (let i = 0; i < workers; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log('Worker %s is online', worker.process.pid);
});
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died. Restarting`);
cluster.fork();
})
} else {
callback();
}
}
}
|
26269e7001ad36b7612dd0b93cb1377db28607c9
|
TypeScript
|
MalpenZibo/wherewolf
|
/src/utils.ts
| 2.578125
| 3
|
import { useIntl } from "react-intl";
import { Faction, RoleId } from "./domain";
export function useFormatRole(): {
formatName: (roleId: RoleId) => string;
formatDescription: (roleId: RoleId) => string;
} {
const { formatMessage } = useIntl();
const formatName = (roleId: RoleId) => {
switch (roleId) {
case "primaryWolf":
return formatMessage({ id: "role.primaryWolf.name" });
case "secondaryWolf":
return formatMessage({ id: "role.secondaryWolf.name" });
case "youngWolf":
return formatMessage({ id: "role.youngWolf.name" });
case "traitor":
return formatMessage({ id: "role.traitor.name" });
case "seer":
return formatMessage({ id: "role.seer.name" });
case "wizard":
return formatMessage({ id: "role.wizard.name" });
case "medium":
return formatMessage({ id: "role.medium.name" });
case "witch":
return formatMessage({ id: "role.witch.name" });
case "healer":
return formatMessage({ id: "role.healer.name" });
case "farmer1":
return formatMessage({ id: "role.farmer.name" });
case "farmer2":
return formatMessage({ id: "role.farmer.name" });
case "innkeeper":
return formatMessage({ id: "role.innkeeper.name" });
case "bard":
return formatMessage({ id: "role.bard.name" });
case "monk":
return formatMessage({ id: "role.monk.name" });
case "heremit":
return formatMessage({ id: "role.heremit.name" });
case "priest":
return formatMessage({ id: "role.priest.name" });
case "sinner":
return formatMessage({ id: "role.sinner.name" });
case "madman":
return formatMessage({ id: "role.madman.name" });
case "jester":
return formatMessage({ id: "role.jester.name" });
}
};
const formatDescription = (roleId: RoleId) => {
switch (roleId) {
case "primaryWolf":
return formatMessage({ id: "role.primaryWolf.description" });
case "secondaryWolf":
return formatMessage({ id: "role.secondaryWolf.description" });
case "youngWolf":
return formatMessage({ id: "role.youngWolf.description" });
case "traitor":
return formatMessage({ id: "role.traitor.description" });
case "seer":
return formatMessage({ id: "role.seer.description" });
case "wizard":
return formatMessage({ id: "role.wizard.description" });
case "medium":
return formatMessage({ id: "role.medium.description" });
case "witch":
return formatMessage({ id: "role.witch.description" });
case "healer":
return formatMessage({ id: "role.healer.description" });
case "farmer1":
return formatMessage({ id: "role.farmer.description" });
case "farmer2":
return formatMessage({ id: "role.farmer.description" });
case "innkeeper":
return formatMessage({ id: "role.innkeeper.description" });
case "bard":
return formatMessage({ id: "role.bard.description" });
case "monk":
return formatMessage({ id: "role.monk.description" });
case "heremit":
return formatMessage({ id: "role.heremit.description" });
case "priest":
return formatMessage({ id: "role.priest.description" });
case "sinner":
return formatMessage({ id: "role.sinner.description" });
case "madman":
return formatMessage({ id: "role.madman.description" });
case "jester":
return formatMessage({ id: "role.jester.description" });
}
};
return { formatName, formatDescription };
}
export function useFormatFaction(): (faction: Faction) => string {
const { formatMessage } = useIntl();
const formatFaction = (faction: Faction) => {
switch (faction) {
case "general":
return formatMessage({ id: "faction.general" });
case "wolf":
return formatMessage({ id: "faction.wolf" });
case "village":
return formatMessage({ id: "faction.village" });
}
};
return formatFaction;
}
|
a2079468f1e71b03dc736a47ebbe93362f35d518
|
TypeScript
|
matias96321/Next-Level-Week-Happy
|
/Web-Back-end/src/views/Orphanages-Views.ts
| 2.53125
| 3
|
import Orphanege from "../models/orphanages";
import imagesViews from './Images-Views'
export default {
Render(orphanages: Orphanege){
return({
id: orphanages.id,
name: orphanages.name,
latitude: orphanages.latitude,
longitude: orphanages.longitude,
about: orphanages.about,
instructions: orphanages.instructions,
opening_hours: orphanages.opening_hours,
open_on_weekends: orphanages.open_on_weekends,
images: imagesViews.RenderAll(orphanages.images)
})
},
RenderAll(orphanages: Orphanege[]){
return(orphanages.map(orphanage => this.Render(orphanage))
)
}
}
|
2bd2c2e0a33c0a063917aa3e61f17c65fd816c1b
|
TypeScript
|
romanzdarek/br
|
/server/src/loot/LootSnapshot.ts
| 3
| 3
|
import LootItem from './LootItem';
import { LootType } from './LootType';
export default class LootSnapshot {
//id
readonly i: number;
x: number;
y: number;
size: number;
type: number;
del?: number;
quantity?: number;
constructor(loot: LootItem) {
//1 = zero digit after the comma
//10 = one digit after the comma
//100 = two digits after the comma
const afterComma = 10;
this.x = Math.round(loot.getX() * afterComma) / afterComma;
this.y = Math.round(loot.getY() * afterComma) / afterComma;
this.i = loot.id;
this.size = loot.size;
this.type = loot.type;
if (!loot.isActive()) this.del = 1;
if (
loot.type === LootType.OrangeAmmo ||
loot.type === LootType.RedAmmo ||
loot.type === LootType.BlueAmmo ||
loot.type === LootType.GreenAmmo ||
loot.type === LootType.Grenade ||
loot.type === LootType.Smoke
) {
this.quantity = loot.quantity;
}
}
}
|
222864a8dd34bf76056e60c79275a277ccfcc1f9
|
TypeScript
|
srinathnms/Test
|
/src/app/onboarding/course-details/model/courseDetail.ts
| 2.734375
| 3
|
export interface ICourseDetail {
id:string,
title:string,
code: string,
url:string,
description:string,
courseType:string,
documentType:string
}
export class CourseDetail implements ICourseDetail {
constructor(
public id: string,
public title: string,
public code: string,
public url: string,
public description: string,
public courseType: string,
public documentType: string) {
}
}
export interface ICourseResponse {
courseDetail:ICourseDetail[],
count: number
}
export class CourseResponse implements ICourseResponse {
constructor(
public courseDetail:ICourseDetail[],
public count: number) {
}
}
|
0cfc6b50cfe32eec73c9e3613c4c6a18a277de7f
|
TypeScript
|
DevExpress/testcafe
|
/src/client/core/barriers/emitters/client-request.ts
| 2.6875
| 3
|
import hammerhead from '../../deps/hammerhead';
import EventEmitter from '../../utils/event-emitter';
import { ClientRequestEmitter } from '../../../../shared/types';
interface XhrEvent { xhr: XMLHttpRequest }
type ClientRequestType = XMLHttpRequest | Promise<Response>;
type ClientRequestEventListener = (req: ClientRequestType) => void;
const REQUEST_SEND_EVENT = 'request-send';
const REQUEST_COMPLETED_EVENT = 'request-completed';
const REQUEST_ERROR_EVENT = 'request-error';
export default class HammerheadClientRequestEmitter extends EventEmitter implements ClientRequestEmitter<ClientRequestType> {
private readonly _hammerheadListenersInfo: { evt: string; listener: (...args: any[]) => void }[];
public constructor () {
super();
this._hammerheadListenersInfo = [];
this._addHammerheadListener(hammerhead.EVENTS.beforeXhrSend, ({ xhr }: XhrEvent) => this.emit(REQUEST_SEND_EVENT, xhr));
this._addHammerheadListener(hammerhead.EVENTS.xhrCompleted, ({ xhr }: XhrEvent) => this.emit(REQUEST_COMPLETED_EVENT, xhr));
this._addHammerheadListener(hammerhead.EVENTS.xhrError, ({ xhr }: XhrEvent) => this.emit(REQUEST_ERROR_EVENT, xhr));
this._addHammerheadListener(hammerhead.EVENTS.fetchSent, (fetch: Promise<Response>) => {
this.emit(REQUEST_SEND_EVENT, fetch);
fetch.then(() => this.emit(REQUEST_COMPLETED_EVENT, fetch), () => this.emit(REQUEST_ERROR_EVENT, fetch));
});
}
private _addHammerheadListener (evt: string, listener: (...args: any[]) => void): void {
hammerhead.on(evt, listener);
this._hammerheadListenersInfo.push({ evt, listener });
}
public onRequestSend (listener: ClientRequestEventListener): void {
this.on(REQUEST_SEND_EVENT, listener);
}
public onRequestCompleted (listener: ClientRequestEventListener): void {
this.on(REQUEST_COMPLETED_EVENT, listener);
}
public onRequestError (listener: ClientRequestEventListener): void {
this.on(REQUEST_ERROR_EVENT, listener);
}
public offAll (): void {
super.offAll();
for (const info of this._hammerheadListenersInfo)
hammerhead.off.call(hammerhead, info.evt, info.listener);
}
}
|
8091d76af1c6f8cc786f2700e78e79ffe34033f7
|
TypeScript
|
schwartzmj/advent-of-code
|
/2020/day5/index.ts
| 3.140625
| 3
|
import * as fs from 'fs'
const BOARDING_PASSES = fs.readFileSync('./day5/boarding-passes', 'utf-8')
.split('\n')
const getNextNumberRow = (min, max, input, idx = 0) => { // F or B (0 - 127)
if (idx > input.length - 1) throw new Error("Went over length of input")
const char = input[idx]
let newMin
let newMax
const rawPivot = (max + min) / 2
if (char === 'F') { // get lower half (127 / 2 = 63.5, so this would be '63' as a new maximum (0-63, inclusive))
newMax = Math.floor(rawPivot);
newMin = min
}
if (char === 'B') { // get upper half (127 / 2 = 63.5, so this would be '64' as a new minimum (64-127, inclusive))
newMax = max
newMin = Math.ceil(rawPivot);
}
if (newMax - newMin === 1) {
const newChar = input[idx+1]
if (newChar === 'F') {
return newMin
} else if (newChar === 'B') {
return newMax
} else {
console.warn('Min, Max, newChar, Idx, Input: ', min, max, newChar, idx, input)
throw new Error('Current character not a B or F!')
}
}
return getNextNumberRow(newMin, newMax, input, idx + 1)
}
const getNextNumberColumn = (min, max, input, idx = 0) => { // R or L (0 - 7)
if (idx > input.length - 1) throw new Error(`Went over length of input: ${min} ${max} ${idx}`)
const char = input[idx]
let newMin
let newMax
const rawPivot = (max + min) / 2
if (char === 'L') { // get lower half (7 / 2 = 3.5, so this would be '3' as a new maximum (0-3, inclusive))
newMax = Math.floor(rawPivot);
newMin = min
}
if (char === 'R') { // get upper half (7 / 2 = 3.5, so this would be '4' as a new minimum (3-7, inclusive))
newMax = max
newMin = Math.ceil(rawPivot);
}
if (newMax - newMin === 1) {
const newChar = input[idx+1]
if (newChar === 'L') {
return newMin
} else if (newChar === 'R') {
return newMax
} else {
console.warn('Min, Max, newChar, Idx, Input: ', min, max, newChar, idx, input)
throw new Error('Current character not a L or R!')
}
}
return getNextNumberColumn(newMin, newMax, input, idx + 1)
}
const getRowColStrings = (boardingPass) => {
return [boardingPass.slice(0, 7), boardingPass.slice(7)]
}
const boardingPassesByRowCol = BOARDING_PASSES.map(bp => {
const [rowStr, colStr] = getRowColStrings(bp)
const rowNumber = getNextNumberRow(0, 127, rowStr)
const colNumber = getNextNumberColumn(0, 7, colStr)
return [rowNumber, colNumber, rowStr, colStr]
})
const seatIds = boardingPassesByRowCol.map(bp => {
return bp[0] * 8 + bp[1]
// return{ id: bp[0] * 8 + bp[1], row: bp[0], col: bp[1], rowStr: bp[2], colStr: bp[3]}
})
// const sortedSeatIds = seatIds.sort((a,b) => a.id-b.id)
const sortedSeatIds = seatIds.sort((a,b) => a-b)
// console.log(sortedSeatIds)
sortedSeatIds.forEach((seatId, idx) => {
if (idx === sortedSeatIds.length - 1) return
if (sortedSeatIds[idx + 1] !== seatId + 1) console.log('Your seat ID is: ', seatId + 1)
})
|
bdb3d666934804a50a96dc5244a187a67d67717c
|
TypeScript
|
piusprince/devkamet
|
/api/middlewares/validationChecklist.ts
| 2.8125
| 3
|
import { check, body } from "express-validator";
export const signIn = [
check("email", "Email is not valid")
.isEmail()
.normalizeEmail()
.trim()
.escape(),
check("password", "Password is not valid")
.not()
.isEmpty({ ignore_whitespace: true })
.isLength({ min: 7 }),
];
export const signUp = [
check("name", "Name is required")
.not()
.isEmpty({ ignore_whitespace: true })
.trim()
.escape(),
body("email", "Email is not valid")
.isEmail()
.normalizeEmail()
.trim()
.escape(),
body("password")
.matches(".*[0-9].*")
.withMessage("Your password should have at least one number")
.matches(/[!@#$%^&*(),.?":{}|<>]/)
.withMessage("Your password should have at least one sepcial character")
.isLength({ min: 8, max: 15 })
.withMessage("Your password should have min and max length between 8-15"),
body("confirmPassword", "Passwords must be equal").custom(
(value, { req }) => value === req.body.password
),
check("confirmPassword", "Confirm Password is not valid").isLength({
min: 8,
max: 15,
}),
];
// FIXME: Not finished
export const job = [
check("language", "language is not valid").isString(),
check("password", "Password is not valid")
.not()
.isEmpty({ ignore_whitespace: true })
.isLength({ min: 7 }),
];
// FIXME: Not finished
export const manageCourse = [
check("title", "Title is not valie").not().isEmpty().trim().escape(),
check("description", "Description is not valid")
.not()
.isEmpty({ ignore_whitespace: true })
.trim()
.escape(),
];
|