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 |
|---|---|---|---|---|---|---|
4384877ba35bcdf76d1b687bed19db9ffb529f66 | TypeScript | Pasakinskas/book-app | /src/services/bookService.ts | 2.84375 | 3 | import { BookModel, Book } from "../models/bookModel";
export class BookService {
async getAllBooks(limit: number = 0, skip: number = 0): Promise<Book[]> {
return BookModel.find()
.limit(limit)
.skip(skip)
}
async getBookById(id: string) {
const book = await BookModel.findById(id);
if (book) {
return book;
} else {
throw new Error("No book with such id");
}
}
createBookFromValues(name: string, author: string, pages: number) {
const bookModel: Book = new BookModel({
name,
author,
pages
});
bookModel.validate();
return bookModel.save();
}
createBook(book: Book): Promise<Book> {
const bookModel: Book = new BookModel({
name: book.name,
author: book.author,
pages: book.pages
});
bookModel.validate();
return bookModel.save();
}
async deleteBook(id: string): Promise<Book> {
const Book = await BookModel.findByIdAndDelete(id);
if (Book) {
return Book;
} else {
throw new Error("No such book");
}
}
} |
9926f96fbce2329a5f18a810b10415e75c3e8678 | TypeScript | michal93cz/NativeTalk-webClient | /src/app/services/notice.service.ts | 2.515625 | 3 | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Notice } from '../models/notice';
@Injectable()
export class NoticeService {
private headers = new Headers({'Authorization': 'Bearer EAAF0TQETtIUBAKXf7vgsjdBTgwu8wbKXvRoKzOZCqBkeribZBF2rG6MY6REYFZBq2ChctZAomDSFMOKdDT5MeLatgupu96f6Cb9yQ5W2ATRchN7wfekaxaQ2WT6V9MzK14m1LYbZByvXLEiK7I73MQKkibGhUa6RQbp6SZBKPD1AZDZD',
'Content-Type': 'application/json'
});
private noticesUrl = 'api/notices'; // URL to web api
constructor(private http: Http) { }
getNotices(type: string, language?: string, city?: string): Promise<Notice[]> {
let url = this.noticesUrl + `?type=${type}&language=${language}&city=${city}`;
return this.http.get(url, {headers: this.headers})
.toPromise()
.then(response => response.json() as Notice[])
.catch(this.handleError);
}
create(notice: Notice): Promise<{}> {
return this.http
.post(this.noticesUrl, JSON.stringify(notice), {headers: this.headers})
.toPromise()
.then(res => res)
.catch(this.handleError);
}
getMyNotices(): Promise<Notice[]> {
let url = this.noticesUrl + `/my`;
return this.http.get(url, {headers: this.headers})
.toPromise()
.then(response => response.json() as Notice[])
.catch(this.handleError);
}
getMyApplies(): Promise<Notice[]> {
let url = this.noticesUrl + `/myapplies`;
return this.http.get(url, {headers: this.headers})
.toPromise()
.then(response => response.json() as Notice[])
.catch(this.handleError);
}
delete(id: string): Promise<void> {
const url = `${this.noticesUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
apply(id: string): Promise<void> {
const url = `${this.noticesUrl}/${id}/apply`;
return this.http.get(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
|
214f10bc93f316ae7de819a33779b075dd74548d | TypeScript | youzan/zent | /packages/zent/src/utils/isPromise.ts | 3.53125 | 4 | /**
* Test whether an object looks like a promise
*
* @export
* @param {any} obj
* @returns {bool}
*/
export default function isPromise<T = unknown>(obj: any): obj is Promise<T> {
return (
!!obj &&
(typeof obj === 'object' || typeof obj === 'function') &&
typeof obj.then === 'function'
);
}
|
24b333dd19e46e229297007cb3b0a92e44a25a51 | TypeScript | suarezgary/ng4-table | /src/pipes/sorting-table.pipe.ts | 3.109375 | 3 | import { Pipe, PipeTransform } from '@angular/core';
/*
* Sort Table for Parameter and Way
* Takes two argument, the parameter to sort and the way (1 (asc) or -1 (desc))
* Usage:
* ObjectArray | sortingTable:init:fin
* Example:
* {{ [{},{},{}] | sortingTable:"lastname":1}}
* result:
* [{},{}]
*/
@Pipe({name: 'sortingTable'})
export class SortingTablePipe implements PipeTransform {
transform(dataArray: any[], param: string, way: string ): any[] {
debugger;
if(!param)
return dataArray;
if(!way)
way = "1";
dataArray.sort(function(a, b){
if(a[param] < b[param]) return (-1 * parseInt(way));
if(a[param] > b[param]) return (1 * parseInt(way));
return 0;
});
return dataArray;
}
} |
71e0bc21cf0c4e631bb7651411ff238becc3dd94 | TypeScript | Vizzuality/marxan-cloud | /api/apps/api/src/modules/specification/application/specification-input.ts | 2.515625 | 3 | import { SpecificationOperation } from '@marxan/specification';
import {
Equals,
IsArray,
IsBoolean,
IsDefined,
IsNumber,
IsOptional,
IsString,
IsUUID,
ValidateNested,
} from 'class-validator';
import {
FeatureConfigCopy,
FeatureConfigSplit,
FeatureConfigStratification,
} from '../domain';
export class SpecificationInput {
@IsUUID()
@IsDefined()
scenarioId!: string;
@IsBoolean()
@IsDefined()
draft!: boolean;
@IsDefined()
raw!: Record<string, unknown>;
@IsDefined()
@IsArray()
@ValidateNested()
features!: (
| SpecificationFeatureCopy
| SpecificationFeatureSplit
| SpecificationFeatureStratification
)[];
}
export class SpecificationFeatureCopy implements FeatureConfigCopy {
@Equals(SpecificationOperation.Copy)
@IsDefined()
operation: SpecificationOperation.Copy = SpecificationOperation.Copy;
@IsUUID()
@IsDefined()
baseFeatureId!: string;
selectSubSets!: never;
@IsNumber()
@IsOptional()
target?: number;
@IsNumber()
@IsOptional()
fpf?: number;
@IsNumber()
@IsOptional()
prop?: number;
}
export class SpecificationFeatureSplit implements FeatureConfigSplit {
@Equals(SpecificationOperation.Split)
@IsDefined()
operation: SpecificationOperation.Split = SpecificationOperation.Split;
@IsUUID()
@IsDefined()
baseFeatureId!: string;
@IsString()
@IsDefined()
splitByProperty!: string;
@IsArray({ each: true })
@IsOptional()
selectSubSets?: FeatureSubSet[];
@IsNumber()
@IsOptional()
target?: number;
@IsNumber()
@IsOptional()
fpf?: number;
@IsNumber()
@IsOptional()
prop?: number;
}
export class SpecificationFeatureStratification
implements FeatureConfigStratification {
@Equals(SpecificationOperation.Stratification)
operation: SpecificationOperation.Stratification =
SpecificationOperation.Stratification;
@IsUUID()
@IsDefined()
baseFeatureId!: string;
@IsUUID()
@IsDefined()
againstFeatureId!: string;
@IsString()
@IsOptional()
splitByProperty?: string;
@IsArray({ each: true })
@IsOptional()
selectSubSets?: FeatureSubSet[];
@IsNumber()
@IsOptional()
target?: number;
@IsNumber()
@IsOptional()
fpf?: number;
@IsNumber()
@IsOptional()
prop?: number;
}
export class FeatureSubSet {
@IsString()
@IsDefined()
value!: string;
@IsNumber()
@IsOptional()
target?: number;
@IsNumber()
@IsOptional()
fpf?: number;
@IsNumber()
@IsOptional()
prop?: number;
}
|
4204ed9193b7e15f0db908de1bd69d07b9915699 | TypeScript | kleva-j/react-use | /tests/useUpsert.test.ts | 3.125 | 3 | import { act, renderHook } from '@testing-library/react-hooks';
import useUpsert from '../src/useUpsert';
interface TestItem {
id: string;
text: string;
}
const testItems: TestItem[] = [
{ id: '1', text: '1' },
{ id: '2', text: '2' },
];
const itemsAreEqual = (a: TestItem, b: TestItem) => {
return a.id === b.id;
};
const setUp = (initialList: TestItem[] = []) =>
renderHook(() => useUpsert<TestItem>(itemsAreEqual, initialList));
describe('useUpsert', () => {
describe('initialization', () => {
const { result } = setUp(testItems);
const [list, utils] = result.current;
it('properly initiates the list content', () => {
expect(list).toEqual(testItems);
});
it('returns an upsert function', () => {
expect(utils.upsert).toBeInstanceOf(Function);
});
});
describe('upserting a new item', () => {
const { result } = setUp(testItems);
const [, utils] = result.current;
const newItem: TestItem = {
id: '3',
text: '3',
};
act(() => {
utils.upsert(newItem);
});
it('inserts a new item', () => {
expect(result.current[0]).toContain(newItem);
});
it('works immutably', () => {
expect(result.current[0]).not.toBe(testItems);
});
});
describe('upserting an existing item', () => {
const { result } = setUp(testItems);
const [, utils] = result.current;
const newItem: TestItem = {
id: '2',
text: '4',
};
act(() => {
utils.upsert(newItem);
});
const updatedList = result.current[0];
it('has the same length', () => {
expect(updatedList).toHaveLength(testItems.length);
});
it('updates the item', () => {
expect(updatedList).toContain(newItem);
});
it('works immutably', () => {
expect(updatedList).not.toBe(testItems);
});
});
});
|
58163f6cb3e5d95952a00db904b916f58cc88ba4 | TypeScript | bensw/DefinitelyTyped | /transducers-js/transducers-js-tests.ts | 3.5625 | 4 | // tests taken from https://github.com/cognitect-labs/transducers-js
import * as t from 'transducers-js';
import * as _ from "lodash";
var map = t.map,
filter = t.filter,
comp = t.comp,
into = t.into;
// basic usage
function inc(n: number) { return n + 1; };
function isEven(n: number) { return n % 2 === 0; };
var xf = comp(map(inc), filter(isEven));
console.log(into([], xf, [0, 1, 2, 3, 4])); // [2, 4]
// integration
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
apush = (arr: number[], x: number) => { arr.push(x); return arr; },
xf = comp(map(inc), filter(isEven)),
toFn = t.toFn;
arr.reduce(toFn(xf, apush), []); // native
_(arr).reduce(toFn(xf, apush), []); // underscore or lodash
// immutable-js
import * as Immutable from 'immutable';
function sum(a: number, b: number): number { return a + b; };
var transduce = t.transduce;
var largeVector = Immutable.List();
for (var i = 0; i < 1000000; i++) {
largeVector = largeVector.push(i);
}
// built in Immutable-js functionality
largeVector.map(inc).filter(isEven).reduce(sum);
// faster with transducers
var xf = comp(map(inc), filter(isEven));
transduce(xf, sum, 0, largeVector);
// source examples
function mapExample() {
var xf = t.map(inc);
t.into([], xf, [1, 2, 3]); // [2, 3, 4]
}
function filterExample() {
var xf = t.filter(isEven);
t.into([], xf, [0, 1, 2, 3, 4]); // [0, 2, 4];
}
function removeExample() {
var xf = t.remove(isEven);
t.into([], xf, [0, 1, 2, 3, 4]); // [1, 3];
}
function complementExample() {
var isOdd = t.complement(isEven);
}
function keepIndexedExample() {
var xf = t.keepIndexed((i: number, x: string|number) => { if (typeof x === "string") return "cool"; });
t.into([], xf, [0, 1, "foo", 3, 4, "bar"]); // ["foo", "bar"]
}
function takeExample() {
var xf = t.take(3);
t.into([], xf, [0, 1, 2, 3, 4, 5]); // [0, 1, 2];
}
function takeWhileExample() {
var xf = t.takeWhile(n => n < 3);
t.into([], xf, [0, 1, 2, 3, 4, 5]); // [0, 1, 2];
}
function intoExample() {
var xf = t.comp(t.map(inc), t.filter(isEven));
t.into([], xf, [1, 2, 3, 4]); // [2, 4]
}
function toFnExample() {
var arr = [0, 1, 2, 3, 4, 5];
var xf = t.comp(t.map(inc), t.filter(isEven));
arr.reduce(t.toFn(xf, apush), []); // [2, 4, 6]
}
function takeNthExample() {
var xf = t.takeNth(3);
t.into([], xf, [0, 1, 2, 3, 4, 5]); // [2, 5];
}
function dropExample() {
var xf = t.drop(3);
t.into([], xf, [0, 1, 2, 3, 4, 5]); // [3, 4, 5];
}
function dropWhileExample() {
var xf = t.dropWhile(n => n < 3);
t.into([], xf, [0, 1, 2, 3, 4, 5]); // [3, 4, 5];
}
function partitionByExample() {
var xf = t.partitionBy((x: string|number) => typeof x === "string");
t.into([], xf, [0, 1, "foo", "bar", 2, 3, "bar", "baz"]); // [[0, 1], ["foo", "bar"], [2, 3], ["bar", "baz"]];
}
function partitionAllExample() {
var xf = t.partitionAll(3);
t.into([], xf, [0, 1, 2, 3, 4, 5]); // [[0, 1, 2], [3, 4, 5]]
}
function wrapExample() {
var arrayPush = t.wrap((arr: number[], x: number) => { arr.push(x); return arr; });
}
function ensureReducedExample() {
var x = t.ensureReduced(1);
var y = t.ensureReduced(x);
x === y; // true
}
function unreducedExample() {
var x = t.reduced(1);
t.unreduced(x); // 1
t.unreduced(t.unreduced(x)); // 1
}
function reverse(arr: number[]) {
var arr: number[] = Array.prototype.slice.call(arr, 0);
arr.reverse();
return arr;
}
function catExample() {
var xf = t.comp(t.map(reverse), t.cat);
t.into([], xf, [[3, 2, 1], [6, 5, 4]]); // [1, 2, 3, 4, 5, 6]
}
function mapcatExample() {
var xf = t.mapcat(reverse);
t.into([], xf, [[3, 2, 1], [6, 5, 4]]); // [1, 2, 3, 4, 5, 6]
}
|
5369ca1802a3cfe7af890cce65eb2c1ace030bd6 | TypeScript | zulqar-abbas/nuces-circle | /src/app/services/reddit-api.service.ts | 2.765625 | 3 | import { Injectable } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
/**
* RedditApiService handles function calls to the API.
*
* @export
* @class RedditApiService
*/
@Injectable({
providedIn: 'root'
})
export class RedditApiService {
constructor(private http: HttpClient) { }
/**
* Handles http errors.
*
* @private
* @param {HttpErrorResponse} error
* @returns an observable with a user-facing error message.
* @memberof RedditApiService
*/
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// Return an observable with a user-facing error message.
return throwError('Something bad happened; please try again later.');
};
/**
* Get data from response.
*
* @private
* @param {Response} res - the http response,
* @returns a string reponse.
* @memberof RedditApiService
*/
private extractData(res: Response) {
let body = res;
return body || {};
}
/**
* Get all posts.
*
* @returns {Observable<any>}
* @memberof RedditApiService
*/
getPosts(): Observable<any> {
return this.http.get("/api/redditapi/all", httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
/**
* Get post by ID.
*
* @param {string} id - the post id.
* @returns {Observable<any>}
* @memberof RedditApiService
*/
getPost(id: string): Observable<any> {
const url = `${"/api/redditapi/all"}/${id}`;
return this.http.get(url, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
/**
* Get all funny/entertaining posts.
*
* @returns {Observable<any>}
* @memberof RedditApiService
*/
getPostsPF(): Observable<any> {
return this.http.get("/api/redditapi/pf", httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
/**
* Get all news/information posts.
*
* @returns {Observable<any>}
* @memberof RedditApiService
*/
getPostsNews(): Observable<any> {
return this.http.get("/api/redditapi/news", httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
/**
* Get all users posts.
*
* @returns {Observable<any>}
* @memberof RedditApiService
*/
getPostsUser(): Observable<any> {
return this.http.get("/api/redditapi/userpost", httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
/**
* Get recent posts made by a user using username.
*
* @param {string} id - id of user.
* @returns {Observable<any>}
* @memberof RedditApiService
*/
getRecentPostsUser(id: string): Observable<any> {
const url = `${"/api/redditapi/allprofile"}/${id}`;
return this.http.get(url, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
/**
* Create a post using post details object.
*
* @param {*} data - the post data.
* @returns {Observable<any>}
* @memberof RedditApiService
*/
postCreate(data): Observable<any> {
return this.http.post("/api/redditapi/postall", data, httpOptions)
.pipe(
catchError(this.handleError)
);
}
/**
* Create user posts using post details object.
*
* @param {*} data - the post data.
* @returns {Observable<any>}
* @memberof RedditApiService
*/
postCreateUser(data): Observable<any> {
return this.http.post("/api/redditapi/postuser", data, httpOptions)
.pipe(
catchError(this.handleError)
);
}
/**
* Posts which have been saved by the user using username and post ID.
*
* @param {*} data - the post data.
* @returns {Observable<any>}
* @memberof RedditApiService
*/
postSave(data): Observable<any> {
return this.http.post("/api/savedPost/post", data, httpOptions)
.pipe(
catchError(this.handleError)
);
}
/**
* Post ID and username to see if an entry matches. If one is found the user is following given post.
*
* @param {string} id1 - users id.
* @param {string} id2 - users id.
* @returns {Observable<any>}
* @memberof RedditApiService
*/
getIsSaved(id1: string, id2: string): Observable<any> {
const url = `${"/api/savedpost/post"}/${id1}/${id2}`;
return this.http.get(url, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
/**
* Get saved posts.
*
* @param {string} id - users username.
* @returns {Observable<any>}
* @memberof RedditApiService
*/
getSaved(id: string): Observable<any> {
const url = `${"/api/savedpost/profile"}/${id}`;
return this.http.get(url, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
/**
* Unsubscribe a user from a post.
*
* @param {string} id1 - user id.
* @param {string} id2 - post id.
* @returns {Observable<any>}
* @memberof RedditApiService
*/
delUnSub(id1: string, id2: string): Observable<any> {
const url = `${"/api/savedpost/delete"}/${id1}/${id2}`;
return this.http.delete(url, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
} |
a223cf93a0b9622de148d1f8583e04be14d9853e | TypeScript | manish336514/AngularTrainingProject | /src/app/components/demo/demo.component.ts | 2.609375 | 3 | import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-demo",
templateUrl: "./demo.component.html",
styleUrls: ["./demo.component.css"]
})
export class DemoComponent implements OnInit {
message;
vegetables;
//or message:string
constructor() {}
ngOnInit() {
console.log("ngOnInit called...");
this.message = "Hello World";
this.vegetables = [
{ name: "Brinjal", price: 14 },
{ name: "Bottle Ground", price: 25 },
{ name: "Tomato", price: 15 },
{ name: "Patato", price: 25 }
];
}
bntClicked(event) {
// alert("The Button Was Clicked");
console.log(event);
}
deleteVeg(index: number) {
this.vegetables.splice(index, 1);
}
addVeg(name, price) {
console.log("veg", name, price);
var addvegitable = {
name: name,
price: price
};
console.log("addvegitable", addvegitable);
this.vegetables.push(addvegitable);
}
}
|
b84ff28480f8c4c42c04528b42abe3ad79d23add | TypeScript | adityamachiraju3/B200251-javascript | /typescript-demo2/datatypes-demo.ts | 3.328125 | 3 | let nums:number[] = [10,12,45,14,26,55,35,17,0,6];
nums.sort(numSort);
function numSort(a:number, b:number){
if(a>b){
return 1;
}else if(b>a){
return -1;
}else{
return 0;
}
}
console.log(nums); |
ffcb0f4f91a5d6c3979553532c8af49cd8d1fe94 | TypeScript | paulswartz/dotcom | /apps/site/assets/ts/helpers/fetch.ts | 3.28125 | 3 | export type fetchAction =
// @ts-ignore should add a generic here
| { type: "FETCH_COMPLETE"; payload: any } // eslint-disable-line
| { type: "FETCH_ERROR" }
| { type: "FETCH_STARTED" };
export interface State {
// @ts-ignore should add a generic
data: any | null; // eslint-disable-line
isLoading: boolean;
error: boolean;
}
export const reducer = (state: State, action: fetchAction): State => {
switch (action.type) {
case "FETCH_STARTED":
return { ...state, isLoading: true, error: false, data: null };
case "FETCH_COMPLETE":
return { ...state, data: action.payload, isLoading: false, error: false };
case "FETCH_ERROR":
return { ...state, error: true, isLoading: false };
default:
return state;
}
};
|
cf02c8095772549452799f9ba78cff720a41f6a0 | TypeScript | gongbaodd/algorithm_study | /src/btree/is_after_order.ts | 3.765625 | 4 | // 二元查找树,左节点<root<右节点
export function isAfterOrder(
arr: number[],
start: number,
end: number
): boolean {
const root = arr[end];
let i = start;
let j;
while (i < end) {
if (arr[i] > root) {
break;
}
i += 1;
}
j = i;
while (j < end) {
if (arr[j] < root) {
return false;
}
j += 1;
}
let leftIsAfterOrder = true;
let rightIsAfterOrder = true;
if (i > start) {
leftIsAfterOrder = isAfterOrder(arr, start, i - 1);
}
if (j < end) {
rightIsAfterOrder = isAfterOrder(arr, i, end);
}
return leftIsAfterOrder && rightIsAfterOrder;
}
|
597c7793cfffcf512c41f7d15abfdaef788852c2 | TypeScript | stonek4/hitmewithten | /hmwt_app/src/tester/tester.ts | 2.515625 | 3 | import { inject, LogManager } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { CssAnimator } from 'aurelia-animator-css';
import { Card } from '../card';
import { Trophies } from '../trophies/trophies';
import { Globals } from '../globals';
const logger = LogManager.getLogger('tester');
@inject(Router, CssAnimator, Trophies, Globals)
export class Tester {
/** The definition */
public definition: string;
/** The dom class of the definition */
private definition_element: string = ".tester-text";
/** The answer */
public answer: string = "";
/** The dom class of the answer */
private input_element: string = ".tester-input";
/** The set of cards */
public cards: Card[];
/** The index of the current card */
public index: number = 0;
/** The style of the progress bar */
public progressStyle: string = "width:0%";
/** The value of the progress bar */
public progressValue: string = "0";
/** Whether the cards should be flipped or not */
public flipped: boolean = false;
private router: Router;
private animator: CssAnimator;
private trophies: Trophies;
private globals: Globals;
public constructor(router: Router, animator: CssAnimator, trophies: Trophies, globals: Globals) {
logger.debug('constructing the tester class');
this.animator = animator;
this.trophies = trophies;
this.router = router;
this.globals = globals;
}
public activate(params, routeData) {
logger.debug('activating the tester class');
this.cards = routeData.settings;
// tslint:disable-next-line:no-null-keyword
if (this.cards === null || typeof this.cards.length === 'undefined') {
logger.debug('cards were detected on the route, adding them');
this.cards = JSON.parse(window.localStorage.getItem(<string>params.id + ".cards"));
}
// tslint:disable-next-line:no-null-keyword
if (this.cards === null || typeof this.cards.length === 'undefined') {
logger.warn('no cards detected, bailing out!');
this.done();
}
this.setDefinition();
}
public setDefinition() {
if (!this.flipped) {
this.definition = this.cards[this.index].definitions[0];
} else {
this.definition = this.cards[this.index].answers[0];
}
}
public getSolution() {
if (!this.flipped) {
return this.cards[this.index].answers[0];
} else {
return this.cards[this.index].definitions[0];
}
}
public attached() {
logger.debug('attaching the tester');
logger.debug('performing entrance animations');
(<HTMLElement>document.querySelector(this.input_element)).focus();
return this.globals.performEntranceAnimations('tester', 'slideInRight');
}
public submit() {
logger.debug('answer was submitted');
let actual = this.getSolution();
let inputted = this.answer;
if (inputted.toLocaleLowerCase() === actual.toLowerCase()) {
logger.debug('answer is correct');
this.trophies.updateCardsPassedTrophies(1);
this.definition = "<correct>" + this.getSolution() + "</correct>";
setTimeout(() => {
this.next().catch((reason) => {
console.error(reason);
});
}, 200);
} else {
logger.debug('answer is incorrect');
this.trophies.updateCardsFailedTrophies(1);
let marked = "";
const edit = this.calcDist(inputted.toLowerCase(), actual.toLowerCase());
logger.debug('edits made are: (none, substitute, insert, delete)');
logger.debug(edit.toString());
if (edit.length === 1) {
logger.debug('edit length is one, assuming insert');
edit[0] = "i";
}
for (let i = 0; i < edit.length; i++) {
if (edit[i] === "n") {
marked += actual[i];
} else {
if (edit[i] === "d") {
marked += "<em>-</em>";
actual = '-' + actual;
} else if (edit[i] === "i") {
inputted = inputted.slice(0, i) + actual[i] + inputted.slice(i);
if (inputted[i] === " ") {
marked += "<em> _ </em>";
} else {
marked += "<em>" + inputted[i] + "</em>";
}
} else if (edit[i] === "s") {
inputted = inputted.substr(0, i) + actual[i] + inputted.substr(i + 1, inputted.length);
if (inputted[i] === " ") {
marked += "<em> _ </em>";
} else {
marked += "<em>" + inputted[i] + "</em>";
}
}
}
}
logger.debug('displaying marked definition');
this.definition = marked;
this.animator.animate(document.querySelector(this.definition_element), 'shake')
.catch((reason) => {
console.error(reason);
});
}
(<HTMLElement>document.querySelector(this.input_element)).focus();
}
public flip() {
logger.debug('flipping cards over');
this.flipped = !this.flipped;
this.setDefinition();
}
public next() {
logger.debug('attempting to move to the next card');
this.index += 1;
this.trophies.updateCardsTestedTrophies(1);
this.trophies.displayNewTrophies();
this.updateProgress();
return this.globals.performExitAnimations('tester-text', 'slideOutLeft').then(() => {
if (this.index < this.cards.length) {
this.setDefinition();
this.answer = "";
return this.globals.performEntranceAnimations('tester-text', 'slideInRight');
} else {
logger.debug('reached last card in the list');
this.done();
}
});
}
public back() {
logger.debug('attempting to move back to the previous card');
if (this.index !== 0) {
this.index -= 1;
this.animator.animate(document.querySelector(this.definition_element), 'slideBack')
.catch((reason) => {
console.error(reason);
});
setTimeout(() => {
(<HTMLElement>document.querySelector(this.definition_element)).style.opacity = "0";
setTimeout(() => {
(<HTMLElement>document.querySelector(this.definition_element)).style.opacity = "1";
this.setDefinition();
this.answer = "";
}, 50);
}, 500);
(<HTMLElement>document.querySelector(this.input_element)).focus();
}
else {
logger.debug('there are no previous cards in the set, exiting');
this.done();
}
}
private updateProgress() {
logger.debug('updating the progress bar');
const progress = (this.index / this.cards.length) * 100;
this.progressStyle = "width:" + progress.toString() + "%";
this.progressValue = progress.toString();
return;
}
private calcDist(aword: string, bword: string) {
logger.debug('calculating the distance between ' + aword + ' and ' + bword);
const dist = new Array<Array<number>>(aword.length + 1);
const paths = new Array(aword.length + 1);
const edits = new Array(aword.length + 1);
for (let i = 0; i < dist.length; i++) {
dist[i] = new Array(bword.length + 1);
paths[i] = new Array(bword.length + 1);
edits[i] = new Array(bword.length + 1);
}
for (let i = 0; i < dist.length; i++) {
dist[i][0] = i;
paths[i][0] = [i - 1, 0];
edits[i][0] = "d";
}
for (let j = 0; j < dist[0].length; j++) {
dist[0][j] = j;
paths[0][j] = [0, j - 1];
edits[0][j] = "i";
}
let cost: number = 0;
for (let j = 1; j < dist[0].length; j++) {
for (let i = 1; i < dist.length; i++) {
if (aword[i - 1] === bword[j - 1]) {
cost = 0;
}
else {
cost = 1;
}
dist[i][j] = Math.min(dist[i - 1][j] + 1, dist[i][j - 1] + 1, dist[i - 1][j - 1] + cost);
if (dist[i][j] === dist[i - 1][j] + 1) {
paths[i][j] = [i - 1, j];
edits[i][j] = "d";
} else if (dist[i][j] === dist[i - 1][j - 1] + cost) {
paths[i][j] = [i - 1, j - 1];
edits[i][j] = "s";
} else {
paths[i][j] = [i, j - 1];
edits[i][j] = "i";
}
}
}
logger.debug('finished calculating the distances of all possible paths');
logger.debug('finding the shortest path');
const path = new Array();
const edit = new Array();
let coord = [aword.length, bword.length];
path.unshift(dist[coord[0]][coord[1]]);
let prev_coord = coord;
coord = paths[coord[0]][coord[1]];
while (coord[0] !== -1 && coord[1] !== -1) {
path.unshift(dist[coord[0]][coord[1]]);
if ( path[1] !== path[0] ) {
edit.unshift(edits[prev_coord[0]][prev_coord[1]]);
} else {
edit.unshift('n');
}
prev_coord = coord;
coord = paths[coord[0]][coord[1]];
}
return edit;
}
public done() {
logger.debug('exiting the tester');
logger.debug('performing exit animations');
this.globals.performExitAnimations('tester', 'slideOutRight').then(() => {
this.router.history.navigateBack();
}).catch(() => {
logger.error('An error occurred while navigating away');
this.router.navigateToRoute('Menu');
});
}
}
|
54a4fe89879ecf4b0f28d505ca398544e20636f3 | TypeScript | denniskempin/vscode-include-fixer | /src/extension.ts | 2.703125 | 3 | 'use strict';
import * as vscode from 'vscode';
import * as cp from 'child_process';
import * as path from 'path';
// clang-include-fixer output format (the bits that we use)
type HeaderInfo = {
QualifiedName: string,
Header: string
};
type CIFHeaders = {
HeaderInfos: HeaderInfo[];
}
// Call clang-include-fixer on the provided document with `params` extra params.
// This will pass the provided document into stdin of clang-include-fixer to
// ensure it's got the current unsaved version.
function callCIF(args: string[], document: vscode.TextDocument):
Promise<string> {
const config = vscode.workspace.getConfiguration(
'clang-include-fixer', document.uri);
const binary = config.get('binary') as string;
return new Promise((resolve, reject) => {
const full_args =
args.concat(['-stdin', path.basename(document.fileName)]);
const params = {cwd: path.dirname(document.fileName)};
let process =
cp.execFile(binary, full_args, params, (err, stdout, stderr) => {
if (err) {
// todo: Add 'not found' error message for windows as well.
const code = (err as any).code;
if (code === 'ENOENT') {
err.message = 'binary not found: ' + binary;
}
if (stderr) {
err.message += '\nSTDERR: ' + stderr;
}
reject(err);
return;
}
resolve(stdout);
});
process.stdin.write(document.getText());
process.stdin.end();
});
}
// Call clang-include-fixer to query possible headers for the `query` symbol.
async function queryPossibleHeaders(
query: string, document: vscode.TextDocument):
Promise<CIFHeaders> {
const headers_str = await callCIF(['-query-symbol', query], document);
return JSON.parse(headers_str) as CIFHeaders;
}
// Pass in a CIFHeaders object with a single header that should be included in
// the document. Will return a string of the entire new document.
function insertHeader(headers: CIFHeaders, document: vscode.TextDocument):
Promise<string> {
return callCIF(['-insert-header', JSON.stringify(headers)], document);
}
// Show quick pick view for user to select a header. Will remove all headers
// from the provided `headers` object to leave just the selected one.
async function askUserToSelectHeader(headers: CIFHeaders):
Promise<CIFHeaders|undefined> {
const items: vscode.QuickPickItem[] = [];
for (const info of headers.HeaderInfos) {
items.push({label: info.QualifiedName, description: info.Header});
}
const selected_item = await vscode.window.showQuickPick(items);
if (!selected_item) {
return undefined;
}
headers.HeaderInfos = headers.HeaderInfos.filter((info: any) => {
return info.Header === selected_item.description;
});
return headers;
}
async function insertIncludeForSymbol(
symbol: string, editor: vscode.TextEditor) {
const headers = await queryPossibleHeaders(symbol, editor.document);
const selected_header = await askUserToSelectHeader(headers);
if (!selected_header) {
return;
}
const position_before = editor.selection.active;
const line_count_before = editor.document.lineCount;
// Update document with content from clang-include-fixer
const updated_doc = await insertHeader(selected_header, editor.document);
await editor.edit((edit) => {
const whole_doc_range = editor.document.validateRange(
new vscode.Range(0, 0, line_count_before, 0));
edit.replace(whole_doc_range, updated_doc);
});
// Remove selection and move cursor down to previous approximate location.
const line_count_change = editor.document.lineCount - line_count_before;
const position_after =
position_before.with({line: position_before.line + line_count_change});
editor.selections = [new vscode.Selection(position_after, position_after)];
}
function getSelectedSymbol(editor: vscode.TextEditor):
string|undefined {
if (editor.selections.length > 1) {
vscode.window.showErrorMessage('Does not support multiple cursors.');
return undefined;
}
if (editor.selection.isEmpty) {
const range =
editor.document.getWordRangeAtPosition(editor.selection.active);
if (range) {
return editor.document.getText(range);
}
return undefined;
} else {
const range =
new vscode.Range(editor.selection.start, editor.selection.end);
return editor.document.getText(range);
}
}
export function activate(context: vscode.ExtensionContext) {
let disposable =
vscode.commands.registerCommand('extension.clangIncludeFixer', () => {
let editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const selected_symbol = getSelectedSymbol(editor);
if (!selected_symbol) {
return;
}
insertIncludeForSymbol(selected_symbol, editor).catch((error) => {
vscode.window.showErrorMessage(
'clang-include-fixer error: ' + error.message);
});
});
context.subscriptions.push(disposable);
}
export function
deactivate() {}
|
779fb50efa8dfa9c808ce8497e49cbaca332b6df | TypeScript | orliin/mathsteps | /lib/src/simplifyExpression/basicsSearch/index.ts | 3.0625 | 3 | /**
* Performs simpifications that are more basic and overaching like (...)^0 => 1
* These are always the first simplifications that are attempted.
* */
import { TreeSearch } from "../../TreeSearch";
import { rearrangeCoefficient } from "./rearrangeCoefficient";
import { convertMixedNumberToImproperFraction } from "./convertMixedNumberToImproperFraction";
import { reduceMultiplicationByZero } from "./reduceMultiplicationByZero";
import { reduceZeroDividedByAnything } from "./reduceZeroDividedByAnything";
import { reduceExponentByZero } from "./reduceExponentByZero";
import { removeExponentByOne } from "./removeExponentByOne";
import { removeExponentBaseOne } from "./removeExponentBaseOne";
import { simplifyDoubleUnaryMinus } from "./simplifyDoubleUnaryMinus";
import { removeAdditionOfZero } from "./removeAdditionOfZero";
import { removeMultiplicationByOne } from "./removeMultiplicationByOne";
import { removeMultiplicationByNegativeOne } from "./removeMultiplicationByNegativeOne";
import { removeDivisionByOne } from "./removeDivisionByOne";
import { NodeStatus } from "../../node/NodeStatus";
const SIMPLIFICATION_FUNCTIONS = [
// convert mixed numbers to improper fractions
convertMixedNumberToImproperFraction,
// multiplication by 0 yields 0
reduceMultiplicationByZero,
// division of 0 by something yields 0
reduceZeroDividedByAnything,
// ____^0 --> 1
reduceExponentByZero,
// Check for x^1 which should be reduced to x
removeExponentByOne,
// Check for 1^x which should be reduced to 1
// if x can be simplified to a constant
removeExponentBaseOne,
// - - becomes +
simplifyDoubleUnaryMinus,
// If this is a + node and one of the operands is 0, get rid of the 0
removeAdditionOfZero,
// If this is a * node and one of the operands is 1, get rid of the 1
removeMultiplicationByOne,
// In some cases, remove multiplying by -1
removeMultiplicationByNegativeOne,
// If this is a / node and the denominator is 1 or -1, get rid of it
removeDivisionByOne,
// e.g. x*5 -> 5x
rearrangeCoefficient,
];
export const basicsSearch = TreeSearch.preOrder(basics);
/**
* Look for basic step(s) to perform on a node. Returns a Status object.
* */
function basics(node) {
for (let i = 0; i < SIMPLIFICATION_FUNCTIONS.length; i++) {
const nodeStatus = SIMPLIFICATION_FUNCTIONS[i](node);
if (nodeStatus.hasChanged) {
return nodeStatus;
} else {
node = nodeStatus.newNode;
}
}
return NodeStatus.noChange(node);
}
|
7fdf060ba8e935d504936773b1fd86bedecfd02d | TypeScript | Jameskmonger/adventofcode | /src/2019/Day 8/imageDecoder.ts | 3.390625 | 3 | export interface ILayer {
bytes: number[];
}
export interface IImage {
width: number;
height: number;
layers: ILayer[];
}
export class ImageDecoder {
/**
* Constructs an instance of image decoder for a give strem
* @param imageStream image stream
* @param layerWidth layer width
* @param layerHeight layer height
*/
constructor(
public imageStream: string,
public layerWidth: number,
public layerHeight: number
) {}
/**
* return the imagerepresented by the raw stream passed to this instance constructor
*/
public getImage(): IImage {
const layers: ILayer[] = [];
const chunks =
this.imageStream.length / (this.layerWidth * this.layerHeight);
for (let chunk = 0; chunk < chunks; chunk++)
layers.push({
bytes: Array.from(
this.imageStream.slice(
chunk * this.layerWidth * this.layerHeight,
(chunk + 1) * this.layerWidth * this.layerHeight
)
).map(c => parseInt(c))
});
return {
width: this.layerWidth,
height: this.layerHeight,
layers
};
}
/**
* Returns an image with one layer composed with non-transparent bytes of the layers stack
* @param image Raw image
*/
public composeImage(image: IImage): IImage {
return {
width: this.layerWidth,
height: this.layerHeight,
layers: [
{
bytes: image.layers[0].bytes.map((byte, index) =>
byte != 2
? byte
: image.layers.find(l => l.bytes[index] != 2).bytes[index]
)
}
]
};
}
}
|
ce718e30e0400e18f0c08e1e8682c2d93e13b474 | TypeScript | mcnguyen/type-plus | /src/array/Concat.spec.ts | 2.953125 | 3 | import { Concat, Equal, isType } from '..'
test('concat array', () => {
type A = Concat<string[], boolean[]>
isType.t<Equal<Array<string | boolean>, A>>()
})
test('concat tuples', () => {
type A = Concat<[1, 2, 3], [4, 5]>
isType.t<Equal<[1, 2, 3, 4, 5], A>>()
})
test('concat array to tuple', () => {
type A = Concat<string[], [1, 2, 3]>
isType.t<Equal<Array<string | 1 | 2 | 3>, A>>()
})
test('concat tuple to array', () => {
type A = Concat<[1, 2, 3], string[]>
isType.t<Equal<[1, 2, 3, ...string[]], A>>()
})
|
69e10f4915b1eb73157b7f21cc960dfcda419a97 | TypeScript | codenamesimon/developers_day_slackbot | /src/slack.ts | 2.6875 | 3 | import * as https from 'https'
import * as querystring from 'querystring'
import { Secrets } from './secrets.js'
import { logger } from './logger.js';
/**
* Class for sending requests to slack
*/
export class Slack {
/**
* Sends application/json request to slack
* @param data Data to send in payload
* @param endpoint Endpoint on which to send the request
*/
public static async SendJsonApiRequest(data: any, endpoint: string, authKeyId: string): Promise<any> {
const postData = JSON.stringify(data);
const authKey = await Secrets.getSecret(authKeyId);
const requestOptions = {
host: "slack.com",
path: "/api/" + endpoint,
method: "POST",
headers: {
'Content-Type': "application/json; charset=utf-8",
'Content-Length': Buffer.byteLength(postData),
'Authorization': "Bearer " + authKey
}
};
return new Promise<any>((resolve, reject) => {
const postRequest = https.request(requestOptions, (response) => {
response.setEncoding('utf8');
let body = '';
response.on('data', (chunk) => {
body += chunk;
});
response.on('end', () => {
let jsonBody = '';
try {
jsonBody = JSON.parse(body);
}
catch (e) {
logger.error('Slack JSON API response parsing failed with error: ' + e, response);
reject(e);
return;
}
logger.info(`Slack API responded with a code ${response.statusCode}.`, jsonBody);
resolve(jsonBody);
});
});
postRequest.on('error', (e) => {
logger.error("Slack JSON API request failed with error: " + e);
reject(e);
});
postRequest.write(postData);
postRequest.end();
});
}
/**
* Sends message to slack by response url
* @param data Data to send in payload
* @param endpoint Endpoint on which to send the request
*/
public static async SendCommandToResponseUrl(data: any, responseUrl: string, authKeyId: string): Promise<any> {
const url = new URL(responseUrl);
const postData = JSON.stringify(data);
const authKey = await Secrets.getSecret(authKeyId);
const requestOptions = {
host: url.hostname,
path: url.pathname,
method: "POST",
headers: {
'Content-Type': "application/json; charset=utf-8",
'Content-Length': Buffer.byteLength(postData),
'Authorization': "Bearer " + authKey
}
};
return new Promise<any>((resolve, reject) => {
const postRequest = https.request(requestOptions, (response) => {
response.setEncoding('utf8');
let body = '';
response.on('data', (chunk) => {
body += chunk;
});
response.on('end', () => {
logger.info(`Slack API responded with a code ${response.statusCode}.`, body);
resolve(body);
});
});
postRequest.on('error', (e) => {
logger.error("Slack JSON API request failed with error: " + e);
reject(e);
});
postRequest.write(postData);
postRequest.end();
});
}
/**
* Sends message to slack by response url
* @param data Data to send in payload
* @param endpoint Endpoint on which to send the request
*/
public static async SendUrlEncoded(data: any, endpoint: string, authKeyId: string): Promise<any> {
const authKey = await Secrets.getSecret(authKeyId);
data.token = authKey;
const postData = querystring.stringify(data);
const requestOptions: https.RequestOptions = {
host: 'slack.com',
path: "/api/" + endpoint + "?" + postData,
method: "GET",
headers: {
'Content-Type': "application/x-www-form-urlencoded; charset=utf-8"
}
};
const responseBody = await new Promise<any>((resolve, reject) => {
const request = https.get(requestOptions, (response) => {
response.setEncoding('utf8');
let body = '';
response.on('data', (chunk) => {
body += chunk;
});
response.on('end', () => {
let jsonBody = null;
try {
jsonBody = JSON.parse(body);
}
catch (e) {
logger.error('Slack JSON API response parsing failed with error: ' + e, response);
reject(e);
return;
}
logger.info(`Slack API responded with a code ${response.statusCode}.`, jsonBody);
resolve(jsonBody);
});
});
request.on('error', (e) => {
logger.error("Slack JSON API request failed with error: " + e);
reject(e);
});
});
return responseBody;
}
} |
7befc0e1931600c8dfa57707149e7590e8419b14 | TypeScript | tiyodev/-Flights-API- | /src/api/v1/controllers/auth.controller.ts | 2.96875 | 3 | import { Request, Response } from 'express';
import { SeedUsers } from '../user/user.seed';
import { HttpStatus } from '../common/error/http_code';
import HttpError from '../common/error/http_error';
import Logger from '../logger/logger';
import { ErrorCode } from '../common/error/error_code';
import { myGenerateJwt } from '../common/tools/jwt.helper';
/**
* Sign in user
* @param {Request} req
* @param {Response} res
*/
export function signIn(req: Request, res: Response): void {
try {
// Get credentials
const { username, password } = req.body;
Logger.logDebug(`Login credentiels: username = ${username}, pwd = ${password?.padEnd(1, '*')}`);
// Find user by username and password
const findedUser = SeedUsers.find(x => x.password === password && x.username === username);
if (!findedUser) {
throw new HttpError(HttpStatus.UNAUTHORIZED, ErrorCode.BAD_CREDENTIALS, 'Bad login or password', {
username,
});
}
// Create a new token with the username in the payload and which expires 300 seconds after issue
const token = myGenerateJwt(findedUser);
Logger.logDebug(`Generated JWT token: ${token}`);
res.json({
status: 'success',
token,
});
} catch (err) {
Logger.logError(err);
if (err.status) {
res.status(err.status).json(err);
} else {
res.status(HttpStatus.INTERNAL_ERROR).json({
status: HttpStatus.INTERNAL_ERROR,
error: err.toString(),
});
}
}
}
|
01265444b80d094851447f5a1131d77d6d7d5c0a | TypeScript | ULL-ESIT-INF-DSI-2021/ull-esit-inf-dsi-20-21-prct07-menu-datamodel-grupo-k | /src/plates/dessert.ts | 2.828125 | 3 | import {Aliment} from "../aliment/aliment";
import {Plate} from "./plate";
/**
* Clase para representar un postre
*/
export class Dessert extends Plate {
/**
* Constructor de la clase Dessert
* @param name Nombre del postre
* @param ingredients Ingredientes del postre
*/
constructor(name: string,
ingredients: Map<Aliment, number>) {
super(name, ingredients);
}
}
|
bf52d8c47e2dc7b295d893c01964593a57af7394 | TypeScript | vetradar/dynadump | /src/export_all_tables.ts | 2.6875 | 3 | import { ExportTable } from './export_table';
export type ExportDynamoDBOptions = {
AWS: any;
ignore: string[];
path: string;
};
export class ExportDynamoDB {
_AWS: any;
_path: string;
_toIgnore: string[];
constructor(options: ExportDynamoDBOptions) {
this._AWS = options.AWS;
this._path = options.path || './export';
this._toIgnore = options.ignore || [];
}
async process() {
return this.exportAllTables();
}
async listTables(): Promise<string[]> {
const dynamodb = new this._AWS.DynamoDB();
const tables = await dynamodb.listTables().promise();
console.log('Found tables:', tables.TableNames);
console.log('Ignoring:', this._toIgnore);
return tables.TableNames;
}
async exportTable(tableName: string) {
const exportTable = new ExportTable({
tableName,
AWS: this._AWS,
path: this._path,
});
return exportTable.process();
}
async exportAllTables() {
const tables = await this.listTables();
const tablesFiltered = tables.filter((tableName) => !this._toIgnore.includes(tableName));
console.log('Exporting:', tablesFiltered);
for (const table of tablesFiltered) {
await this.exportTable(table);
console.log(`Exported ${table}`);
}
}
}
|
c4660a5b01851c0ab5dd267482ae50e797cfcbdb | TypeScript | Wellington19/nlw1-ecoleta | /frontend/src/components/Input/masks.ts | 2.6875 | 3 | export function maskCep(e: React.FormEvent<HTMLInputElement>) {
e.currentTarget.maxLength = 9;
let value = e.currentTarget.value;
value = value.replace(/\D/g, '');
value = value.replace(/^(\d{5})(\d)/, '$1-$2');
e.currentTarget.value = value;
return e;
}
export function maskPhone(e: React.FormEvent<HTMLInputElement>) {
let value = e.currentTarget.value;
let qtdeCaracter = value.length;
if (qtdeCaracter > 14) {
e.currentTarget.value = value.substring(0,14);
return e;
} else {
value = value.replace(/\D/g, '');
value = value.replace(/^(\d{2})(\d)/g, '($1)$2');
value = value.replace(/(\d)(\d{4})$/, '$1-$2');
e.currentTarget.value = value;
return e;
}
}
export function maskCurrency(e: React.FormEvent<HTMLInputElement>) {
let value = e.currentTarget.value;
value = value.replace(/\D/g, '');
value = value.replace(/(\d)(\d{2})$/, '$1,$2');
value = value.replace(/(?=(\d{3})+(\D))\B/g, '.');
e.currentTarget.value = value;
return e;
} |
297ac745d0b2adf341afd7c8658e504c0cc6b102 | TypeScript | thiagorm28/crud-gazin | /server/developers/middleware/developers.middleware.ts | 2.671875 | 3 | import express from 'express';
import developerService from '../services/developers.service';
class DevelopersMiddleware {
// Facilitando a extração do id do desenvolvedor
async extractDeveloperId(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
req.body.id = req.params.developerId;
next();
}
async validateDeveloperExists(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
const developer = await developerService.readById(req.params.developerId);
if (developer) {
next();
} else {
res.status(404).send({
error: `Developer ${req.params.developerId} not found`,
});
}
}
}
export default new DevelopersMiddleware(); |
e214cf743a98d8cbd50fc7e69187d64d5b528b66 | TypeScript | quantumsheep/reservation-avaibility-service | /src/api/reservations.api.ts | 2.703125 | 3 | import axios from 'axios'
import moment from 'moment'
import api from '../api'
const url = process.env.API_URL
export interface IReservation {
reservationStart: string
reservationEnd: string
}
export interface IReservations {
reservations?: IReservation[]
error?: string
}
export async function get(date: string, id: string): Promise<IReservations> {
const { data } = await axios.get(`${url}/reservations?date=${date}&resourceId=${id}`)
return data
}
export async function is_available(id: string, date: string, hour: number) {
const reservations = await api.reservations.get(date, id)
const timetables = await api.timetables.get(date, id)
if (reservations.error) {
throw new Error(reservations.error)
} else if (!reservations.reservations) {
throw new Error('An error occured.')
}
if (timetables.error) {
throw new Error(timetables.error)
} else if (!timetables.timetables) {
throw new Error('An error occured.')
}
let available = false
const selected = moment(`${date} ${hour}`, 'YYYY-MM-DD HH')
if (timetables.open) {
for (const timetable of timetables.timetables) {
const opening = moment(timetable.opening, 'YYYY-MM-DD HH::mm:ss')
const closing = moment(timetable.closing, 'YYYY-MM-DD HH::mm:ss')
if (selected >= opening && selected < closing) {
available = true
break;
}
}
for (const reservation of reservations.reservations) {
const reservationStart = moment(reservation.reservationStart, 'YYYY-MM-DD HH::mm:ss')
const reservationEnd = moment(reservation.reservationEnd, 'YYYY-MM-DD HH::mm:ss')
if (selected >= reservationStart && selected < reservationEnd) {
available = false
break;
}
}
}
return available
}
|
074402eccc463367295bf355e0f38449d00ca45f | TypeScript | PetarShopov/My-Organizer | /src/app/tasks/task.ts | 2.8125 | 3 | export interface ITask {
_id: string;
content: string;
}
export class Task implements ITask {
_id: string;
content: string;
constructor(
content: string,
) {
this.content = content;
}
}
|
eeb730c591c58f610dd1b38dd556f09e329f3fa4 | TypeScript | mohamedelgarnaoui/FleetManagementAngular | /src/app/services/auth.service.ts | 2.625 | 3 | import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable } from 'rxjs';
import {User} from '../model/user.model';
import {tap} from 'rxjs/operators';
export interface AuthResponseData {
accessToken: string;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
// subject: reactivly update the user interface
// BehaviorSubject: like subject but it gave immediate access
// to previous emitted values even we didn't subscribe at the point of time they was emitted
// it takes default value in params
user = new BehaviorSubject<User>(null);
constructor(private http: HttpClient) { }
signUp(emailUsr: string, passwordUsr: string): Observable<any> {
return this.http.post<AuthResponseData>('http://localhost:3000/register',
{
email: emailUsr,
password: passwordUsr
}).pipe(
// do some actions without changing the response
tap(resDat => {
this.handleAuthentication(emailUsr, resDat.accessToken);
}));
}
login(emailUsr: string, passwordUsr: string): Observable<any> {
return this.http.post<AuthResponseData>('http://localhost:3000/login',
{
email: emailUsr,
password: passwordUsr
}).pipe(
tap(resDat => {
this.handleAuthentication(emailUsr, resDat.accessToken);
}));
}
logout(): void {
this.user.next(null);
localStorage.removeItem('userData');
}
private handleAuthentication(email: string, token: string): void {
const usr = new User(email, token);
this.user.next(usr);
// convert the usr to string and store it to localStorage
localStorage.setItem('userData', JSON.stringify(usr));
}
autoLogin(): void {
// get the user from localStorage
const userData: User = JSON.parse(localStorage.getItem('userData'));
if (!userData) {
return;
}
this.user.next(userData);
}
}
|
76f9997b1cf35f3d99df23d122266f2ecc1f0c68 | TypeScript | rostgoat/ea-blog-api | /src/comment/comment.entity.ts | 2.578125 | 3 | import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
BeforeInsert,
JoinColumn,
} from 'typeorm'
import { Post } from '../post/post.entity'
import { User } from '../user/user.entity'
import { v4 as uuid } from 'uuid'
/**
* Comments Entity
*/
@Entity('comments')
export class Comment {
@PrimaryGeneratedColumn('uuid') comment_id: string
@Column({ type: 'varchar', nullable: false, unique: true }) uid: string
@Column('text') content: string
@ManyToOne(
type => Post,
post => post.comments,
)
@JoinColumn({ name: 'post_id' })
post: Post
@BeforeInsert() async createUID() {
this.uid = uuid()
}
}
|
4b150d145725e333cd66fdf5d28064634ecdfad1 | TypeScript | frandefreitas/nossaslojas2.0 | /entity/Loja.ts | 2.5625 | 3 | import {Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn} from "typeorm";
import {Cidade} from "./Cidade";
@Entity()
export class Loja{
@PrimaryGeneratedColumn()
id: number;
@Column()
endereco: string;
@Column()
telefone: string;
@Column()
cnpj: string;
@Column()
horario: string;
@ManyToOne(type => Cidade, idCidade => idCidade.id)
@JoinColumn({name: "idCidade"})
cidade: Cidade;
} |
f2055f5db8c138154f6960a03c7280631606901d | TypeScript | PradaZD/mooc_TS | /typescript/枚举.ts | 3 | 3 | //枚举
enum Status {
OFFLINE,
ONLINE,
DELETE,
}
// console.log(Status.OFFLINE);
// console.log(Status.ONLINE);
// console.log(Status.DELETE);
// const Status={
// OFFLINE:0,
// ONLINE:1,
// DELETE:2,
// }
|
b63568161ac16e8aadbe89f29c9d08e26af56bd3 | TypeScript | mitsuyoshi-yamazaki/AntOS | /src/v8/process/application_process/economy_process.ts | 2.5625 | 3 | import { Process, ProcessExecutionOrder, ProcessExecutionPriority, ProcessExecutionSpec, ProcessId, ProcessState } from "../process"
import { ProcessType, ProcessTypeConverter } from "../process_type"
import { Application } from "../application/application_process"
import { LaunchMessageObserver } from "../message_observer/launch_message_observer"
import { ArgumentParser } from "shared/utility/argument_parser/argument_parser"
import { OwnedRoomProcessRequest } from "../owned_room_process/owned_room_process_request"
import type { RoomName } from "shared/utility/room_name_types"
import { SemanticVersion } from "shared/utility/semantic_version"
import { PrimitiveLogger } from "v8/operating_system/primitive_logger"
const processType = "EconomyProcess"
export interface EconomyProcessState extends ProcessState {
}
export class EconomyProcess extends Process implements LaunchMessageObserver, Application {
public readonly applicationName: string = processType
public readonly version = new SemanticVersion(1, 0, 0)
public readonly processType = processType
// private ownedRoomProcesses: OwnedRoomProcess[] = []
private constructor(
) {
super()
PrimitiveLogger.info(`${this.applicationName} ${this.version}`)
}
public encode(): EconomyProcessState {
return {
t: ProcessTypeConverter.convert(this.processType),
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public static decode(state: EconomyProcessState): EconomyProcess {
return new EconomyProcess()
}
public decodeChildProcess(processType: ProcessType, state: ProcessState): Process | null {
switch (processType) {
// case "OwnedRoomProcess":
// return OwnedRoomProcess.decode(state as OwnedRoomProcessState)
default:
return null
}
}
public static create(): EconomyProcess {
return new EconomyProcess()
}
public shortDescription = (): string => {
return `${this.version}`
}
/** @throws */
public didReceiveLaunchMessage(processType: ProcessType, args: ArgumentParser): Process {
switch (processType) {
// case "OwnedRoomProcess": {
// const roomResource = args.list.ownedRoomResource(0, "room name").parse()
// const process = OwnedRoomProcess.create(roomResource)
// this.ownedRoomProcesses.push(process)
// return process
// }
default:
throw `${this.constructor.name} doesn't launch ${processType}`
}
}
public executionSpec(): ProcessExecutionSpec {
return {
executionPriority: ProcessExecutionPriority.high - 1,
executionOrder: ProcessExecutionOrder.normal,
interval: 1,
}
}
public load(processId: ProcessId): void {
// this.ownedRoomProcesses = []
// ProcessManager.getChildProcesses(processId).forEach(childProcess => {
// if (childProcess instanceof OwnedRoomProcess) {
// this.ownedRoomProcesses.push(childProcess)
// return
// }
// })
}
public run = (): void => {
// TODO: 部屋ごとの優先順位をつける(攻撃、防御、拡張、upgrade
const ownedRoomRequests = this.runOwnedRoomProcess()
// TODO: request処理
}
private runOwnedRoomProcess(): Map<RoomName, OwnedRoomProcessRequest> {
const requests = new Map<RoomName, OwnedRoomProcessRequest>()
// this.ownedRoomProcesses.forEach(ownedRoomProcess => {
// ownedRoomProcess.run = (processId: ProcessId): void => {
// const request: OwnedRoomProcessRequest = {}
// requests.set(ownedRoomProcess.roomName, request)
// ownedRoomProcess.runWith(processId, request)
// }
// })
return requests
}
}
|
63044ba517e6d071813c766f9d6b2dd290d9d7a9 | TypeScript | yoyo930021/vc2c | /src/plugins/vue-class-component/object/Prop.ts | 2.515625 | 3 | import { ASTConverter, ASTResultKind, ReferenceKind } from '../../types'
import type ts from 'typescript'
export const convertObjProps: ASTConverter<ts.PropertyAssignment> = (node, options) => {
if (node.name.getText() === 'props') {
const tsModule = options.typescript
const attributes = (tsModule.isArrayLiteralExpression(node.initializer))
? node.initializer.elements
.filter(expr => expr.kind === tsModule.SyntaxKind.StringLiteral)
.map((el) => (el as ts.StringLiteral).text)
: (node.initializer as ts.ObjectLiteralExpression).properties
.map((el) => el.name?.getText() ?? '')
const nodes = (tsModule.isArrayLiteralExpression(node.initializer))
? node.initializer.elements
.filter(expr => expr.kind === tsModule.SyntaxKind.StringLiteral)
.map((el) => tsModule.createPropertyAssignment((el as ts.StringLiteral).text, tsModule.createNull()))
: (node.initializer as ts.ObjectLiteralExpression).properties
.map((el) => el as ts.PropertyAssignment)
return {
tag: 'Prop',
kind: ASTResultKind.OBJECT,
reference: ReferenceKind.PROPS,
imports: [],
attributes,
nodes
}
}
return false
}
|
431432d151ad36c2f9dbd97f358895b86e7b0bc5 | TypeScript | Anapher/Drinctet | /web/src/core/parsing/card-parser-factory.ts | 2.71875 | 3 | import { CardParser } from "./card-parser";
/** a factory that creates the right parser for a card type */
export interface CardParserFactory {
createParser(cardType: string) : CardParser | undefined;
} |
4ee559c77b257c93d88e241e139f0b7ce0c78fc6 | TypeScript | Ta1265/tubesock | /server/index.ts | 2.671875 | 3 | /* eslint-disable @typescript-eslint/no-var-requires */
import axios from 'axios';
import express from 'express';
import bodyParser from 'body-parser';
import YouTubeGetID from './youTubeUrlParser';
require('dotenv').config();
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
interface Room {
cueVideoId: string;
users: Array<User>;
}
interface User {
userName: string;
id: string;
roomName: string;
}
interface roomMap {
[keyRoomName: string]: Room;
}
const roomMap: roomMap = {};
io.on('connection', (socket: any): void => {
const { id } = socket;
console.log('socketio connected id = ', id);
let user: User;
socket.on('join_room', ({ roomName, userName }: any): void => {
user = { userName, id, roomName };
socket.join(roomName);
console.log(`${userName}, has joined room - ${roomName}`);
if (roomMap[roomName]) {
roomMap[roomName].users.push(user);
socket.on('youtube-player-ready', () => {
io.in(roomName).emit('change-video-id', roomMap[roomName].cueVideoId); // send qued video to new user / reset everyone;
});
} else {
roomMap[roomName] = { cueVideoId: '', users: [user] };
}
const minusSelf = roomMap[roomName].users.filter((u) => u.id !== user.id);
if (minusSelf.length > 0) {
socket.emit('getuptospeed-list', minusSelf);
}
socket.to(roomName).emit('new-user-joined', user.id); // sends to all in room except the sender
io.in(roomName).emit(
'message',
`Server - ${user.userName} has joined room ${roomName}, total in room= ${roomMap[roomName].users.length}`,
);
});
socket.on('message', (msg: any) => {
const { userName, roomName } = user;
console.log(
`Room-${roomName}, userName-${userName} received message from client ->`,
msg,
);
io.in(roomName).emit('message', `${userName} says - ${msg}`);
});
socket.on('disconnect', (reason: any) => {
if (!user) {
console.log('visitor has disconnected before entering a room');
} else {
const { roomName, userName } = user;
const { users } = roomMap[roomName];
if (roomName) {
console.log(
`${userName}, id ${id} has disconnection from${roomName}, ${reason}`,
);
roomMap[roomName].users = users.filter((i) => i.id !== id);
io.in(roomName).emit('connection-count', roomMap[roomName].users.length);
io.in(roomName).emit(
'message',
`${userName} has disconnected from room ${roomName}`,
);
}
}
});
socket.on('peer_connection_relay', (message: any, toId: any) => {
const fromId = user.id;
console.log('fromid', fromId, 'toId', toId);
socket.to(toId).emit('peer_connection_relay', message, fromId); // (private message);
});
socket.on('youtube-sync', (message: any) => {
const { roomName } = user;
io.to(roomName).emit('youtube-sync', message); // emit to whole room to sync playback
});
socket.on('change-video-id', (message: string) => {
const { roomName } = user;
roomMap[roomName].cueVideoId = message;
io.to(roomName).emit('change-video-id', message); // emit to whole room to sync playback
});
socket.on('change-video-url', (message: any) => {
const { roomName } = user;
roomMap[roomName].cueVideoId = YouTubeGetID(message);
io.to(roomName).emit('change-video-id', roomMap[roomName].cueVideoId); // emit to whole room to sync playback
});
});
// const { PORT } = process.env;
const PORT = 3000;
app.use(bodyParser.json());
app.use(express.static('client/dist'));
app.get('/search-videos/:searchTerms', (req: any, res: any) => {
const { searchTerms } = req.params;
const { YOUTUBE_API_KEY } = process.env;
console.log(searchTerms);
axios({
method: 'get',
url: 'https://www.googleapis.com/youtube/v3/search',
params: {
part: 'snippet',
q: searchTerms,
maxResults: 5,
key: YOUTUBE_API_KEY,
type: 'video',
},
})
.then((results) => res.send(results.data.items))
.catch((err) => console.log(err.message));
});
server.listen(PORT, (err: Error) => {
if (err) return console.log('error starting express msg-', err.message);
return console.log('Express server listening on port-', PORT);
});
|
2c96acd3e44d8153f67586831b8acffc8c97147b | TypeScript | VictorNevola/next-project-student | /resources/cookies.ts | 2.71875 | 3 | import ms from 'ms';
export const setCookie = (nameCookies: string, valueCookie: string, expireDate: string) => {
const time = ms(expireDate) / 1000;
document.cookie = `${nameCookies}=${valueCookie}; max-age=${time}; path=/; Secure;`;
return true;
}
export const captureCookie = (nameCookie: string | undefined) => {
if(nameCookie) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${nameCookie}=`);
if (parts && parts.length === 2) return parts?.pop()?.split(';').shift();
}
} |
cd058a7916dbe1f5ad432367d0e4ac2c744d5175 | TypeScript | snakamura/mvc_rx | /7/mvc/index.ts | 3.296875 | 3 | class Model {
constructor(values: number[] = []) {
this._values = values;
}
get values() {
return [...this._values];
}
get sum() {
return this._values.reduce((sum, value) => sum + value, 0);
}
addValue(value: number): Model {
return new Model([...this._values, value]);
}
save(): string {
return JSON.stringify(this._values);
}
static load(values: string): Model {
return new Model(parseNumberArray(values));
}
private readonly _values: number[];
}
class Controller {
constructor(document: HTMLDocument) {
const $add = document.getElementById('add') as HTMLInputElement;
const $save = document.getElementById('save') as HTMLInputElement;
const $load = document.getElementById('load') as HTMLInputElement;
this._$value = document.getElementById('value') as HTMLInputElement;
this._$view = document.getElementById('view') as HTMLInputElement;
this._$sum = document.getElementById('sum') as HTMLInputElement;
$add.addEventListener('click', () => {
if (this._$value.value.length > 0) {
const v = Number(this._$value.value);
if (!isNaN(v)) {
this.updateModel(this._model.addValue(v));
}
}
});
$save.addEventListener('click', () => {
window.alert(this._model.save());
});
$load.addEventListener('click', () => {
const values = window.prompt('Load');
if (values != null) {
try {
this.updateModel(Model.load(values));
}
catch (e) {
window.alert(`Error: ${ e.message }`);
}
}
});
}
private updateModel(model: Model) {
this._model = model;
this._$view.innerText = model.values.join(', ');
this._$sum.innerText = model.sum.toString();
this._$value.value = '';
}
private _model = new Model();
private readonly _$value: HTMLInputElement;
private readonly _$view: HTMLInputElement;
private readonly _$sum: HTMLInputElement;
}
new Controller(document);
function parseNumberArray(string: string): number[] {
const json = JSON.parse(string);
if (!(json instanceof Array)) {
throw new Error('Not an array.');
}
if (!json.every(v => typeof v === 'number')) {
throw new Error('Not a number array.');
}
return json;
}
|
b756f14b5d8b6a2a6bb79f48815c764feec7a5c8 | TypeScript | dera-/houkai-sensou | /src/repository/model/GamePlayerRepository.ts | 2.96875 | 3 | import {GamePlayerModel} from "../../model/GamePlayerModel";
import {GamePlayerStateType} from "../../type/GamePlayerStateType";
import {GameTeamType} from "../../type/GameTeamType";
g.game.vars.players = {};
export const getPlayer = (playerId: string): GamePlayerModel|null => {
const player = g.game.vars.players[playerId];
return player != null && player instanceof GamePlayerModel ? player : null;
};
export const addPlayer = (model: GamePlayerModel): void => {
g.game.vars.players[model.id] = model;
};
export const deletePlayer = (playerId: string): void => {
delete g.game.vars.players[playerId];
};
export const getPlayerInField = (stageId: number, playerId: string): GamePlayerModel|null => {
const player = getPlayer(playerId);
return player != null && player.stageId === stageId && player.state === "play" ? player : null;
};
export const getSameTeamPlayersInField = (stageId: number, team: GameTeamType): GamePlayerModel[] => {
const players: GamePlayerModel[] = [];
Object.keys(g.game.vars.players).forEach(id => {
const player = g.game.vars.players[id];
if (player.team === team && player.stageId === stageId && player.state === "play") {
players.push(player);
}
});
return players;
};
export const addPlayersIntoStage = (stageId: number): void => {
Object.keys(g.game.vars.players).forEach(id => {
const player = g.game.vars.players[id];
if (player.stageId === stageId && player.state === "join") {
player.setState("play");
}
});
};
export const removePlayersFromStage = (stageId: number): void => {
Object.keys(g.game.vars.players).forEach(id => {
const player = g.game.vars.players[id];
if (player.stageId === stageId && player.state === "play") {
player.setState("none");
player.setStageId(null);
player.setTeam(null); // チーム登録削除はここでやるべきか
}
});
};
|
33c245194d4052f59340b822a373f81e9f84063f | TypeScript | DBotThePony/DBotTheDiscordBot | /lib/SteamID.ts | 2.71875 | 3 |
//
// Copyright (C) 2017 DBot
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import BigNumber = require('bignumber.js')
const SteamIDTo64 = function(id: string): [string, number] {
let server = 0
let AuthID = 0
let split = id.split(':')
server = Number(split[1])
AuthID = Number(split[2])
let Mult = AuthID * 2
let one = new BigNumber.BigNumber('76561197960265728')
let two = new BigNumber.BigNumber(Mult)
let three = new BigNumber.BigNumber(server)
return [one.plus(two).plus(three).toString(10), server]
}
const SteamIDFrom64 = function(id: string): [string, number] {
let newNum = new BigNumber.BigNumber(id)
let num = Number(newNum.minus(new BigNumber.BigNumber('76561197960265728')).toString(10))
let server = num % 2
num = num - server
return ['STEAM_0:' + server + ':' + (num / 2), server]
}
const SteamIDTo3 = function(id: string): [string, number] {
let server = 0
let AuthID = 0
let split = id.split(':')
server = Number(split[1])
AuthID = Number(split[2])
return ['[U:1:' + (AuthID * 2 + server) + ']', server]
}
const SteamIDFrom3 = function(id: string): [string, number] {
let sub = id.substr(1, id.length - 2)
let split = sub.split(':')
let uid = Number(split[2])
let server = uid % 2
uid = uid - server
return ['STEAM_0:' + server + ':' + (uid / 2), server]
}
const SteamIDFrom64To3 = function(id: string) {
const [steamid, server] = SteamIDFrom64(id)
return SteamIDTo3(steamid)
}
const SteamIDFrom3To64 = function(id: string) {
const [steamid, server] = SteamIDFrom3(id)
return SteamIDTo64(steamid)
}
class SteamID {
protected _steamid: string | null = null
protected _steamid3: string | null = null
protected _steamid64: string | null = null
protected _server: number | null = null
get server(): number | null { return this._server }
get steamid(): string | null { return this._steamid }
get steamid3(): string | null { return this._steamid3 }
get steamid64(): string | null { return this._steamid64 }
set steamid(steamidIn: string | null) {
if (steamidIn) {
this.setupSteamID(steamidIn)
} else {
this.reset()
}
}
set steamid3(steamidIn: string | null) {
if (steamidIn) {
this.setupSteamID3(steamidIn)
} else {
this.reset()
}
}
set steamid64(steamidIn: string | null) {
if (steamidIn) {
this.setupSteamID64(steamidIn)
} else {
this.reset()
}
}
reset () {
this._server = null
this._steamid = null
this._steamid3 = null
this._steamid64 = null
return this
}
setupSteamID3 (steamidIn: string) {
try {
const [steamid, server] = SteamIDFrom3(steamidIn)
const [steamid64, server64] = SteamIDTo64(steamid)
this._steamid3 = steamidIn
this._steamid = steamid
this._server = server
this._steamid64 = steamid64
} catch(err) {
console.error(`Attempt to parse bad SteamID: ${steamidIn} (was detected as SteamID3)`)
console.error(err)
}
}
setupSteamID (steamidIn: string) {
try {
const [steamid3, server] = SteamIDTo3(steamidIn)
const [steamid64, server64] = SteamIDTo64(steamidIn)
this._steamid3 = steamid3
this._steamid = steamidIn
this._server = server
this._steamid64 = steamid64
} catch(err) {
console.error(`Attempt to parse bad SteamID: ${steamidIn} (was detected as SteamID2)`)
console.error(err)
}
}
setupSteamID64 (steamidIn: string) {
try {
const [steamid3, server] = SteamIDFrom64To3(steamidIn)
const [steamid, server64] = SteamIDFrom64(steamidIn)
this._steamid3 = steamid3
this._steamid = steamid
this._server = server
this._steamid64 = steamidIn
} catch(err) {
console.error(`Attempt to parse bad SteamID: ${steamidIn} (was detected as SteamID64)`)
console.error(err)
}
}
setup (steamidIn: string) {
steamidIn = String(steamidIn)
if (steamidIn.substr(0, 2) === '[U') {
this.setupSteamID3(steamidIn)
} else if (steamidIn.substr(0, 7) === 'STEAM_0') {
this.setupSteamID(steamidIn)
} else {
const parse = parseInt(steamidIn)
if (parse == parse) {
this.setupSteamID64(steamidIn)
}
}
return this
}
constructor (steamidIn?: string) {
this.reset()
if (steamidIn) {
this.setup(steamidIn)
}
}
valid() {
return this._server != null &&
this._steamid != null &&
this._steamid64 != null &&
this._steamid3 != null
}
equals (target: SteamID | string) {
if (typeof target == 'object') {
return this.steamid == target.steamid ||
this.steamid3 == target.steamid3 ||
this.steamid3 == target.steamid3
} else {
target = target.trim()
return this.steamid == target ||
this.steamid3 == target ||
this.steamid3 == target
}
}
}
import crypto = require('crypto')
class BotSteamID extends SteamID {
protected _botName: string
protected _steamid: string
protected _steamid3: string
protected _steamid64: string
constructor (botName: string) {
super()
this._botName = botName
const stream = crypto.createHash('md5')
stream.update(botName)
const hex = stream.digest('hex')
this._steamid = 'STEAM_1:' + hex
this._steamid3 = '[U:1:' + hex + ']'
this._steamid64 = '76561197960265728'
}
get steamid(): string { return this._steamid }
get steamid3(): string { return this._steamid3 }
get steamid64(): string { return this._steamid64 }
set steamid(steamidIn: string) { }
set steamid3(steamidIn: string) { }
set steamid64(steamidIn: string) { }
get botName () { return this._botName }
reset () { return this }
setup () { return this }
}
export {SteamID, BotSteamID, SteamIDTo64, SteamIDFrom64, SteamIDTo3, SteamIDFrom3, SteamIDFrom64To3, SteamIDFrom3To64}
|
fc7d4398653a398ebceb030e8895060c3698f849 | TypeScript | Molsbee/rdbs-ui-prototype | /frontend/src/main/api/ActionLogAPI.ts | 2.546875 | 3 | import * as moment from "moment";
import Moment = moment.Moment;
declare var atlas: any;
export class ActionLog {
timestamp: Moment;
message: string;
details: string;
user: string;
constructor(data: any) {
this.timestamp = moment.utc(data.timeStamp).local();
this.message = data.message;
this.details = data.details;
this.user = data.user;
}
}
export interface ActionLogCallback {
(actionLogs: Array<ActionLog>) : void;
}
export class ActionLogAPI {
private api: string;
private accountContext: KnockoutObservable<any>;
constructor(api: string, accountContext: KnockoutObservable<any>) {
this.api = api;
this.accountContext = accountContext;
}
getActionLogs = (callback: ActionLogCallback): void => {
let actionLogs: Array<ActionLog> = [];
atlas.ajax({
method: 'GET',
url: this.api + "/" + this.accountContext().accountAlias + "/history",
success: (data: Array<any>) => {
data.forEach((d: any) => {
actionLogs.push(new ActionLog(d));
})
},
complete: () => {
callback(actionLogs);
}
});
};
} |
4fbbfb7fdba5dde54a52a799461c94070fbbb974 | TypeScript | romanepifanov/flexible-calendar | /src/setting/languages.ts | 3.03125 | 3 | import { Language, Languages } from "../models/language.model";
const en: Language = {
month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'],
days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
daysMiddle: ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'],
daysShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
}
const de: Language = {
month: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
monthShort: ['Jan', 'Feb', 'März', 'Apr', 'Mai', 'Juni', 'Juli', 'Aug', 'Sept', 'Okt', 'Nov', 'Dez'],
days: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
daysMiddle: ['Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam'],
daysShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa']
}
const ru: Language = {
month: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
monthShort: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'],
days: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
daysMiddle: ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'],
daysShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб']
}
class LanguageHandler {
private languages: Languages = {
en: en,
de: de,
ru: ru
}
public get = (name: string): Language => {
switch (name) {
case 'de': return this.languages.de
case 'ru': return this.languages.ru
case 'en':
default: return this.languages.en
}
}
}
export default LanguageHandler; |
9402ee092600f45cea197a188c581f4381b8548e | TypeScript | news-catalyst/presspass-frontend | /src/store/clients/actions.ts | 2.90625 | 3 | import {
UPSERT_CLIENT,
Client,
UPSERT_CLIENTS,
DELETE_CLIENT,
DeleteClientAction,
UpsertClientAction,
UpsertClientsAction
} from "./types";
export function upsertClient(client: Client): UpsertClientAction {
return {
type: UPSERT_CLIENT,
client: client
};
}
// This action is necessary because if one wants to
// upsert multiple clients into the store at load time,
// calling each `upsertClient` individually would cause
// the 'hydrated' field to be set to `true` after the first
// upsert (but before all the data has been loaded). This
// can cause issues when there are multiple clients,
// as a view might be waiting for `hydrated` to be `true`
// before displaying data from a particular client. If
// `hydrated` is set to `true` too early, this can cause
// these views to fail.
export function upsertClients(clients: Client[]): UpsertClientsAction {
return {
type: UPSERT_CLIENTS,
clients: clients
};
}
export function deleteClient(client: Client): DeleteClientAction {
return {
type: DELETE_CLIENT,
client: client
};
}
|
2441f6aa349774762cdfe8a4a0551a10955a6108 | TypeScript | deandreee/electron_ml_nn_research | /src/strat/rescale.ts | 2.984375 | 3 | import * as statslite from "stats-lite";
// https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range
// newvalue= (max'-min')/(max-min)*(value-max)+max'
// min' to max' => new
export const rescale = (value: number, min: number, max: number): number => {
const newMin = -1;
const newMax = 1;
return ((newMax - newMin) / (max - min)) * (value - max) + newMax;
};
export const rescaleArr0to1 = (arr: number[]): number[] => {
const min = Math.min(...arr);
const max = Math.max(...arr);
const newMin = 0;
const newMax = 1;
return arr.map(value => ((newMax - newMin) / (max - min)) * (value - max) + newMax);
};
export const rescaleArrPlusMinus1 = (arr: number[]): number[] => {
const min = Math.min.apply(null, arr);
const max = Math.max.apply(null, arr);
const newMin = -1;
const newMax = 1;
return arr.map(value => ((newMax - newMin) / (max - min)) * (value - max) + newMax);
};
// from here https://github.com/mljs/libsvm/issues/14
export const rescaleForSvm = (arr: number[]): number[] => {
const mean = statslite.mean(arr);
const stddev = statslite.stdev(arr);
return arr.map(x => (x - mean) / stddev);
};
|
7435ec4c1126c568d6d0d747469c50393636e058 | TypeScript | teshimafu/redux_calculator_sample | /src/modules/CalculatorContainer.ts | 3.09375 | 3 | import { OPT, Calculator } from "src/services/CalculatorService";
const INPUT_NUMBER = "INPUT_NUMBER";
const OPERATION = "OPERATION";
const EQUAL = "EQUAL";
const RESET = "RESET";
const onNumClick = (number: number) => ({
type: INPUT_NUMBER,
number
});
const onOperationClick = (opt: OPT) => ({
type: OPERATION,
opt
});
const onEqualClick = () => ({
type: EQUAL
});
const onResetClick = () => ({
type: RESET
});
type ClickActions =
| ReturnType<typeof onNumClick>
| ReturnType<typeof onOperationClick>
| ReturnType<typeof onEqualClick>
| ReturnType<typeof onResetClick>;
interface CalcState {
inputValue: number;
resultValue: number;
temporaryValue: number;
lastOperation?: OPT;
showingResult: boolean;
}
export const GetAllActions = {
onNumClick: onNumClick,
onOperationClick: onOperationClick,
onEqualClick: onEqualClick,
onResetClick: onResetClick
};
const initialAppState: CalcState = {
inputValue: 0,
temporaryValue: 0,
resultValue: 0,
showingResult: false
};
const calculator = (state = initialAppState, action: ClickActions) => {
switch (action.type) {
case INPUT_NUMBER:
const numAction = action as ReturnType<typeof onNumClick>;
return {
...state,
inputValue: state.inputValue * 10 + numAction.number,
showingResult: false
};
case OPERATION:
const opAction = action as ReturnType<typeof onOperationClick>;
const temp = state.lastOperation
? Calculator(state.lastOperation, state.temporaryValue, state.inputValue)
: state.showingResult
? state.resultValue
: state.inputValue;
return {
...state,
inputValue: 0,
temporaryValue: temp,
resultValue: 0,
lastOperation: opAction.opt
};
case EQUAL:
if (state.showingResult) {
return state;
}
const result = state.lastOperation
? Calculator(state.lastOperation, state.temporaryValue, state.inputValue)
: state.inputValue;
return {
...state,
inputValue: 0,
temporaryValue: 0,
resultValue: result,
lastOperation: undefined,
showingResult: true
};
case RESET:
return initialAppState;
default:
return state;
}
};
export default calculator;
|
d28feefe804ff7690429aae20535b2c8803559f7 | TypeScript | DylanYang0523/node-pg-migrate | /test/indexes-test.ts | 2.640625 | 3 | import { expect } from 'chai'
import * as Indexes from '../src/operations/indexes'
import { options1, options2 } from './utils'
type CreateIndexParams = Parameters<ReturnType<typeof Indexes.createIndex>>
describe('lib/operations/indexes', () => {
describe('.create', () => {
it('check schema not included in index name', () => {
const args: CreateIndexParams = [{ schema: 'mySchema', name: 'myTable' }, ['colA', 'colB']]
const sql1 = Indexes.createIndex(options1)(...args)
const sql2 = Indexes.createIndex(options2)(...args)
expect(sql1).to.equal('CREATE INDEX "myTable_colA_colB_index" ON "mySchema"."myTable" ("colA", "colB");')
expect(sql2).to.equal('CREATE INDEX "my_table_col_a_col_b_index" ON "my_schema"."my_table" ("col_a", "col_b");')
})
it('add opclass option (deprecated)', () => {
const args: CreateIndexParams = [
'xTable',
['yName'],
{
method: 'gist',
name: 'zIndex',
opclass: 'someOpclass',
where: 'some condition',
},
]
const sql1 = Indexes.createIndex(options1)(...args)
const sql2 = Indexes.createIndex(options2)(...args)
expect(sql1).to.equal(
'CREATE INDEX "zIndex" ON "xTable" USING gist ("yName" "someOpclass") WHERE some condition;',
)
expect(sql2).to.equal(
'CREATE INDEX "z_index" ON "x_table" USING gist ("y_name" "some_opclass") WHERE some condition;',
)
})
it('add opclass option', () => {
const args: CreateIndexParams = [
'xTable',
[{ name: 'yName', opclass: { schema: 'someSchema', name: 'someOpclass' } }],
{
method: 'gist',
name: 'zIndex',
where: 'some condition',
},
]
const sql1 = Indexes.createIndex(options1)(...args)
const sql2 = Indexes.createIndex(options2)(...args)
expect(sql1).to.equal(
'CREATE INDEX "zIndex" ON "xTable" USING gist ("yName" "someSchema"."someOpclass") WHERE some condition;',
)
expect(sql2).to.equal(
'CREATE INDEX "z_index" ON "x_table" USING gist ("y_name" "some_schema"."some_opclass") WHERE some condition;',
)
})
it('add sort option', () => {
const args: CreateIndexParams = [
'xTable',
[{ name: 'yName', sort: 'DESC' }],
{
method: 'gist',
name: 'zIndex',
where: 'some condition',
},
]
const sql1 = Indexes.createIndex(options1)(...args)
const sql2 = Indexes.createIndex(options2)(...args)
expect(sql1).to.equal('CREATE INDEX "zIndex" ON "xTable" USING gist ("yName" DESC) WHERE some condition;')
expect(sql2).to.equal('CREATE INDEX "z_index" ON "x_table" USING gist ("y_name" DESC) WHERE some condition;')
})
it('add include option', () => {
const args: CreateIndexParams = ['xTable', ['yName'], { name: 'zIndex', include: 'someOtherColumn' }]
const sql1 = Indexes.createIndex(options1)(...args)
const sql2 = Indexes.createIndex(options2)(...args)
expect(sql1).to.equal('CREATE INDEX "zIndex" ON "xTable" ("yName") INCLUDE ("someOtherColumn");')
expect(sql2).to.equal('CREATE INDEX "z_index" ON "x_table" ("y_name") INCLUDE ("some_other_column");')
})
})
})
|
ca24b6c6421e626acaad42a7c1879a28640af3cb | TypeScript | skwidz/jobber-library | /src/interfaces/BookInterface.ts | 3.21875 | 3 | export interface Book {
title: any;
author: string,
genre: string,
synopsis: string,
// id: number;
// avalible: boolean;
// signed_out_to: string;
}
export interface AdditionalBookInfo{
subtitle: string,
description: string,
imageLink: string,
}
export function createBook(config: Book): {
title: string,
author: string,
genre: string,
synopsis: string,
// id: number,
// avalible: boolean,
// signed_out_to: string,
} {
return {
title: config.title,
author: config.author,
genre: config.genre,
synopsis: config.synopsis,
// id: config.id,
// avalible: config.avalible,
// signed_out_to: config.signed_out_to,
}
}
export function createAdditionalInfo(config: AdditionalBookInfo) :{
subtitle: string,
description: string,
imageLink: string,
} {
return {
subtitle: config.subtitle,
description: config.description,
imageLink: config.imageLink,
}
}
export const emptyBook = createBook({
title: "",
author: "",
genre: "",
synopsis: "",
// id: 0,
// avalible: false,
// signed_out_to: "",
})
export const emptyAdditionalInfo = createAdditionalInfo({
subtitle: "",
description: "",
imageLink: ""
}) |
5beea212b79ba506c2202b69f915ef11dc9ddfc5 | TypeScript | reecewbourgeois/CMPS401_Language_Presentation_Code | /source/TLoop.ts | 3.5625 | 4 | /*
* Test Loops: while, for, and nested loops.
* Program-ID: TSub.ts
* Author: Kwentin Ransom
* OS: Ubuntu 20.04
* Compiler: TSC
* Note:
* The following instructions are used to
* edit, compile, and run this program
* $nano TLoop.ts
* $tsc TLoop.ts
* $node TLoop.js
*/
//setting numeric and boolean variables
let x: boolean = true;
let y: number = 0;
let i: number = 0;
//while loop that prints the value of y until the condition is met
while(x != false){
if(y! != 10) {
console.log(y);
y++;
}
else {
x = false;
}
}
console.log();
//creating numbers array
//for loop prints out numbers
var numbers: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for(i=0;i<=10;i++) {
console.log("Loading in progress..." + numbers[i]);
}
/*
* Output:
* 1
* 2
* 3
* 4
* 5
* 6
* 7
* 8
* 9
* 10
*
* Loading in progress...1
* Loading in progress...2
* Loading in progress...3
* Loading in progress...4
* Loading in progress...5
* Loading in progress...6
* Loading in progress...7
* Loading in progress...8
* Loading in progress...9
* Loading in progress...10
*/
|
1b1dabc5a1fde1617a20547025175a9d22968aae | TypeScript | NormanFrieman/storiesbook | /backend/src/commands/tools/encrypt.ts | 2.65625 | 3 | import bcrypt from 'bcrypt';
import { ResponseFunction } from '../../protocols';
export const encrypt = async (password: string): Promise<ResponseFunction> => {
const hash: string = await bcrypt.hash(password, 10);
if(!hash){
const response: ResponseFunction = {
sucess: false,
body: 'the hash could not be created'
};
return response;
}
const response: ResponseFunction = {
sucess: true,
body: hash
};
return response;
} |
84520820bef4a312229b2bec701a0cd104530225 | TypeScript | koshevy/codegena | /libs/definitions/oas3/src/types/request.ts | 2.765625 | 3 | import { HasRef } from '@codegena/definitions/aspects';
import { HasContent } from './has-content';
/**
* Request Body Object. Describes a single request body.
* @see https://swagger.io/specification/#requestBodyObject
*/
export interface Request extends HasRef, HasContent {
/**
* A brief description of the request body. This could contain examples of
* use. CommonMark syntax MAY be used for rich text representation.
*/
description?: string;
/**
* Determines if the request body is required in the request. Defaults to `false`.
* TODO support request required. now is not
*/
required?: boolean;
}
|
a7bad6590098dc26b0e11b3e12be160c78c50e36 | TypeScript | liridonRama/ts-web-framework-task | /src/models/ApiSync.ts | 2.625 | 3 | import axios, { AxiosPromise } from "axios"
import { nanoid } from "nanoid";
import { HasId } from "../interfaces/HasId"
export class ApiSync<T extends HasId> {
constructor(private rootUrl: string) { }
fetch = (id: string): AxiosPromise => {
return axios.get(`${this.rootUrl}/users/${id}`);
}
save = (data: T): AxiosPromise => {
const { id } = data;
if (id) {
return axios.put(`${this.rootUrl}/users/${id}`, data);
} else {
return axios.post(`${this.rootUrl}/users`, { ...data, id: nanoid(7) });
}
}
} |
589a689734fbe2d86d9ed17d5da4f7a9dc2f10f8 | TypeScript | adriancarriger/experiments | /algorithms/2/src/permutations/string.ts | 3.203125 | 3 | export function permutations(input: string, output = '', set = new Set()) {
if (!input) {
set.add(output);
}
input.split('').forEach((letter, index) => {
permutations(input.slice(0, index) + input.slice(index + 1), output + letter, set);
});
return set;
}
|
d820e93cb5208794920b158c80e159eea4dcad90 | TypeScript | dmyxs/react-ts-jira | /src/hooks/use-documentTitle.ts | 3.171875 | 3 | import { useRef, useEffect } from "react"
// 版本一:最简单的写法
// export const useDocumentTitle = (title: string) => {
// useEffect(() => {
// document.title = title
// }, [title])
// }
// 版本二:保留第一次的title
// isUnmount 是否卸载
export const useDocumentTitle = (title: string, isUnmount: boolean = true) => {
const oldTitle = useRef(document.title).current
useEffect(() => {
document.title = title
}, [title])
useEffect(() => {
return () => {
if (!isUnmount) {
document.title = oldTitle
}
}
}, [oldTitle, isUnmount])
}
//闭包写法:实现保留第一次的title
// export const useDocumentTitle = (title: string, isUnmount: boolean = true) => {
// const oldTitle = document.title
// useEffect(() => {
// document.title = title
// }, [title])
// useEffect(() => {
// return () => {
// if (!isUnmount) {
// document.title = oldTitle
// }
// }
// // eslint-disable-next-line react-hooks/exhaustive-deps
// }, [])
// }
|
861d8c331acdbf168888adf93fe9f5d37e8e228a | TypeScript | Drane/surfwatch-mess | /api/surfwatch-old/src/models/location.model.ts | 2.65625 | 3 | import {property, model} from '@loopback/repository';
@model()
export class Location {
@property({required: true})
latitude: number;
@property({required: true})
longitude: number;
constructor(latitude: number, longitude: number) {
this.latitude = latitude;
this.longitude = longitude;
}
}
|
2db580567238c75c0b70994f2a307c6229d057ed | TypeScript | DenMantm/personal-blog-page | /app/common/array-utility-service.ts | 3.078125 | 3 | import { Injectable } from '@angular/core';
@Injectable()
export class ArrayUtilityService{
snippetElements:any
snippetTemplate:any
constructor() {
}
// addNewElement(item,itemList){
// }
addNewSnippet(itemList){
//adding item to the array and passing item length
console.log(itemList)
itemList.push(this.snippetFactory(itemList.length));
}
addNewElementDiv(item){
let param = "div";
//adding item to the array and passing item length
item.push(this.elementFactory(item.length,param));
}
addNewElementPre(item){
let param = "pre";
//adding item to the array and passing item length
item.push(this.elementFactory(item.length,param));
}
sortObjArrayById(list){
list.sort(this.sortById);
}
rewriteIds(list){
let indexPointer = 0;
for(let i = 0;i<list.length;i++){
list[i].id = indexPointer;
indexPointer++;
}
}
removeItem(item,itemList){
for(let i = 0;i<itemList.length;i++){
//finding the right match
if (itemList[i].id == item.id ){
//removing index
itemList.splice(i, 1);
//resetting indexes and sorting
this.rewriteIds(itemList);
}
}
}
moveItemUp(item,itemList){
//if this is not the last item
if(0 !== item.id){
//changing is'd places
console.log(itemList);
itemList[item.id-1].id++;
itemList[item.id].id--;
console.log(itemList);
//sortin array
this.sortObjArrayById(itemList);
console.log(itemList);
}
}
moveItemDown(item,itemList){
//if this is not the last item
if(itemList.length !== item.id +1){
//changing is'd places
console.log(itemList);
itemList[item.id+1].id--;
itemList[item.id].id++;
console.log(itemList);
//sortin array
this.sortObjArrayById(itemList);
console.log(itemList);
}
}
sortById(a,b) {
if (a.id < b.id) return -1;
if (a.id > b.id) return 1;
return 0;
}
elementFactory(id,param){
let text;
param == "div"
? text = "<p>This fresh element</p>"
: text = "code block"
return {
"id": id,
"type": param,
"style": null,
"text": text
};
}
//Generate new template for snippet
snippetFactory(id){
return {
"id": id,
"titleText": "New Snippet",
"elements": [
{
"id": 0,
"type": "div",
"style": null,
"text": "<h3>This is the title element</h3>"
},
{
"id": 1,
"type": "p",
"style": null,
"text": "<p>This is paragraph entery</p>"
},
{
"id": 2,
"type": "pre",
"style": null,
"text": "This is pre block element"
}
],
"comments": null
};
}
//Not a very good place for this her, but there is really no point to create new service just for this one,
//if in future more helpper functions will be created will mve to the new helpper func service
deepCopy(oldObj) {
var newObj = oldObj;
if (oldObj && typeof oldObj === 'object') {
newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
for (var i in oldObj) {
newObj[i] = this.deepCopy(oldObj[i]);
}
}
return newObj;
}
} |
dfa31dd1df33c22ede3e4451aa4663d82b0c52a3 | TypeScript | wlf-io/chip-project | /src/designer/chip/Pin.ts | 3.09375 | 3 | import { PinData } from "../../common/interfaces/source.interfaces"
class Pin {
private _chip: string;
private _output: boolean;
private _name: string;
public get id(): string {
return `${this.chip}_${this.output}_${this.name}`;
}
public static Factory(chip: string = "", output: boolean = false, name: string = ""): Pin {
return new Pin(chip, output, name);
}
constructor(chip: string = "", output: boolean = false, name: string = "") {
this._chip = chip;
this._output = output;
this._name = name;
}
public toJSON(): PinData {
return {
chip: this.chip,
output: this.output,
name: this.name,
};
}
public fromJSON(data: { [k: string]: any }): Pin {
this._chip = data.chip ?? this.chip;
this._output = data.output ?? this.output;
this._name = data.name ?? this.name;
return this;
}
public isEqualTo(pin: Pin): boolean {
return this.chip == pin.chip && this.output == pin.output && this.name == pin.name;
}
public get chip(): string { return this._chip; }
public get output(): boolean { return this._output; }
public get name(): string { return this._name; }
}
export default Pin; |
9a08fc928147ac272c12f12d9fb236fdac77c754 | TypeScript | rostacik/CodeCon2014TSSamples | /CodeConTSSamples/09-Classes/file5.ts | 3.1875 | 3 | class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
this._fullName = newName + " was supplied";
}
} |
b17d9ad164fed58cdaeae56105e5cde1f2bfbac9 | TypeScript | doubco/world | /src/index.ts | 2.5625 | 3 | import {
Translation,
TranslationKey,
TranslationContext,
TranslationLocale,
Translations,
WorldFormatter,
WorldOnLocaleChange,
WorldFetch,
WorldConfig,
TranslationOptions,
} from "./types";
import { isObject, isString, isArray } from "@doubco/wtf";
export class World {
initializedLocales: Array<TranslationLocale>;
locales: Array<TranslationLocale>;
locale: TranslationLocale;
fallbackLocale: TranslationLocale;
translations: Translations;
formatter?: WorldFormatter;
onLocaleChange?: WorldOnLocaleChange;
fetch?: WorldFetch;
constructor(config: WorldConfig) {
const {
locale,
locales,
fallbackLocale = "en",
translations = {},
formatter,
onLocaleChange,
fetch,
} = config;
this.initializedLocales = [];
this.locales = locales || [fallbackLocale];
this.locale = locale || fallbackLocale;
this.fallbackLocale = fallbackLocale;
this.translations = translations || {};
this.formatter = formatter;
this.onLocaleChange = onLocaleChange;
this.fetch = fetch;
this.t = this.t.bind(this);
this.parse = this.parse.bind(this);
this.setLocale = this.setLocale.bind(this);
this.registerTranslation = this.registerTranslation.bind(this);
this.registerTranslations = this.registerTranslations.bind(this);
if (this.fetch) {
this.fetch = this.fetch.bind(this);
}
}
parse(phrase: string) {
return (props: TranslationOptions) => {
return phrase.replace(/{{([^{}]*)}}/g, (a, b) => {
let k = b.replace(/ /g, "");
let value = "";
let key;
let method;
if (k.includes(",")) {
let [x, m] = k.split(",");
let v = props[x];
if (v && m) {
value = v;
method = m;
key = x;
}
} else {
let x = k;
let v = String(props[x]);
if (v) {
value = v;
key = x;
}
}
if (this.formatter) {
value = this.formatter({ key, value, method, locale: this.locale });
}
return value;
});
};
}
registerTranslation(key: string, translation: Translation) {
if (!this.initializedLocales.includes(key)) {
this.initializedLocales.push(key);
}
const previousTranslation: Translation = this.translations[key] || {};
this.translations[key] = {
...previousTranslation,
...translation,
};
}
registerTranslations(translations: Translations) {
Object.keys(translations).forEach((key) => {
let translation = translations[key];
if (!this.initializedLocales.includes(key)) {
this.initializedLocales.push(key);
}
const previousTranslation: Translation = this.translations[key] || {};
this.translations[key] = {
...previousTranslation,
...translation,
};
});
}
createContext(locale: string) {
// eslint-disable-next-line
return new Promise((resolve) => {
this.setLocale(locale, () => {
resolve({
locale: this.locale,
translations: this.translations,
});
});
});
}
registerContext(context: TranslationContext) {
this.registerTranslations(context.translations);
this.setLocale(context.locale, null, true);
}
setLocale(locale = this.fallbackLocale, callback?: any, dontFetch?: boolean) {
if (!isString(locale)) locale = this.fallbackLocale;
this.locale = locale;
if (this.fetch && !dontFetch) {
this.fetch(this.locale).then((translation) => {
if (translation) {
this.registerTranslation(this.locale, translation);
}
if (this.onLocaleChange) {
this.onLocaleChange(this.locale, callback);
} else {
if (callback) callback();
}
});
} else {
if (this.onLocaleChange) {
this.onLocaleChange(this.locale, callback);
} else {
if (callback) callback();
}
}
}
t(
key: TranslationKey,
options?: TranslationOptions,
locale?: TranslationLocale,
) {
let phrase;
if (!locale) locale = this.locale || this.fallbackLocale;
if (!key) key = "";
if (!options) options = {};
if (isObject(key)) {
phrase = key[locale];
if (!phrase) {
phrase = key[this.fallbackLocale];
}
if (phrase) {
if (isArray(phrase) && phrase.length) {
phrase = phrase.join("\n");
}
if (isString(phrase)) {
return this.parse(phrase)(options);
} else {
return phrase;
}
}
return "";
}
let phrases = this.translations[locale];
if (phrases) {
phrase = phrases[key];
// TODO: add support for other pluralization rules (arabic etc.)
// plural
if (options.count && options.count > 1) {
let pluralKey = `${key}_plural`;
if (phrases[pluralKey]) {
phrase = phrases[pluralKey];
}
}
// zero
if (options.count === 0) {
let pluralKey = `${key}_zero`;
if (phrases[pluralKey]) {
phrase = phrases[pluralKey];
}
}
}
if (phrase) {
if (isString(phrase)) {
return this.parse(phrase)(options);
} else {
return phrase;
}
} else {
return key;
}
}
}
|
6f7286c7316a4c91177ef5a5e273aad5d880a3fd | TypeScript | bradgarropy/adobe-rules | /src/statement.ts | 3.140625 | 3 | import {Data} from "."
import {Condition, evaluateCondition} from "./condition"
type Combinator = "and" | "or"
type Statement = {
combinator: Combinator
conditions: Array<Condition | Statement>
}
const isStatement = (rule: Statement | Condition): boolean => {
const statement = rule as Statement
if (statement.combinator) {
return true
}
return false
}
const evaluateStatement = (statement: Statement, data: Data): boolean => {
const result = statement.conditions.reduce((acc, rule) => {
if (isStatement(rule)) {
return evaluateStatement(rule as Statement, data)
}
const condition = rule as Condition
switch (statement.combinator) {
case "and":
return evaluateCondition(condition, data) && acc
case "or": {
return evaluateCondition(condition, data) || acc
}
}
}, true)
return result
}
export {evaluateStatement, isStatement}
export type {Statement}
|
6719ae35271a090f9303c4fd0617b61ecd9ccd08 | TypeScript | Electromasta/eastmarchescom | /src/app/nav/model/subsection.model.ts | 2.90625 | 3 | export class Subsection {
public header: string;
public text: string;
public list: Array<Subsection>;
constructor(header: string, text: string, list?: Array<Subsection>) {
this.header = header;
this.text = text;
this.list = list;
}
} |
71e9e898ef78a6b106931ee8a94c52a2375e6ecf | TypeScript | yangxin1994/every-color-picker | /src/alpha-controller.ts | 2.59375 | 3 | import { BaseElementController } from './base-element';
import { Color } from './colors';
import { RANGE_STYLE, ALPHA_BG } from './common';
export class AlphaController extends BaseElementController {
constructor(e: HTMLElement) {
super(e);
this.root.innerHTML = `
<style>
${RANGE_STYLE}
:host {
--thumb-color: transparent;
}
#container {
width: 100%;
box-sizing: border-box;
height: 12px;
border-radius: 12px;
position: relative;
pointer-events: none;
}
#gradient {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
pointer-events: none;
border-radius: 12px;
background-image: linear-gradient(to right, var(--alpha-g1, hsla(0, 100%, 50%, 0)), var(--alpha-g2, hsla(0, 100%, 50%, 1)));
}
#checker {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
pointer-events: none;
border-radius: 12px;
background-image: url(${ALPHA_BG});
background-size: 12px 11px;
}
</style>
<div id="container">
<div id="checker"></div>
<div id="gradient" style=""></div>
<input id="range" type="range" min="0" max="100" value="100" aria-label="Alpha">
</div>
`;
this.attach();
}
attach() {
this.$add('range', 'input', this.handleInput);
}
detach() {
this.$remove('range', 'input', this.handleInput);
super.detach();
}
set hue(value: number) {
this.e.style.setProperty('--alpha-g1', `hsla(${value}, 100%, 50%, 0)`);
this.e.style.setProperty('--alpha-g2', `hsla(${value}, 100%, 50%, 1)`);
}
set hsl(hsla: Color) {
this.e.style.setProperty('--alpha-g1', `hsla(${hsla[0]}, ${hsla[1]}%, ${hsla[2]}%, 0)`);
this.e.style.setProperty('--alpha-g2', `hsla(${hsla[0]}, ${hsla[1]}%, ${hsla[2]}%, 1)`);
}
private handleInput = (event: Event) => {
event.stopPropagation();
this.fire('range', { value: this.value });
}
get value(): number {
const range = this.$<HTMLInputElement>('range');
if (range) {
return (+range.value) / 100;
}
return 0;
}
set value(v: number) {
const range = this.$<HTMLInputElement>('range');
if (range) {
range.value = `${Math.max(0, Math.min(1, v)) * 100}`;
}
}
} |
7136dd66ce51b8f5f63b035a03eff7ba57ceb6a0 | TypeScript | lizzzp1/tslint-microsoft-contrib | /src/informativeDocsRule.ts | 2.875 | 3 | import * as Lint from 'tslint';
import * as ts from 'typescript';
import { getApparentJsDoc, getNodeName } from './utils/NodeDocs';
import { ExtendedMetadata } from './utils/ExtendedMetadata';
const defaultUselessWords = ['a', 'an', 'of', 'our', 'the'];
const defaultAliases: { [i: string]: string[] } = {
a: ['an', 'our']
};
const failureString = "This comment is roughly the same as the object's name. Either be more informative or don't include a comment.";
interface RawOptions {
aliases?: { [i: string]: string[] };
uselessWords?: string[];
}
interface Options {
aliases: Map<string, string>;
uselessWords: Set<string>;
}
/**
* Implementation of the informative-docs rule.
*/
export class Rule extends Lint.Rules.AbstractRule {
public static metadata: ExtendedMetadata = {
description: 'Enforces that comments do more than just reiterate names of objects.',
options: undefined,
optionsDescription: 'Not configurable.',
optionExamples: [
true,
[
true,
{
aliases: {
a: ['an', 'our'],
emoji: ['smiley']
},
uselessWords: [...defaultUselessWords, 'also']
}
]
],
rationale: Lint.Utils.dedent`
The documentation for an object should not be equivalent to just the object's name.
If we strip out non-alphabet characters, common words such as "the" or "a",
and lowercase everything, they shouldn't be the same.
Using informative documentation can be helpful for variables to help explain their usage.
Alternately, if something's name is so descriptive that it doesn't need to be fully documented,
just leave out documentation altogether.
`,
issueClass: 'Non-SDL',
issueType: 'Warning',
severity: 'Moderate',
level: 'Opportunity for Excellence',
group: 'Clarity',
recommendation: 'true',
ruleName: 'informative-docs',
type: 'maintainability',
typescriptOnly: false
};
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk, parseOptions(this.getOptions().ruleArguments));
}
}
function parseOptions(ruleArguments: unknown[]): Options {
const rawOptions: RawOptions = ruleArguments.length === 0 ? {} : <RawOptions>ruleArguments[0];
return {
aliases: parseAliasesOption(rawOptions.aliases === undefined ? defaultAliases : rawOptions.aliases),
uselessWords: new Set(rawOptions.uselessWords === undefined ? defaultUselessWords : rawOptions.uselessWords)
};
}
function parseAliasesOption(rawAliases: { [i: string]: string[] }): Map<string, string> {
const aliases = new Map<string, string>();
for (const alias of Object.keys(rawAliases)) {
for (const aliasedName of rawAliases[alias]) {
aliases.set(aliasedName.toLowerCase(), alias.toLowerCase());
}
}
return aliases;
}
function walk(context: Lint.WalkContext<Options>) {
const { aliases, uselessWords } = context.options;
function nodeNameContainsUsefulWords(nameWords: string[], docWords: string[]): boolean {
const realDocWords = new Set(docWords);
for (const nameWord of nameWords) {
realDocWords.delete(nameWord);
}
uselessWords.forEach(
(uselessWord: string): void => {
realDocWords.delete(uselessWord);
}
);
return realDocWords.size !== 0;
}
function normalizeWord(word: string): string {
word = word.toLowerCase();
const aliasedWord = aliases.get(word);
if (aliasedWord !== undefined) {
word = aliasedWord;
}
return word;
}
function splitNameIntoWords(name: string): string[] | undefined {
if (name.length > 2 && name[0] === 'I' && Lint.Utils.isUpperCase(name[1])) {
name = name.substring(1);
}
const nameSpaced = name
.replace(/\W/g, '')
.replace(/([a-z])([A-Z])/g, '$1 $2')
.trim();
if (nameSpaced.length === 0) {
return undefined;
}
return nameSpaced.split(' ').map(normalizeWord);
}
function getNodeDocComments(node: ts.Node): string[] | undefined {
const docsRaw = getApparentJsDoc(node);
if (docsRaw === undefined) {
return undefined;
}
const docs = docsRaw.map(doc => doc.comment).filter(comment => comment !== undefined);
if (docs.length === 0) {
return undefined;
}
return docs
.join(' ')
.replace(/[^A-Za-z0-9 ]/g, '')
.split(' ')
.map(normalizeWord);
}
function verifyNodeWithName(node: ts.Node, name: string): void {
const docs = getNodeDocComments(node);
if (docs === undefined) {
return;
}
const nameSplit = splitNameIntoWords(name);
if (nameSplit === undefined) {
return;
}
if (!nodeNameContainsUsefulWords(nameSplit, docs)) {
context.addFailureAtNode(node, failureString);
}
}
function visitNode(node: ts.Node): void {
const name = getNodeName(node);
if (name !== undefined) {
verifyNodeWithName(node, name);
}
return ts.forEachChild(node, visitNode);
}
return ts.forEachChild(context.sourceFile, visitNode);
}
|
654bab8941d1a00107ed58192e2955d2af1d09a6 | TypeScript | samwaters/WebAssembly | /src/app/store/wasm.store.ts | 2.75 | 3 | import { createAction, createSlice, PayloadAction } from '@reduxjs/toolkit'
export enum WASMStates {
NOT_LOADED = "not_loaded",
LOADING = "loading",
LOADED = "loaded"
}
export interface WASMState {
addition: WASMStates
prime: WASMStates
}
const initialState: WASMState = {
addition: WASMStates.NOT_LOADED,
prime: WASMStates.NOT_LOADED
}
const wasmSlice = createSlice({
initialState,
name: 'wasm',
reducers: {
load: (state, action: PayloadAction<string>) => {
state[action.payload] = WASMStates.LOADING
},
loaded: (state, action: PayloadAction<string>) => {
state[action.payload] = WASMStates.LOADED
},
}
})
export const loadWASMAction = createAction<string>("wasm/load")
export const loadedWASMAction = createAction<string>("wasm/loaded")
export const { load, loaded } = wasmSlice.actions
export default wasmSlice.reducer
|
fd7a62884ef48b87e77f131ab54f218cca3844ef | TypeScript | marianbret/dashboard | /src/auth/auth.controller.ts | 2.578125 | 3 | import { Controller, Get, UseGuards, Req, Res, Post, Body } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { User } from './auth.entity';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get('google')
@UseGuards(AuthGuard('google'))
googleLogin()
{
// initiates the Google OAuth2 login flow
}
@Get('google/callback')
@UseGuards(AuthGuard('google'))
async googleLoginCallback(@Req() req, @Res() res)
{
const profile: string = req.user.profile;
if (profile) {
const name = req.user.profile.name.givenName;
const familyName = req.user.profile.name.familyName;
const isConnected = true;
await this.update_id(req.user.profile.id, name, req.user.profile.emails[0].value, familyName, isConnected);
res.redirect('http://localhost:8080/dashboard?name='+ name + '&familyName=' + familyName);
}
else
res.redirect('http://localhost:8080/login/failure');
}
@Post()
async update_id(g_id: string, name: string, email: string, familyName: string, isConnected: boolean): Promise<User> {
try {
const isExisting = await this.authService.findOneByGoogleId(g_id)
if (!isExisting) {
const user = await this.authService.create(g_id, name, email, familyName, isConnected);
return user;
}
else if (isExisting) {
const payloadUser = {
isConnected: true,
};
const user = await this.authService.findOneByGoogleId(g_id);
await this.authService.authRepository.update(user, payloadUser);
return user;
}
} catch(err) {
throw Error("something went wrong");
}
}
}
|
06165db59ce95f0a90afb4812b41c81590b3f532 | TypeScript | kopenkinda/fun | /prolog-problems/src/03-logic-and-codes/04-gray-code.ts | 3.5625 | 4 | // An n-bit Gray code is a sequence of n-bit strings constructed
// according to certain rules. For example,
// n = 1: C(1) = ['0','1'].
// n = 2: C(2) = ['00','01','11','10'].
// n = 3: C(3) = ['000','001','011','010','110','111','101','100'].
// Find out the construction rules and write a predicate with the following
// specification:
// % gray(N,C) :- C is the N-bit Gray code
// Can you apply the method of "result caching" in order to make the predicate
// more efficient, when it is to be used repeatedly?
//
// |
2031cb0a18e1aba48c89bb4efba94e7ed1f25861 | TypeScript | jryx0/vscode-sqlite | /tests/unit/sqlite/resultSetParser.test.ts | 2.640625 | 3 | import { ResultSetParser } from '../../../src/sqlite/resultSetParser';
describe("ResultSetParser Tests", function () {
test("should build resultset if chunks are valid", function() {
let resultSetParser = new ResultSetParser();
resultSetParser.push("SELECT * FROM company;\n\"h1\" \"h");
resultSetParser.push("2\"\n\"r1\" \"r2\"\n");
resultSetParser.push("\"r1\" \"r2\"\n");
let expected = [];
expected.push({stmt: "SELECT * FROM company;", header: ["h1", "h2"], rows: [["r1", "r2"], ["r1", "r2"]]});
let actual = resultSetParser.done();
expect(actual).toEqual(expected);
});
test("should build resultset on Windows if chunks are valid", function() {
let resultSetParser = new ResultSetParser();
resultSetParser.push("SELECT * FROM company;\r\n\"h1\" \"h");
resultSetParser.push("2\"\r\n\"r1\" \"r2\"\r\n");
resultSetParser.push("\"r1\" \"r2\"\r\n");
let expected = [];
expected.push({stmt: "SELECT * FROM company;", header: ["h1", "h2"], rows: [["r1", "r2"], ["r1", "r2"]]});
let actual = resultSetParser.done();
expect(actual).toEqual(expected);
});
}); |
5500f7a810739e94cf5807282afc0851f58d381f | TypeScript | GoogleCloudPlatform/testgrid | /web/src/APIClient.ts | 2.53125 | 3 | import {
ListDashboardsResponse,
ListDashboardGroupsResponse,
} from './gen/pb/api/v1/data.js';
export interface APIClient {
getDashboards(): Array<String>;
getDashboardGroups(): Array<String>;
}
export class APIClientImpl implements APIClient {
host: String = 'testgrid-data.k8s.io';
public getDashboards(): Array<String> {
const dashboards: Array<String> = [];
fetch(`${this.host}/api/v1/dashboards`).then(async response => {
const resp = ListDashboardsResponse.fromJson(await response.json());
resp.dashboards.forEach(db => {
dashboards.push(db.name);
});
});
return dashboards;
}
public getDashboardGroups(): Array<String> {
const dashboardGroups: Array<String> = [];
fetch(`${this.host}/api/v1/dashboard-groups`).then(async response => {
const resp = ListDashboardGroupsResponse.fromJson(await response.json());
resp.dashboardGroups.forEach(db => {
dashboardGroups.push(db.name);
});
});
return dashboardGroups;
}
}
|
b2ad5a7923537c53516e96ee274391b8d9367de7 | TypeScript | acarrara/clash-of-lords | /app/pieces/world/Coordinates.ts | 3.171875 | 3 | import {Objects} from '../commons/Objects';
export class Coordinates {
private _x:number;
private _y:number;
private xDimension:number;
private yDimension:number;
public constructor(x:number, y:number) {
this._x = x;
this._y = y;
}
public get x():number {
return this._x;
}
public get y():number {
return this._y;
}
public neighbours(xDimension:number, yDimension:number):Array<Coordinates> {
var neighbours:Array<Coordinates> = [];
this.xDimension = xDimension;
this.yDimension = yDimension;
var neighbour:Coordinates = this.westNeighbour();
this.pushNeighbour(neighbour, neighbours);
neighbour = this.eastNeighbour();
this.pushNeighbour(neighbour, neighbours);
neighbour = this.southNeighbour();
this.pushNeighbour(neighbour, neighbours);
neighbour = this.northNeighbour();
this.pushNeighbour(neighbour, neighbours);
this.xDimension = undefined;
this.yDimension = undefined;
return neighbours;
}
private pushNeighbour(neighbour:Coordinates, neighbours:Array<Coordinates>):void {
if (Objects.isDefined(neighbour)) {
neighbours.push(neighbour);
}
};
private insideBorders(x:number, y:number):boolean {
return x >= 0 && x < this.xDimension && y >= 0 && y < this.yDimension;
}
private westNeighbour():Coordinates {
return this.insideBorders(this._x, this._y - 1) ? new Coordinates(this._x, this._y - 1) : undefined;
}
private eastNeighbour():Coordinates {
return this.insideBorders(this._x, this._y + 1) ? new Coordinates(this._x, this._y + 1) : undefined;
}
private northNeighbour():Coordinates {
return this.insideBorders(this._x - 1, this._y) ? new Coordinates(this._x - 1, this._y) : undefined;
}
private southNeighbour():Coordinates {
return this.insideBorders(this._x + 1, this._y) ? new Coordinates(this._x + 1, this._y) : undefined;
}
} |
44d8a36bef0751779596db3ce89263921c78abde | TypeScript | haproxyhq/frontend | /app/models/toast.model.ts | 2.734375 | 3 | export class ToastModel {
content: string;
style: string;
timeout: number;
htmlAllowed: boolean;
constructor(content: string, style: string = '', timeout: number = 3000, htmlAllowed: boolean = true) {
this.content = content;
this.style = style;
this.timeout = timeout;
this.htmlAllowed = htmlAllowed;
};
}
|
cf9d38eda23d5ad94a0ea72204e8cdde1168170d | TypeScript | cdcalderon/SpotifyTypescriptNodeApi | /server/spotify/base-request.ts | 2.703125 | 3 | export class Request {
host: any;
port: any;
scheme: any;
queryParameters: any;
bodyParameters: any;
headers: any;
path: any;
constructor(builder: any) {
if (!builder) {
throw new Error('No builder supplied to constructor');
}
this.host = builder.host;
this.port = builder.port;
this.scheme = builder.scheme;
this.queryParameters = builder.queryParameters;
this.bodyParameters = builder.bodyParameters;
this.headers = builder.headers;
this.path = builder.path;
}
getHost() {
return this.host;
};
getPort() {
return this.port;
};
getScheme() {
return this.scheme;
};
getPath() {
return this.path;
};
getQueryParameters() {
return this.queryParameters;
};
getBodyParametersfunction() {
return this.bodyParameters;
};
getHeadersfunction() {
return this.headers;
};
getURI() {
if (!this.scheme || !this.host || !this.port) {
throw new Error('Missing components necessary to construct URI');
}
let uri = this.scheme + '://' + this.host;
if (this.scheme === 'http' && this.port !== 80 ||
this.scheme === 'https' && this.port !== 443) {
uri += ':' + this.port;
}
if (this.path) {
uri += this.path;
}
return uri;
};
getURL() {
let uri = this.getURI();
if (this.getQueryParameters()) {
return uri + this.getQueryParameterString();
} else {
return uri;
}
};
addQueryParameters(queryParameters: any) {
for (let key in queryParameters) {
this.addQueryParameter(key, queryParameters[key]);
}
};
addQueryParameter(key: any, value: any) {
if (!this.queryParameters) {
this.queryParameters = {};
}
this.queryParameters[key] = value;
};
addBodyParameters(bodyParameters: any) {
for (let key in bodyParameters) {
this.addBodyParameter(key, bodyParameters[key]);
}
};
addBodyParameter(key: any, value: any) {
if (!this.bodyParameters) {
this.bodyParameters = {};
}
this.bodyParameters[key] = value;
};
addHeaders(headers: any) {
if (!this.headers) {
this.headers = headers;
} else {
for (let key in headers) {
this.headers[key] = headers[key];
}
}
};
getQueryParameterString() {
let queryParameters = this.getQueryParameters();
if (!queryParameters) {
return;
}
let queryParameterString = '?';
let first = true;
for (let key in queryParameters) {
if (queryParameters.hasOwnProperty(key)) {
if (!first) {
queryParameterString += '&';
} else {
first = false;
}
queryParameterString += key + '=' + queryParameters[key];
}
}
return queryParameterString;
};
}
|
59988293ce52df4ed4457c698bebe2cd30e50e17 | TypeScript | baptistemanson/webgpu-samples | /src/examples/fractalCube.ts | 2.625 | 3 | import { mat4, vec3 } from "gl-matrix";
import {
cubeVertexArray,
cubeVertexSize,
cubeColorOffset,
cubeUVOffset,
cubePositionOffset,
} from "../cube";
import glslangModule from "../glslang";
import { updateBufferData } from "../helpers";
/**
* This demo renders a cube into a cube, into a cube.
*
* In order to do this, the cube is rendered to the framebuffer.
* Then on the next render, the framebuffer is used as a texture for the same cube.
* There is only one render pass, as we reuse the framebuffer from the previous frame.
*
* In WebGL, I think we would need two draw calls to get the same effect. The first one would render to a texture, the second one would render this texture in the framebuffer.
* Overall,
*/
export const title = "Fractal Cube";
export const description =
"This example uses the previous frame's rendering result \
as the source texture for the next frame.";
// in the text layout(set = 0, binding = 0), "binding" is the important number for gluing things together in WebGPU.
export async function init(canvas: HTMLCanvasElement) {
const vertexShaderGLSL = `#version 450
layout(set = 0, binding = 0) uniform Uniforms {
mat4 modelViewProjectionMatrix;
} uniforms;
layout(location = 0) in vec4 position;
layout(location = 1) in vec4 color;
layout(location = 2) in vec2 uv;
layout(location = 0) out vec4 fragColor;
layout(location = 1) out vec2 fragUV;
void main() {
gl_Position = uniforms.modelViewProjectionMatrix * position;
fragColor = color;
fragUV = uv;
}`;
// New stuff!
// sampler and textures are different now.
// the sampler contains the rules to mag or min the texture
// meanwhile the texture is just the texture.
// it mimics Vulkan, - the motivation for it is that the sampler rules are usually about the same in the whole app, so there is no need to duplicate it in every texture.
const fragmentShaderGLSL = `#version 450
layout(set = 0, binding = 1) uniform sampler mySampler;
layout(set = 0, binding = 2) uniform texture2D myTexture;
layout(location = 0) in vec4 fragColor;
layout(location = 1) in vec2 fragUV;
layout(location = 0) out vec4 outColor;
void main() {
vec4 texColor = texture(sampler2D(myTexture, mySampler), fragUV * 0.8 + 0.1);
// 1.0 if we're sampling the background
float f = float(length(texColor.rgb - vec3(0.5, 0.5, 0.5)) < 0.01);
outColor = mix(texColor, fragColor, f);
}`;
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
const glslang = await glslangModule();
const aspect = Math.abs(canvas.width / canvas.height); // why would the aspect ratio go negative?
let projectionMatrix = mat4.create();
mat4.perspective(projectionMatrix, (2 * Math.PI) / 5, aspect, 1, 100.0);
const context = canvas.getContext("gpupresent");
// @ts-ignore:
const swapChain = context.configureSwapChain({
device,
format: "bgra8unorm", // [0,1] 32 bit w transparency
usage: GPUTextureUsage.OUTPUT_ATTACHMENT | GPUTextureUsage.COPY_SRC,
});
const [verticesBuffer, vertexMapping] = device.createBufferMapped({
// cpu accessible buffer
size: cubeVertexArray.byteLength,
usage: GPUBufferUsage.VERTEX, // vertex buffer
});
new Float32Array(vertexMapping).set(cubeVertexArray);
verticesBuffer.unmap(); // hand off to the gpu
// reflects the shader code. Could be generated by the compiler.
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
// Transform
binding: 0,
visibility: GPUShaderStage.VERTEX,
type: "uniform-buffer",
},
{
// Sampler
binding: 1,
visibility: GPUShaderStage.FRAGMENT,
type: "sampler",
},
{
// Texture view
binding: 2,
visibility: GPUShaderStage.FRAGMENT,
type: "sampled-texture",
},
],
});
// the pipeline layout is a collection of bind groups layouts.
const pipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout],
});
const pipeline = device.createRenderPipeline({
layout: pipelineLayout,
vertexStage: {
module: device.createShaderModule({
code: glslang.compileGLSL(vertexShaderGLSL, "vertex"),
// @ts-ignore
source: vertexShaderGLSL,
transform: (source) => glslang.compileGLSL(source, "vertex"),
}),
entryPoint: "main",
},
fragmentStage: {
module: device.createShaderModule({
code: glslang.compileGLSL(fragmentShaderGLSL, "fragment"),
// @ts-ignore
source: fragmentShaderGLSL,
transform: (source) => glslang.compileGLSL(source, "fragment"),
}),
entryPoint: "main",
},
primitiveTopology: "triangle-list",
depthStencilState: {
depthWriteEnabled: true,
depthCompare: "less", // explicit
format: "depth24plus-stencil8",
},
vertexState: {
vertexBuffers: [
// only one vertex buffer, containing all attributes interlaced.
{
arrayStride: cubeVertexSize,
attributes: [
{
// position
shaderLocation: 0,
offset: cubePositionOffset,
format: "float4",
},
{
// color
shaderLocation: 1,
offset: cubeColorOffset,
format: "float4",
},
{
// uv
shaderLocation: 2,
offset: cubeUVOffset,
format: "float2",
},
],
},
],
},
rasterizationState: {
cullMode: "back",
},
colorStates: [
{
format: "bgra8unorm",
},
],
});
const depthTexture = device.createTexture({
// depth texture needs to be explicitely created.
// a depth texture is used when we need to figure out which pixel is on top of which one.
// imagine a cube. We want the faces on the back to be behind the ones on the front.
// when writing the fragment/triangles, the depth buffer is used for this.
size: { width: canvas.width, height: canvas.height, depth: 1 }, // 2d
format: "depth24plus-stencil8",
usage: GPUTextureUsage.OUTPUT_ATTACHMENT,
});
const renderPassDescriptor: GPURenderPassDescriptor = {
colorAttachments: [
{
attachment: undefined, // Attachment is set later
loadValue: { r: 0.5, g: 0.5, b: 0.5, a: 1.0 },
},
],
depthStencilAttachment: {
attachment: depthTexture.createView(),
depthLoadValue: 1.0,
depthStoreOp: "store",
stencilLoadValue: 0,
stencilStoreOp: "store",
},
};
const uniformBufferSize = 4 * 16; // 4x4 matrix
const uniformBuffer = device.createBuffer({
size: uniformBufferSize,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const cubeTexture = device.createTexture({
size: { width: canvas.width, height: canvas.height, depth: 1 },
format: "bgra8unorm",
usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.SAMPLED,
});
const sampler = device.createSampler({
// cool, samplers are separate from the texture.
magFilter: "linear",
minFilter: "linear",
});
const uniformBindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: uniformBuffer,
},
},
{
binding: 1,
resource: sampler,
},
{
binding: 2,
resource: cubeTexture.createView(),
},
],
});
function getTransformationMatrix() {
let viewMatrix = mat4.create();
mat4.translate(viewMatrix, viewMatrix, vec3.fromValues(0, 0, -4));
let now = Date.now() / 10000;
mat4.rotate(
viewMatrix,
viewMatrix,
1,
vec3.fromValues(Math.sin(now), Math.cos(now), 0)
);
let modelViewProjectionMatrix = mat4.create();
mat4.multiply(modelViewProjectionMatrix, projectionMatrix, viewMatrix);
return modelViewProjectionMatrix as Float32Array;
}
return function frame() {
const swapChainTexture = swapChain.getCurrentTexture();
renderPassDescriptor.colorAttachments[0].attachment = swapChainTexture.createView();
const commandEncoder = device.createCommandEncoder();
const { uploadBuffer } = updateBufferData(
// custom made function that updates a buffer GPU side, via a transfer of a delta and applying it after via a copy.
device,
uniformBuffer,
0,
getTransformationMatrix(),
commandEncoder
);
// 1 render pass. The framebuffer is then copied in a texture for the next pass. After a few frames, we should have enough depths.
// it's a nice usecase of what can be possible with webgpu. In WebGL, I would have to use CopyTexImage2D.
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setPipeline(pipeline);
passEncoder.setBindGroup(0, uniformBindGroup); // the 0 corresponds to the layout index in the pipeline layout
passEncoder.setVertexBuffer(0, verticesBuffer);
passEncoder.draw(36, 1, 0, 0);
passEncoder.endPass();
commandEncoder.copyTextureToTexture(
{
texture: swapChainTexture,
},
{
texture: cubeTexture,
},
{
width: canvas.width,
height: canvas.height,
depth: 1,
}
);
device.defaultQueue.submit([commandEncoder.finish()]);
uploadBuffer.destroy();
};
}
|
b74b0a65daddb16d5d53fd353653e27b0f1f21f5 | TypeScript | NervJS/nerv-server | /src/index.ts | 2.78125 | 3 | // tslint:disable-next-line:max-line-length
import {
isVNode,
isVText,
isWidget,
isStateLess,
isString,
isNumber,
isFunction,
isNullOrUndef,
isArray,
isInvalid
} from './is'
import {
encodeEntities,
isVoidElements,
escapeText,
getCssPropertyName,
isUnitlessNumber,
assign
} from './utils'
const skipAttributes = {
ref: true,
key: true,
children: true
}
function hashToClassName (obj) {
const arr: string[] = []
for (const i in obj) {
if (obj[i]) {
arr.push(i)
}
}
return arr.join(' ')
}
function renderStylesToString (styles: string | object): string {
if (isString(styles)) {
return styles
} else {
let renderedString = ''
for (const styleName in styles) {
const value = styles[styleName]
if (isString(value)) {
renderedString += `${getCssPropertyName(styleName)}${value};`
} else if (isNumber(value)) {
renderedString += `${getCssPropertyName(
styleName
)}${value}${isUnitlessNumber[styleName] ? '' : 'px'};`
}
}
return renderedString
}
}
function renderVNodeToString (vnode, parent, context, firstChild) {
const { tagName, props, children } = vnode
if (isVText(vnode)) {
return encodeEntities(vnode.text)
} else if (isVNode(vnode)) {
let renderedString = `<${tagName}`
let html
if (!isNullOrUndef(props)) {
for (const prop in props) {
const value = props[prop]
if (skipAttributes[prop]) {
continue
}
if (prop === 'dangerouslySetInnerHTML') {
html = value.__html
} else if (prop === 'style') {
renderedString += ` style="${renderStylesToString(value)}"`
} else if (prop === 'class' || prop === 'className') {
renderedString += ` class="${isString(value) ? value : hashToClassName(value)}"`
} else if (prop === 'defaultValue') {
if (!props.value) {
renderedString += ` value="${escapeText(value)}"`
}
} else if (prop === 'defaultChecked') {
if (!props.checked) {
renderedString += ` checked="${value}"`
}
} else {
if (isString(value)) {
renderedString += ` ${prop}="${escapeText(value)}"`
} else if (isNumber(value)) {
renderedString += ` ${prop}="${value}"`
} else if (value === true) {
renderedString += ` ${prop}`
}
}
}
}
if (isVoidElements[tagName]) {
renderedString += `/>`
} else {
renderedString += `>`
if (!isInvalid(children)) {
if (isString(children)) {
renderedString += children === '' ? ' ' : escapeText(children)
} else if (isNumber(children)) {
renderedString += children + ''
} else if (isArray(children)) {
for (let i = 0, len = children.length; i < len; i++) {
const child = children[i]
if (isString(child)) {
renderedString += child === '' ? ' ' : escapeText(child)
} else if (isNumber(child)) {
renderedString += child
} else if (!isInvalid(child)) {
renderedString += renderVNodeToString(
child,
vnode,
context,
i === 0
)
}
}
} else {
renderedString += renderVNodeToString(children, vnode, context, true)
}
} else if (html) {
renderedString += html
}
if (!isVoidElements[tagName]) {
renderedString += `</${tagName}>`
}
}
return renderedString
} else if (isWidget(vnode)) {
const { ComponentType: type } = vnode
const instance = new type(props, context)
instance._disable = true
if (isFunction(instance.getChildContext)) {
context = assign(assign({}, context), instance.getChildContext())
}
instance.context = context
if (isFunction(instance.componentWillMount)) {
instance.componentWillMount()
}
const nextVnode = instance.render(props, instance.state, context)
if (isInvalid(nextVnode)) {
return '<!--!-->'
}
return renderVNodeToString(nextVnode, vnode, context, true)
} else if (isStateLess(vnode)) {
const nextVnode = tagName(props, context)
if (isInvalid(nextVnode)) {
return '<!--!-->'
}
return renderVNodeToString(nextVnode, vnode, context, true)
}
}
export function renderToString (input: any): string {
return renderVNodeToString(input, {}, {}, true) as string
}
export function renderToStaticMarkup (input: any): string {
return renderVNodeToString(input, {}, {}, true) as string
}
|
ba63749bda07e2215444837f9e4f9360b3cb48c0 | TypeScript | grndctrl/next-world-builder | /src/utilities/GeometryGenerators.ts | 2.9375 | 3 | import * as THREE from 'three';
import { mergeBufferGeometries } from 'three-stdlib';
import * as GeometryUtilities from '@utilities/GeometryUtilities';
/**
* Check each side, generate a segmented face if there is no neighbour.
* Returns null when all sides have neighbours.
*
* @param {number} blockSize
* @param {number} segments
* @param {boolean[]} neighbours
* @return {*} {(THREE.BufferGeometry | null)}
*/
function generateBlockSide(
blockSize: number,
segments: number,
side: THREE.Vector3,
color: THREE.Color = new THREE.Color('#fff')
): THREE.BufferGeometry {
const plane = new THREE.PlaneBufferGeometry(blockSize, blockSize, segments, segments);
const { position } = plane.attributes;
const colors: number[] = [];
for (let i = 0; i < position.count; i++) {
position.setZ(i, blockSize * 0.5);
colors.push(color.r, color.g, color.b);
}
if (side.x === -1) {
plane.rotateY(Math.PI * -0.5);
} else if (side.x === 1) {
plane.rotateY(Math.PI * 0.5);
} else if (side.y === -1) {
plane.rotateX(Math.PI * 0.5);
} else if (side.y === 1) {
plane.rotateX(Math.PI * -0.5);
} else if (side.z === -1) {
plane.rotateY(Math.PI * 1);
} else if (side.z === 1) {
// do nothing
}
plane.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
plane.deleteAttribute('uv');
return plane;
}
function generateBlockSideHalf(
blockSize: number,
segments: number,
side: THREE.Vector3,
half: THREE.Vector2,
color: THREE.Color = new THREE.Color('#fff')
): THREE.BufferGeometry {
let width = blockSize;
let height = blockSize;
if (half.y === 0) {
width *= 0.5;
} else if (half.x === 0) {
height *= 0.5;
}
const plane = new THREE.PlaneBufferGeometry(width, height, segments, segments);
const { position } = plane.attributes;
const colors: number[] = [];
for (let i = 0; i < position.count; i++) {
if (half.x === -1) {
position.setX(i, position.getX(i) - width * 0.5);
} else if (half.x === 1) {
position.setX(i, position.getX(i) + width * 0.5);
} else if (half.y === -1) {
position.setY(i, position.getY(i) - height * 0.5);
} else if (half.y === 1) {
position.setY(i, position.getY(i) + height * 0.5);
}
position.setZ(i, blockSize * 0.5);
colors.push(color.r, color.g, color.b);
}
if (side.x === -1) {
plane.rotateY(Math.PI * -0.5);
} else if (side.x === 1) {
plane.rotateY(Math.PI * 0.5);
} else if (side.y === -1) {
plane.rotateX(Math.PI * 0.5);
} else if (side.y === 1) {
plane.rotateX(Math.PI * -0.5);
} else if (side.z === -1) {
plane.rotateY(Math.PI * 1);
} else if (side.z === 1) {
// do nothing
}
plane.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
plane.deleteAttribute('uv');
return plane;
}
function generateBlockSides(
blockSize: number,
segments: number,
neighbours: boolean[],
color: THREE.Color = new THREE.Color('#fff')
): THREE.BufferGeometry | null {
const sides = [];
// -X axis
if (!neighbours[8]) {
const side = generateBlockSide(blockSize, segments, new THREE.Vector3(-1, 0, 0), color);
sides.push(side);
}
// +X axis
if (!neighbours[9]) {
const side = generateBlockSide(blockSize, segments, new THREE.Vector3(1, 0, 0), color);
sides.push(side);
}
// -Y axis
if (!neighbours[6]) {
const plane = new THREE.PlaneBufferGeometry(blockSize, blockSize, 4, 4);
const segment = blockSize / 4;
const { position } = plane.attributes;
const colors: number[] = [];
const innerIndices = [
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(-segment, -segment, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(0, -segment, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(segment, -segment, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(-segment, 0, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(0, 0, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(segment, 0, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(-segment, segment, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(0, segment, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(segment, segment, 0)),
];
innerIndices.forEach((index) => {
const { position } = plane.attributes;
position.setXYZ(index, position.getX(index) * 0.5, position.getY(index) * 0.5, position.getZ(index) * 0.5);
});
plane.rotateX(Math.PI * 0.5);
for (let i = 0; i < position.count; i++) {
position.setY(i, -blockSize * 0.5);
colors.push(color.r, color.g, color.b);
}
plane.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
plane.deleteAttribute('uv');
sides.push(plane);
}
// +Y axis
if (!neighbours[11]) {
const plane = new THREE.PlaneBufferGeometry(blockSize, blockSize, 4, 4);
const segment = blockSize / 4;
const { position } = plane.attributes;
const colors: number[] = [];
const innerIndices = [
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(-segment, -segment, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(0, -segment, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(segment, -segment, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(-segment, 0, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(0, 0, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(segment, 0, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(-segment, segment, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(0, segment, 0)),
...GeometryUtilities.positionIndicesAtPosition(plane, new THREE.Vector3(segment, segment, 0)),
];
innerIndices.forEach((index) => {
const { position } = plane.attributes;
position.setXYZ(index, position.getX(index) * 0.5, position.getY(index) * 0.5, position.getZ(index) * 0.5);
});
plane.rotateX(Math.PI * -0.5);
for (let i = 0; i < position.count; i++) {
position.setY(i, blockSize * 0.5);
colors.push(color.r, color.g, color.b);
}
plane.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
plane.deleteAttribute('uv');
sides.push(plane);
}
// -Z axis
if (!neighbours[2]) {
const side = generateBlockSide(blockSize, segments, new THREE.Vector3(0, 0, -1), color);
sides.push(side);
}
// +Z axis
if (!neighbours[15]) {
const side = generateBlockSide(blockSize, segments, new THREE.Vector3(0, 0, 1), color);
sides.push(side);
}
if (sides.length === 0) {
return null;
}
return mergeBufferGeometries(sides);
}
export { generateBlockSides, generateBlockSide, generateBlockSideHalf };
|
ca5321297e0a56e6c3ffa10d4b142d1df534d989 | TypeScript | r2magarcia/restpkm | /src/services/DigimonsService.ts | 2.984375 | 3 | import { DigimonI } from "../interfaces/DigimonInterfaces";
import { MonsterTypeI } from "../interfaces/MonsterTypeI";
const db = require('../db/Digimons.json');
module DigimonsService {
export function getAll(): Array<DigimonI> {
const digimons: Array<DigimonI> = db;
return digimons
}
export function get(id: number): DigimonI {
const digimons: Array<DigimonI> = db;
const digimon: Array<DigimonI> = digimons.filter(e => e.id === id);
if (digimon.length < 1) {
throw "No se encontró el digimon"
}
return digimon[0];
}
export function getByName(name: string): Array<DigimonI> {
const digimons: Array<DigimonI> = db;
const matches: Array<DigimonI> = digimons.filter(function(el) {
return el.name.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, "").indexOf(name.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, "")) > -1;
})
if (matches.length < 1) {
throw "No se encontró el digimon"
}
return matches;
}
export function getByType(type: string): Array<DigimonI> {
const digimons: Array<DigimonI> = db;
let matches: Array<DigimonI> = [];
digimons.forEach(digimon => {
const found = digimon.type.filter(e => e.name.toLowerCase() === type.toLowerCase());
if (found.length>0) {
matches.push(digimon);
}
})
if (matches.length < 1) {
throw "No se encontró el tipo"
}
return matches;
}
export function create(name:string,nametype:string,img:string):DigimonI{
const digimons: Array<DigimonI> = db;
const id=digimons.length+1;
const type:MonsterTypeI={
name:nametype,
strongAgainst:[],
weakAgainst:[]
}
const digimon:DigimonI={
id:id,
name:name,
type:[type],
img:img,
}
digimons.push(digimon);
return digimon;
}
}
export default DigimonsService;
|
6313c19a0599bcbd2a200b014efbc251a23e8a73 | TypeScript | crazywook/class101-quiz | /vehicles/Vehicle.ts | 3.5 | 4 | import {Wheel} from "./components/Wheel";
import {VehicleType} from "./types";
export class Vehicle<T = VehicleType> {
readonly type: T;
private readonly wheels: Wheel[];
private readonly numberOfWheels: number; // bigger than -1
private fuel: number; // 0~100
constructor(type: T, numberOfWheels: number, wheels: Wheel[], fuel: number) {
this.type = type;
this.numberOfWheels = numberOfWheels;
this.validateNumOfWheels(numberOfWheels);
this.validateWheelsArrayLength(wheels, numberOfWheels);
this.validateFuel(fuel);
this.wheels = wheels;
this.fuel = fuel;
}
validateFuel(fuel: number) {
if (fuel < 0 || fuel > 100) {
throw new Error("Fuel must have a range 0~100");
}
}
validateNumOfWheels(numberOfWheels: number) {
if (numberOfWheels < 0 || numberOfWheels % 1 !== 0) {
throw new Error("NumberOfWheels must be Natural bigger than -1");
}
}
validateWheelsArrayLength(wheels: Wheel[], numberOfWheels: number) {
if (!wheels) {
throw new Error("Wheel does not exist");
}
if (wheels.length !== numberOfWheels) {
throw new Error("Wheels length is different with numberOfWheels");
}
}
getNumberOfWheels(): number {
return this.numberOfWheels;
}
getFuel(): number {
return this.fuel;
}
getType(): T {
return this.type;
}
getWheels() {
return this.wheels;
}
}
|
10c6776f2581c7ab58d59be597d044d16befb9fa | TypeScript | K-REBO/autoGoogleForm | /msg/mod.ts | 2.796875 | 3 | const delete_pass = "asdfjkl;123";
let memory:Array<any> = new Array();
addEventListener("fetch", (event)=> {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request: Request) {
if(request.method == "GET") {
return new Response(JSON.stringify(
{
"result": memory,
}
), {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers":"Content-Type"
}
})
}
else if (request.method === "POST") {
let json = await request.json()
let deleteKey:number = json["delete"];
if(!isNaN(deleteKey)) {
if(String(json["delete_pass"]) === delete_pass) {
console.log(memory);
console.log(deleteKey);
memory.splice(deleteKey, deleteKey + 1);
console.log(memory);
return new Response(JSON.stringify({
"msg":`delete memory with ${deleteKey} as key`
}),{
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers":"Content-Type"
}
});
}
return new Response(JSON.stringify({
"msg":`Invalid ${json["delete_pass"]}`
}),{
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers":"Content-Type"
}
});
}
memory.push({
hrno:json["hrno"],
msg:json["data"]
});
return new Response(JSON.stringify (
{
"msg": "Hello",
}
),{
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers":"Content-Type"
}
});
}
else {
return new Response(JSON.stringify(
{
"msg": "Bad method"
}
),
{
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers":"Content-Type"
}
})
}
} |
89f456f59f6c76605065e107b4a8d370189f4f95 | TypeScript | Pucek9/multiplayerGameEngine | /src/client/UserInterface/PlayersList.ts | 2.71875 | 3 | import { compareBy } from '../../shared/helpers';
import PlayerListModel from '../interfaces/PlayerListModel';
declare const playerListPanel: HTMLDivElement;
declare const playersList: HTMLUListElement;
export default class PlayerListComponent {
constructor() {}
show() {
playerListPanel.style.display = 'block';
}
hide() {
playerListPanel.style.display = 'none';
}
update(players: Array<PlayerListModel>) {
playersList.innerHTML = '';
players
.sort((player1, player2) => compareBy(player1, player2, { kills: 1, deaths: -1, hp: 1 }))
.forEach(_player => {
const li = document.createElement('li');
li.style.color = _player.color;
li.appendChild(
document.createTextNode(
`${_player.name}: Kills:${_player.kills} Deaths:${_player.deaths} HP:${_player.hp}`,
),
);
playersList.append(li);
});
}
}
|
faa9b5c147ab9e2877be02e561d8e3431a3a3ddd | TypeScript | JRiyaz/angular-basics | /src/app/components/routing/reactive-forms/reactive-forms.component.ts | 2.59375 | 3 | import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { CustomEmailValidator } from 'src/app/classes/custom-email-validator';
@Component({
selector: 'app-reactive-forms',
templateUrl: './reactive-forms.component.html',
styleUrls: ['./reactive-forms.component.css']
})
export class ReactiveFormsComponent implements OnInit {
genders: string[] = ['Male', 'Female'];
languages: string[] = ['English', 'Arabic', 'Hindi', 'Urdu'];
pgTechnologies: string[] = ['Java', 'Python', 'Go', 'PHP'];
reactiveForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.initializeForm();
// https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable
// https://stackoverflow.com/questions/58246831/looping-through-form-array-inside-form-group-angular
// this.pgTechnologies.forEach(element => {
// this.technologies.push(this.fb.group({ [element]: new FormControl(element == 'Java' ? true : false) }))
// });
}
initializeForm(): void {
this.reactiveForm = this.fb.group({
email: new FormControl('j.riyazu@gmail.com', [
CustomEmailValidator.needed,
Validators.required,
Validators.minLength(6),
Validators.maxLength(20),
Validators.email,
Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")
], CustomEmailValidator.unique),
language: new FormControl('English'),
gender: new FormControl('Male'),
technologies: this.fb.group({
java: new FormControl(true),
python: new FormControl(false),
go: new FormControl(false),
php: new FormControl(false)
}),
address: this.fb.group({
city: new FormControl('B.Kothakota'),
street: new FormControl('Santha Bazar'),
zipcode: new FormControl('517370')
}),
hobbies: this.fb.array([this.fb.control('')])
});
}
get technologies(): FormArray {
return this.reactiveForm.get('technologies') as FormArray;
}
get hobbies(): FormArray {
return this.reactiveForm.get('hobbies') as FormArray;
}
get email(): AbstractControl {
return this.reactiveForm.get('email');
}
onSubmit(): void {
console.log(this.reactiveForm);
}
removeHobby(index: number): void {
if (confirm(`do you want to delete hobby: ${index + 1}`))
this.hobbies.removeAt(index);
}
addHobby(): void {
this.hobbies.push(this.fb.control(''));
}
}
|
c9c098e5f644551b680c29eb0d67d552a99a3a56 | TypeScript | Voya100/VoyaCode | /src/app/projects/chess/chess-settings.service.ts | 2.96875 | 3 | import { Injectable } from '@angular/core';
@Injectable()
export class ChessSettingsService {
readonly boardSize: number = 8;
positions: string[];
whiteComputer: boolean = false;
blackComputer: boolean = true;
boardReversed: boolean = false;
// Contains tile positions on the board interface
// boardTilePositions[y][x][tile.x, tile.y]
boardTilePositions: number[][][];
private readonly defaultPositions: string[] = ['RKBQXBKR',
'PPPPPPPP'];
constructor() {
this.changeReversed(false);
this.positions = this.defaultPositions;
}
// Changes game mode
changeMode(mode: number){
switch(mode){
case 0: // Player vs computer
this.whiteComputer = false;
this.blackComputer = true;
break;
case 1: // Local multiplayer
this.whiteComputer = false;
this.blackComputer = false;
break;
case 2: // Computer vs computer
this.whiteComputer = true;
this.blackComputer = true;
break;
}
}
setPositions(topRow: string, bottomRow: string){
this.positions = [bottomRow, topRow];
}
// Changes piece layout back to default
resetPositions(){
this.positions = this.defaultPositions;
}
// Sets template for tile positions used by ChessBoardComponent
changeReversed(reversed: boolean){
this.boardReversed = reversed;
if(reversed){
this.boardTilePositions = Array(this.boardSize).fill(1).map((x, j) => Array(this.boardSize).fill(1).map((_, i) => [j, 7-i]));
}else{
this.boardTilePositions = Array(this.boardSize).fill(1).map((x, j) => Array(this.boardSize).fill(1).map((_, i) => [i, j]));
}
}
}
|
794486843125b9a2927f709fd5e30ed877111630 | TypeScript | staltz/xstream | /src/extra/sampleCombine.ts | 2.96875 | 3 | import {InternalListener, Operator, Stream} from '../index';
export interface SampleCombineSignature {
(): <T>(s: Stream<T>) => Stream<[T]>;
<T1>(s1: Stream<T1>): <T>(s: Stream<T>) => Stream<[T, T1]>;
<T1, T2>(
s1: Stream<T1>,
s2: Stream<T2>): <T>(s: Stream<T>) => Stream<[T, T1, T2]>;
<T1, T2, T3>(
s1: Stream<T1>,
s2: Stream<T2>,
s3: Stream<T3>): <T>(s: Stream<T>) => Stream<[T, T1, T2, T3]>;
<T1, T2, T3, T4>(
s1: Stream<T1>,
s2: Stream<T2>,
s3: Stream<T3>,
s4: Stream<T4>): <T>(s: Stream<T>) => Stream<[T, T1, T2, T3, T4]>;
<T1, T2, T3, T4, T5>(
s1: Stream<T1>,
s2: Stream<T2>,
s3: Stream<T3>,
s4: Stream<T4>,
s5: Stream<T5>): <T>(s: Stream<T>) => Stream<[T, T1, T2, T3, T4, T5]>;
<T1, T2, T3, T4, T5, T6>(
s1: Stream<T1>,
s2: Stream<T2>,
s3: Stream<T3>,
s4: Stream<T4>,
s5: Stream<T5>,
s6: Stream<T6>): <T>(s: Stream<T>) => Stream<[T, T1, T2, T3, T4, T5, T6]>;
<T1, T2, T3, T4, T5, T6, T7>(
s1: Stream<T1>,
s2: Stream<T2>,
s3: Stream<T3>,
s4: Stream<T4>,
s5: Stream<T5>,
s6: Stream<T6>,
s7: Stream<T7>): <T>(s: Stream<T>) => Stream<[T, T1, T2, T3, T4, T5, T6, T7]>;
<T1, T2, T3, T4, T5, T6, T7, T8>(
s1: Stream<T1>,
s2: Stream<T2>,
s3: Stream<T3>,
s4: Stream<T4>,
s5: Stream<T5>,
s6: Stream<T6>,
s7: Stream<T7>,
s8: Stream<T8>): <T>(s: Stream<T>) => Stream<[T, T1, T2, T3, T4, T5, T6, T7, T8]>;
(...streams: Array<Stream<any>>): (s: Stream<any>) => Stream<Array<any>>;
}
const NO = {};
export class SampleCombineListener<T> implements InternalListener<T> {
constructor(private i: number, private p: SampleCombineOperator<any>) {
p.ils[i] = this;
}
_n(t: T): void {
const p = this.p;
if (p.out === NO) return;
p.up(t, this.i);
}
_e(err: any): void {
this.p._e(err);
}
_c(): void {
this.p.down(this.i, this);
}
}
export class SampleCombineOperator<T> implements Operator<T, Array<any>> {
public type = 'sampleCombine';
public ins: Stream<T>;
public others: Array<Stream<any>>;
public out: Stream<Array<any>>;
public ils: Array<SampleCombineListener<any>>;
public Nn: number; // *N*umber of streams still to send *n*ext
public vals: Array<any>;
constructor(ins: Stream<T>, streams: Array<Stream<any>>) {
this.ins = ins;
this.others = streams;
this.out = NO as Stream<Array<any>>;
this.ils = [];
this.Nn = 0;
this.vals = [];
}
_start(out: Stream<Array<any>>): void {
this.out = out;
const s = this.others;
const n = this.Nn = s.length;
const vals = this.vals = new Array(n);
for (let i = 0; i < n; i++) {
vals[i] = NO;
s[i]._add(new SampleCombineListener<any>(i, this));
}
this.ins._add(this);
}
_stop(): void {
const s = this.others;
const n = s.length;
const ils = this.ils;
this.ins._remove(this);
for (let i = 0; i < n; i++) {
s[i]._remove(ils[i]);
}
this.out = NO as Stream<Array<any>>;
this.vals = [];
this.ils = [];
}
_n(t: T): void {
const out = this.out;
if (out === NO) return;
if (this.Nn > 0) return;
out._n([t, ...this.vals]);
}
_e(err: any): void {
const out = this.out;
if (out === NO) return;
out._e(err);
}
_c(): void {
const out = this.out;
if (out === NO) return;
out._c();
}
up(t: any, i: number): void {
const v = this.vals[i];
if (this.Nn > 0 && v === NO) {
this.Nn--;
}
this.vals[i] = t;
}
down(i: number, l: SampleCombineListener<any>): void {
this.others[i]._remove(l);
}
}
let sampleCombine: SampleCombineSignature;
/**
*
* Combines a source stream with multiple other streams. The result stream
* will emit the latest events from all input streams, but only when the
* source stream emits.
*
* If the source, or any input stream, throws an error, the result stream
* will propagate the error. If any input streams end, their final emitted
* value will remain in the array of any subsequent events from the result
* stream.
*
* The result stream will only complete upon completion of the source stream.
*
* Marble diagram:
*
* ```text
* --1----2-----3--------4--- (source)
* ----a-----b-----c--d------ (other)
* sampleCombine
* -------2a----3b-------4d--
* ```
*
* Examples:
*
* ```js
* import sampleCombine from 'xstream/extra/sampleCombine'
* import xs from 'xstream'
*
* const sampler = xs.periodic(1000).take(3)
* const other = xs.periodic(100)
*
* const stream = sampler.compose(sampleCombine(other))
*
* stream.addListener({
* next: i => console.log(i),
* error: err => console.error(err),
* complete: () => console.log('completed')
* })
* ```
*
* ```text
* > [0, 8]
* > [1, 18]
* > [2, 28]
* ```
*
* ```js
* import sampleCombine from 'xstream/extra/sampleCombine'
* import xs from 'xstream'
*
* const sampler = xs.periodic(1000).take(3)
* const other = xs.periodic(100).take(2)
*
* const stream = sampler.compose(sampleCombine(other))
*
* stream.addListener({
* next: i => console.log(i),
* error: err => console.error(err),
* complete: () => console.log('completed')
* })
* ```
*
* ```text
* > [0, 1]
* > [1, 1]
* > [2, 1]
* ```
*
* @param {...Stream} streams One or more streams to combine with the sampler
* stream.
* @return {Stream}
*/
sampleCombine = function sampleCombine(...streams: Array<Stream<any>>) {
return function sampleCombineOperator(sampler: Stream<any>): Stream<Array<any>> {
return new Stream<Array<any>>(new SampleCombineOperator(sampler, streams));
};
} as SampleCombineSignature;
export default sampleCombine; |
d2b5290a176211918041613388b448e11e265c3b | TypeScript | carlosjmarin/ts-sandbox | /main.ts | 2.734375 | 3 | let a: number;
let b: boolean;
let c: string;
let d: any;
let e: number[] = [1, 2, 3];
let f: any[] = [1,true, 'a', false];
const CarLambo = 0;
const CarFerrari = 1;
const CarTesla = 2;
enum Car { Lambo = 0, Ferrari = 1, Tesla = 2 }; |
a861b11a9f937103974cdfd3c59494221355ffe9 | TypeScript | wedev-siqr/siqr-server | /src/controllers/membership.controller.ts | 2.515625 | 3 | import { status } from 'server/reply';
import { Context } from 'server/typings/common';
import { Membership, MembershipAttributes } from '../models';
export const getMemberships = async (ctx: Context) => {
ctx.log.info('Starting getMemberships');
const memberships = await Membership.findAll();
ctx.log.info('Finishing getMemberships');
return status(200).json(memberships);
};
export const getMembershipById = async (ctx: Context) => {
const membershipId = ctx.params.id;
const membership = await Membership.findByPk(membershipId);
if (!membership)
return status(404).json({
message: `Membership with id ${membershipId} doesn't exist.`,
});
return status(200).json(membership);
};
export const createMembership = async (ctx: Context) => {
ctx.log.info('Starting createMemberships');
const payload: MembershipAttributes = ctx.req.body;
try {
const membership = await Membership.create(payload);
ctx.log.info('Finishing createMemberships');
return status(200).json(membership);
} catch ({ errors }) {
ctx.log.error('Finishing createMemberships with error');
return status(400).json(errors.map((error: any) => error.message));
}
};
export const updateMembership = async (ctx: Context) => {
ctx.log.info('Starting updateMemberships');
const payload: MembershipAttributes = ctx.req.body;
try {
ctx.log.info('Finding membership with id: %d.', ctx.params.id);
const membership = await Membership.findByPk(ctx.params.id);
if (!membership) {
ctx.log.error("Membership with id %d doesn't exist.", ctx.params.id);
return status(404).json({
message: `Membership with id ${ctx.params.id} doesn't exist.`,
});
}
ctx.log.info('Updating membership');
await Membership.update(payload, {
fields: ['name', 'price', 'duration', 'durationTimeUnit'],
where: { id: ctx.params.id },
});
ctx.log.info('Finishing updateMemberships');
return status(204);
} catch (error) {
ctx.log.error('Finishing updateMemberships with error');
return status(409).json(error);
}
};
export const deleteMembership = async (ctx: Context) => {
ctx.log.info('Starting deleteMemberships');
try {
ctx.log.info('Finding membership with id: %d', ctx.params.id);
const membership = await Membership.findByPk(ctx.params.id);
if (!membership) {
ctx.log.error("Membership with id %d doesn't exist.", ctx.params.id);
return status(404).json({
message: `Membership with id ${ctx.params.id} doesn't exist.`,
});
}
ctx.log.info('Deleting membership');
await Membership.destroy({ where: { id: ctx.params.id } });
ctx.log.info('Finishing deleteMemberships');
return status(204);
} catch (error) {
ctx.log.info('Finishing deleteMemberships with error');
return status(409).json(error);
}
};
|
48fae27b0150b8e553a0a9d0976eb9622d6830de | TypeScript | TwanvandenBor/twans_chess_game | /src/helpers/DamBoardHelper.ts | 2.96875 | 3 | import { DamStone } from "@/model/DamStone";
import { BoardCoordinate } from "@/model/BoardCoordinate";
import { DamStoneCoordinate } from "@/model/DamStoneCoordinate";
export class DamBoardHelper {
getNumberOfTilesPerBoardRow(): number {
return 8;
}
getBoardCoordinateFromXAndY(x: number, y: number): BoardCoordinate {
return new BoardCoordinate(x, y);
}
getDamStoneCoordinateFromXAndY(x: number, y: number): DamStoneCoordinate {
return new DamStoneCoordinate(x, y);
}
getIsWhiteTileForCoordinate(damTileRowIndex: number, damTileIndex: number): boolean {
return !(
(((damTileRowIndex % 2) == 0) && (damTileIndex % 2 == 0)) ||
(((damTileRowIndex % 2) == 1) && (damTileIndex % 2 != 0))
);
}
isStoneTryToMoveStepBackwards(currentStone: DamStone, movingToCoordinate: BoardCoordinate, areStonesInTopRowsWhite: boolean): boolean {
if(areStonesInTopRowsWhite){
if(
currentStone?.isColorWhite &&
movingToCoordinate?.yPositionFromTopLeftOfBoard < currentStone?.coordinate?.yPositionFromTopLeftOfBoard
){
return true;
} else if(
!currentStone?.isColorWhite &&
movingToCoordinate?.yPositionFromTopLeftOfBoard > currentStone?.coordinate?.yPositionFromTopLeftOfBoard
){
return true;
}
} else {
if(
currentStone?.isColorWhite &&
movingToCoordinate?.yPositionFromTopLeftOfBoard > currentStone?.coordinate?.yPositionFromTopLeftOfBoard
){
return true;
} else if(
!currentStone?.isColorWhite &&
movingToCoordinate?.yPositionFromTopLeftOfBoard < currentStone?.coordinate?.yPositionFromTopLeftOfBoard
){
return true;
}
}
return false;
}
isTileCoordinatePossibleStepForSelectedDamStone(damStones: DamStone[], damStoneToShowPossibleStepsFor: DamStone, tileCoordinateToPossiblyStepTo: BoardCoordinate, isWhitePlayersTurn: boolean, areStonesInTopRowsWhite: boolean): boolean {
if(!damStoneToShowPossibleStepsFor?.coordinate){ return false; }
if(damStoneToShowPossibleStepsFor?.isColorWhite != isWhitePlayersTurn){ return false; }
// Validate step backwards if stone is NOT a dam
if(!damStoneToShowPossibleStepsFor?.isDam){
if(
this.isStoneTryToMoveStepBackwards(
damStoneToShowPossibleStepsFor,
tileCoordinateToPossiblyStepTo,
areStonesInTopRowsWhite
)
){
return false;
}
}
const possibleCoordinatesToStepToFromSelectedDamStone = this.getListOfPossibleStepCoordinatesOneStepFromCurrentCoordinate(damStoneToShowPossibleStepsFor?.coordinate)
.filter((damStoneCoordinate: DamStoneCoordinate) => {
return (
!this.isCoordinateOutsidePlayerField(damStoneCoordinate) &&
!this.isOtherStoneAlreadyOnCoordinate(damStones, damStoneCoordinate)
);
});
const isPossibleCoordinateTileCoordinateToPossiblyStepTo = possibleCoordinatesToStepToFromSelectedDamStone.find((coordinate: DamStoneCoordinate) => {
return (
coordinate?.xPositionFromTopLeftOfBoard == tileCoordinateToPossiblyStepTo?.xPositionFromTopLeftOfBoard &&
coordinate?.yPositionFromTopLeftOfBoard == tileCoordinateToPossiblyStepTo?.yPositionFromTopLeftOfBoard
);
});
if(isPossibleCoordinateTileCoordinateToPossiblyStepTo){
return true;
} else {
return false;
}
}
getDamStonesForNewGameState(areStonesInTopRowsWhite = false): DamStone[] {
const damStones = [];
for(const damboardRowNumber of Array(this.getNumberOfTilesPerBoardRow()).keys()){
for(const damboardTileInRow of Array(this.getNumberOfTilesPerBoardRow()).keys()){
// Fill first three rows
if(damboardTileInRow < 3){
if(!this.getIsWhiteTileForCoordinate(
damboardRowNumber, damboardTileInRow)){
const damStoneCoordinate = new DamStoneCoordinate(
damboardRowNumber,
damboardTileInRow
);
const isDamStoneWhite = areStonesInTopRowsWhite ? true : false;
const damStone = new DamStone(
damStoneCoordinate,
false,
isDamStoneWhite
);
damStones.push(damStone);
}
}
// Fill last three rows
if(damboardTileInRow >= (this.getNumberOfTilesPerBoardRow() - 3)){
if(!this.getIsWhiteTileForCoordinate(
damboardRowNumber, damboardTileInRow)){
const damStoneCoordinate = new DamStoneCoordinate(
damboardRowNumber,
damboardTileInRow
);
const isDamStoneWhite = areStonesInTopRowsWhite ? false : true;
const damStone = new DamStone(
damStoneCoordinate,
false,
isDamStoneWhite
);
damStones.push(damStone);
}
}
}
}
const filteredDamStones = damStones.filter((damStone: DamStone) => {
return !(damStone?.coordinate?.yPositionFromTopLeftOfBoard > 2 && !damStone?.isColorWhite) &&
!((damStone?.coordinate?.yPositionFromTopLeftOfBoard < (this.getNumberOfTilesPerBoardRow() - 3)) && damStone?.isColorWhite)
});
return damStones;
}
getDamStoneForCoordinateIfAvailable(damStones: DamStone[], damStoneCoordinate: DamStoneCoordinate): DamStone | null {
let damStoneIfAvailable = null;
damStones.forEach((damStone: DamStone) => {
if(damStone?.coordinate?.xPositionFromTopLeftOfBoard == damStoneCoordinate?.xPositionFromTopLeftOfBoard &&
damStone?.coordinate?.yPositionFromTopLeftOfBoard == damStoneCoordinate?.yPositionFromTopLeftOfBoard
){
damStoneIfAvailable = damStone;
}
});
return damStoneIfAvailable;
}
getListOfPossibleStepCoordinatesOneStepFromCurrentCoordinate(coordinate: DamStoneCoordinate): DamStoneCoordinate[] {
const listOfCoordinates: DamStoneCoordinate[] = [];
const directions = [-1, 1];
directions.forEach((horizontalDirector: number) => {
directions.forEach((verticalDirector: number) => {
const coordinateOneStepFromCurrent = new DamStoneCoordinate(
coordinate?.xPositionFromTopLeftOfBoard + +horizontalDirector,
coordinate?.yPositionFromTopLeftOfBoard + +verticalDirector,
);
listOfCoordinates.push(coordinateOneStepFromCurrent);
});
});
return listOfCoordinates;
}
isCoordinateOutsidePlayerField(coordinate: DamStoneCoordinate): boolean {
return (
(coordinate?.xPositionFromTopLeftOfBoard < 0) ||
(coordinate?.xPositionFromTopLeftOfBoard >= this.getNumberOfTilesPerBoardRow()) ||
(coordinate?.yPositionFromTopLeftOfBoard < 0) ||
(coordinate?.yPositionFromTopLeftOfBoard >= this.getNumberOfTilesPerBoardRow())
);
}
isOtherStoneAlreadyOnCoordinate(allDamStones: DamStone[], damStoneCoordinate: DamStoneCoordinate): boolean {
let isOtherStoneAlreadyOnCoordinate = false;
allDamStones.forEach((damStone: DamStone) => {
if(damStone?.coordinate?.xPositionFromTopLeftOfBoard == damStoneCoordinate?.xPositionFromTopLeftOfBoard &&
damStone?.coordinate?.yPositionFromTopLeftOfBoard == damStoneCoordinate?.yPositionFromTopLeftOfBoard
){
isOtherStoneAlreadyOnCoordinate = true;
}
});
return isOtherStoneAlreadyOnCoordinate;
}
isOneStepWithoutHitInAnyDirectionPossibleForStone(allDamStones: DamStone[], stone: DamStone, isWhitePlayersTurn: boolean): boolean {
if(!stone?.coordinate){ return false; }
if(stone?.isColorWhite != isWhitePlayersTurn){ return false; }
let isOneStepWithoutHitInAnyDirectionPossible = false;
const coordinatesOneStepFromCurrentStone =
this.getListOfPossibleStepCoordinatesOneStepFromCurrentCoordinate(stone?.coordinate);
coordinatesOneStepFromCurrentStone.forEach((coordinate: DamStoneCoordinate) => {
if(
!this.isCoordinateOutsidePlayerField(coordinate) &&
!this.isOtherStoneAlreadyOnCoordinate(allDamStones, coordinate)
){
isOneStepWithoutHitInAnyDirectionPossible = true;
}
});
return isOneStepWithoutHitInAnyDirectionPossible;
}
} |
a6665de7a1bf3cd1fa2929432c2fc75bb3527a1d | TypeScript | GBichon/Planificador-Dron-Angular-4- | /drone-app/src/app/services/geojson.services/geojson.coordinate.searcher.service.ts | 3.171875 | 3 | declare var turf: any;
export class GeoJson_Coordinate_Searcher_Service {
constructor(){}
/**
* Search for the coordinate that is further to the west and further to the
* south from the given array of coordinates
* @param coordinates An array of coordinates
* @return [ return = {} ]
* [ return.coordinate = number[]] Value of the found coordinate
* [ return.coordinate_index = number] Index of the coordinate in the array
*/
public searchWestSouthCoordinate(coordinates: number[][]): any{
// Validations
coordinates.forEach( coordinate => {
if (coordinate.length !== 2)
throw new Error("Expected a coordinate in every element of 'coordinates'");
});
// Search for coordinate
let west_south_coordinate = undefined;
let west_south_coordinate_index = -1;
coordinates.forEach( (coordinate, coordinate_index) => {
let replace_current_coordinate = (west_south_coordinate === undefined) ||
(coordinate[1] < west_south_coordinate[1]) ||
(coordinate[1] === west_south_coordinate[1] && coordinate[0] < west_south_coordinate[0]);
if (replace_current_coordinate){
west_south_coordinate = coordinate;
west_south_coordinate_index = coordinate_index;
}
})
return { coordinate: west_south_coordinate, coordinate_index: west_south_coordinate_index };
}
}
|
2e3a61a1f6e69ea186f384b44a514afc35e6a8a6 | TypeScript | design-automation/mobius-external-grader | /src/core/inline/_conversion.ts | 2.875 | 3 | import { getArrDepth2 } from '@assets/libs/util/arrs';
export function radToDeg(rad: number|number[]): number|number[] {
if (Array.isArray(rad)) { return rad.map(a_rad => radToDeg(a_rad)) as number[]; }
return rad * (180 / Math.PI);
}
export function degToRad(deg: number|number[]): number|number[] {
if (Array.isArray(deg)) { return deg.map(a_deg => degToRad(a_deg)) as number[]; }
return deg * (Math.PI / 180);
}
export function numToStr(num: number|number[], frac_digits?: number, locale?: string): string|string[] {
if (Array.isArray(num)) {
for (let i = 0; i < num.length; i++) {
num[i] = typeof num === 'number' ? num : Number(num);
}
} else {
num = typeof num === 'number' ? num : Number(num);
}
const options = {};
if (frac_digits !== undefined) { options['maximumFractionDigits'] = frac_digits; options['minimumFractionDigits'] = frac_digits; }
locale = locale === undefined ? 'en-GB' : locale;
if (Array.isArray(num)) { return num.map(a_num => a_num.toLocaleString(locale, options)) as string[]; }
return num.toLocaleString(locale, options) as string;
}
export function numToCurr(num: number|number[], currency: string, locale?: string): string|string[] {
if (Array.isArray(num)) {
for (let i = 0; i < num.length; i++) {
num[i] = typeof num === 'number' ? num : Number(num);
}
} else {
num = typeof num === 'number' ? num : Number(num);
}
const options = {};
options['style'] = 'currency';
options['currency'] = currency;
locale = locale === undefined ? 'en-GB' : locale;
if (Array.isArray(num)) { return num.map(a_num => a_num.toLocaleString(locale, options)) as string[]; }
return num.toLocaleString(locale, options) as string;
}
|
2695b34710500d7e4855587e645df755220f2f3c | TypeScript | codeuniversity/ppp-profile-peeker | /src/contexts/ShortTermStoreContext.ts | 2.828125 | 3 | import React from "react";
export type ShortTermValue = number | string | object;
export interface ShortTermStore {
[key: string]: ShortTermValue;
}
export interface ShortTermStoreValue {
shortTermStore: ShortTermStore;
setShortTermValue: (key: string, value: ShortTermValue, timeToLive: number, setIn?: number) => void;
}
const defaultValue: ShortTermStoreValue = {
shortTermStore: {},
setShortTermValue: () => {},
};
const ShortTermStoreContext = React.createContext(defaultValue);
export default ShortTermStoreContext;
|
4450795f359538a9ff6ee20c9ce905af831f7851 | TypeScript | Maniae/ld44-your-life-is-currency | /src/entities/banker.ts | 2.75 | 3 | import { Point } from "../math";
import { Entity, ColliderType } from "./entity";
export class Banker implements Entity {
position: Point;
velocity: Point;
acceleration = 1;
friction = 0.7;
maxSpeed = 5;
width = 32;
height = 48;
colliderType: ColliderType = "rect";
dead = false;
stealDelay = 1000;
lastSteal = 0;
constructor(x: number, y: number) {
this.position = {
x,
y,
};
this.velocity = { x: 0, y: 0 };
}
}
|
b38d66e118943399a0d489e31931502c33f3fd99 | TypeScript | x4AEKx/vanilla-tests | /src/03/03.test.ts | 2.90625 | 3 | import {CityType} from "./../02/02";
import {addMoneyToBudget, repairHouse, toFireStaff, toHireStaff} from "./03";
let city: CityType;
beforeEach(() => {
city = {
title: "New Your",
houses: [
{
buildAt: 2012,
repaired: false,
address: {
number: 100,
street: {
title: "White street"
}
}
},
{
buildAt: 2008,
repaired: false,
address: {
number: 100,
street: {
title: "Happy street"
}
}
},
{
buildAt: 2020,
repaired: false,
address: {
number: 101,
street: {
title: "Happy street"
}
}
},
],
governmentBuildings: [
{
type: "HOSPITAL",
budget: 200000,
staffCount: 200,
address: {
street: {
title: "Central Str"
}
}
},
{
type: "FIRE_STATION",
budget: 500000,
staffCount: 1000,
address: {
street: {
title: "South Str"
}
}
}
],
citizensNumber: 1000000
}
})
test("Budget should be changed for HOSPITAL", () => {
addMoneyToBudget(city.governmentBuildings[0], 100000)
expect(city.governmentBuildings[0].budget).toBe(300000)
})
test("Budget should be changed for FIRE_STATION", () => {
addMoneyToBudget(city.governmentBuildings[1], -100000)
expect(city.governmentBuildings[1].budget).toBe(400000)
})
test("House should be repaired", () => {
repairHouse(city.houses[1])
expect(city.houses[1].repaired).toBeTruthy()
})
test("staff should be decrement", () => {
toFireStaff(city.governmentBuildings[0], 20)
expect(city.governmentBuildings[0].staffCount).toBe((180))
})
test("staff should be increment", () => {
toHireStaff(city.governmentBuildings[0], 20)
expect(city.governmentBuildings[0].staffCount).toBe((220))
}) |
8f185f9777ab4ab99c8eac50647238efd1b2f6b6 | TypeScript | Aaron-K-T-Berry/ubuy-poc | /backend/src/model/order/orders.model.ts | 2.671875 | 3 | import mongoose, { Document } from "mongoose";
enum StatusTypes {
packing = "packing",
delivering = "delivering",
complete = "complete"
}
export interface Order {
userId: string;
items: {
itemId: string;
quantity: number;
branchId: string;
}[];
billingAddress: string;
deliveryAddress: string;
orderTime: Date;
status: StatusTypes;
}
export interface OrderModel extends Document, Order {}
export const ItemsSchema = new mongoose.Schema({
itemId: { type: String, required: true },
quantity: { type: Number, required: true },
branchId: { type: String, required: true }
});
const OrderSchema = new mongoose.Schema({
userId: { type: String, required: true },
items: {
type: [{}],
required: true
},
billingAddress: { type: String, required: true },
deliveryAddress: { type: String, required: true },
orderTime: { type: Date, required: true },
status: { type: StatusTypes, required: true }
});
export default mongoose.model("Order", OrderSchema);
|
caf5f148cbce0698f61da96a9ba625fe682c632b | TypeScript | dmitry-egorov/storia | /app/scripts/tools/utils/ScopeObservable.ts | 2.828125 | 3 | module Rx
{
export class ScopeObservable<T> implements IObservable<T>
{
constructor(private $scope: ng.IScope, private observable: IObservable<T>) {}
subscribe(observer: Observer<T>): IDisposable;
subscribe(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable;
subscribe(onNext?: any, onError?: (exception: any) => void, onCompleted?: () => void): IDisposable
{
if(typeof(onNext) !== 'function')
{
throw 'Not supported';
}
var subscription = this.observable.subscribe(
value => this.$scope.$evalAsync(() => onNext(value)),
value => this.$scope.$evalAsync(() => onError(value)),
() => this.$scope.$evalAsync(() => onCompleted())
);
this.$scope.$on('$destroy', () => {
subscription.dispose();
});
return subscription;
}
}
Observable.prototype.withScope = BehaviorSubject.prototype.withScope = function($scope)
{
return new ScopeObservable($scope, this);
};
export interface Observable<T>
{
withScope($scope);
}
export interface BehaviorSubject<T>
{
withScope($scope);
}
export interface ObservableStatic
{
prototype: any;
}
export interface BehaviorSubjectStatic
{
prototype: any;
}
}
|
b2618093f6c4ddf643c38ae60015d0571e2083c8 | TypeScript | ace-study-group/assignment-itsfs | /petstore-client/src/app/services/pet.service.ts | 2.5625 | 3 | import { Injectable } from '@angular/core';
import { Pet } from '../model/pet';
import { Observable, of } from 'rxjs';
import { Subject } from 'rxjs/Subject';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, tap } from 'rxjs/operators';
import { environment } from '../../environments/environment';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class PetService {
private petsUrl = environment.apiUrl + 'pet';
private selectedPet = new Subject<Pet>();
private pets: Pet[];
constructor(
private http: HttpClient) { }
getPets(): Observable<Pet[]> {
return this.http
.get<Pet[]>(this.petsUrl)
.pipe(
tap((pets: Pet[]) => {
this.log(`fetched pets`);
this.pets = pets;
}),
catchError(this.handleError('getPets', []))
);
}
getStatuses(): string[] {
return ["PENDING", "AVAILABLE", "SOLD"];
}
addPet(pet: Pet): Observable<Pet> {
return this.http
.post<Pet>(this.petsUrl, pet, httpOptions)
.pipe(
tap((pet: Pet) => {
this.log(`created Pet with id=${pet.id}`);
this.pets.push(pet);
}),
catchError(this.handleError<Pet>('addPet'))
);
}
deletePet(pet: Pet): Observable<Pet> {
const url = `${this.petsUrl}/${pet.id}`;
return this.http
.delete<Pet>(url, httpOptions)
.pipe(
tap(_ => {
this.log(`deleted Pet with id=${pet.id}`);
this.pets.splice(this.pets.findIndex(p=> p==pet), 1);
}),
catchError(this.handleError<Pet>('deletePet'))
);
}
setSelectedPet(pet: Pet) {
this.selectedPet.next(pet);
}
getSelectedPet(): Observable<Pet> {
return this.selectedPet.asObservable();
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
alert(error.error.message);
console.error(error);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
/** Log a HeroService message with the MessageService */
private log(message: string) {
console.log('PetService: ' + message);
}
}
|
d6aefa73aaa2e6f37e7c9c47b688a9a4de437152 | TypeScript | whiskyjs/selection-menu | /app/inject/scripts/components/SelectionMenu.ts | 2.625 | 3 | import actions from "@common/actions";
export class SelectionMenu {
protected static readonly CURSOR_WIDTH = 20;
protected static readonly MARGIN_Y = 8;
protected static readonly MARGIN_X = 8;
protected static readonly containerTemplate = `
<link rel="stylesheet" type="text/css" href=%inject.css%>
<div class="container" style="opacity: 0">
</div>
`;
protected outer: HTMLDivElement;
protected shadowRoot: ShadowRoot;
protected container: HTMLDivElement;
constructor() {
this.outer = document.createElement("div");
this.outer.dataset.chromeExtension = "selection-menu";
this.shadowRoot = this.outer.attachShadow({mode: "open"});
this.shadowRoot.innerHTML = SelectionMenu.containerTemplate.replace(
/%inject\.css%/gm,
chrome.runtime.getURL("styles/inject.css"),
);
this.container = this.shadowRoot.querySelector(".container") as HTMLDivElement;
}
/**
* Attach the root element to the document.
*/
public attach() {
document.body.appendChild(this.outer);
}
/**
* Show the container relative to the target coordinates. Handles edge cases.
* @param x
* @param y
* @param text Currently selected text
*/
public show(x: number, y: number, text: string, onClose?: () => void) {
this.fillWithActions(text, onClose);
let left: number;
let top: number;
if (y < this.container.offsetHeight + SelectionMenu.MARGIN_Y * 2) {
top = y + SelectionMenu.MARGIN_Y;
} else {
top = y - SelectionMenu.MARGIN_Y - this.container.offsetHeight;
}
if (x < this.container.offsetWidth / 2 + SelectionMenu.MARGIN_X) {
left = x + SelectionMenu.CURSOR_WIDTH;
top = y - this.container.offsetHeight / 2;
} else if (x + this.container.offsetWidth / 2 + SelectionMenu.MARGIN_X > window.innerWidth) {
left = x - this.container.offsetWidth - SelectionMenu.MARGIN_X - SelectionMenu.CURSOR_WIDTH;
top = y - this.container.offsetHeight / 2;
} else {
left = x - this.container.offsetWidth / 2;
}
this.position(left, top);
this.container.classList.add("container--visible");
}
public get visible() {
return this.container.classList.contains("container--visible");
}
/**
* Hide the container outside viewport.
*/
public hide() {
this.container.classList.remove("container--visible");
setTimeout(() => {
this.position(-9999, -9999);
this.clearActions();
}, 100);
}
/**
* Set left and top of the container element.
* @param x
* @param y
*/
protected position(x: number, y: number): void {
this.container.style.left = `${window.pageXOffset + x}px`;
this.container.style.top = `${window.pageYOffset + y}px`;
}
/**
* Fill the container with action elements and set event handlers.
* The only currently supported action event is click.
* @param text Currently selected text
*/
protected fillWithActions(text: string, onClose?: () => void) {
const separator = this.createSeparator();
for (const klass of actions) {
const action = new klass(text);
if (!action.applicable) {
continue;
}
const actionElement = document.createElement("a");
actionElement.href = "#";
actionElement.classList.add("container__action");
const bound = action.bind(actionElement);
if (!bound) {
actionElement.textContent = chrome.i18n.getMessage(`action_${action.uid}_name`);
for (const event of ["mousedown", "mouseup"]) {
actionElement.addEventListener(event, this.silenceEvent);
}
actionElement.addEventListener("click", async (e) => {
e.preventDefault();
await action.perform();
this.hide();
if (typeof onClose !== "undefined") {
onClose();
}
});
}
this.container.appendChild(actionElement);
if (klass !== actions[actions.length - 1]) {
this.container.appendChild(separator.cloneNode(true));
}
}
}
/**
* Remove all action elements from the container.
*/
protected clearActions() {
this.container.innerHTML = ``;
}
/**
* Stop propagation of an event.
* @param e
*/
protected silenceEvent(e: Event) {
e.stopPropagation();
}
/**
* Creates separator element for action menu.
*/
protected createSeparator(): HTMLDivElement {
const separatorElement = document.createElement("div");
const separatorInnerElement = document.createElement("div");
separatorElement.classList.add("container__separator");
separatorInnerElement.classList.add("container__separator-inner");
separatorElement.appendChild(separatorInnerElement);
return separatorElement;
}
}
|
511fadf93a9626fb64598d59b2a0bdc68e512e78 | TypeScript | securenative/securenative-node-agent | /src/rules/rule.ts | 2.703125 | 3 | interface RuleInterception {
module: string;
method: string;
processor: string;
}
interface RuleData {
key: string;
value: string;
}
export default interface Rule {
name: string;
data: RuleData;
interception: RuleInterception
}
|
e212b962226ba3dda8cbeb8fd371e635cc32967c | TypeScript | EvgenyMuryshkin/dsp-playground | /src/lib/assign.ts | 3.171875 | 3 | import deepmerge from "deepmerge";
// https://stackoverflow.com/questions/41980195/recursive-partialt-in-typescript-2-1
export type RecursivePartial<T> = {
[P in keyof T]?:
T[P] extends (infer U)[] ? RecursivePartial<U>[] :
T[P] extends object ? RecursivePartial<T[P]> :
T[P];
};
export class Assign {
// https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge
public static recursive<T>(source: T, change: RecursivePartial<T>): T {
return deepmerge(source, change as unknown as Partial<T>);
}
} |
3464d50d43500997e9cdc4749f1913d82616414d | TypeScript | Kirtika22/Kir | /sample/src/app/employee-list/employee-list.component.ts | 2.515625 | 3 | import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-employee-list',
template: `
`,
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
constructor() { }
ngOnInit() {
}
onSubmit(recvalue: any){
console.log(recvalue);
}
}
// import { Component, OnInit } from '@angular/core';
// @Component({
// selector: 'app-employee-list',
// template: `
// <div class="container">
// <h2>User Data</h2>
// <form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)">
// <div class="form-group">
// <label>Name</label>
// <input type="text" minlength="4" #nameref="ngModel" name="name" required class="form-control" ngModel>
// <div *ngIf="nameref.errors && (nameref.dirty || nameref.touched)" class="alert alert-danger">
// <div [hidden]="!nameref.errors.required">
// <b>Please enter a name</b>
// </div>
// <div [hidden]="!nameref.errors.minlength">
// <b>Please enter minimum 4 chars</b>
// </div>
// </div>
// </div>
// <div class="form-group">
// <label>Email</label>
// <input type="email" name="email" class="form-control" ngModel>
// </div>
// <div ngModelGroup="address">
// <div class="form-group">
// <label>Street</label>
// <input type="text" class="form-control" name="street" ngModel>
// </div>
// <div class="form-group">
// <label>City</label>
// <input type="text" class="form-control" name="city" ngModel>
// </div>
// </div>
// <div class="form-group">
// <label>PostalCode</label>
// <input type="text" #refPincode="ngModel" pattern="^[1-9][0-9]{4}$"
// name="postalcode" ngModel class="form-control">
// <div *ngIf="refPincode.errors &&(refPincode.dirty||refPincode.touched)">
// <div [hidden]="!refPincode.errors.pattern">
// please enter a five number
// </div>
// </div>
// </div>
// <button [disabled]="!userForm.form.valid" type="submit" class="btn btn-primary">Sign up</button>
// </form>
// </div>
// `,
// styles: []
// })
// export class EmployeeListComponent implements OnInit {
// constructor() { }
// ngOnInit() {
// }
// onSubmit(recvalue: any){
// console.log(recvalue);
// }}
|
812a6429fd1d6ebd8ae24eab8e7d935962d20b27 | TypeScript | snowcoders/sortier | /src/utilities/string-utils.ts | 2.96875 | 3 | export class StringUtils {
public static getBlankLineLocations(string: string, rangeStart = 0, rangeEnd: number = string.length) {
const regex = /\n\s*\n/gim;
let result: null | RegExpExecArray;
const contextBarrierIndices: number[] = [];
while ((result = regex.exec(string))) {
if (rangeStart < result.index && result.index < rangeEnd) {
contextBarrierIndices.push(result.index);
}
}
return contextBarrierIndices;
}
public static stringEndsWithAny(text: string, endings: string[]) {
// If the user didn't override the parser type, try to infer it
let endsWithAny = false;
for (const extension of endings) {
endsWithAny = endsWithAny || text.endsWith(extension);
}
return endsWithAny;
}
}
|
1c8f1f197b9bae6937380b07c5fe8f7707ed1855 | TypeScript | Lil-C0der/filmo_server | /libs/db/src/models/post.model.ts | 2.640625 | 3 | import { ModelOptions, prop } from '@typegoose/typegoose';
// 回复楼层 需要有用户 id 和回复内容
export interface IReply {
userId: string;
username: string;
replyAt: string;
content: string;
}
// 帖子
@ModelOptions({
schemaOptions: { timestamps: true }
})
export class Post {
@prop()
public title: string;
@prop()
public id: string;
@prop()
public creatorId: string;
@prop()
public creatorUsername: string;
@prop()
public content: string;
@prop()
public replies: IReply[];
}
|
ca17f6b0412996c714184a2f17b02394e02d8347 | TypeScript | Diplomatiq/crypto-random | /test/specs/uniformDistribution.test.ts | 2.921875 | 3 | import { expect } from 'chai';
import { RandomGenerator } from '../../src/randomGenerator';
import { ChiSquaredTest } from '../utils/chiSquaredTest';
import { windowMock } from '../utils/windowMock';
describe('Generated values should follow a uniform distribution', (): void => {
// Setting unique = true would not really have a meaning here, since the output would be biased.
const unique = false;
let randomGeneratorInstance: RandomGenerator;
before((): void => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.window = windowMock();
});
after((): void => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.window = undefined;
});
beforeEach((): void => {
randomGeneratorInstance = new RandomGenerator();
});
describe('alphabetLength = 2', (): void => {
const alphabetLength = 2;
it('howMany = 10', async (): Promise<void> => {
const howMany = 10;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100', async (): Promise<void> => {
const howMany = 100;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 1000', async (): Promise<void> => {
const howMany = 1000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100000', async (): Promise<void> => {
const howMany = 100000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
});
describe('alphabetLength = 10', (): void => {
const alphabetLength = 10;
it('howMany = 10', async (): Promise<void> => {
const howMany = 10;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100', async (): Promise<void> => {
const howMany = 100;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 1000', async (): Promise<void> => {
const howMany = 1000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100000', async (): Promise<void> => {
const howMany = 100000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
});
describe('alphabetLength = 62', (): void => {
const alphabetLength = 62;
it('howMany = 10', async (): Promise<void> => {
const howMany = 10;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100', async (): Promise<void> => {
const howMany = 100;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 1000', async (): Promise<void> => {
const howMany = 1000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100000', async (): Promise<void> => {
const howMany = 100000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
});
describe('alphabetLength = 100', (): void => {
const alphabetLength = 100;
it('howMany = 10', async (): Promise<void> => {
const howMany = 10;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100', async (): Promise<void> => {
const howMany = 100;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 1000', async (): Promise<void> => {
const howMany = 1000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100000', async (): Promise<void> => {
const howMany = 100000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
});
describe('alphabetLength = 10000', (): void => {
const alphabetLength = 10000;
it('howMany = 10', async (): Promise<void> => {
const howMany = 10;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100', async (): Promise<void> => {
const howMany = 100;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 1000', async (): Promise<void> => {
const howMany = 1000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100000', async (): Promise<void> => {
const howMany = 100000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
});
describe('alphabetLength = 1000000', (): void => {
const alphabetLength = 1000000;
it('howMany = 10', async (): Promise<void> => {
const howMany = 10;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100', async (): Promise<void> => {
const howMany = 100;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 1000', async (): Promise<void> => {
const howMany = 1000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
it('howMany = 100000', async (): Promise<void> => {
const howMany = 100000;
const generatedValues: number[][] = [];
for (let i = 0; i < ChiSquaredTest.TEST_TRIES; i++) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const random = await randomGeneratorInstance.getUniformlyDistributedRandomCharIndexesOfAlphabet(
alphabetLength,
howMany,
unique,
);
generatedValues.push(random);
}
const result = ChiSquaredTest.test(generatedValues, alphabetLength);
expect(result).to.be.true;
});
});
});
|
6c49b4bf8edf56f8780242e80e356d2b1bca9f55 | TypeScript | fizk/cpu | /test/lexer.test.ts | 2.953125 | 3 | import { assertEquals } from "https://deno.land/std@0.90.0/testing/asserts.ts";
import Lexer, {TOKENS} from '../src/parser/Lexer.ts';
Deno.test("LEXER - line begins with comment", () => {
const tokens = new Lexer(`
; This is a comment
`).parse();
assertEquals(tokens, []);
});
Deno.test("LEXER - many lines comment", () => {
const tokens = new Lexer(`
; This is a comment
; This is another one
`).parse();
assertEquals(tokens, []);
});
Deno.test("LEXER - op-code", () => {
const tokens = new Lexer(`
LDA
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
]);
});
Deno.test("LEXER - comment > op-code", () => {
const tokens = new Lexer(`
; this is some comment
LDA
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 2, from: 8, to: 10 },
]);
});
Deno.test("LEXER - label: > op-code", () => {
const tokens = new Lexer(`
label: LDA`
).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 13 },
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 15, to: 17 },
]);
});
Deno.test("LEXER - label > op-code", () => {
const tokens = new Lexer(`
label LDA`
).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 12 },
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 14, to: 16 },
]);
});
Deno.test("LEXER - label: > break > op-code", () => {
const tokens = new Lexer(`
label:
LDA
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 13 },
{ token: TOKENS.OPCODE, value: 'LDA', line: 2, from: 12, to: 14 },
]);
});
Deno.test("LEXER - label > break > op-code", () => {
const tokens = new Lexer(`
label
LDA
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 12 },
{ token: TOKENS.OPCODE, value: 'LDA', line: 2, from: 12, to: 14 },
]);
});
Deno.test("LEXER - op-code > $hex-number", () => {
const tokens = new Lexer(`
LDA $1234
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: TOKENS.NUMBER, value: '$1234', line: 1, from: 12, to: 16 },
]);
});
Deno.test("LEXER - op-code > $hex-number", () => {
const tokens = new Lexer(`
LDA $ff00aa
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: TOKENS.NUMBER, value: '$ff00aa', line: 1, from: 12, to: 18 },
]);
});
Deno.test("LEXER - op-code > %binary-number", () => {
const tokens = new Lexer(`
LDA %101001
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: TOKENS.NUMBER, value: '%101001', line: 1, from: 12, to: 18 },
]);
});
Deno.test("LEXER - op-code > immediate > hex-number", () => {
const tokens = new Lexer(`
LDA #$ffffff
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: '#', value: null, line: 1, from: 12, to: 12 },
{ token: TOKENS.NUMBER, value: '$ffffff', line: 1, from: 13, to: 19 },
]);
});
Deno.test("LEXER - op-code > immediate > binary-number", () => {
const tokens = new Lexer(`
LDA #%101001
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: '#', value: null, line: 1, from: 12, to: 12 },
{ token: TOKENS.NUMBER, value: '%101001', line: 1, from: 13, to: 19 },
]);
});
Deno.test("LEXER - assignment", () => {
const tokens = new Lexer(`
BOARD = $50
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'BOARD', line: 1, from: 8, to: 12 },
{ token: TOKENS.PSEUDO_OPERATION, value: '=', line: 1, from: 16, to: 16 },
{ token: TOKENS.NUMBER, value: '$50', line: 1, from: 21, to: 23 },
]);
});
Deno.test("LEXER - pseudo assignment", () => {
const tokens = new Lexer(`
BOARD .equ $50
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'BOARD', line: 1, from: 8, to: 12 },
{ token: TOKENS.PSEUDO_OPERATION, value: 'EQU', line: 1, from: 16, to: 19 },
{ token: TOKENS.NUMBER, value: '$50', line: 1, from: 24, to: 26 },
]);
});
Deno.test("LEXER - parentheses > number > parentheses", () => {
const tokens = new Lexer(`
LDA ($1234)
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: '(', value: null, line: 1, from: 13, to: 13 },
{ token: TOKENS.NUMBER, value: '$1234', line: 1, from: 14, to: 18 },
{ token: ')', value: null, line: 1, from: 19, to: 19 },
]);
});
Deno.test("LEXER - parentheses > space > number > space > parentheses", () => {
const tokens = new Lexer(`
LDA ( $1234 )
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: '(', value: null, line: 1, from: 13, to: 13 },
{ token: TOKENS.NUMBER, value: '$1234', line: 1, from: 15, to: 19 },
{ token: ')', value: null, line: 1, from: 21, to: 21 },
]);
});
Deno.test("LEXER - parentheses > space > number > , > identifier > parentheses", () => {
const tokens = new Lexer(`
LDA ( $1234, X )
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: '(', value: null, line: 1, from: 13, to: 13 },
{ token: TOKENS.NUMBER, value: '$1234', line: 1, from: 15, to: 19 },
{ token: ',', value: null, line: 1, from: 20, to: 20 },
{ token: TOKENS.IDENTIFIER, value: 'X', line: 1, from: 22, to: 22 },
{ token: ')', value: null, line: 1, from: 24, to: 24 },
]);
});
Deno.test("LEXER - parentheses > space > number > space > , > identifier > parentheses", () => {
const tokens = new Lexer(`
LDA ( $1234 , X )
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: '(', value: null, line: 1, from: 13, to: 13 },
{ token: TOKENS.NUMBER, value: '$1234', line: 1, from: 15, to: 19 },
{ token: ',', value: null, line: 1, from: 21, to: 21 },
{ token: TOKENS.IDENTIFIER, value: 'X', line: 1, from: 23, to: 23 },
{ token: ')', value: null, line: 1, from: 25, to: 25 },
]);
});
Deno.test("LEXER - parentheses > number > parentheses > , > identifier", () => {
const tokens = new Lexer(`
LDA ($1234), X
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: '(', value: null, line: 1, from: 13, to: 13 },
{ token: TOKENS.NUMBER, value: '$1234', line: 1, from: 14, to: 18 },
{ token: ')', value: null, line: 1, from: 19, to: 19 },
{ token: ',', value: null, line: 1, from: 20, to: 20 },
{ token: TOKENS.IDENTIFIER, value: 'X', line: 1, from: 22, to: 22 },
]);
});
Deno.test("LEXER - parentheses > number > parentheses > , > identifier", () => {
const tokens = new Lexer(`
LDA ($1234) , X
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: '(', value: null, line: 1, from: 13, to: 13 },
{ token: TOKENS.NUMBER, value: '$1234', line: 1, from: 14, to: 18 },
{ token: ')', value: null, line: 1, from: 19, to: 19 },
{ token: ',', value: null, line: 1, from: 21, to: 21 },
{ token: TOKENS.IDENTIFIER, value: 'X', line: 1, from: 23, to: 23 },
]);
});
Deno.test("LEXER - * > assignment > number", () => {
const tokens = new Lexer(`
*=$50
`).parse();
assertEquals(tokens, [
{ token: TOKENS.PSEUDO_OPERATION, value: '*=', line: 1, from: 8, to: 9 },
{ token: TOKENS.NUMBER, value: '$50', line: 1, from: 10, to: 12 },
]);
});
Deno.test("LEXER - * > assignment > space > number", () => {
const tokens = new Lexer(`
*= $50
`).parse();
assertEquals(tokens, [
{ token: TOKENS.PSEUDO_OPERATION, value: '*=', line: 1, from: 8, to: 9 },
{ token: TOKENS.NUMBER, value: '$50', line: 1, from: 11, to: 13 },
]);
});
Deno.test("LEXER - type > number", () => {
const tokens = new Lexer(`
.byte $10
`).parse();
assertEquals(tokens, [
{ token: TOKENS.PSEUDO_OPERATION, value: 'BYTE', line: 1, from: 8, to: 12 },
{ token: TOKENS.NUMBER, value: '$10', line: 1, from: 14, to: 16 },
]);
});
Deno.test("LEXER - label > type > number", () => {
const tokens = new Lexer(`
label: .byte $10
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 13 },
{ token: TOKENS.PSEUDO_OPERATION, value: 'BYTE', line: 1, from: 15, to: 19 },
{ token: TOKENS.NUMBER, value: '$10', line: 1, from: 21, to: 23 },
]);
});
Deno.test("LEXER - label > type > number, number", () => {
const tokens = new Lexer(`
label: .byte $10, $EE
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 13 },
{ token: TOKENS.PSEUDO_OPERATION, value: 'BYTE', line: 1, from: 15, to: 19 },
{ token: TOKENS.NUMBER, value: '$10', line: 1, from: 21, to: 23 },
{ token: ',', value: null, line: 1, from: 24, to: 24 },
{ token: TOKENS.NUMBER, value: '$EE', line: 1, from: 26, to: 28 },
]);
});
Deno.test("LEXER - label > type > double-string", () => {
const tokens = new Lexer(`
label: .byte "word"
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 13 },
{ token: TOKENS.PSEUDO_OPERATION, value: 'BYTE', line: 1, from: 15, to: 19 },
{ token: TOKENS.DOUBLE_STRING, value: 'word', line: 1, from: 21, to: 26 },
]);
});
Deno.test("LEXER - label > type > single-string", () => {
const tokens = new Lexer(`
label: .byte 'word'
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 13 },
{ token: TOKENS.PSEUDO_OPERATION, value: 'BYTE', line: 1, from: 15, to: 19 },
{ token: TOKENS.SINGLE_STRING, value: 'word', line: 1, from: 21, to: 26 },
]);
});
Deno.test("LEXER - label > type > single-string with double", () => {
const tokens = new Lexer(`
label: .byte 'wo"rd'
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 13 },
{ token: TOKENS.PSEUDO_OPERATION, value: 'BYTE', line: 1, from: 15, to: 19 },
{ token: TOKENS.SINGLE_STRING, value: "wo\"rd", line: 1, from: 21, to: 27 },
]);
});
Deno.test("LEXER - label > type > double-string with single", () => {
const tokens = new Lexer(`
label: .byte "wo'rd"
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 13 },
{ token: TOKENS.PSEUDO_OPERATION, value: 'BYTE', line: 1, from: 15, to: 19 },
{ token: TOKENS.DOUBLE_STRING, value: "wo'rd", line: 1, from: 21, to: 27 },
]);
});
Deno.test("LEXER - label > type > double-string special char", () => {
const tokens = new Lexer(`
label: .byte "word:#"
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 13 },
{ token: TOKENS.PSEUDO_OPERATION, value: 'BYTE', line: 1, from: 15, to: 19 },
{ token: TOKENS.DOUBLE_STRING, value: "word:#", line: 1, from: 21, to: 28 },
]);
});
Deno.test("LEXER - label > type > double-string more special char", () => {
const tokens = new Lexer(`
label: .byte "@^&*!*%$="
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 13 },
{ token: TOKENS.PSEUDO_OPERATION, value: 'BYTE', line: 1, from: 15, to: 19 },
{ token: TOKENS.DOUBLE_STRING, value: "@^&*!*%$=", line: 1, from: 21, to: 31 },
]);
});
Deno.test("LEXER - increment", () => {
const tokens = new Lexer(`
LDA label+1
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 12, to: 16 },
{ token: '+', value: null, line: 1, from: 17, to: 17 },
{ token: TOKENS.NUMBER, value: '1', line: 1, from: 18, to: 18 },
]);
});
Deno.test("LEXER - decrement", () => {
const tokens = new Lexer(`
LDA label-123
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 12, to: 16 },
{ token: '-', value: null, line: 1, from: 17, to: 17 },
{ token: TOKENS.NUMBER, value: '123', line: 1, from: 18, to: 20 },
]);
});
Deno.test("LEXER - increment space", () => {
const tokens = new Lexer(`
LDA label + 1321
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 12, to: 16 },
{ token: '+', value: null, line: 1, from: 18, to: 18 },
{ token: TOKENS.NUMBER, value: '1321', line: 1, from: 20, to: 23 },
]);
});
Deno.test("LEXER - increment location", () => {
const tokens = new Lexer(`
BNE *+4
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'BNE', line: 1, from: 8, to: 10 },
{ token: TOKENS.ORIGIN, value: '*', line: 1, from: 12, to: 12 },
{ token: '+', value: null, line: 1, from: 13, to: 13 },
{ token: TOKENS.NUMBER, value: '4', line: 1, from: 14, to: 14 },
]);
});
Deno.test("LEXER - decrement space", () => {
const tokens = new Lexer(`
LDA label - 1
`).parse();
assertEquals(tokens, [
{ token: TOKENS.OPCODE, value: 'LDA', line: 1, from: 8, to: 10 },
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 12, to: 16 },
{ token: '-', value: null, line: 1, from: 18, to: 18 },
{ token: TOKENS.NUMBER, value: '1', line: 1, from: 20, to: 20 },
]);
});
Deno.test("LEXER - label *=*+1", () => {
const tokens = new Lexer(`
label *=*+1
`).parse();
assertEquals(tokens, [
{ token: TOKENS.IDENTIFIER, value: 'label', line: 1, from: 8, to: 12 },
{ token: TOKENS.PSEUDO_OPERATION, value: '*=', line: 1, from: 14, to: 15 },
{ token: TOKENS.ORIGIN, value: '*', line: 1, from: 16, to: 16 },
{ token: '+', value: null, line: 1, from: 17, to: 17 },
{ token: TOKENS.NUMBER, value: '1', line: 1, from: 18, to: 18 },
]);
});
Deno.test("LEXER - snippet", () => {
const list = new Lexer(`
; modified by Daryl Rictor to work over a serial terminal connection, August 2002.
;
; 6551 I/O Port Addresses
;
ACIADat = $7F70
ACIASta = $7F71
;
; page zero variables
;
BOARD=$50
;
`).parse()
const tokens = list.map(item => item.token);
assertEquals(tokens, [
TOKENS.IDENTIFIER, TOKENS.PSEUDO_OPERATION, TOKENS.NUMBER,
TOKENS.IDENTIFIER, TOKENS.PSEUDO_OPERATION, TOKENS.NUMBER,
TOKENS.IDENTIFIER, TOKENS.PSEUDO_OPERATION, TOKENS.NUMBER,
])
});
Deno.test("LEXER - program", () => {
const lexer = new Lexer(`
; modified by Daryl Rictor to work over a serial terminal connection, August 2002.
;
; 6551 I/O Port Addresses
;
ACIADat = $7F70
ACIASta = $7F71
;
; page zero variables
;
BOARD=$50
;
*=$1000 ; load into RAM @ $1000-$15FF
;
LDA #$00 ; REVERSE TOGGLE
STA REV
FOUNX: LDA POINTS,Y ; BEST CAP
CMP BCAP0,X ; AT THIS
POUT1: lDA #"|" ; print vert edge
match:
CMP BOARD,X ; match found?
;
*= $1580
SETW: .byte $03, $04, $00
.byte $10, $17, $11
`);
const tokens = lexer.parse().map(item => item.token);
assertEquals(tokens, [
TOKENS.IDENTIFIER, TOKENS.PSEUDO_OPERATION, TOKENS.NUMBER, // ACIADat = $7F70
TOKENS.IDENTIFIER, TOKENS.PSEUDO_OPERATION, TOKENS.NUMBER, // ACIASta = $7F71
TOKENS.IDENTIFIER, TOKENS.PSEUDO_OPERATION, TOKENS.NUMBER, // BOARD=$50
TOKENS.PSEUDO_OPERATION, TOKENS.NUMBER, // *=$1000
TOKENS.OPCODE, '#', TOKENS.NUMBER, // LDA #$00
TOKENS.OPCODE, TOKENS.IDENTIFIER, // STA REV
TOKENS.IDENTIFIER, TOKENS.OPCODE, TOKENS.IDENTIFIER, ',', TOKENS.IDENTIFIER,// FOUNX: LDA POINTS,Y
TOKENS.OPCODE, TOKENS.IDENTIFIER, ',', TOKENS.IDENTIFIER, // CMP BCAP0,X
TOKENS.IDENTIFIER, TOKENS.OPCODE, '#', TOKENS.DOUBLE_STRING, // POUT1: lDA #"|"
TOKENS.IDENTIFIER, // match:
TOKENS.OPCODE, TOKENS.IDENTIFIER, ',', TOKENS.IDENTIFIER, // CMP BOARD,X
TOKENS.PSEUDO_OPERATION, TOKENS.NUMBER, // *= $1580
TOKENS.IDENTIFIER, TOKENS.PSEUDO_OPERATION, TOKENS.NUMBER, ',', TOKENS.NUMBER, ',', TOKENS.NUMBER,
TOKENS.PSEUDO_OPERATION, TOKENS.NUMBER, ',', TOKENS.NUMBER, ',', TOKENS.NUMBER,
])
});
|
68580a356156d4ca20fc23a59706de486939834f | TypeScript | tooploox/thanksy-client-elm | /src/emoji.ts | 2.671875 | 3 | import { DateTime } from "luxon"
const emojiRegex = require("emoji-regex")()
const emojilib = require("emojilib")
const twemoji = require("twemoji").default
const Text = (caption: string): TextChunk => ({ type: "text", caption })
const Nickname = (caption: string): TextChunk => ({ type: "nickname", caption: caption === "🥳" ? "" : caption })
const Emoji = (caption: string, url: string = ""): TextChunk => ({ type: "emoji", caption, url })
const remap = <T, S>(vs: SMap<T>, toKey: (t: T, k: string) => string, toValue: (t: T, k: string) => S): SMap<S> => {
const res: SMap<S> = {}
Object.keys(vs).forEach(k => (res[toKey(vs[k], k)] = toValue(vs[k], k)))
return res
}
export const extend = <T>(obj: T) => (delta: Partial<T>): T => ({ ...obj, ...delta })
type EmojiObj = { char: string }
const emojiByName = remap<EmojiObj, EmojiObj>(emojilib.lib, (_, name) => `:${name}:`, v => v)
const emojiNameByUtf8 = remap<EmojiObj, string>(emojiByName, v => v.char, (_, name) => name)
const replaceEmoji = (name: string) => (emojiByName[name] ? emojiByName[name].char : name)
const replaceUtf8Emoji = (text: string) => text.replace(emojiRegex, match => emojiNameByUtf8[match] || match)
const parseTextRec = (text: string, acc: TextChunk[] = []): TextChunk[] => {
const emojiRes = /(:[a-zA-Z_0-9+-]+:)/g.exec(text)
const emojiIndex = emojiRes ? text.indexOf(emojiRes[0]) : -1
const nicknameRes = /(@[a-zA-Z_0-9.-]+)/g.exec(text)
const nicknameIndex = nicknameRes ? text.indexOf(nicknameRes[0]) : -1
if (emojiRes && (emojiIndex < nicknameIndex || nicknameIndex === -1)) {
if (emojiIndex !== 0) acc.push(Text(text.substr(0, emojiIndex)))
acc.push(Emoji(emojiRes[0]))
return parseTextRec(text.substring(emojiIndex + emojiRes[0].length), acc)
}
if (nicknameRes && (nicknameIndex < emojiIndex || emojiIndex === -1)) {
if (nicknameIndex !== 0) acc.push(Text(text.substr(0, nicknameIndex)))
acc.push(Nickname(nicknameRes[0]))
return parseTextRec(text.substring(nicknameIndex + nicknameRes[0].length), acc)
}
return text ? [...acc, Text(text)] : acc
}
const parseText = (text: string, acc: TextChunk[] = []) => parseTextRec(replaceUtf8Emoji(text), acc)
const emojiUrl = (name: string) => `https://twemoji.maxcdn.com/2/72x72/${name}.png`
const getter = <T, T2 extends keyof T>(obj: T, field: T2): T[T2] | null => (obj ? obj[field] : null)
const extEmoji = ({ caption }: Emoji, name: string): TextChunk =>
Emoji(getter(emojiByName[caption], "char") || caption, emojiUrl(name))
const setEmojiUrl = async (c: TextChunk) => {
if (c.type !== "emoji") return c
const caption = replaceEmoji(c.caption)
if (c.caption === caption) return new Promise<TextChunk>(res => res(c))
return new Promise<TextChunk>(res =>
twemoji.parse(caption, {
callback: (name: string) => res(extEmoji(c, name)),
onerror: () => res(c)
})
)
}
export const setThxUrls = async (t: ThxPartial) => extend(t)({ chunks: await Promise.all(t.chunks.map(setEmojiUrl)) })
const toRelativeDate = (s: string) =>
(d => `${d.toRelativeCalendar()} at ${d.toLocaleString(DateTime.TIME_SIMPLE)}`)(DateTime.fromISO(s))
export const toChunks = (d: ThxPartialRaw): ThxPartial => ({
chunks: parseText(d.body),
id: d.id,
createdAt: toRelativeDate(d.createdAt)
})
|
109af7ef3a6a3c4c97493aec3f2db0161cb92be2 | TypeScript | akshaynair319/infinite-canvas | /src/areas/infinity/point-at-infinity.ts | 3 | 3 | import { SubsetOfLineAtInfinity } from "./subset-of-line-at-infinity";
import { Point } from "../../geometry/point";
import { Area } from "../area";
import { Ray } from "../line/ray";
import { LineSegmentAtInfinity } from "./line-segment-at-infinity";
import { TwoOppositePointsOnLineAtInfinity } from "./two-opposite-points-on-line-at-infinity";
export class PointAtInfinity implements SubsetOfLineAtInfinity{
constructor(private direction: Point){}
public addPointAtInfinity(direction: Point): SubsetOfLineAtInfinity{
if(direction.inSameDirectionAs(this.direction)){
return this;
}
if(direction.cross(this.direction) === 0){
return new TwoOppositePointsOnLineAtInfinity(this.direction);
}
return new LineSegmentAtInfinity(this.direction, direction);
}
public addPoint(point: Point): Area{
return new Ray(point, this.direction);
}
public addArea(area: Area): Area{
return area.expandToIncludeInfinityInDirection(this.direction);
}
} |
801184320d4f264ec7b4477be0e624b578b54c52 | TypeScript | larryaubstore/faucon-millenium | /src/components/faucon/eventLoop.ts | 2.59375 | 3 | import { Game } from './game';
import { Faucon } from './faucon';
import { Storage } from '@ionic/storage';
import * as debug from 'debug';
import * as rafLoop from 'raf-loop';
const log = debug('eventLoop');
export class EventLoop {
game: Game = null;
originalHorizontalIndex: number = 0;
touchStartPos: number = 0;
constructor(containerWidth: number, containerHeight: number, faucon: Faucon, storage: Storage) {
log('eventLoop');
this.game = new Game(2, containerWidth, containerHeight, faucon, storage);
}
isPaused() {
return this.game.isPaused;
}
isOverlay() {
return this.game.isOverlay;
}
pause() {
this.game.pause();
}
explosion() {
this.game.explosion();
}
hideOverlay() {
this.game.hideOverlay();
}
isInitialMode() {
return this.game.isInitialMode();
}
async initialize() {
document.onkeydown = this.checkKey.bind(this);
document.ontouchmove = this.touchMove.bind(this);
document.ontouchstart = this.touchStart.bind(this);
try {
await this.game.initialize();
var engine = rafLoop((dt) => {
this.run();
}).start();
} catch (err) {
log('error ==> ' + err);
}
}
run() {
this.game.draw();
}
touchStart(evt: any) {
log('touchStart');
this.game.hideOverlay();
log(evt.changedTouches[0].pageX);
this.originalHorizontalIndex = this.game.horizontalIndex;
this.touchStartPos = evt.changedTouches[0].pageX;
}
touchMove(evt: any) {
log('touchMove');
log(evt.changedTouches[0].pageX);
let delta: number = (this.touchStartPos - evt.changedTouches[0].pageX) / (window.innerWidth / 5);
this.game.moveHorizontally(this.originalHorizontalIndex - delta);
}
checkKey(e: any) {
e = e || window.event;
this.game.hideOverlay();
if (e.keyCode == '38') {
this.game.up();
}
else if (e.keyCode == '40') {
this.game.down();
}
else if (e.keyCode == '37') {
this.game.left();
}
else if (e.keyCode == '39') {
this.game.right();
}
}
}
|
a2b107cf4327c087a97431a63a87332fae065f46 | TypeScript | yihongang/graphics-experiments | /particles2/vector.ts | 3.71875 | 4 | class Vec2 {
x: number
y: number
constructor(x: number = 0, y: number = 0) {
this.x = x
this.y = y
}
clone(): Vec2 { return new Vec2(this.x, this.y) }
// Non-mutating operations
plus(other: Vec2): Vec2 { return new Vec2(this.x + other.x, this.y + other.y) }
minus(other: Vec2): Vec2 { return new Vec2(this.x - other.x, this.y - other.y) }
dot(other: Vec2): number { return this.x * other.x + this.y * other.y }
scaledBy(scalar: number): Vec2 { return new Vec2(this.x * scalar, this.y * scalar) }
length2(): number { return this.x * this.x + this.y * this.y }
length(): number { return Math.sqrt(this.x * this.x + this.y * this.y) }
// Mutation operations
add(other: Vec2) { this.x += other.x; this.y += other.y }
subtract(other: Vec2) { this.x -= other.x; this.y -= other.y }
scale(scalar: number) { this.x *= scalar; this.y *= scalar }
set(x: number, y: number) { this.x = x; this.y = y }
copyFrom(other: Vec2) { this.x = other.x; this.y = other.y }
clear() { this.x = 0; this.y = 0}
// Memory pooling
static freeList: Vec2[] = []
static allocateFromPool(): Vec2 { return Vec2.freeList.pop() || new Vec2() }
returnToPool() { Vec2.freeList.push(this) }
}
|