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 |
|---|---|---|---|---|---|---|
753698eaabcb11f567c8112c769a3e920767ca43 | TypeScript | ngAnzar/rpc | /src/runtime/client.ts | 2.546875 | 3 | import { Inject, Injectable } from "@angular/core"
import { of, throwError } from "rxjs"
import { map, switchMap } from "rxjs/operators"
import { HTTPTransport, Transport } from "./transport"
export abstract class Client {
public abstract readonly transport: Transport
}
export interface MethodOptions {
name: string
map?: (obj: any) => any,
hasParams?: boolean
}
export function Method(options: MethodOptions) {
return (target: any, propertyKey: string, descriptor?: PropertyDescriptor) => {
const type = Reflect.getMetadata("design:type", target, propertyKey)
if (type !== Function) {
throw new Error("RpcMethod must be function type")
}
const action_ = options.name
const hasParams = options.hasParams
const map_ = options.map
if (map_ && typeof map_ !== "function") {
throw new Error("'map' option must be a function")
}
function lf(src: any) {
// TODO: ...
if (typeof src.getLoadFields === "function") {
return src.getLoadFields()
}
return null
}
target[propertyKey] = map_
? function (this: Client, params: { [key: string]: any }, meta?: any): any {
return (hasParams ? this.transport.call(action_, params, meta) : this.transport.call(action_, null, params))
.pipe(switchMap(function (result: any) {
return result instanceof Error ? throwError(() => result) : of(map_(result))
}))
}
: function (this: Client, params: { [key: string]: any }, meta?: any): any {
return (hasParams ? this.transport.call(action_, params, meta) : this.transport.call(action_, null, params))
}
}
}
@Injectable()
export class HTTPClient extends Client {
public constructor(@Inject(HTTPTransport) public readonly transport: Transport) {
super()
}
}
|
7dbd92790b5eaed40021a344f6f5fe519dfda36c | TypeScript | desktop/desktop | /app/src/models/author.ts | 3.828125 | 4 | /** This represents known authors (authors for which there is a GitHub user) */
export type KnownAuthor = {
readonly kind: 'known'
/** The real name of the author */
readonly name: string
/** The email address of the author */
readonly email: string
/**
* The GitHub.com or GitHub Enterprise login for
* this author or null if that information is not
* available.
*/
readonly username: string | null
}
/** This represents unknown authors (for which we still don't know a GitHub user) */
export type UnknownAuthor = {
readonly kind: 'unknown'
/**
* The GitHub.com or GitHub Enterprise login for this author.
*/
readonly username: string
/** Whether we're currently looking for a GitHub user or if search failed */
readonly state: 'searching' | 'error'
}
/**
* A representation of an 'author'. In reality we're
* talking about co-authors here but the representation
* is general purpose.
*
* For visualization purposes this object represents a
* string such as
*
* Foo Bar <foo@bar.com>
*
* Additionally it includes an optional username which is
* solely for presentation purposes inside AuthorInput
*/
export type Author = KnownAuthor | UnknownAuthor
/** Checks whether or not a given author is a known user */
export function isKnownAuthor(author: Author): author is KnownAuthor {
return author.kind === 'known'
}
|
1d32dbf5b97c7c62b9478325ef05cfd190bc2e66 | TypeScript | Pendrokar/magia-ts | /js/scroll.ts | 2.71875 | 3 | export class Scroller {
// Declare variables:
private debug : boolean = false;
private paperHeight : number = 1610;
private viewHeight : number = 0;
private scrollTopOffset : number = 240 - this.paperHeight;
private scrollBottomOffset : number = this.scrollTopOffset - this.paperHeight;
private scrollTimer : number = -1;
// jQuery Objects:
private container : JQuery;
private footer : JQuery;
private scrollView : JQuery;
private scrollTop : JQuery;
private scrollBottom : JQuery;
constructor() {
// Assign variables:
window.scroll({
behavior: 'smooth'
})
// Find & assign jQuery Objects to variables:
this.container = $('.container').eq(0);
this.footer = $('.footer').eq(0);
this.scrollView = $('.scroll-view').eq(0);
this.scrollTop = $('.scroll-top').eq(0);
this.scrollBottom = $('.scroll-bottom').eq(0);
// On: Window resizing/Orientation change
$(window)
.on('resize', (event) => this.onResize())
.trigger('resize')
.on('scroll', (event) => this.onScroll())
.trigger('scroll')
;
if (this.debug) {
console.log('Scroll manager ready');
}
}
onScrollTimer() {
this.scrollTimer = window.setTimeout(() => this.onScroll(), 30);
}
onResize() : void {
this.viewHeight = <number>$(window).height();
if (this.debug) {
console.log('Scroll manager: window resized');
}
}
onScroll() : void {
let scrollTopVal = <number>$(window).scrollTop();
this.scrollTop
.css("background-position", "0 " + (this.paperHeight - this.scrollTopOffset + scrollTopVal) + "px");
this.scrollBottom
.css("background-position", "0 " + (this.viewHeight + 120 + scrollTopVal) + "px");
}
}
|
2bb10839ee045c9658d6ebd8d58073a75a9a10e8 | TypeScript | project-koku/koku-ui | /src/api/accountSettings.ts | 2.578125 | 3 | import axios from 'axios';
import type { PagedLinks, PagedMetaData } from './api';
export interface AccountSettingsData {
cost_type?: string;
currency?: string;
}
export interface PagedMetaDataExt extends PagedMetaData {
limit?: number;
offset?: number;
}
export interface AccountSettings {
meta: PagedMetaDataExt;
links?: PagedLinks;
data: AccountSettingsData;
}
export interface AccountSettingsPayload {
cost_type?: string;
currency?: string;
}
// eslint-disable-next-line no-shadow
export const enum AccountSettingsType {
settings = 'settings',
costType = 'costType',
currency = 'currency',
}
export const AccountSettingsTypePaths: Partial<Record<AccountSettingsType, string>> = {
[AccountSettingsType.settings]: 'account-settings/',
[AccountSettingsType.costType]: 'account-settings/cost-type/',
[AccountSettingsType.currency]: 'account-settings/currency/',
};
export function fetchAccountSettings(settingsType: AccountSettingsType) {
const path = AccountSettingsTypePaths[settingsType];
return axios.get<AccountSettings>(`${path}`);
}
export function updateAccountSettings(settingsType: AccountSettingsType, payload: AccountSettingsPayload) {
const path = AccountSettingsTypePaths[settingsType];
return axios.put(`${path}`, payload);
}
|
54ce65a634026814b1802314ef92b3e9ad863ffc | TypeScript | nestjs/nest | /packages/microservices/helpers/kafka-parser.ts | 2.875 | 3 | import { isNil } from '@nestjs/common/utils/shared.utils';
import { KafkaParserConfig } from '../interfaces';
export class KafkaParser {
protected readonly keepBinary: boolean;
constructor(config?: KafkaParserConfig) {
this.keepBinary = (config && config.keepBinary) || false;
}
public parse<T = any>(data: any): T {
// Clone object to as modifying the original one would break KafkaJS retries
const result = {
...data,
headers: { ...data.headers },
};
if (!this.keepBinary) {
result.value = this.decode(data.value);
}
if (!isNil(data.key)) {
result.key = this.decode(data.key);
}
if (!isNil(data.headers)) {
const decodeHeaderByKey = (key: string) => {
result.headers[key] = this.decode(data.headers[key]);
};
Object.keys(data.headers).forEach(decodeHeaderByKey);
} else {
result.headers = {};
}
return result;
}
public decode(value: Buffer): object | string | null | Buffer {
if (isNil(value)) {
return null;
}
// A value with the "leading zero byte" indicates the schema payload.
// The "content" is possibly binary and should not be touched & parsed.
if (
Buffer.isBuffer(value) &&
value.length > 0 &&
value.readUInt8(0) === 0
) {
return value;
}
let result = value.toString();
const startChar = result.charAt(0);
// only try to parse objects and arrays
if (startChar === '{' || startChar === '[') {
try {
result = JSON.parse(value.toString());
} catch (e) {}
}
return result;
}
}
|
fb7b4d9eb6b65e3858b93259f03c8bfb7a647397 | TypeScript | webkam11/tensorflowjs-iris-demo | /src/index.ts | 2.75 | 3 | import * as tf from "@tensorflow/tfjs"
import iris from "./resources/iris.json";
import irisTesting from "./resources/iris-testing.json";
// convert/setup our data
const trainingData = tf.tensor2d(iris.map(item => [
item.sepal_length, item.sepal_width, item.petal_length, item.petal_width,
]))
const outputData = tf.tensor2d(iris.map(item => [
item.species === "setosa" ? 1 : 0,
item.species === "virginica" ? 1 : 0,
item.species === "versicolor" ? 1 : 0,
]))
const testingData = tf.tensor2d(irisTesting.map(item => [
item.sepal_length, item.sepal_width, item.petal_length, item.petal_width,
]))
// build neural network
const model = tf.sequential()
model.add(tf.layers.dense({
inputShape: [4],
activation: "sigmoid",
units: 5,
}))
model.add(tf.layers.dense({
inputShape: [5],
activation: "sigmoid",
units: 3,
}))
model.add(tf.layers.dense({
activation: "sigmoid",
units: 3,
}))
model.compile({
loss: "meanSquaredError",
optimizer: tf.train.adam(.06),
})
// train/fit our network
const startTime = Date.now()
model.fit(trainingData, outputData, {epochs: 100})
.then((history) => {
console.log('history---------------------------', history);
const guess = model.predict(testingData);
console.log('guess', guess);
})
// test network
|
1b3e51df670d0de30119d2d7fb59da355f3f21e5 | TypeScript | richardfigueroa/shopifyrichard | /src/helpers/omdb_api.ts | 2.96875 | 3 | import { Movie } from "../models/Movie";
const OMDB_API_KEY = process.env.REACT_APP_OMDB_API_KEY || "";
const searchMoviesWithQuery = async (
query: string,
callback: (results: Movie[], error: Error | null) => void
) => {
const trimmedQuery = query.trim();
if (trimmedQuery.length === 0) {
callback([], null);
return;
}
fetch(
`https://www.omdbapi.com/?apikey=${OMDB_API_KEY}&s=${encodeURIComponent(
trimmedQuery
)}&type=movie`,
{
method: "GET",
headers: {
Accept: "application/json",
},
}
)
.then((response) => response.json())
.then((searchResponse) => {
const errorMessage = searchResponse["Error"];
if (errorMessage !== null && errorMessage !== undefined) {
const error = new Error(errorMessage);
callback([], error);
} else {
const searchResponseResults: Movie[] = searchResponse["Search"];
if (Array.isArray(searchResponseResults)) {
callback(searchResponseResults, null);
} else {
callback([], null);
}
}
})
.catch((error) => {
console.log(`Something went wrong: ${error}`);
callback([], error);
});
};
export default searchMoviesWithQuery;
|
ed1a090f8b8aadcb2ca1554ca1d4e2b09da414ce | TypeScript | tgbaldo/flashcards-api-node-typescript | /src/application/Deck/GetAllDeck.ts | 2.6875 | 3 | import RepositoryFactory from '../../domain/Core/RepositoryFactory';
import Deck from '../../domain/Deck/Deck';
import DeckRepository from '../../domain/Deck/DeckRepository';
import GetDeckOutput from './GetDeckOutput';
export default class GetAllDeck {
deckRepository: DeckRepository;
constructor (repositoryFactory: RepositoryFactory) {
this.deckRepository = repositoryFactory.createDeckRepository();
}
public async execute(): Promise<GetDeckOutput[] | []> {
const decks = await this.deckRepository.getAll();
if (!decks) {
return [];
}
return decks.map((d: Deck) => {
return new GetDeckOutput({ id: d.id, name: d.name });
});
}
}
|
b0c0bec7daba0b976714c8613e2d6e3e57ea37de | TypeScript | kripton-it/matrix-ui | /src/lib/matrix.ts | 3.375 | 3 | import autobind from 'autobind'
import { isSquare } from 'src/lib/analyzer'
export type Items = number[][];
export type Rows = number[][];
export type Row = number[];
export interface Size { width: number; height: number }
export type Initiator = (x?: number, y?: number, size?: Size) => number
export default class Matrix {
public width: number;
public height: number;
protected items: Items;
public constructor (items: Items = []) {
if (!this.checkItems(items)) {
throw new TypeError('Incorrect matrix data')
}
this.items = this.cloneItems(items)
this.height = items.length;
this.width = items.length ? items[0].length : 0;
}
protected cloneItems(items: Items): Items {
return items.map(row => row.slice()).slice()
}
protected checkItems(items: Items): boolean {
if (!Array.isArray(items)) {
return false
}
for (let i = 0; i < items.length; i++) {
if (!Array.isArray(items[i])) {
return false
}
if (i>0 && items[i].length !== items[i - 1].length) {
return false
}
}
return true;
}
public static create(width: number, height: number, initial: number | Initiator = 0): Matrix {
return new Matrix(
Array.from(new Array(height)).map((_, j) => (
Array.from(new Array(width)).map((__, i) => (
typeof initial === "function" ? initial(i, j, { width, height }) : initial
))
))
);
}
public static isEqual(firstMatrix: Matrix, secondMatrix: Matrix): boolean {
if (firstMatrix.height !== secondMatrix.height) {
return false
}
if (firstMatrix.width !== secondMatrix.width) {
return false
}
for (let i = 0; i < firstMatrix.width; i++) {
for (let j = 0; j < firstMatrix.height; j++) {
if (firstMatrix.getCell(i, j) !== secondMatrix.getCell(i, j)) {
return false;
}
}
}
return true;
}
public static from(items: Items): Matrix {
return new Matrix(items);
}
public getItems(): Items {
return this.cloneItems(this.items);
}
protected createRow(withInitial = 0): Row {
const row = []
let last = this.width
while(last > 0) {
row.push(withInitial)
last--;
}
return row
}
@autobind
public getRow(index): Row {
return this.items.slice()[index] || null
}
@autobind
public getRows(from, to): Rows {
return this.items.slice(from, to)
}
@autobind
public getCell(x: number, y: number): number {
return this.items[x][y];
}
@autobind
public addRowAbove(withInitial = 0): Matrix {
this.items.unshift(this.createRow(withInitial))
return Matrix.from(this.items);
}
@autobind
public addRowBelow(withInitial = 0): Matrix {
this.items.push(this.createRow(withInitial))
return Matrix.from(this.items);
}
@autobind
public addColumnLeft(withInitial = 0): Matrix {
this.items.forEach(row => row.unshift(withInitial));
return Matrix.from(this.items);
}
@autobind
public addColumnRight(withInitial = 0): Matrix {
this.items.forEach(row => row.push(withInitial));
return Matrix.from(this.items);
}
@autobind
public removeColumn(index: number): Matrix {
this.items.forEach(row => {
row.splice(index, 1)
})
return Matrix.from(this.items);
}
@autobind
public removeRow(index: number): Matrix {
this.items.splice(index, 1)
return Matrix.from(this.items);
}
@autobind
public multiplyByValue(multiplier: number): Matrix {
const matrix = Matrix.from(this.items)
for (let i = 0; i < this.height; i++) {
for (let j = 0; j < this.width; j++) {
matrix.items[i][j] *= multiplier
}
}
return matrix;
}
@autobind
public canMultiplyOnMatrix(matrix: Matrix): boolean {
return this.width === matrix.height
}
@autobind
public multiplyByMatrix(matrix: Matrix): Matrix {
if (!this.canMultiplyOnMatrix(matrix)) {
throw new TypeError("Incorrect multiplier")
}
const newMatrix = Matrix.create(matrix.width, this.height)
for (let i = 0; i < matrix.width; i++) {
for (let j = 0; j < this.height; j++) {
let value = 0
for (let r = 0; r < this.width; r++) {
value += matrix.getCell(r, i) * this.getCell(j, r)
}
newMatrix.items[j][i] = value
}
}
return newMatrix
}
@autobind
public multiply(multiplier: Matrix | number): Matrix {
if (multiplier instanceof Matrix) {
return this.multiplyByMatrix(multiplier)
}
return this.multiplyByValue(multiplier)
}
@autobind
public canAddToMatrix(matrix: Matrix): boolean {
return this.width === matrix.width && this.height === matrix.height
}
@autobind
public add(matrix: Matrix): Matrix {
if (!this.canAddToMatrix(matrix)) {
throw new TypeError("Incorrect addend")
}
const newMatrix = Matrix.create(this.width, this.height)
for (let i = 0; i < this.height; i++) {
for (let j = 0; j < this.width; j++) {
newMatrix.items[i][j] = matrix.getCell(i, j) + this.getCell(i, j)
}
}
return newMatrix
}
@autobind
public clone(): Matrix {
const newMatrix = Matrix.create(this.width, this.height)
for (let i = 0; i < this.height; i++) {
for (let j = 0; j < this.width; j++) {
newMatrix.items[i][j] = this.getCell(i, j)
}
}
return newMatrix
}
@autobind
public getDeterminant(): number {
if (!isSquare(this)) {
throw new TypeError("Determinant can't be found")
}
if (this.width === 1) {
return this.getCell(0, 0)
}
const row = this.getRow(0)
return row.reduce((acc, item, index) => {
console.log(this.width);
const minor = this.clone().removeRow(0).removeColumn(index)
console.log(minor, minor.getDeterminant.bind(minor)());
return acc + (-1) ** index * item * minor.getDeterminant.bind(minor)()
}, 0)
}
}
|
dd4368db4f16407a043d1a5cbd7dbf4e247c6a24 | TypeScript | linux-china/kotlin-is-like-typescript | /code/range-operator.ts | 3.078125 | 3 | import * as _ from 'lodash';
const names = ["Anna", "Alex", "Brian", "Jack"];
const count = names.length;
for (let i of _.range(0, count)) {
console.log(`Person ${i + 1} is called ${names[i]}`)
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
|
f99a79c011f2bc406e3e82ce9a8f51fcda4b9d5d | TypeScript | maxgherman/ts-haskell | /test/ghc/base/maybe/monoid.test.ts | 3.09375 | 3 | import tap from 'tap'
import { compose } from 'ghc/base/functions'
import { monoid as createMonoid } from 'ghc/base/maybe/monoid'
import { MaybeBox, $case as maybeCase, just, nothing } from 'ghc/base/maybe/maybe'
import { FunctionArrowSemigroup, semigroup as createSemigroup } from 'ghc/base/function-arrow/semigroup'
import { FunctionArrowBox } from 'ghc/prim/function-arrow'
import { semigroup as createEitherSemigroup, EitherSemigroup } from 'data/either/semigroup'
import { right, left, EitherBox, $case as eitherCase } from 'data/either/either'
import { cons, nil } from 'ghc/base/list/list'
type Arrow = FunctionArrowSemigroup<string, EitherSemigroup<Error, number>>
type ArrowBox = FunctionArrowBox<string, EitherBox<Error, number>>
const innerSemigroup = createEitherSemigroup<Error, number>()
const semigroup = createSemigroup<string, EitherSemigroup<Error, number>>(innerSemigroup)
const monoid = createMonoid<Arrow>(semigroup)
const getMaybeValue = (box: MaybeBox<Arrow>, arrowValue: string): undefined | Error | number =>
maybeCase<ArrowBox, undefined | Error | number>({
nothing: () => undefined,
just: (x) =>
eitherCase<Error, number, Error | number>({
left: (x) => x,
right: (x) => x,
})(x(arrowValue)),
})(box)
tap.test('MaybeMonoid', async (t) => {
t.test('mempty', async (t) => {
const result = maybeCase({
nothing: () => undefined,
just: (x) => x,
})(monoid.mempty)
t.equal(result, undefined)
})
t.test('<>', async (t) => {
const par1 = (s: string) => right<Error, number>(Number(s) + 1)
const par2 = () => right<Error, number>(0)
const result = monoid['<>'](just(par1), just(par2))
const value = getMaybeValue(result, '123')
t.equal(value, 124)
})
t.test('mappend', async (t) => {
const part1 = () => left<Error, number>(new Error('test'))
const part2 = () => right<Error, number>(0)
const result = monoid.mappend(just(part1), just(part2))
const value = getMaybeValue(result, '123')
t.equal(value, 0)
})
t.test('mconcat', async (t) => {
const part = (s: string) => right<Error, number>(Number(s) + 1)
const list = compose(cons(just(part)), cons(just(part)), cons(just(part)))(nil())
const result1 = monoid.mconcat(nil())
const result2 = monoid.mconcat(list)
t.equal(getMaybeValue(result1, ''), undefined)
t.equal(getMaybeValue(result2, '123'), 124)
})
t.test('Monoid law - associativity : (x <> y) <> z = x <> (y <> z)', async (t) => {
const part1 = (s: string) => right<Error, number>(Number(s) + 1)
const part2 = () => right<Error, number>(0)
const part3 = (s: string) => right<Error, number>(Number(s) + 10)
const result1 = monoid['<>'](monoid['<>'](just(part1), just(part2)), just(part2))
const result2 = monoid['<>'](just(part1), monoid['<>'](just(part2), just(part3)))
const result3 = monoid.mappend(monoid.mappend(nothing(), nothing()), nothing())
const result4 = monoid.mappend(nothing(), monoid.mappend(nothing(), nothing()))
t.equal(getMaybeValue(result1, '123'), getMaybeValue(result2, '123'))
t.equal(getMaybeValue(result1, '123'), 124)
t.same(getMaybeValue(result3, '123'), getMaybeValue(result4, '123'))
t.same(getMaybeValue(result3, '123'), null)
})
t.test('Monoid law - right identity: mempty <> x = x', async (t) => {
const part1 = () => left<Error, number>(new Error('test'))
const part2 = (s: string) => right<Error, number>(Number(s) + 1)
const result1 = monoid['<>'](monoid.mempty, just(part1))
const result2 = monoid['<>'](monoid.mempty, just(part2))
const result3 = monoid['<>'](monoid.mempty, nothing())
t.same(getMaybeValue(result1, ''), new Error('test'))
t.equal(getMaybeValue(result2, '123'), 124)
t.same(getMaybeValue(result3, '123'), null)
})
t.test('Monoid law - left identity: x <> mempty = x', async (t) => {
const part1 = () => left<Error, number>(new Error('test'))
const part2 = (s: string) => right<Error, number>(Number(s) + 1)
const result1 = monoid['<>'](just(part1), monoid.mempty)
const result2 = monoid['<>'](just(part2), monoid.mempty)
const result3 = monoid['<>'](monoid.mempty, nothing())
t.same(getMaybeValue(result1, ''), new Error('test'))
t.equal(getMaybeValue(result2, '123'), 124)
t.same(getMaybeValue(result3, '123'), null)
})
})
|
16d0450f0c2751563049ce5d11d2eb928ea5f92e | TypeScript | gherz-lau/babana-rebuild | /src/app/components/items/item-box/item-box.component.ts | 2.546875 | 3 | import { Component, OnInit, SkipSelf } from '@angular/core';
import { ItemsService } from './../../../services/items.service';
@Component({
selector: 'app-item-box',
templateUrl: './item-box.component.html',
styleUrls: ['./item-box.component.scss'],
})
export class ItemBoxComponent implements OnInit {
constructor(public miServicio: ItemsService) {}
ngOnInit(): void {}
addNewItem() {
this.miServicio.listItems.push({
id:
this.miServicio.listItems.length > 0
? this.miServicio.listItems[this.miServicio.listItems.length - 1].id +
1
: 1,
image: '',
title: '', //Fire for flowers
description: '',
});
}
killChild(item) {
//const index = this.listItems.indexOf(item); //creas una variable llamada index, para guardar ahi el id del item que se va a matar
//this.listItems.splice(index, 1); //matas el item (orden splice), un solo item, con el index indicado (o sea el id)
const index = this.miServicio.listItems.findIndex((i) => i.id == item.id);
//array.indexOf busca primitivos en arrays
//array.findIndex permite buscar el indice con base en el resultado de una funcion
this.miServicio.listItems.splice(index, 1);
}
}
|
c07f4212279c2dfb03a6e1aca409edd5dce21438 | TypeScript | acmeframework/af-documents | /src/lib/properties/normalizers/noop-normalizer.ts | 2.6875 | 3 | import { Normalizer, NormalizerOptions } from './normalizer';
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface NoopNormalizerOptions extends NormalizerOptions {}
export class NoopNormalizer<
T = any,
O extends NoopNormalizerOptions = NoopNormalizerOptions
> extends Normalizer<T, O> {
protected _normalize(value: T): T {
return value;
}
}
|
031a2063496111c31e1050e521a6db6576be8087 | TypeScript | jacobwindsor/MetabMaster | /src/app/pathway.service.ts | 2.734375 | 3 | import { Injectable } from '@angular/core';
import {FirebaseService} from "./firebase.service";
import {Observable, Subject} from "rxjs/Rx";
export interface Pathway {
id: string;
WPId: number;
title: string;
description: string;
userId: string;
createdAt: number;
reversedCreatedAt: number;
}
@Injectable()
export class PathwayService {
private lastReversedCreatedAt: number;
private pathwayList: Subject<Pathway> = new Subject();
pathwayList$: Observable<Pathway> = this.pathwayList.asObservable();
constructor(public fb: FirebaseService) {
}
/**
* Create a pathway
* @param values
*/
create(values: { WPId: number, title: string, description: string, userId: string }): Promise<any> {
const ref = this.fb.db.ref('pathways').push();
const timestamp = Date.now();
const toSet = Object.assign({
createdAt: timestamp,
reversedCreatedAt: -timestamp
}, values);
return new Promise((resolve, reject) => {
ref.set(toSet)
.then(
snapshot => resolve(ref.key),
err => reject(err));
});
}
/**
* Get a specific pathway.
* @param id
* @returns {Observable}
*/
get(id: string): Observable<Pathway> {
return Observable.fromPromise(new Promise((resolve, reject) => {
this.fb.db.ref('pathways/' + id).once('value').then(snapshot => {
const val = snapshot.val();
resolve({
id: snapshot.key,
WPId: val.WPId,
title: val.title,
description: val.description,
userId: val.userId,
createdAt: val.createdAt,
reversedCreatedAt: val.reversedCreatedAt
});
}).catch(err => {
reject(err);
});
}));
}
/**
* Update a specific pathway
* @param id
* @param updates
*/
update(id: string, updates: {WPId: number, title: string, description: string }): Promise<any> {
return this.fb.db.ref('pathways/' + id).update(updates);
}
/**
* Delete a pathway
* @param id
*/
destroy(id: string): Promise<any> {
return this.fb.db.ref('pathways/' + id).remove();
}
/**
* List all the pathways in ascending order. Ordered by the value of the WPId
* @param limit - number of entries to return
* @param startAt - The timestamp to start at (inclusive)
* @returns {Observable}
*/
list(limit = 10, startAt?): Observable<Pathway[]> {
return Observable.create(observer => {
let ref = this.fb.db.ref('pathways').orderByChild('reversedCreatedAt').limitToFirst(limit);
if (startAt) {
ref = ref.startAt(startAt);
}
ref.once('value', snapshot => {
const pathways = [];
snapshot.forEach(singlePathway => {
pathways.push(
Object.assign({id: singlePathway.key}, singlePathway.val())
);
});
observer.next(pathways);
});
});
}
/**
* Get the static image URL from a WikiPathways ID
* @param WPId
* @returns {string}
*/
staticImageUrlFromWPId(WPId: number): Promise<string> {
const url = `http://webservice.wikipathways.org/getPathwayAs?fileType=png&pwId=WP${WPId}&revision=0&format=json`;
const request = new Request(url);
return new Promise((resolve, reject) => {
fetch(request).then(response => {
return response.json().then(json => {
const data = json.data;
const image = `data:image/png;base64,${data}`;
resolve(image);
});
});
});
}
}
|
9c61eedb7ada337156848fe5df1385c5135e612d | TypeScript | JoseEncinoza/Mystique_desktop | /src/app/modules/marketing/promocion/config-promocion/segundo-paso/segundo-paso.component.ts | 2.671875 | 3 | import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-segundo-paso',
templateUrl: './segundo-paso.component.html',
styleUrls: ['./segundo-paso.component.scss']
})
export class SegundoPasoComponent implements OnInit {
listaTipoParam: ITipoParametro[]=[
{id:1,nombre:"Datos básicos",fecha_creacion:"2018-03-02",estatus:"activo"},
];
parametros: IParametro[]=[
{
id:1,
id_tipo_parametro:1,
nombre:"Sexo",
fecha_creacion:"2018-02-02",
estatus:"activo"},
{
id:2,
id_tipo_parametro:2,
nombre:"Hijos",
fecha_creacion:"2018-02-02",
estatus:"activo"},
{
id:3,
id_tipo_parametro:3,
nombre:"Edad",
fecha_creacion:"2018-02-02",
estatus:"activo"},
];
valoresParametro: IValorParametro[]=[
{
id:1,
id_parametro:1,
nombre:"Mujer",
descripcion:" femenino",
fecha_creacion:"2018-02-02",
estatus:"activo"},
{
id:2,
id_parametro:1,
nombre:"Hombre",
descripcion:"sexo hombre",
fecha_creacion:"2018-02-02",
estatus:"activo"},
{
id:3,
id_parametro:1,
nombre:"Indefinido",
descripcion:"sexo indefinido",
fecha_creacion:"2018-02-02",
estatus:"activo"},
{
id:4,
id_parametro:2,
nombre:"Si",
descripcion:"sexo hombre",
fecha_creacion:"2018-02-02",
estatus:"activo"},
{
id:5,
id_parametro:2,
nombre:"No",
descripcion:"sexo indefinido",
fecha_creacion:"2018-02-02",
estatus:"activo"},
];
datos_a_mostrar: IParametroValorParametro[]=[];
step = 0;
setStep(index: number) {
this.step = index;
}
nextStep() {
this.step++;
}
prevStep() {
this.step--;
}
constructor() { }
ngOnInit() { /*Aca se inicializa la lista de valores parametro*/
this.parametros.forEach(elem=> {let longi=0;let arra:IValorParametro[]=[];this.valoresParametro.forEach(element => {if(element.id_parametro==elem.id){longi=arra.push(element);}});longi=this.datos_a_mostrar.push({nombre_parametro:elem,valores_parametro:arra});});
}
checkear(parametro){
if (parametro.estatus=="activo")
{parametro.estatus="inactivo";
this.n=0;
///////////////////////////////////////////////BORRA UN PARAMETRO DE LA LISTA PARA MOSTRAR VALORES PARAMETROS.
let b:IParametroValorParametro[];
for (let i = 0; i < this.datos_a_mostrar.length; i++) {
const element = this.datos_a_mostrar[i];
if (element.nombre_parametro.id==parametro.id) {
b=this.datos_a_mostrar.splice(this.datos_a_mostrar.indexOf(element),1);
break;
}
}
///////////////////////////////////////////////
}
else
{parametro.estatus="activo";
///////////////////////////////////////////////AGREGA PARAMETROS A LA LISTA DE VALORES PARAMETROS
let longitud=0;
let arr:IValorParametro[]=[];
this.valoresParametro.forEach(element => {
if(element.id_parametro==parametro.id){longitud=arr.push(element);}});
longitud=this.datos_a_mostrar.push({nombre_parametro:parametro,valores_parametro:arr});
this.n=(longitud-1);
///////////////////////////////////////////////
}
}
n=0;
siguiente(){
if(this.n==(this.datos_a_mostrar.length-1)){
this.n=0;
}
else{
this.n++;
}
}
}
/* DE LA PARAMETRIZACION */
interface ITipoParametro{ //Ejm: Cabello
id:number;
nombre:string;
fecha_creacion:string;//Date
estatus:string;
}
interface IParametro{ //Ejm: longitud
id:number;
id_tipo_parametro:number;
nombre:string;
fecha_creacion:string;//Date
estatus:string;
}
interface IValorParametro{ //Ejm: corto
id:number;
id_parametro:number;
nombre:string;
descripcion:string;//Lo agregue, pero no esta contemplado en la entidad
fecha_creacion:string//Date;
estatus:string;
}
interface IParametroValorParametro{
nombre_parametro: IParametro;
valores_parametro: IValorParametro[];
}
|
c9576f90a20f8b6ef8380be0f7a81c4940821e40 | TypeScript | AlexisK/finance | /src/app_modules/directives/scroll-css.directive.ts | 2.78125 | 3 | import {Directive, ElementRef, Input, HostListener, AfterViewInit} from '@angular/core';
@Directive({selector : '[scrollCss]'})
export class ScrollCssDirective implements AfterViewInit {
@Input() scrollCss: any;
constructor(private el: ElementRef) {
}
ngAfterViewInit() {
this.normalizeData();
this.doOnScroll();
}
@HostListener('window:scroll', ['$event'])
onScroll(ev: Event) {
this.doOnScroll();
}
/*
executes normalized data.
each function receives 2 values:
- dom-element
- boolean, true if scroll position is below marker, false if above
*/
doOnScroll() {
for (let k in this.scrollCss) {
if (document.body.scrollTop > parseFloat(k)) {
this.scrollCss[k][0](this.el.nativeElement, true);
} else {
this.scrollCss[k][1](this.el.nativeElement, false);
}
}
}
/*
normalize data so doOnScroll method could just execute.
normalised data should look like dict, where:
key - amount of pixels from top(marker)
value - pair(list.length = 2):
0: function to execute when we below specified marker
1: function to execute when we above specified marker
*/
normalizeData() {
Object.keys(this.scrollCss).forEach(k => {
let data = this.scrollCss[k];
if (data.constructor === String) {
/*
css class received
*/
this.scrollCss[k] = [
function (node: any) {
node.classList.add(data);
},
function (node: any) {
node.classList.remove(data);
}
];
} else if (data.constructor === Array) {
/*
pair received, any member could be null
*/
data[0] = data[0] || (() => true);
data[1] = data[1] || (() => true);
} else if (data.constructor === Function) {
/*
parser received - we don't bother what it does, we execute it all the time
*/
this.scrollCss[k] = [data, data];
} else {
throw new Error('Unknown type for [scrollCss]');
}
});
}
}
|
75c9eea3ccc0457f48dd19cf46cd3114a935b0b7 | TypeScript | gulfofmaine/Neracoos-1-Buoy-App | /src/Shared/erddap/metadata.ts | 2.6875 | 3 | import { ErddapDataset } from './types'
/**
* Return the metadata URL for a given dataset.
*
* @param dataset Source dataset to extract URL from.
* @returns String with URL to ERDDAP server dataset metadata.
*/
export function datasetInfoJson(dataset: ErddapDataset): string {
return dataset.server + '/info/' + dataset.datasetId + '/index.json'
}
|
854e3f7241dd960dc5ade167a02d9850b00dc3cd | TypeScript | lbeder/openzeppelin-upgrades | /packages/core/src/utils/log.ts | 2.78125 | 3 | import chalk from 'chalk';
import { indent } from './indent';
export function logWarning(title: string, lines: string[] = []): void {
const parts = [chalk.yellow.bold('Warning:') + ' ' + title + '\n'];
if (lines.length > 0) {
parts.push(lines.map(l => indent(l, 4) + '\n').join(''));
}
console.error(parts.join('\n'));
}
|
ee8abc548da15ee7e7064a44ba5885c85390095e | TypeScript | mmoskal/dapjs | /src/util.ts | 2.921875 | 3 | import {ApReg, DapVal, Reg} from "./dap/constants";
export const readUInt32LE = (b: Uint8Array, idx: number) => {
return (b[idx] |
(b[idx + 1] << 8) |
(b[idx + 2] << 16) |
(b[idx + 3] << 24)) >>> 0;
};
export const bufferConcat = (bufs: Uint8Array[]) => {
let len = 0;
for (const b of bufs) {
len += b.length;
}
const r = new Uint8Array(len);
len = 0;
for (const b of bufs) {
r.set(b, len);
len += b.length;
}
return r;
};
export const delay = async (t: number) => {
return new Promise((resolve) => {
setTimeout(resolve, t);
});
};
export const addInt32 = (arr: number[], val: number) => {
if (!arr) {
arr = [];
}
arr.push(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, (val >> 24) & 0xff);
return arr;
};
export const hex = (v: number) => {
return "0x" + v.toString(16);
};
export const rid = (v: number) => {
const m = [
"DP_0x0",
"DP_0x4",
"DP_0x8",
"DP_0xC",
"AP_0x0",
"AP_0x4",
"AP_0x8",
"AP_0xC",
];
return m[v] || "?";
};
export const bank = (addr: number) => {
const APBANKSEL = 0x000000f0;
return (addr & APBANKSEL) | (addr & 0xff000000);
};
export const apReg = (r: ApReg, mode: DapVal) => {
const v = r | mode | DapVal.AP_ACC;
return (4 + ((v & 0x0c) >> 2)) as Reg;
};
export const bufToUint32Array = (buf: Uint8Array) => {
assert((buf.length & 3) === 0);
const r: number[] = [];
if (!buf.length) {
return r;
}
r[buf.length / 4 - 1] = 0;
for (let i = 0; i < r.length; ++i) {
r[i] = readUInt32LE(buf, i << 2);
}
return r;
};
export const assert = (cond: any) => {
if (!cond) {
throw new Error("assertion failed");
}
};
export const regRequest = (regId: number, isWrite = false) => {
let request = !isWrite ? DapVal.READ : DapVal.WRITE;
if (regId < 4) {
request |= DapVal.DP_ACC;
} else {
request |= DapVal.AP_ACC;
}
request |= (regId & 3) << 2;
return request;
};
export const hexBytes = (bytes: number[]) => {
let chk = 0;
let r = ":";
bytes.forEach((b) => chk += b);
bytes.push((-chk) & 0xff);
bytes.forEach((b) => r += ("0" + b.toString(16)).slice(-2));
return r.toUpperCase();
};
export const hex2bin = (hexstr: string) => {
const array = new Uint8Array(hexstr.length / 2);
for (let i = 0; i < hexstr.length / 2; i++) {
array[i] = parseInt(hexstr.substr(2 * i, 2), 16);
}
return array;
}
|
11fcc5a484c6e43725c8cb97330094c7384ffca4 | TypeScript | sheweichun/future | /packages/free-canvas-shared/src/pos.ts | 3.203125 | 3 |
type PosRect = {
left:number,
top:number,
_left:number,
_top:number,
}
const MINI_NUMBER = 0.0000000001
function fixPercent(percent:number){
return percent < MINI_NUMBER ? MINI_NUMBER : percent
}
function fixValue(val:number){
// return val;
return Math.floor(val);
}
function getRelativeRect(rect:OperationPos,parentRect?:PosRect){
return {
left:rect._left - parentRect._left ,
top:rect._top - parentRect._top,
width:rect._width,
height:rect._height
}
// return new OperationPos(rect.left - curRect.left,rect.top - curRect.top,rect.width,rect.height)
}
export function calculateIncludeRect(poses:OperationPos[]){
const item = poses[0];
const left = item.left;
const top = item.top;
let pos = {
left,
top,
width:item.width,
height:item.height,
rightLeft:left + item.width,
bottomTop:top + item.height
}
for(let i = 1; i < poses.length; i++){
const curItem = poses[i];
const left = curItem.left;
const top = curItem.top;
const rightLeft = left + curItem.width;
const bottomTop = top + curItem.height;
const posLeft = pos.left < left ? pos.left : left
const posTop = pos.top < top ? pos.top : top
const posWidth = (pos.rightLeft > rightLeft ? pos.rightLeft : rightLeft) - posLeft
const posHeight = (pos.bottomTop > bottomTop ? pos.bottomTop : bottomTop) - posTop
pos = {
left: posLeft,
top: posTop,
width : posWidth,
height : posHeight,
rightLeft: posLeft + posWidth,
bottomTop: posTop + posHeight,
}
}
return pos;
}
export class OperationPos{
public _left:number
public _top:number
public _width:number
public _height:number
constructor(
public left:number,
public top:number,
public width:number,
public height:number,
private _updater?:(pos:OperationPos)=>void){
this._left = left;
this._top = top;
this._width = width;
this._height = height;
}
// static EmptyPos = new OperationPos(0,0,0,0);
static createEmpty(){
return new OperationPos(0,0,0,0);
}
getDiffX(){
return this.width - this._width
}
getDiffY(){
return this.height - this._height
}
update(noUpdate:boolean){
(this._updater && !noUpdate) && this._updater(this)
return this;
}
include(left:number,top:number){
return (left > this.left && left - this.left < this.width)
&& (top > this.top && top - this.top < this.height)
}
isOverlap(pos:OperationPos){
return (this.left + this.width > pos.left &&
pos.left + pos.width > this.left &&
this.top + this.height > pos.top &&
pos.top + pos.height > this.top
)
}
getHMiddle(){
return Math.floor(this.left + this.width / 2)
}
getVMiddle(){
return Math.floor(this.top + this.height / 2)
}
moveLeftAndTop_immutation(x:number,y:number){
return new OperationPos(this.left + x,this.top + y,this.width,this.height,this._updater);
}
updateLeftAndTop(x:number,y:number,noUpdate:boolean=false){
this.left = x;
this.top = y;
(this._updater && !noUpdate) && this._updater(this)
}
moveLeftAndTop(x:number,y:number,noUpdate:boolean=false){
this.left += x;
this.top += y;
(this._updater && !noUpdate) && this._updater(this)
// return new OperationPos(this.left + x,this.top + y,this.width,this.height,this._updater)
// .update(noUpdate)
}
moveLeft(diffx:number,diffy:number,noUpdate:boolean=false){
this.left = this._left + diffx;
this.width = this._width - diffx;
(this._updater && !noUpdate) && this._updater(this)
}
moveLeftTop(diffx:number,diffy:number,noUpdate:boolean=false){
this.left = this._left + diffx;
this.width = this._width - diffx;
this.top = this._top + diffy;
this.height = this._height - diffy;
(this._updater && !noUpdate) && this._updater(this)
}
moveRightTop(diffx:number,diffy:number,noUpdate:boolean=false){
this.width = this._width + diffx;
this.top = this._top + diffy;
this.height = this._height - diffy;
(this._updater && !noUpdate) && this._updater(this)
}
moveLeftBottom(diffx:number,diffy:number,noUpdate:boolean=false){
this.left = this._left + diffx;
this.width = this._width - diffx;
this.height = this._height + diffy;
(this._updater && !noUpdate) && this._updater(this)
}
moveRightBottom(diffx:number,diffy:number,noUpdate:boolean=false){
this.width = this._width + diffx;
this.height = this._height + diffy;
(this._updater && !noUpdate) && this._updater(this)
}
moveRight(diffx:number,diffy:number,noUpdate:boolean=false){
this.width = this._width + diffx;
(this._updater && !noUpdate) && this._updater(this)
}
moveTop(diffx:number,diffy:number,noUpdate:boolean=false){
this.top = this._top + diffy;
this.height = this._height - diffy;
(this._updater && !noUpdate) && this._updater(this)
}
moveBottom(diffx:number,diffy:number,noUpdate:boolean=false){
this.height = this._height + diffy;
(this._updater && !noUpdate) && this._updater(this)
}
moveLeftPercent(pPos:OperationPos,rootPos:OperationPos,noUpdate:boolean=false){
const xPercent = rootPos.width / rootPos._width;
const pos = getRelativeRect(this,pPos);
this.left = fixValue(pPos.left + pos.left * xPercent);
this.width = fixValue(this._width * xPercent);
(this._updater && !noUpdate) && this._updater(this)
}
moveLeftTopPercent(pPos:OperationPos,rootPos:OperationPos,noUpdate:boolean=false){
const xPercent = rootPos.width / rootPos._width,yPercent = rootPos.height / rootPos._height;
const pos = getRelativeRect(this,pPos);
this.left = fixValue(pPos.left + pos.left * xPercent);
this.width = fixValue(this._width * xPercent);
this.top = fixValue(pPos.top + pos.top * yPercent);
this.height = fixValue(this._height * yPercent);
(this._updater && !noUpdate) && this._updater(this)
}
moveLeftBottomPercent(pPos:OperationPos,rootPos:OperationPos,noUpdate:boolean=false){
this.moveLeftTopPercent(pPos,rootPos,noUpdate);
}
moveRightTopPercent(pPos:OperationPos,rootPos:OperationPos,noUpdate:boolean=false){
this.moveLeftTopPercent(pPos,rootPos,noUpdate);
}
moveRightBottomPercent(pPos:OperationPos,rootPos:OperationPos,noUpdate:boolean=false){
this.moveLeftTopPercent(pPos,rootPos,noUpdate);
}
moveRightPercent(pPos:OperationPos,rootPos:OperationPos,noUpdate:boolean=false){
// const hPercent = (diffx + curRect._width) / curRect._width),vPercent = fixPercent((diffy + curRect._height) / curRect._height);
// const diffx = pPos.getDiffX()
const xPercent = rootPos.width / rootPos._width;
const pos = getRelativeRect(this,pPos);
this.left = fixValue(pPos.left + pos.left * xPercent);
this.width = fixValue(this._width * xPercent);
(this._updater && !noUpdate) && this._updater(this)
}
moveTopPercent(pPos:OperationPos,rootPos:OperationPos,noUpdate:boolean=false){
// const diffy = pPos.getDiffY()
const yPercent = rootPos.height / rootPos._height;
const pos = getRelativeRect(this,pPos);
this.top = fixValue(pPos.top + pos.top * yPercent);
this.height = fixValue(this._height * yPercent);
(this._updater && !noUpdate) && this._updater(this)
}
moveBottomPercent(pPos:OperationPos,rootPos:OperationPos,noUpdate:boolean=false){
// this.moveTopPercent(diffx,diffy,noUpdate);
// const diffy = pPos.getDiffY()
const yPercent = rootPos.height / rootPos._height;
const pos = getRelativeRect(this,pPos);
this.top = fixValue(pPos.top + pos.top * yPercent);
this.height = fixValue(this._height * yPercent);
(this._updater && !noUpdate) && this._updater(this)
}
// moveLeft(diffx:number,diffy:number,noUpdate:boolean=false){
// // this.left += diffx;
// // this.width -= diffx;
// // (this._updater && !noUpdate) && this._updater(this)
// return new OperationPos(this.left + diffx,this.top,this.width - diffx,this.height,this._updater)
// .update(noUpdate);
// }
// moveRight(diffx:number,diffy:number,noUpdate:boolean=false){
// // this.width += diffx;
// // (this._updater && !noUpdate) && this._updater(this)
// return new OperationPos(this.left,this.top,this.width + diffx,this.height,this._updater)
// .update(noUpdate);
// }
// moveTop(diffx:number,diffy:number,noUpdate:boolean=false){
// // this.top += diffy;
// // this.height -= diffy;
// // (this._updater && !noUpdate) && this._updater(this)
// return new OperationPos(this.left,this.top + diffy,this.width,this.height - diffy,this._updater)
// .update(noUpdate);
// }
// moveBottom(diffx:number,diffy:number,noUpdate:boolean=false){
// // this.height += diffy;
// // (this._updater && !noUpdate) && this._updater(this)
// return new OperationPos(this.left,this.top,this.width,this.height + diffy,this._updater)
// .update(noUpdate);
// }
// moveByPercent(xPercent:number,yPercent:number,noUpdate:boolean=false){
// console.log(xPercent,yPercent);
// // const totalXPercent = 1 + xPercent,totalYPercent = 1 + yPercent;
// this.left *= xPercent;
// this.width *= xPercent;
// this.top *= yPercent;
// this.height *= yPercent;
// (this._updater && !noUpdate) && this._updater(this)
// }
}
// moveByPercent(parentWidth:number,parentNewWidth:number,parentHeight:number,parentNewHeight:number,noUpdate:boolean=false){
// const xPercent = parentNewWidth / parentWidth,yPercent = parentNewHeight / parentHeight;
// this.left *= totalXPercent;
// this.width *= totalXPercent;
// this.top *= totalYPercent;
// this.height *= totalYPercent;
// (this._updater && !noUpdate) && this._updater(this)
// }
// moveLeftPercent(pPos:PosRect,pos:PosRect,xPercent:number,yPercent:number,noUpdate:boolean=false){
// // // const originLeft = this.left;
// // console.log('xpercent :',xPercent);
// // this.left = Math.floor(pPos.left + pos.left * xPercent);
// // this.width *= xPercent;
// // console.log('pPos.left :',pPos.left,pos.left,xPercent,pPos.left + pos.left * xPercent);
// return new OperationPos(pPos.left + pos.left * xPercent,this.top,this.width * xPercent,this.height,this._updater)
// .update(noUpdate)
// }
// moveRightPercent(pPos:PosRect,pos:PosRect,xPercent:number,yPercent:number,noUpdate:boolean=false){
// return this.moveLeftPercent(pPos,pos,xPercent,yPercent,noUpdate)
// // this.moveLeftPercent(diffx,diffy,noUpdate);
// // (this._updater && !noUpdate) && this._updater(this)
// }
// moveTopPercent(diffx:number,diffy:number,noUpdate:boolean=false){
// this.top = Math.floor(this.top * diffy);
// this.height = Math.floor(this.height * diffy);
// (this._updater && !noUpdate) && this._updater(this)
// }
// moveBottomPercent(diffx:number,diffy:number,noUpdate:boolean=false){
// this.moveTopPercent(diffx,diffy,noUpdate);
// } |
4e77fca9b6e6be8bc6eeb1d7fe688372d3d3bd7f | TypeScript | Meowchacho/core-ts | /src/EntityLoader.ts | 3.078125 | 3 | export interface IEntityLoaderConfig {
area?: string;
bundle?: string;
path?: string;
db?: string;
}
export interface IDataSource {
name: string;
resolvePath(config: { path: string; bundle: string; area: string }): string;
hasData(config: IEntityLoaderConfig): Promise<any>;
fetchAll?(config: IEntityLoaderConfig): Promise<any>;
fetch?(config: IEntityLoaderConfig, id: string | number): any;
replace?(config: IEntityLoaderConfig, data: any): void;
update?(config: IEntityLoaderConfig, id: string | number, data: any): void;
delete?(config: IEntityLoaderConfig, id: string | number): void;
}
/**
* Used to CRUD an entity from a configured DataSource
*/
export class EntityLoader {
dataSource: IDataSource;
config: IEntityLoaderConfig;
/**
* @param {DataSource}
* @param {object} config
*/
constructor(dataSource: IDataSource, config: IEntityLoaderConfig = {}) {
this.dataSource = dataSource;
this.config = config;
}
setArea(name: string) {
this.config.area = name;
}
setBundle(name: string) {
this.config.bundle = name;
}
hasData(): Promise<any> {
return this.dataSource.hasData(this.config);
}
fetchAll(): Promise<any> {
if (!this.dataSource.fetchAll) {
throw new Error(`fetchAll not supported by ${this.dataSource.name}`);
}
return this.dataSource.fetchAll(this.config);
}
fetch(id: string | number) {
if (!this.dataSource.fetch) {
throw new Error(`fetch not supported by ${this.dataSource.name}`);
}
return this.dataSource.fetch(this.config, id);
}
replace(data: any) {
if (!this.dataSource.replace) {
throw new Error(`replace not supported by ${this.dataSource.name}`);
}
return this.dataSource.replace(this.config, data);
}
update(id: string | number, data: any) {
if (!this.dataSource.update) {
throw new Error(`update not supported by ${this.dataSource.name}`);
}
return this.dataSource.update(this.config, id, data);
}
delete(id: string | number) {
if (!this.dataSource.delete) {
throw new Error(`delete not supported by ${this.dataSource.name}`);
}
return this.dataSource.delete(this.config, id);
}
}
|
34589bec7a6cd1d0d4850aa9492f7ace5d76814b | TypeScript | SergioEGGit/Project_Translator_From_Java_To_Javascript_And_Python_SEG | /Source Code/Backend/Traductores/Javascript/src/AnalizadorLexicoSintactico/If.ts | 3.109375 | 3 | // Imports
// Clase Abstracta
import { Instruccion } from "./Instruccion";
// Metodo Identacion
import { AgregarIdentacion } from "./Variables_Metodos";
// Clase Principal
export class If extends Instruccion {
// Constructor
constructor(Linea: number, Columna: number, private Condicion: Instruccion, private BloqueIf: Instruccion, private BloqueElse: Instruccion | null) {
// Super
super(Linea, Columna)
}
// Método Traducir
public Traducir() {
// Declaraciones
let Condicion = this.Condicion.Traducir();
let BloqueIf = this.BloqueIf.Traducir();
let BloqueElse = "";
// Verificar Si Hay Bloque Else
if(this.BloqueElse != null) {
// Recuperar Bloque
BloqueElse = this.BloqueElse.Traducir();
// Verificar Si Es Clase Heredada De If
if (this.BloqueElse instanceof If) {
// Traduccion Else If
let Traduccion_ElseIf = AgregarIdentacion() + "if(" + Condicion + ") " +
"{ \n\n" +
BloqueIf + "\n" +
AgregarIdentacion() + "} else " +
BloqueElse.trim() + "\n\n";
return Traduccion_ElseIf;
}
// Traduccion Else
let Traduccion_Else = AgregarIdentacion() + "if(" + Condicion + ") " +
"{ \n\n" +
BloqueIf + "\n" +
AgregarIdentacion() + "} else { \n\n" +
BloqueElse + "\n" +
AgregarIdentacion() + "} \n\n";
return Traduccion_Else;
}
// Traduccion If
let Traduccion_If = AgregarIdentacion() + "if(" + Condicion + ") " +
"{ \n\n" +
BloqueIf + "\n" +
AgregarIdentacion() + "} \n\n";
return Traduccion_If;
}
} |
b5e2c352862fb5b38c326f654ec878e72269e5b1 | TypeScript | JosephWaldman/JB-FinalProject-2020---Client-Angular8 | /src/app/Manager Area/manage-users/manage-users.component.ts | 2.546875 | 3 | import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FileUploader } from 'ng2-file-upload';
@Component({
selector: 'manage-users',
templateUrl: './manage-users.component.html',
styleUrls: ['./manage-users.component.css']
})
export class ManageUsersComponent implements OnInit {
private TableData;// אובייקט אליו מושמים כל רכבי החברה
private LocalHost: string = "http://localhost:61955/";
private ShowEditTable: boolean = false; // משתנה בוליאני לצורך עריכת הטבלה
private EditRowID: any = ""; // משתנה עבור בחירת שורה לצורך עריכה
private Gender: string; // מועבר מהטופס לפונקציה שמוסיפה סוג רכב חדש
private Rank: string; // מועבר מהטופס לפונקציה שמוסיפה סוג רכב חדש
private Thumbnail:string; // משתנה אליו תהיה השמה עם שם קובץ התמונה
private uploader:FileUploader = new FileUploader({url: ""}); // ספרית צד שלישי לשליפת המידע מהקובץ, במקרה זה שם הקובץ, המשך בפונקצית און איניט
constructor(private http: HttpClient) {
http.get(this.LocalHost + "Get/Admin/GetUserFields/")// גט ריקווסט של רשימת כל המשתמשים
.subscribe(c => this.TableData = c);
}
Edit(value) // פונקציה עבור עריכת שורות בטבלה, מקבל מזהה ומשווה אותו לאחר מכן באנג'י-איפ לפרופרטי מהאובייקט הנוכחי - 'איי' באיטרציה
{
this.EditRowID = value;
}
Update(UpdateUser: any) { // פונקיה הפונה לשרת עם פוט מת'וד, נשלח אובייקט עם השורה שנבחרה מתוך הרשימה
this.http.put(this.LocalHost + "Put/Admin/PutUserFields",
{
"ID": UpdateUser.ID,
"DriverLicense": UpdateUser.DriverLicense,
"Username": UpdateUser.Username,
"Password": UpdateUser.Password,
"FullName": UpdateUser.FullName,
"Birthdate": UpdateUser.Birthdate,
"Gender": UpdateUser.Gender,
"Email": UpdateUser.Email,
"Thumbnail": this.Thumbnail,
"Rank": UpdateUser.Rank
}).subscribe();
this.EditRowID = "";// איפוס אמצעי מזהה לצורך יציאה מחלון עריכה
}
Delete(DeleteUser: any) // פונקציה למחיקת משתמש
{
this.http.delete(this.LocalHost + "Delete/Admin/DeleteUserFields/?UserID=" +
DeleteUser.ID, {}).subscribe(
f => {
this.http.get(this.LocalHost + "Get/Admin/GetUserFields/")
.subscribe(c => this.TableData = c);
}
);
this.EditRowID = "";// איפוס אמצעי מזהה לצורך יציאה מחלון עריכה
}
Add(DriverLicense: string, Username: string, Password: string, FullName: string,
Birthdate: string, Email: string) {this.http.post
(
this.LocalHost + "Post/Admin/PostUserFields/", // פונקציה להוספת משתמש/ת חדש/ה, ערכי השדות הינם הערכים שהפונקציה מקבלת לתוכה, ונשלחים בתור אובייקט לווב איי פי איי
{
"DriverLicense": DriverLicense,
"Username": Username,
"Password": Password,
"FullName": FullName,
"Birthdate": Birthdate,
"Gender": this.Gender,
"Email": Email,
"Thumbnail": this.Thumbnail,
"Rank": this.Rank
}
).subscribe(//סבסקרייב נוסף כדי לרענן ויזואלית את הטבלה בדף
f => {
this.http.get(this.LocalHost + "Get/Admin/GetUserFields/").subscribe(c => this.TableData = c);
}
)
}
ngOnInit() {
this.uploader.onAfterAddingFile = (item:any) => { // בהשלמת ההעלאה,
this.Thumbnail = item.file.name}; // תבצע השמה של שם הקובץ למשתנה ת'אמבנייל
};
}; |
e2b7992efb806bef4c0425159898fa5937f62ee5 | TypeScript | jamescarr/frontend-learning | /testing/ts-with-jest/src/main.spec.ts | 3.234375 | 3 | import {isInternalLink, GenericNumber} from './main';
describe('internal link checker', () => {
it('should return false given external link', () => {
expect(isInternalLink('https://google.com')).toBe(false)
})
it('should return true given internal link', () => {
expect(isInternalLink('/some-page')).toBe(true)
})
})
describe('Typescript Features', () => {
describe('typed arrays', () => {
it('still allows string types in the runtime', () => {
let list: number[] = [1, 2, 3];
list.push("Foo")
expect(list).toEqual([1, 2, 3, "Foo"])
})
})
it("has generics", () => {
let theGenericNumber = new GenericNumber<number>();
theGenericNumber.zeroValue = 0;
theGenericNumber.add = (x, y) => x + y;
expect(theGenericNumber.add(4, 3)).toEqual(7);
})
})
|
2067adc15f632b1ad5e758e5946818a8a7fe659c | TypeScript | guzmanoj/diffx | /chrome-extension/src/utils/get-object-map.ts | 3.515625 | 4 | export interface ObjectMap {
id: string,
key: string,
value: string,
type: 'string' | 'boolean' | 'number' | 'array' | 'object',
children: ObjectMap[]
}
export function getObjectMap(obj: any, id = ''): ObjectMap[] {
return Object.keys(obj)
.map(key => {
const value = obj[key];
return {
id: id + key,
key,
value: getValueString(value),
type: getType(value),
children: hasChildren(value) ? getObjectMap(value, id + key) : []
} as ObjectMap;
});
}
function getValueString(value: any) {
const type = getType(value);
if (type === 'string' || type === 'boolean' || type === 'number') {
return value;
}
if (type === 'array') {
return `Array[${value.length}]`;
}
return `Object{${Object.keys(value).length}}`;
}
function getType(value: any) {
if (typeof value === 'string') {
return 'string';
}
if (typeof value === 'boolean') {
return 'boolean';
}
if (typeof value === 'number') {
return 'number';
}
if (Array.isArray(value)) {
return 'array';
}
return 'object';
}
function hasChildren(value: any) {
const type = getType(value);
return type === 'array' || type === 'object';
} |
2b4b9ddf57aa29991027400f3799ba29120a427b | TypeScript | ulfik/angular-projects | /src/app/common/pipes/filter.pipe.ts | 2.625 | 3 | import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'arrayOfObjectsFilter',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(value: any, key: any, objectValue: any): any {
if (!value.length || !objectValue) {
return value;
}
return value.filter((element) => element[key] === objectValue);
}
}
|
1f4f5cf4974edeb26297a813ec058dd84bb243a4 | TypeScript | netanelgilad/deaven | /src/prophet/eval/eval.ts | 2.515625 | 3 | import { ESFunction } from "../Function/Function";
import { TExecutionContext } from "../execution-context/ExecutionContext";
import { Any, Undefined } from "../types";
import { tuple } from "@deaven/tuple";
import { TESString } from "../string/String";
import { unsafeCast } from "@deaven/unsafe-cast.macro";
import { evaluate } from "../evaluate";
import { parseECMACompliant } from "../parseECMACompliant";
export const evalFn = ESFunction(function*(
_self: Any,
args: Any[],
execContext: TExecutionContext
) {
const source = unsafeCast<string>(unsafeCast<TESString>(args[0]).value);
const parsedSource = parseECMACompliant(source);
const statements = parsedSource.body;
let currentEvaluationResult = tuple(Undefined, execContext);
for (const statement of statements.slice(0, statements.length - 1)) {
currentEvaluationResult = yield evaluate(
statement,
currentEvaluationResult[1]
);
}
const lastStatement = statements[statements.length - 1];
if (lastStatement.type === "ExpressionStatement") {
return evaluate(lastStatement.expression, currentEvaluationResult[1]);
}
return evaluate(lastStatement, currentEvaluationResult[1]);
});
|
a6904d3b50c7ad5afad10e7125897b7c683592f1 | TypeScript | razjel/dependency-injection-test | /src/common/actionFlow/action/process/AFLegacyBaseProcess.ts | 2.890625 | 3 | /*
* a
*/
/*
* a
*/
import {afProcess} from "../decorators/AFActionDecorators";
/**
* can be async or singular
*/
export class AFLegacyBaseProcess {
/** namespace */
public pbxLib = {
singular: false,
playbackBlocking: false,
// mark processes which might stop to work when we change how process return Promise
doesntUseAwait: false,
_promise: null,
_promiseResolve: null,
_promiseReject: null,
};
protected _isCanceled: boolean = false;
public get isCanceled(): boolean {
return this._isCanceled;
}
protected _isTerminated: boolean = false;
public get isTerminated(): boolean {
return this._isTerminated || this._isCanceled;
}
//---------------------------------------------------------------
//
// execute
//
//---------------------------------------------------------------
/**
* This function is only to show how it should look like.
* Here it does nothing and it doesn't need decorator, but any process extending this must
* specify it and apply decorator to it.
* Options should be declared only in static function decorator
*/
@afProcess("LegacyBaseProcess", {})
public static execute(...args) {
throw new Error(
"static execute function must be written in your process class " + "and must apply same decorator as here"
);
}
/**
* This function is only to show how it should look like.
* Here it does nothing and it doesn't need decorator, but any process extending this must
* specify it and apply decorator to it.
*/
@afProcess("LegacyBaseProcess")
public execute(...args) {
throw new Error(
"execute function must be overridden in your process class " +
"and it can't call this base `execute()` function"
);
}
//TODO razjel: change all usages to new ProcessClass
public static newInst(clazz): AFLegacyBaseProcess {
return new clazz() as AFLegacyBaseProcess;
}
//---------------------------------------------------------------
//
// finish async
//
//---------------------------------------------------------------
/**
* Only single argument can be returned from async/await call. If one need to pass more
* arguments she has to wrap it inside object or array.
* <code>
* ...
* Promise(function(resolve, reject) {
* ...
* resolve(arg1, arg2, arg3); //only first argument will be returned in await
* ...
* }
* ...
* var result = await fn(); //result will be equal to arg1
* </code>
* @param asyncResult
*/
public finish = (asyncResult?: any): void => {
this._end(asyncResult, this.pbxLib._promiseResolve);
};
public terminate = (): void => {
this._isTerminated = true;
this._end(null, this.pbxLib._promiseReject);
};
protected _end = (asyncResult: any, resultFunction: Function): void => {
if (resultFunction) resultFunction(asyncResult);
this.pbxLib._promise = null;
this.pbxLib._promiseResolve = null;
this.pbxLib._promiseReject = null;
};
//---------------------------------------------------------------
//
// cancel
//
//---------------------------------------------------------------
public cancel(): void {
this._isCanceled = true;
}
}
|
44aaa2bc2797cf85656c708cbf02a6810ef6bbde | TypeScript | Kabir-Sagi/Employee-Portal-App | /src/app/services/employee.service.ts | 2.578125 | 3 | import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {retry} from 'rxjs/operators';
import {Observable} from 'rxjs';
import {IEmployee} from '../IEmployee';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
constructor(private _httpClient:HttpClient) { }
// GET all employees
public getAllEmployees():Observable<IEmployee[]>{
let dataURL = 'http://127.0.0.1:3000/api/employees';
return this._httpClient.get<IEmployee[]>(dataURL).pipe(
retry(1)
);
}
// GET a single Employee
public getEmployee(employeeId):Observable<IEmployee>{
let dataURL = `http://127.0.0.1:3000/api/employees/${employeeId}`;
return this._httpClient.get<IEmployee>(dataURL).pipe(
retry(1)
);
}
// Create (POST) a new Employee
public addEmployee(employee:IEmployee){
let newEmployee = {
first_name : employee.first_name,
last_name : employee.last_name,
email : employee.email,
gender : employee.gender,
ip_address : employee.ip_address
};
let dataURL = 'http://127.0.0.1:3000/api/employees';
return this._httpClient.post<any>(dataURL,newEmployee).pipe(
retry(1)
);
}
// update an employee
public updateEmployee(employeeId,employee){
let dataURL = `http://127.0.0.1:3000/api/employees/${employeeId}`;
let updatedEmployee = {
first_name : employee.first_name,
last_name : employee.last_name,
email : employee.email,
gender : employee.gender,
ip_address : employee.ip_address
};
return this._httpClient.put<any>(dataURL,updatedEmployee).pipe(
retry(1)
);
}
// delete an Employee
public deleteEmployee(employeeId){
let dataURL = `http://127.0.0.1:3000/api/employees/${employeeId}`;
return this._httpClient.delete<any>(dataURL).pipe(
retry(1)
);
}
}
|
1596ddf8058b85bccdbe5b94eef432c2cb5c92da | TypeScript | meighan/slack-admin-tools | /admin_app_management-master/auth.ts | 2.609375 | 3 | import express = require('express');
import bodyParser = require('body-parser');
require('dotenv').config();
const authApp: express.Application = express();
authApp.use(bodyParser.json());
authApp.use(function (error: Error, req: any, res: any, next: any) {
if (error instanceof SyntaxError) {
res.send("Bad Payload");
} else {
next();
}
});
const port = 5000
authApp.get('/redirect/oauth', function (req, res) {
const client_id = process.env.SLACK_CLIENT_ID;
const client_secret = process.env.SLACK_CLIENT_SECRET;
const code = req.query.code;
const url = `https://slack.com/api/oauth.v2.access?code=${code}&client_id=${client_id}&client_secret=${client_secret}`
res.redirect(url);
});
authApp.get('/', function (req, res) {
res.send('Try adding a specific method to call');
});
authApp.listen(port, () => console.log(`Listening on port ${port} (/redirect/oauth)`)); |
acde968a718102f42c88da53778abbc3a912d59a | TypeScript | nadermedhet148/Nodejs-Streamers | /src/CopyFile.ts | 2.671875 | 3 | import {createReadStream , createWriteStream} from 'fs';
const readStream = createReadStream("logs" , {
});
const writeStream = createWriteStream("logs2");
// will send the
readStream.pipe(writeStream)
readStream.on("close", (e) => console.log("closed" , e));
readStream.on("drain", (e) => console.log("closed ", e));
readStream.on("finish", (e) => console.log("finish", e));
readStream.on("open", (e) => console.log("open", e));
readStream.on("pipe", (e) => console.log("pipe"));
readStream.on("data" , (data)=>{
console.log('data : ' ,data);
})
|
8ba92f32a2e4bec12e2064b97164946fb782807a | TypeScript | joyan828/ts-practice | /src/temp/practice.ts | 4.34375 | 4 | // basic types
let count: number = 0
count += 1
const done: boolean = true
const numbers: number[] = [1, 2, 3]
const messages: string[] = ['hello', 'world']
let mightBeUndefined: string | undefined = undefined
let nullableNumber : number | null = null
let color: 'red' | 'orange' | 'yellow' = 'red'
color = 'orange'
// function
function sumArray(numbers: number[]): number {
return numbers.reduce((acc, current) => acc + current, 1)
}
function returnNothing(): void {
console.log('return nothing!')
}
returnNothing()
// interface - class
interface Shape {
getArea(): Number
}
class Circle implements Shape {
constructor(public radius: number) {
this.radius = radius
}
getArea(){
return this.radius * this.radius * Math.PI
}
}
class Rectangle implements Shape {
constructor(private width: number, private height: number ) {
this.width = width
this.height = height
}
getArea() {
return this.width * this.height
}
}
const circle = new Circle(5)
const rectangle = new Rectangle(10, 5)
console.log(circle.radius)
const shapes: Shape[] = [new Circle(5), new Rectangle(10, 5)]
shapes.forEach(shape => {
console.log(shape.getArea())
})
// interface - object
interface Person {
name: string,
age?: number
}
interface Developer extends Person{
skills: string[]
}
const expert: Developer = {
name: 'saebom',
skills: ['javascript', 'react']
}
const people: Person[] = [expert, expert]
console.log(people)
// type alias
type _Developer = Person & {
skills: string[]
}
const person: Person = {
name: 'saebom'
}
const _expert: _Developer = {
name: 'joy',
skills : ['javascript', 'react']
}
type People = Person[]
const _people: People = [person, _expert]
console.log(_people)
type Color = 'red' | 'gray' | 'brown'
const _color: Color = 'red'
const colors: Color[] = ['red', 'brown']
// generics
function merge<A, B> (a: A, b: B): A & B {
return {
...a,
...b
}
}
const merged = merge({foo: 1}, 'string')
function wrap<T>(param: T) {
return {
param
}
}
const wrapped = wrap('10')
// generics in interface
interface Items<T>{
list: T[]
}
const items: Items<string> = {
list: ['1', '2', '3']
}
// generics in type
type Strings<T> = {
list: T[]
}
const strings: Strings<string> = {
list: ['1', '2', '3']
}
// generics in class
class Queue<T> {
list: T[] = []
get length() {
return this.list.length
}
enqueue(item: T) {
this.list.push(item)
}
dequeue() {
return this.list.shift()
}
}
const queue = new Queue<number>()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
console.log(queue.dequeue())
console.log(queue.dequeue())
console.log(queue.dequeue())
console.log(queue.dequeue()) //undefined |
dbaa19105ddcc4c41a53ae1f71dea959cbcde81c | TypeScript | tanshio/amplify-sns-to-slack | /src/lambda/amplify/index.ts | 2.765625 | 3 | import axios from 'axios'
const PREFIX = `Your build status is `
const STATUSES = ['STARTED', 'SUCCEED', 'FAILED'] as const
type StatusType = typeof STATUSES[number]
type messageType = {
[k in StatusType]: any
}
const createSlackMessage = (msg: string): any => {
return [
{
type: 'section',
text: {
type: 'mrkdwn',
text: msg,
},
},
]
}
const slackMessages: messageType = {
STARTED: `🚀 *デプロイが開始されました*`,
SUCCEED: `🤩 *デプロイに成功しました*`,
FAILED: `🤬 *デプロイに失敗しました*`,
}
export async function handler(event: any) {
const message = event.Records[0]['Sns']['Message']
const status =
STATUSES.find((s) => {
return `${message}`.includes(`${PREFIX}${s}`)
}) || 'FAILED'
await axios.post(process.env.SLACK_WEBHOOK_URL || '', {
text: slackMessages[status],
// Block Kit Builderを参考にする https://api.slack.com/tools/block-kit-builder
blocks: createSlackMessage(slackMessages[status]),
})
return
}
|
a8a2f8ba906268280f987237477bebea9063ff98 | TypeScript | jeromeraffin/blackjack | /src/core/services/api.ts | 2.859375 | 3 | import axios, { AxiosResponse } from 'axios';
import Deck from '../types/Deck';
import Card from '../types/Card';
// setup the base API URL
axios.defaults.baseURL = 'https://deckofcardsapi.com/api/';
export async function getNewDeck(): Promise<Deck> {
const response: AxiosResponse<Deck> = await axios.get(
'deck/new/shuffle/?deck_count=6'
);
return response.data;
}
export async function getNewCard(deckId: string): Promise<Card> {
const response: AxiosResponse<{ cards: Card[] }> = await axios.get(
`deck/${deckId}/draw/?count=1`
);
return response.data.cards[0];
}
|
e2be6860442e8770643d943c93638520ed4a31e5 | TypeScript | conventional-changelog/commitlint | /@commitlint/load/src/utils/load-parser-opts.ts | 2.71875 | 3 | import {ParserPreset} from '@commitlint/types';
type Awaitable<T> = T | PromiseLike<T>;
function isObjectLike(obj: unknown): obj is Record<string, unknown> {
return Boolean(obj) && typeof obj === 'object'; // typeof null === 'object'
}
function isParserOptsFunction<T extends ParserPreset>(
obj: T
): obj is T & {
parserOpts: (
cb: (_: never, parserOpts: Record<string, unknown>) => unknown
) => Record<string, unknown> | undefined;
} {
return typeof obj.parserOpts === 'function';
}
export async function loadParserOpts(
pendingParser:
| string
| Awaitable<ParserPreset>
| (() => Awaitable<ParserPreset>)
| undefined
): Promise<ParserPreset | undefined> {
if (typeof pendingParser === 'function') {
return loadParserOpts(pendingParser());
}
if (!pendingParser || typeof pendingParser !== 'object') {
return undefined;
}
// Await for the module, loaded with require
const parser = await pendingParser;
// exit early, no opts to resolve
if (!parser.parserOpts) {
return parser;
}
// Pull nested parserOpts, might happen if overwritten with a module in main config
if (typeof parser.parserOpts === 'object') {
// Await parser opts if applicable
parser.parserOpts = await parser.parserOpts;
if (
isObjectLike(parser.parserOpts) &&
isObjectLike(parser.parserOpts.parserOpts)
) {
parser.parserOpts = parser.parserOpts.parserOpts;
}
return parser;
}
// Create parser opts from factory
if (
isParserOptsFunction(parser) &&
typeof parser.name === 'string' &&
parser.name.startsWith('conventional-changelog-')
) {
return new Promise((resolve) => {
const result = parser.parserOpts((_: never, opts) => {
resolve({
...parser,
parserOpts: opts?.parserOpts,
});
});
// If result has data or a promise, the parser doesn't support factory-init
// due to https://github.com/nodejs/promises-debugging/issues/16 it just quits, so let's use this fallback
if (result) {
Promise.resolve(result).then((opts) => {
resolve({
...parser,
parserOpts: opts?.parserOpts,
});
});
}
return;
});
}
return parser;
}
|
5583afa051a70b52536c35bfe9799cef1e8baa1d | TypeScript | nishantnaithani97/TypeScript_Node | /test/routes/userLogin.test.ts | 2.78125 | 3 | /**
* USER LOGIN TEST FILE
* This file contains the test cases for testing the user"s login function.
*/
require("../../src/database");
import request from "supertest";
import Users from "../../src/models/Users";
import app from "../../src/app";
import Register from "../fixtures/register";
import Login from "../fixtures/login";
import { expect } from "chai";
// TEST CASE FOR SUCCESSFULLY LOGIN USER WITH PROVIDING ALL THE REQUIRED DATA.
describe("Inserting user for performing login operations (SUCCESS CASE)", () => {
describe("/api/user/login", () => {
describe("Success case", () => {
beforeAll(async (done) => {
await Users.remove({});
const user = new Users(Register.testData);
// console.log(user);
await user.save();
done();
});
// Test Case for login the user with the required details.
it("Successfuly login of a user", (done) => {
const user: object = Login.properData;
return request(app)
.get("/api/user/login")
.set(user)
.expect(200)
.then((res) => {
console.log("------30------", res.body);
expect(res.body.status).to.equal("success");
done();
});
});
});
// TEST CASES FOR NOT LOGIN USER DUE TO SOME ERRORS OR BY NOT PROVIDING ALL THE REQUIRED DETAILS.
describe("Error Case", () => {
// Test Case for login the user with the wrong email.
it("Error in login of a user (WRONG EMAIL)", (done) => {
const user = Login.userNotFound;
request(app)
.get("/api/user/login")
.set(user)
.then((res) => {
console.log("------30------", res.body);
expect(res.body.status).to.equal("error");
done();
});
});
// Test Case for login the user with the wrong password.
it("Error in login of a user (WRONG PASSWORD)", (done) => {
const user = Login.wrongPassword;
request(app)
.get("/api/user/login")
.set(user)
.then((res) => {
console.log("------30------", res.body);
expect(res.body.status).to.equal("error");
done();
});
});
// Test Case for login the user without any data.
it("Error in login of a user (WITHOUT ANY DATA)", (done) => {
const user = Login.withoutData;
request(app)
.get("/api/user/login")
.set(user)
.then((res) => {
console.log("------30------", res.body);
expect(res.body.status).to.equal("error");
done();
});
});
// Test Case for login the user without email.
it("Error in login of a user (WITHOUT EMAIL)", (done) => {
const user = Login.withoutEmail;
request(app)
.get("/api/user/login")
.set(user)
.then((res) => {
console.log("------30------", res.body);
expect(res.body.status).to.equal("error");
done();
});
});
// Test Case for login the user without password.
it("Error in login of a user (WITHOUT PASSWORD)", (done) => {
const user = Login.withoutPassword;
request(app)
.get("/api/user/login")
.set(user)
.then((res) => {
console.log("------30------", res.body);
expect(res.body.status).to.equal("error");
done();
});
});
});
});
});
|
e7d8adc101ec9abfad6caf8ce6f8928d2999f939 | TypeScript | murtekbey/ReCapProject-SPA | /src/app/store/auth/auth.reducer.ts | 2.546875 | 3 | import { createReducer, on } from '@ngrx/store';
import { setUserDetail, deleteUserDetail } from './auth.actions';
import { UserDetailDto } from '../../models/dtos/userDetailDto';
export interface AuthState {
userDetailDto?: UserDetailDto;
}
const initialAuthState: AuthState = {
userDetailDto: undefined,
};
export const AuthReducer = createReducer(
initialAuthState,
on(setUserDetail, (state: AuthState, { userDetailDto }) => ({
...state,
userDetailDto: userDetailDto,
})),
on(deleteUserDetail, (state: AuthState) => ({
...state,
userDetailDto: undefined,
}))
);
|
867fd06d32205aca297a40ccc2199d17eaaf0f59 | TypeScript | JamesNikolaidis/e-Cinema | /eCinemaApplication/src/app/objects/userComments.object.ts | 3.125 | 3 | export class UserComments{
private userName:string;
private message:string;
constructor(userName:string,message:string){
this.userName = userName;
this.message=message;
}
public setUserName(userName:string):void{
this.userName= userName
}
public setMessage(message:string):void{
this.message= message;
}
public getUserName():string{
return this.userName;
}
public getMessage():string{
return this.message;
}
} |
4ce257e22f0d34794216942749656623d531b029 | TypeScript | zhouhoujun/type-task | /packages/core/src/activities/Dependence.ts | 2.5625 | 3 | import { IActivity, InjectAcitityToken, DependenceConfigure, Activity } from '../core';
import { Registration, Type } from '@ts-ioc/core';
import { Task } from '../decorators';
import { ControlActivity } from './ControlActivity';
/**
* dependence activity inject token.
*
* @export
* @class InjectDependenceActivity
* @extends {Registration<T>}
* @template T
*/
export class InjectDependenceActivity<T extends IActivity> extends Registration<T> {
constructor(type: Type<T>) {
super(type, 'DependenceActivity');
}
}
/**
* Dependence activity token.
*/
export const DependenceActivityToken = new InjectAcitityToken<DependenceActivity>('dependence');
/**
* dependence activity.
*
* @export
* @class DependenceActivity
* @extends {ControlActivity}
*/
@Task(DependenceActivityToken)
export class DependenceActivity extends ControlActivity {
/**
* custom dependence
*
* @type {IActivity}
* @memberof DependenceActivity
*/
dependence: IActivity;
/**
* body
*
* @type {IActivity}
* @memberof DependenceActivity
*/
body: IActivity;
async onActivityInit(config: DependenceConfigure): Promise<any> {
await super.onActivityInit(config);
this.dependence = await this.buildActivity(config.dependence);
this.body = await this.buildActivity(config.body);
}
/**
* execute body.
*
* @protected
* @memberof DependenceActivity
*/
protected async execute() {
if (this.dependence) {
await this.dependence.run(this.getContext());
}
await this.body.run(this.getContext());
}
}
|
6381f53692219cdaee3d0b23de521f4b69472135 | TypeScript | langzitc/fastweb | /web/src/core/util.ts | 2.765625 | 3 | export function findTarget(data: any, action: string): any {
let target = null;
if(Array.isArray(data)) {
for(let i = 0; i < data.length; i ++) {
if(data[i].action === action) {
target = data[i];
}else if(data[i].options) {
target = findTarget(data[i].options, action);
}
if(target) {
break;
}
}
}else{
for(let key in data) {
target = findTarget(data[key], action);
if(target) {
break;
}
}
}
return target;
}
export function fullScreen(element: any = document.documentElement) {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen();
}
}
export function exitFullScreen() {
const element: any = document;
if (element.exitFullscreen) {
element.exitFullscreen();
} else if (element.msExitFullscreen) {
element.msExitFullscreen();
} else if (element.mozCancelFullScreen) {
element.mozCancelFullScreen();
} else if (element.webkitExitFullscreen) {
element.webkitExitFullscreen();
}
} |
65e21b9b7d8f7418d6d1f5fd1615232aa9714cc4 | TypeScript | onyettr/c-stack | /stack_check.ts | 3.328125 | 3 | #include <stdio.h>
#include "stack.h"
#test create_negative
Stack_t *sp;
printf("create_negative\n");
sp = StackCreate(-1);
fail_unless(sp == NULL, "negative create failed");
#test create_positive
Stack_t *sp;
printf("create_positive\n");
sp = StackCreate(5);
fail_unless(sp != NULL, "positive create failed");
#test push_negative_no_stack
Stack_t *sp = (Stack_t*)NULL;
printf("push_negative_no_stack\n");
fail_unless(push(sp,101) == -1, "push no stack failed");
#test push_positive_with_stack
Stack_t *sp = (Stack_t*)NULL;
printf("push_positive_no_stack\n");
sp = StackCreate(4);
fail_unless(push(sp,101) == 0, "push with stack failed");
#test push_positive_with_stack_beyond_limit
Stack_t *sp = (Stack_t*)NULL;
printf("push_positive_with_stack_beyond_limit\n");
sp = StackCreate(2);
fail_unless(push(sp,101) == 0, "push fail");
fail_unless(push(sp,102) == 0, "push fail");
fail_unless(push(sp,103) == -1, "push beyond limit");
#test pop_negative_no_stack
Stack_t *sp = (Stack_t*)NULL;
// push(sp, 101);
fail_unless(pop(sp) == -1, "pop no stack failed");
#test pop_negative_with_stack_no_push
Stack_t *sp = (Stack_t*)NULL;
fail_unless(pop(sp) == -1, "pop no pushes failed");
#test pop_positive_with_stack
Stack_t *sp;
sp = StackCreate(5);
push(sp, 101);
fail_unless(pop(sp) == 101, "pop failed");
#test top_positive_with_stack
Stack_t *sp;
sp = StackCreate(5);
push(sp, 101);
fail_unless(top(sp) != -1, "top with stack failed");
#test top_negative_null_stack
Stack_t *sp = NULL;
sp = StackCreate(5);
fail_unless(top(sp) == -1, "top with empty stack failed");
#test top_negative_empty_stack
Stack_t *sp = NULL;
fail_unless(top(sp) == -1, "top with no stack failed");
#test empty_postive__not_empty_stack
Stack_t *sp = NULL;
sp = StackCreate(5);
(void)push(sp,400);
(void)push(sp,500);
(void)push(sp,600);
(void)push(sp,700);
fail_unless(empty(sp) == 0, "empty with not empty stack");
#test empty_negatve_empty_stack
Stack_t *sp = NULL;
sp = StackCreate(5);
fail_unless(empty(sp) == 1, "empty with empty stack");
#test destroy_stack_no_stack
Stack_t *sp = NULL;
fail_unless(StackDestroy(sp) == -1, "Destroy failed, no stack created");
|
11cca2b0b603999da519003bfcf11e4b5c5ac8f4 | TypeScript | adaapp-sd3/advanced-programming-2-jade-genevieve | /src/models/crops/Bean.ts | 2.96875 | 3 | import Crop from "../abstract/Crop"
import Farm from "../Farm";
import Farmer from "../Farmer";
class Bean extends Crop {
name: string = "Bean"
genus: string = "Legume"
imgUrl: string = "/img/twtr/1f331.png"
eats: string = "water"
thirst: number = 5
farm: Farm
farmer!: Farmer
constructor(farm: Farm) {
super()
this.farm = farm
}
// if not watered, reduce crop total
dieWhenDry() {
if ( this.thirst === 0 ) {
}
}
// if plant is thirsty, yield less beans
yieldBeans(): number {
return this.thirst > 0 ? 100 / this.thirst : 300
}
drinkWater() {
if (this.thirst <= 5 && this.thirst !== 0) {
if (this.farmer.temp > 1.0) {
this.thirst = this.thirst - 1
}
}
}
public preload() {
this.p5Img = this.p5.loadImage(this.imgUrl)
//console.log(this.p5Img)
}
public draw(): any {
this.constrainItem()
this.doSomethingOccasionally(() => this.drinkWater())
this.stopForFarmer()
}
}
export default Bean
|
f3b12ad701017c7c232c4159a607b4ddcd41a433 | TypeScript | PoorlyDefinedBehaviour/discord-clone-backend | /src/chat/Chat.ts | 2.984375 | 3 | import Observer from "../interfaces/Observer";
import Observable from "../interfaces/Observable";
type Dictionary<T> = {
[key: string]: T;
};
export default class Chat implements Observable {
private observers: Dictionary<Set<Observer>> = {};
public subscribe(server_id: string, observer: Observer): void {
if (!this.observers[server_id]) {
this.observers[server_id] = new Set<Observer>();
}
this.observers[server_id].add(observer);
}
public unsubscribe(server_id: string, observer: Observer): void {
if (this.observers[server_id]) {
this.observers[server_id].delete(observer);
}
}
public notify(server_id: string, data): void {
if (this.observers[server_id]) {
this.observers[server_id].forEach((observer) => observer.notify(data));
}
}
public send(data): void {
this.notify(data.message.server_id, data);
}
}
|
cc127cf19fcd81ed5e64f775ef1d1310d5461b8b | TypeScript | developeramarish/Financial-Planner-Forecast-Ledger | /FPFL-UI/src/app/core/services/common/general-util.service.ts | 2.890625 | 3 | import { Injectable } from '@angular/core';
import { IClaims } from '../../model/claims';
/**
* General Application Utilities: Creates a singleton Service that provides
* or createss the Local Storage Claims object or the user OID contained within
*/
@Injectable({
providedIn: 'root'
})
export class GeneralUtilService {
private claims!: IClaims;
/**
* Will create and provide or if already set will provide the Claims object
* in Local Storage
* @param {any} token The result from logging in
* @returns {IClaims}
*/
setClaims(token: any): IClaims {
if (this.claims === undefined) {
this.claims = JSON.parse(JSON.stringify(token.idTokenClaims || '{}')) as IClaims;
localStorage.setItem('claims', JSON.stringify(this.claims));
}
return this.claims;
}
/**
* Returns Claims and if not there will go get it from the Local Storage
* in Local Storage
* @param {any} token The result from logging in
* @returns {IClaims}
*/
getClaims(): IClaims {
if (this.claims !== undefined) {
return this.claims;
}
this.claims = JSON.parse(localStorage.getItem('claims') || '{}') as IClaims;
return this.claims;
}
/**
* Gets the User's OID Guid for use in CRUD operations
* @returns {string} User's OID
*/
getUserOid(): string {
if (this.claims !== undefined && this.claims.oid !== undefined) {
return this.claims.oid?.toString() || '';
}
this.claims = JSON.parse(localStorage.getItem('claims') || '{}') as IClaims;
return this.claims.oid?.toString() || '';
}
}
|
0bbe3ac044d91faeea39c90b56a8bf56652bb081 | TypeScript | Vbitz/globalgamejam2018 | /oldGame/src/Building.ts | 2.78125 | 3 | import * as THREE from 'three';
import {LoadedMesh} from './common';
export enum BuildingHoverState {
Deselected,
Hovered,
Selected,
}
const modelData = JSON.parse(
require('fs').readFileSync(__dirname + '/../res/building.json', 'utf8'));
export class Building extends THREE.Mesh {
material: THREE.MeshPhongMaterial[];
state: BuildingHoverState;
static mesh: LoadedMesh|null = null;
private connected: boolean;
constructor(floors: number) {
if (!Building.mesh) {
Building.loadMesh();
}
super(
Building.mesh.geometry.clone(),
Building.mesh.materials.map((mat) => mat.clone()));
this.scale.set(0.5, 0.5, 0.5);
this.position.setY(-(floors));
this.state = BuildingHoverState.Deselected;
this.connected = Math.random() > 0.25;
this.updateColor();
}
changeState(newState: BuildingHoverState) {
this.state = newState;
this.updateColor();
}
getBuildingId(): string {
return `{${12}-${1234}-${13}}`;
}
getBuildingConnected(): boolean {
return this.connected;
}
getBuildingBandwidth(): string {
return '0 kbps';
}
private static loadMesh() {
const modelLoader = new THREE.JSONLoader();
const model = modelLoader.parse(modelData);
Building.mesh = model;
}
private updateColor() {
if (this.state === BuildingHoverState.Selected) {
this.material[1].color.setHex(0xabfe2d);
} else if (this.state === BuildingHoverState.Hovered) {
this.material[1].color.setHex(0x808080);
} else if (this.state === BuildingHoverState.Deselected) {
this.material[1].color.setHex(0x575757);
}
if (this.getBuildingConnected()) {
this.material[2].color.setHex(0x10ea10);
} else {
this.material[2].color.setHex(0xea1010);
}
const buildingActivityLevels = [0x808080, 0x808080, 0x808080];
const activityLevel = Math.floor(Math.random() * 3) + 1;
for (let i = 0; i < 3; i++) {
if (activityLevel > i) {
this.material[3 + i].color.setHex(buildingActivityLevels[i]);
} else {
this.material[3 + i].color.setHex(0x404040);
}
}
}
} |
7a4cb80db82022e25b91b7dd9021cb2c2a2a0e64 | TypeScript | green-fox-academy/danielTiringer-todo-app | /main.ts | 2.71875 | 3 | 'use strict'
const fs = require('fs');
import { listFunctions } from './taskClasses';
import { taskList } from './taskClasses';
// let fileContent = 'I can write';
// fs.writeFileSync('message.txt', fileContent);
let args: string[] = process.argv;
let danielsToDoList = new taskList;
let mainProcess = () => {
if (!args[2]) {
listFunctions.listArguments();
} else if (args[2] == '-l') {
danielsToDoList.printAllTasks();
} else if (args[2] == '-a') {
danielsToDoList.addTaskToTheList(args[3]);
danielsToDoList.getTaskList();
} else if (args[2] == '-r') {
danielsToDoList.removeTaskFromTheList(args[3]);
danielsToDoList.getTaskList();
} else if (args[2] == '-c') {
danielsToDoList.completeTask(args[3]);
danielsToDoList.getTaskList();
}
}
mainProcess();
|
682a2c6f9aa2320f50d3eb2d398fe37988cfc6ec | TypeScript | dgp1130/bxpb | /packages/protoc-plugin/src/generators/services.ts | 2.640625 | 3 | import * as path from 'path';
import { FileDescriptorProto } from 'google-protobuf/google/protobuf/descriptor_pb';
import { CodeGeneratorResponse } from 'google-protobuf/google/protobuf/compiler/plugin_pb';
/**
* Returns an iterable of generated BXPB services from the given *.proto file and its descriptor.
*/
export function* generateServiceFiles(file: string, fileDescriptor: FileDescriptorProto):
Iterable<CodeGeneratorResponse.File> {
// If there are no services, don't generate anything.
if (fileDescriptor.getServiceList().length === 0) return;
const filePath = path.parse(file);
const generatedBaseName = `${filePath.name}_bxservices`;
// Generate JavaScript file.
const jsFile = new CodeGeneratorResponse.File();
jsFile.setName(path.format({
...filePath,
base: undefined, // Must not specify base for name and ext to be used.
name: generatedBaseName,
ext: '.js',
}));
jsFile.setContent(generateServiceJs(filePath, fileDescriptor));
yield jsFile;
// Generate TypeScript definitions.
const dtsFile = new CodeGeneratorResponse.File();
dtsFile.setName(path.format({
...filePath,
base: undefined, // Must not specify base for name and ext to be used.
name: generatedBaseName,
ext: '.d.ts',
}));
dtsFile.setContent(generateServiceDts(filePath, fileDescriptor));
yield dtsFile;
}
/** Returns the generated JavaScript source as a string. */
function generateServiceJs(filePath: path.ParsedPath, descriptor: FileDescriptorProto): string {
const serviceNames = descriptor.getServiceList().map((service) => {
const name = service.getName();
if (!name) throw new Error(`${path.format(filePath)}: Service has no name.`);
return name;
});
return `
/** @fileoverview Service code for implementing services defined in ${path.format(filePath)}. */
import { internalOnlyDoNotDependOrElse as internal } from '@bxpb/runtime';
import * as descriptors from './${filePath.name}_bxdescriptors.js';
${serviceNames.map((serviceName) => `
/**
* Run {@link ${serviceName}Service} on the given transport endpoint, using the provided
* implementation for each RPC method.
*/
export function serve${serviceName}(transport, serviceImpl) {
internal.serve(transport, descriptors.${serviceName}Service, serviceImpl);
}
`.trim()).join('\n\n')}
`.trim();
}
/** Returns the generated TypeScript definitions as a string. */
function generateServiceDts(filePath: path.ParsedPath, descriptor: FileDescriptorProto): string {
const serviceNames = descriptor.getServiceList().map((service) => {
const name = service.getName();
if (!name) throw new Error(`${path.format(filePath)}: Service has no name.`);
return name;
});
return `
/** @fileoverview Service code for implementing services defined in ${path.format(filePath)}. */
import { internalOnlyDoNotDependOrElse as internal } from '@bxpb/runtime';
import * as descriptors from './${filePath.name}_bxdescriptors';
${serviceNames.map((serviceName) => `
/**
* Run {@link ${serviceName}Service} on the given transport endpoint, using the provided
* implementation for each RPC method.
*/
export function serve${serviceName}(transport: internal.Transport, serviceImpl: internal.ServiceImplementation<descriptors.I${serviceName}Service>);
`.trim()).join('\n\n')}
`.trim();
} |
0e2ffcf98af9a8a85c831a26f69c329790124a5b | TypeScript | amoskim71/roadside-app | /server/src/user/entity/user.entity.ts | 2.515625 | 3 | import { Entity, PrimaryGeneratedColumn, Column, OneToOne } from 'typeorm';
import { UserRole } from '../user-role.interface';
import { Customer } from './customer.entity';
import { Professional } from './professional.entity';
@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true })
email: string;
@Column()
passwordHash: string;
@Column({ enum: UserRole })
role: UserRole;
@OneToOne(type => Customer, customer => customer.user, {
nullable: true,
})
customerInfo?: Customer;
@OneToOne(type => Professional, professional => professional.user, {
nullable: true,
})
professionalInfo?: Professional;
@Column({ type: 'boolean', default: false })
banned: boolean;
}
|
fdf35c3b1fee34d6bf0c6bd2b56b7e5fc5896280 | TypeScript | kschuetz/calculator | /src/display/stack/models.ts | 3.578125 | 4 | import * as Immutable from 'immutable';
export interface Entry {
readonly lineCount: number;
lines(index: number): string;
}
class SimpleEntry implements Entry {
readonly text: string;
constructor(text: string) {
this.text = text;
}
get lineCount(): number {
return 1;
};
lines(index: number): string {
return this.text;
}
static default: SimpleEntry = new SimpleEntry('');
}
class MultiLineEntry implements Entry {
readonly text: Immutable.List<string>;
constructor(lines?: string[] | Immutable.List<string>) {
this.text = Immutable.List(lines || []);
}
get lineCount(): number {
return this.text.size;
}
lines(index: number): string {
return this.text.get(index) || "";
}
}
export class StackDisplayModel {
readonly entries: Immutable.Stack<Entry>;
constructor(entries?: Entry[] | Immutable.List<Entry> | Immutable.Stack<Entry>) {
this.entries = Immutable.Stack(entries || []);
}
modify(f: (prev: Immutable.Stack<Entry>) => Immutable.Stack<Entry>): StackDisplayModel {
return new StackDisplayModel(f(this.entries));
}
push(entry: Entry): StackDisplayModel {
return this.modify(entries => entries.push(entry));
}
}
export function createEntry(lines?: string | string[] | Immutable.List<string>): Entry {
if(!lines) {
return SimpleEntry.default;
} else if(typeof lines === 'string') {
return new SimpleEntry(lines);
} else if (Array.isArray(lines)) {
if(lines.length === 0) {
return SimpleEntry.default;
} else if(lines.length === 1) {
return createEntry(lines[0]);
} else {
return new MultiLineEntry(lines);
}
} else {
if(lines.size === 0) {
return SimpleEntry.default;
} else if(lines.size === 1) {
return createEntry(lines.get(0));
} else {
return new MultiLineEntry(lines);
}
}
}
|
febdab58b1f1cdbe2b2510f533a7ac000ecccebe | TypeScript | gainamit/FirstRepo | /pre-requisites/02-typescript-basics/after/03-interface-05-implementing-interfaces-in-classes.ts | 3.78125 | 4 | /**
* One or more interfaces can be implemented by a class - the class's properties and methods then have to implement the properties and methods in the interfaces
*/
(function() {
interface IncreaseLifespan {
( incr: number ) : void
}
interface IBreed {
name: string;
averageLifespan: number;
readonly placeOfOrigin?: string;
increaseLifespan: IncreaseLifespan;
}
interface ICorgiBreed extends IBreed {
// In TypeScript, a set of number literals can also be specified in place of type
energyLevel: 1 | 2 | 3 | 4 | 5;
}
interface IStats {
height: number; /* in pounds */
weight: number; /* in feet */
}
// CorgiBreed class has to include all properties from ICorgiBreed and IStats
// Additionally the methods declared in the interfaces need to be implemented
class CorgiBreed implements ICorgiBreed, IStats {
name: string;
// the data type need not be repeated. If repeated it must be same as in interface
averageLifespan;
// readonly placeOfOrigin?: string; // optional property need not be implemented
energyLevel; // takes on interface specified number values in the range 1 - 5
height: number;
weight: number;
constructor( name: string, averageLifespan: number, energyLevel: number, height: number, weight: number ) {
this.name = name;
this.averageLifespan = averageLifespan;
this.energyLevel = energyLevel;
this.height = height;
this.weight = weight;
}
increaseLifespan( incr: number ) {
this.averageLifespan += incr;
};
}
let pembrokeWelsh = new CorgiBreed( 'Pembroke Welsh Corgi', 13, 4, 1, 25 );
pembrokeWelsh.increaseLifespan( 0.5 );
let cardiganWelsh = new CorgiBreed( 'Cardigan Welsh Corgi', 14, 3, 1, 31.5 );
cardiganWelsh.increaseLifespan( 0.25 );
}()); |
4547ac31f1d7afe050ced578055c800c24d51e25 | TypeScript | HevertonOGS/gazin-test | /backend/src/modules/developers/repositories/fakes/FakeDevelopersRepository.ts | 2.796875 | 3 | import { v4 as uuid } from 'uuid';
import IDevelopersRepository from '@modules/developers/repositories/IDevelopersRepository';
import ICreateDeveloperDTO from '@modules/developers/dtos/ICreateDeveloperDTO';
import Developer from '../../infra/typeorm/entities/Developer';
class FakeDevelopersRepository implements IDevelopersRepository {
private developers: Developer[] = [];
public async findById(id: string): Promise<Developer | undefined> {
const findDeveloper = this.developers.find(developer => developer.id === id);
return findDeveloper;
}
public async find(): Promise<Developer[] | undefined> {
return this.developers;
}
public async create(developerData: ICreateDeveloperDTO): Promise<Developer> {
const developer = new Developer();
Object.assign(developer, { id: uuid() }, developerData);
this.developers.push(developer);
return developer;
}
public async save(developer: Developer): Promise<Developer> {
const findIndex = this.developers.findIndex(findDeveloper => findDeveloper.id === developer.id);
this.developers[findIndex] = developer;
return developer;
}
public async delete(id: string): Promise<Developer> {
const findIndex = this.developers.findIndex(findDeveloper => findDeveloper.id === id);
const developer = this.developers[findIndex];
this.developers.splice(findIndex, 1);
return developer;
}
}
export default FakeDevelopersRepository;
|
c24f6ab973273bfb5fa9ba8e0d145a254739a587 | TypeScript | AkiaCode/saidbysoloisbaka | /commands/saebasol.ts | 2.578125 | 3 | import { Command, CommandContext, GuildTextChannel, Embed } from "../deps.ts"
import { Rest } from "../packages/doujinshiman/models/rest.ts"
export class SaebasolCommand extends Command {
name = 'saebsol'
aliases = ['sbl']
async execute(ctx: CommandContext) {
if (ctx.args[0] === undefined) return ctx.channel.send('Saebasol의 `private api`를 활용하였습니다.')
switch (ctx.args[0]) {
case "번호":
const num = await new Rest().getInfo(Number(ctx.args[1]))
const embed = new Embed()
if (num === undefined){
ctx.channel.send('None')
break
}
embed.addField('galleryid', num.galleryid)
if (num.characters === []) {
embed.addField('characters', 'None')
} else {
num.characters.forEach(async (e) => {
embed.addField('characters', e.value)
})
}
if (num.title.value === undefined) {
embed.addField('title', 'None')
} else {
embed.addField('title', num.title.value)
}
if (num.artist === []) {
embed.addField('artists', 'None')
} else {
num.artist.forEach( async (e) => {
embed.addField('artists', e.value)
})
}
if (num.group === []) {
embed.addField('group', 'None')
} else {
num.group.forEach( async (e) => {
embed.addField('group', e.value)
})
}
if (num.language.value === undefined) {
embed.addField('language', 'None')
} else {
embed.addField('language', num.language.value)
}
if (num.series.length === 0) {
embed.addField('series', 'None')
} else {
num.series.forEach( async (e) => {
embed.addField('series', e.value)
})
}
if (num.tags.length === 0) {
embed.addField('tags', 'None')
} else {
let d: string[] = []
num.tags.forEach( async (e) => d.push(e.value))
embed.addField('tags', d.join(', '))
}
if (num.type.value === undefined) {
embed.addField('type', 'None')
} else {
embed.addField('type', num.type.value)
}
await ctx.channel.send(embed)
break
case 'list':
if ((ctx.channel as GuildTextChannel).nsfw) {
if (ctx.args[1] === '랜덤'){
const num = await new Rest().getIndex()
if (num !== undefined) {
const random = Math.floor(Math.random() * num.length) + 1
const images = await new Rest().getImages(Number(random))
if (images?.images !== undefined) images?.images.forEach(e => { ctx.channel.send(e.url) })
}
} else {
const images = await new Rest().getImages(Number(ctx.args[1]))
if (images?.images !== undefined) images?.images.forEach(e => { ctx.channel.send(e.url) })
}
}
break
default:
ctx.channel.send('다시 입력하세요')
}
}
}
|
137cb23afe074c964271686c92ffed9200ca87db | TypeScript | ana-ya/ionic | /src/util/dom-controller.ts | 2.921875 | 3 | /**
* Adopted from FastDom
* https://github.com/wilsonpage/fastdom
* MIT License
*/
import { nativeRaf } from './dom';
import { removeArrayItem } from './util';
export type DomCallback = { (timeStamp: number) };
export class DomDebouncer {
private writeTask: Function = null;
private readTask: Function = null;
constructor(private dom: DomController) { }
read(fn: DomCallback): Function {
if (this.readTask) {
return;
}
return this.readTask = this.dom.read((t) => {
this.readTask = null;
fn(t);
});
}
write(fn: DomCallback, ctx?: any): Function {
if (this.writeTask) {
return;
}
return this.writeTask = this.dom.write((t) => {
this.writeTask = null;
fn(t);
});
}
cancel() {
const writeTask = this.writeTask;
writeTask && this.dom.cancelW(writeTask);
this.writeTask = null;
const readTask = this.readTask;
readTask && this.dom.cancelR(readTask);
this.readTask = null;
}
}
export class DomController {
private r: Function[] = [];
private w: Function[] = [];
private q: boolean;
debouncer(): DomDebouncer {
return new DomDebouncer(this);
}
read(fn: DomCallback, ctx?: any): Function {
const task = !ctx ? fn : fn.bind(ctx);
this.r.push(task);
this.queue();
return task;
}
write(fn: DomCallback, ctx?: any): Function {
const task = !ctx ? fn : fn.bind(ctx);
this.w.push(task);
this.queue();
return task;
}
cancel(task: any): boolean {
return removeArrayItem(this.r, task) || removeArrayItem(this.w, task);
}
cancelW(task: any): boolean {
return removeArrayItem(this.w, task);
}
cancelR(task: any): boolean {
return removeArrayItem(this.r, task);
}
protected queue() {
const self = this;
if (!self.q) {
self.q = true;
nativeRaf(function rafCallback(timeStamp) {
self.flush(timeStamp);
});
}
}
protected flush(timeStamp: number) {
try {
this.dispatch(timeStamp);
} finally {
this.q = false;
}
}
private dispatch(timeStamp: number) {
let i: number;
const r = this.r;
const rLen = r.length;
const w = this.w;
const wLen = w.length;
// ******** DOM READS ****************
for (i = 0; i < rLen; i++) {
r[i](timeStamp);
}
// ******** DOM WRITES ****************
for (i = 0; i < wLen; i++) {
w[i](timeStamp);
}
r.length = 0;
w.length = 0;
}
}
|
8668f1456111ff86047531c897672dd0674504f5 | TypeScript | ghidoz/item-manager | /src/app/shared/wishlist/wishlist.service.ts | 2.640625 | 3 | import { Injectable } from '@angular/core';
import { Item } from '../item';
@Injectable()
export class WishlistService {
wishlist: Item[] = [];
constructor() { }
add(item: Item){
this.wishlist.push(item);
}
remove(id: number){
this.wishlist = _.reject(<any>this.wishlist, (item: any) => item.id === id);
}
isAdded(id: number){
return typeof _.findWhere(this.wishlist, {id: id}) !== 'undefined';
}
filterByTitle(title: string){
return _.filter(this.wishlist, (item) => {
return item.title.toLowerCase().indexOf(title) !== -1;
});
}
} |
39aed2733249f367ca1a79edf6da0d1b0f0e88ea | TypeScript | bth1994/CR-MacroLabs-TypeScript-Casino | /Casino/BlackjackPlayer.ts | 3.265625 | 3 | import {Cards} from "./Card";
import {CardFactory} from "./CardFactory";
import {CardShuffler} from "./CardShuffler";
import Deck from "./Deck";
import Wallet from "./Wallet";
class BlackjackPlayer{
private hand: Array<Cards>;
private canHit: Boolean;
protected firstName: string;
protected lastName: string;
protected wallet: Wallet;
constructor(firstName: string, lastName: string, balance: number) {
this.firstName = firstName;
this.lastName = lastName;
this.wallet = new Wallet(balance);
}
getName(): string {
return this.firstName + " " + this.lastName;
}
setName(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
getBalance(): number {
return this.wallet.getBalance();
}
setHand(hand: Array<Cards>) {
this.hand = hand;
}
addToHand(card: Cards) {
this.hand.push(card);
}
getHand(): Array<Cards> {
return this.hand;
}
canIHit(): Boolean {
return this.canHit;
}
setCanHit(bool: Boolean) {
this.canHit = bool;
}
getHandValue(): number {
var handValue: number = 0;
var aceCounter: number = 0;
for(var i = 0; i < this.hand.length; i++) {
if(this.hand[i].getRank() == 1) {
aceCounter += 1;
handValue += 11;
} else if(this.hand[i].getRank() > 9) {
handValue += 10;
} else {
handValue += this.hand[i].getRank();
}
if(aceCounter > 0 && handValue > 21) {
handValue -= 10;
}
}
return handValue;
}
payoutWin(amount: number) {
this.wallet.add(amount);
}
payoutLoss(amount: number) {
this.wallet.subtract(amount);
}
}
export default BlackjackPlayer; |
67c1d56a208e085b57659202dd99a5613cd0318f | TypeScript | alocquet/aoc-2016 | /src/day-05/step-1/index.ts | 2.703125 | 3 | import { Day5 } from '../day-05';
import { Index } from '../model';
export class Day5Step1 extends Day5 {
execute(input: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
let res = '';
let curIndex = new Index(0, '');
for (let idx = 0; idx < 8; idx++) {
curIndex = this.computeNextIndex(input, curIndex);
res += curIndex.hash.charAt(5);
}
resolve(res);
});
}
} |
a9a9e49f807e4ff88f076e151490d5aefb268d5f | TypeScript | haifahrul/ng-bootstrap | /e2e-app/src/app/typeahead/autoclose/typeahead-autoclose.e2e-spec.ts | 2.5625 | 3 | import {openUrl, expectFocused, sendKey, rightClick} from '../../tools.po';
import {TypeaheadAutoClosePage} from './typeahead-autoclose.po';
import {Key} from 'protractor';
describe('Typeahead Autoclose', () => {
let page: TypeaheadAutoClosePage;
const expectTypeaheadToBeOpen = async(message: string) => {
expect(await page.getDropdown().isPresent()).toBeTruthy(message);
expect(await page.getOpenStatus().getText()).toBe('open', message);
};
const expectTypeaheadToBeClosed = async(message: string) => {
expect(await page.getDropdown().isPresent()).toBeFalsy(message);
expect(await page.getOpenStatus().getText()).toBe('closed', message);
};
const openTypeahead = async() => {
await page.setTypeaheadValue('o');
await expectTypeaheadToBeOpen(`Opening typeahead`);
expect(await page.getDropdownItems().count()).toBe(2);
};
beforeAll(() => page = new TypeaheadAutoClosePage());
beforeEach(async() => await openUrl('typeahead/autoclose'));
it(`should not close typeahead on right clicks`, async() => {
await openTypeahead();
await rightClick(page.getTypeaheadInput());
await expectTypeaheadToBeOpen(`Dropdown should stay visible when right-clicking on the input`);
await rightClick(page.getDropdownItems().get(0));
await expectTypeaheadToBeOpen(`Dropdown should stay visible when right-clicking inside`);
await page.rightClickOutside();
await expectTypeaheadToBeOpen(`Dropdown should stay visible when right-clicking outside`);
});
it(`should close typeahead on outside click and lose focus`, async() => {
await openTypeahead();
await page.getOutsideButton().click();
await expectTypeaheadToBeClosed(`Dropdown should become hidden`);
await expectFocused(page.getOutsideButton(), `Clicked button should be focused`);
});
it(`should close typeahead on outside click and lose focus (with hint)`, async() => {
await page.showHint(true);
await openTypeahead();
expect(await page.getTypeaheadValue()).toBe('one', `Hint should be shown`);
await page.getOutsideButton().click();
await expectTypeaheadToBeClosed(`Dropdown should become hidden`);
await expectFocused(page.getOutsideButton(), `Clicked button should be focused`);
expect(await page.getTypeaheadValue()).toBe('o', `Hint should have been removed`);
});
it(`should not close typeahead on input click and stay focused`, async() => {
await openTypeahead();
await page.getTypeaheadInput().click();
await expectTypeaheadToBeOpen(`Dropdown should stay visible`);
await expectFocused(page.getTypeaheadInput(), `Typeahead input should stay focused`);
});
it(`should close typeahead on item click and stay focused`, async() => {
await openTypeahead();
await page.getDropdownItems().get(0).click();
await expectTypeaheadToBeClosed(`Dropdown should become hidden`);
await expectFocused(page.getTypeaheadInput(), `Typeahead input should stay focused`);
});
it(`should close typeahead on Escape and stay focused`, async() => {
await openTypeahead();
await sendKey(Key.ESCAPE);
await expectTypeaheadToBeClosed(`Dropdown should become hidden`);
await expectFocused(page.getTypeaheadInput(), `Typeahead input should stay focused`);
});
it(`should close typeahead on Escape and stay focused (with hint)`, async() => {
await page.showHint(true);
await openTypeahead();
expect(await page.getTypeaheadValue()).toBe('one', `Hint should be shown`);
await sendKey(Key.ESCAPE);
await expectTypeaheadToBeClosed(`Dropdown should become hidden`);
await expectFocused(page.getTypeaheadInput(), `Typeahead input should stay focused`);
expect(await page.getTypeaheadValue()).toBe('o', `Hint should have been removed`);
});
});
|
b320e03ae1422372a7449be28c4a354aa9e3aa4d | TypeScript | SocketDB/plugin-validate | /test/validate.test.ts | 2.765625 | 3 | import { nodeify } from 'socketdb/dist/node';
import schemaPlugin, { JSONSchemaType } from '../src';
type Data = {
[key: string]: {
player: {
[id: string]: {
name: string;
x: number;
y: number;
};
};
};
};
const schema: JSONSchemaType<Data> = {
type: 'object',
required: [],
additionalProperties: {
type: 'object',
required: ['player'],
properties: {
player: {
type: 'object',
required: [],
additionalProperties: {
type: 'object',
required: ['name', 'y', 'x'],
properties: {
name: {
type: 'string',
},
x: {
type: 'integer',
},
y: {
type: 'integer',
},
},
},
},
},
},
};
test('validates updated data', () => {
const plugin = schemaPlugin(schema);
const validData = nodeify({
'123': {
player: {
'1': {
name: 'Thomas',
x: 0,
y: 1,
},
},
},
} as Data);
const invalidData = nodeify({
somedata: {
player: {
anArray: [1, 2, 3],
},
},
aNumber: 123,
});
expect(() =>
plugin.hooks['server:update']?.(
{
data: validData,
},
{
client: { id: '123' },
api: {
get: () => validData,
delete() {},
update() {},
},
}
)
).not.toThrow();
expect(() =>
plugin.hooks['server:update']?.(
{
data: invalidData,
},
{
client: { id: '123' },
api: {
get: () => invalidData,
delete() {},
update() {},
},
}
)
).toThrow();
});
test('allow partial updates', () => {
const plugin = schemaPlugin(schema);
const storedData = nodeify({
'123': {
player: {
'1': {
name: 'Thomas',
x: 0,
y: 1,
},
},
},
} as Data);
const updatedData = nodeify({
'123': {
player: {
'1': {
y: 2,
},
},
},
});
expect(() =>
plugin.hooks['server:update']?.(
{
data: updatedData,
},
{
client: { id: '123' },
api: {
get: () => storedData,
delete() {},
update() {},
},
}
)
).not.toThrow();
});
test('validates deleted data', () => {
const plugin = schemaPlugin(schema);
const storedData = nodeify({
'123': {
player: {
'1': {
name: 'Thomas',
x: 0,
y: 1,
},
},
},
} as Data);
const validDeletePath = '123';
const invalidDeletePath = '123/player/1/name';
expect(() => {
plugin.hooks['server:delete']?.(
{ path: validDeletePath },
{
client: { id: '123' },
api: {
get: () => storedData,
delete() {},
update() {},
},
}
);
}).not.toThrow();
expect(() => {
plugin.hooks['server:delete']?.(
{ path: invalidDeletePath },
{
client: { id: '123' },
api: {
get: () => storedData,
delete() {},
update() {},
},
}
);
}).toThrow();
});
|
5b59e24414a2b4a9bb5d519384dc19555402f2ab | TypeScript | patrykkowalski0617/elevator-symulator | /src/components/car/logic/carTarget.ts | 3.03125 | 3 | // This part of code is supposed to be run
// after ShaftContext update allCarsFloorAssignments by addCarFloorAssignment
const carTarget = (
floorAssignments: number[],
carState: string,
currentFloor: number
) => {
let target: number | undefined;
const above = floorAssignments.filter(item => item >= currentFloor);
const below = floorAssignments.filter(item => item <= currentFloor);
if (floorAssignments.length === 1) {
target = floorAssignments[0];
} else if (carState === "go-up") {
target = Math.min.apply(Math, above);
} else if (carState === "go-down") {
target = Math.max.apply(Math, below);
}
if (target !== Infinity && target !== -Infinity) {
return target;
}
};
export default carTarget;
|
f12c5b218fa30d03ee685018df6ab7f9da155f45 | TypeScript | nozgurozturk/marvin | /cli/src/models/repo.ts | 2.546875 | 3 | export type PackageVersion = {
current: string;
last: string;
};
export type Package = {
name: string;
version: PackageVersion;
file: string;
isOutdated: boolean;
};
export type Repo = {
id?: string;
userID: string;
name: string;
owner: string;
path: string;
provider: string;
packageList: [Package];
};
|
bacc982f51ea3b7b49d70c94350d66bf63e79ce3 | TypeScript | arjun-1/kafkaSaur | /src/broker/saslAuthenticator/oauthBearer.ts | 2.53125 | 3 | /**
* The sasl object must include a property named oauthBearerProvider, an
* async function that is used to return the OAuth bearer token.
*
* The OAuth bearer token must be an object with properties value and
* (optionally) extensions, that will be sent during the SASL/OAUTHBEARER
* request.
*
* The implementation of the oauthBearerProvider must take care that tokens are
* reused and refreshed when appropriate.
*
* @format
*/
import oauthBearer from '../../protocol/sasl/oauthBearer/index.ts';
import { KafkaJSSASLAuthenticationError } from '../../errors.ts';
export class OAuthBearerAuthenticator {
connection: any;
logger: any;
saslAuthenticate: any;
constructor(connection: any, logger: any, saslAuthenticate: any) {
this.connection = connection;
this.logger = logger.namespace('SASLOAuthBearerAuthenticator');
this.saslAuthenticate = saslAuthenticate;
}
async authenticate() {
const { sasl } = this.connection;
if (sasl.oauthBearerProvider == null) {
throw new KafkaJSSASLAuthenticationError(
'SASL OAUTHBEARER: Missing OAuth bearer token provider'
);
}
const { oauthBearerProvider } = sasl;
const oauthBearerToken = await oauthBearerProvider();
if (oauthBearerToken.value == null) {
throw new KafkaJSSASLAuthenticationError(
'SASL OAUTHBEARER: Invalid OAuth bearer token'
);
}
const request = await oauthBearer.request(sasl, oauthBearerToken);
const response = oauthBearer.response;
const { host, port } = this.connection;
const broker = `${host}:${port}`;
try {
this.logger.debug('Authenticate with SASL OAUTHBEARER', { broker });
await this.saslAuthenticate({ request, response });
this.logger.debug('SASL OAUTHBEARER authentication successful', {
broker,
});
} catch (e) {
const error = new KafkaJSSASLAuthenticationError(
`SASL OAUTHBEARER authentication failed: ${e.message}`
);
this.logger.error(error.message, { broker });
throw error;
}
}
}
|
aef7ab7062726633a7bc277568d97a9143d7fdaf | TypeScript | V4Fire/Core | /lib/core/async/interface.d.ts | 2.6875 | 3 | /*!
* V4Fire Core
* https://github.com/V4Fire/Core
*
* Released under the MIT license
* https://github.com/V4Fire/Core/blob/master/LICENSE
*/
import type Async from '../../core/async';
import type { Task, MarkReason, ClearReason, BoundFn, ClearFn, AsyncProxyOptions, ClearProxyOptions } from '../../core/async/modules/base/interface';
import type { AsyncWorkerOptions, AsyncPromiseOptions } from '../../core/async/modules/proxy/interface';
import type { AsyncPromisifyOnceOptions } from '../../core/async/modules/events/interface';
export * from '../../core/async/modules/base/interface';
export * from '../../core/async/modules/events/interface';
export * from '../../core/async/modules/proxy/interface';
export * from '../../core/async/modules/timers/interface';
export * from '../../core/async/modules/wrappers/interface';
export declare enum Namespaces {
proxy = 0,
proxyPromise = 1,
promise = 2,
iterable = 3,
request = 4,
idleCallback = 5,
idleCallbackPromise = 6,
timeout = 7,
timeoutPromise = 8,
interval = 9,
intervalPromise = 10,
immediate = 11,
immediatePromise = 12,
worker = 13,
eventListener = 14,
eventListenerPromise = 15
}
export declare type Namespace = keyof typeof Namespaces;
/** @deprecated */
export { Namespaces as LinkNames };
export declare type FullAsyncOptions<CTX extends object = Async> = {
/**
* Namespace of the task
*
* @example
* ```typescript
* setImmediate(cb: Function, opts?: AsyncCbOptions<CTX>): Nullable<TimerId> {
* return this.registerTask({
* ...opts,
*
* // This operation has a namespace from this.namespaces.immediate
* name: this.namespaces.immediate,
*
* obj: cb,
* clearFn: clearImmediate,
* wrapper: setImmediate,
* linkByWrapper: true
* });
* }
* ```
*/
name: string;
/**
* Object to wrap with Async
*
* @example
* ```typescript
* setImmediate(cb: Function, opts?: AsyncCbOptions<CTX>): Nullable<TimerId> {
* return this.registerTask({
* ...opts,
* name: this.namespaces.immediate,
*
* // We need to pack cb with setImmediate
* obj: cb,
*
* clearFn: clearImmediate,
* wrapper: setImmediate,
* linkByWrapper: true
* });
* }
* ```
*/
obj: object & {
name?: string;
};
/**
* True, if the task can fire multiple times
*
* @example
* ```typescript
* setInterval(cb: Function, opts?: AsyncCbOptions<CTX>): Nullable<TimerId> {
* return this.registerTask({
* ...opts,
* name: this.namespaces.interval,
* obj: cb,
* clearFn: clearInterval,
* wrapper: setInterval,
* linkByWrapper: true,
*
* // setInterval doesn't stop automatically
* periodic: true
* });
* }
* ```
*/
periodic?: boolean;
/**
* If true, then the passed object can be executed as a function if it is possible
*/
callable?: boolean;
/**
* @deprecated
* @see [[FullAsyncOptions.needCall]]
*/
needCall?: boolean;
/**
* Function that wraps the original object
*
* @example
* ```typescript
* setImmediate(cb: Function, opts?: AsyncCbOptions<CTX>): Nullable<TimerId> {
* return this.registerTask({
* ...opts,
* name: this.namespaces.immediate,
* obj: cb,
* clearFn: clearImmediate,
*
* // Wrap cb by using setImmediate
* wrapper: setImmediate,
*
* linkByWrapper: true
* });
* }
* ```
*/
wrapper?: BoundFn<CTX>;
/**
* Additional arguments to a task wrapper
*
* @example
* ```typescript
* setInterval(cb: Function, opts?: AsyncCbOptions<CTX>): Nullable<TimerId> {
* return this.registerTask({
* ...opts,
* name: this.namespaces.interval,
* obj: cb,
* clearFn: clearInterval,
* wrapper: setInterval,
* linkByWrapper: true,
* periodic: true,
*
* // We need to provide a timeout value
* args: [timeout]
* });
* }
* ```
*/
args?: CanArray<unknown>;
/**
* If true, then a value that returns the wrapper will be interpreted as the unique operation identifier
*
* @example
* ```typescript
* setImmediate(cb: Function, opts?: AsyncCbOptions<CTX>): Nullable<TimerId> {
* return this.registerTask({
* ...opts,
* name: this.namespaces.immediate,
* obj: cb,
* clearFn: clearImmediate,
* wrapper: setImmediate,
*
* // setImmediate returns the unique identifier
* linkByWrapper: true
* });
* }
* ```
*/
linkByWrapper?: boolean;
/**
* Function to clear the operation
*
* @example
* ```typescript
* setImmediate(cb: Function, opts?: AsyncCbOptions<CTX>): Nullable<TimerId> {
* return this.registerTask({
* ...opts,
* name: this.namespaces.immediate,
* obj: cb,
*
* // Clear the operation
* clearFn: clearImmediate,
*
* wrapper: setImmediate,
* linkByWrapper: true
* });
* }
* ```
*/
clearFn?: ClearFn<CTX>;
} & AsyncProxyOptions<CTX> & (AsyncPromiseOptions | AsyncWorkerOptions<CTX> | AsyncPromisifyOnceOptions<unknown, unknown, CTX>);
export interface FullClearOptions<ID = any> extends ClearProxyOptions<ID> {
/**
* Namespace of the task to clear
*/
name: string;
/**
* Reason to clear or mark the task
*/
reason?: MarkReason | ClearReason;
/**
* If true, the operation was registered as a promise
*/
promise?: boolean;
/**
* Link to a task that replaces the current
*/
replacedBy?: Task;
}
|
e37e9510c59b3314738e77cb5d08b9fa0fbea370 | TypeScript | denniske/gartic | /server/src/index.ts | 2.953125 | 3 | // This is the Edge Chat Demo Worker, built using Durable Objects!
// ===============================
// Introduction to Modules
// ===============================
//
// The first thing you might notice, if you are familiar with the Workers platform, is that this
// Worker is written differently from others you may have seen. It even has a different file
// extension. The `mjs` extension means this JavaScript is an ES Module, which, among other things,
// means it has imports and exports. Unlike other Workers, this code doesn't use
// `addEventListener("fetch", handler)` to register its main HTTP handler; instead, it _exports_
// a handler, as we'll see below.
//
// This is a new way of writing Workers that we expect to introduce more broadly in the future. We
// like this syntax because it is *composable*: You can take two workers written this way and
// merge them into one worker, by importing the two Workers' exported handlers yourself, and then
// exporting a new handler that call into the other Workers as appropriate.
//
// This new syntax is required when using Durable Objects, because your Durable Objects are
// implemented by classes, and those classes need to be exported. The new syntax can be used for
// writing regular Workers (without Durable Objects) too, but for now, you must be in the Durable
// Objects beta to be able to use the new syntax, while we work out the quirks.
//
// To see an example configuration for uploading module-based Workers, check out the wrangler.toml
// file or one of our Durable Object templates for Wrangler:
// * https://github.com/cloudflare/durable-objects-template
// * https://github.com/cloudflare/durable-objects-rollup-esm
// * https://github.com/cloudflare/durable-objects-webpack-commonjs
// ===============================
// Required Environment
// ===============================
//
// This worker, when deployed, must be configured with two environment bindings:
// * rooms: A Durable Object namespace binding mapped to the ChatRoom class.
// * limiters: A Durable Object namespace binding mapped to the RateLimiter class.
//
// Incidentally, in pre-modules Workers syntax, "bindings" (like KV bindings, secrets, etc.)
// appeared in your script as global variables, but in the new modules syntax, this is no longer
// the case. Instead, bindings are now delivered in an "environment object" when an event handler
// (or Durable Object class constructor) is called. Look for the variable `env` below.
//
// We made this change, again, for composability: The global scope is global, but if you want to
// call into existing code that has different environment requirements, then you need to be able
// to pass the environment as a parameter instead.
//
// Once again, see the wrangler.toml file to understand how the environment is configured.
// =======================================================================================
// The regular Worker part...
//
// This section of the code implements a normal Worker that receives HTTP requests from external
// clients. This part is stateless.
// With the introduction of modules, we're experimenting with allowing text/data blobs to be
// uploaded and exposed as synthetic modules. By suffixing `chat.html.bin` with ".bin", Wrangler
// knows to interpret the file as a module of type `application/octet-stream`, i.e. just a byte blob.
// So when we import it as `HTML` here, we get the HTML content as an `ArrayBuffer`. So, we can
// serve our app's static asset without relying on any separate storage. (However, the space
// available for assets served this way is very limited; larger sites should continue to use Workers
// KV to serve assets.)
// import HTML from "chat.html.bin";
import {handleErrors} from "./util";
import {EnvInterface} from "./types";
export { ChatRoom } from "./chat-room"
export { RateLimiter } from "./rate-limiter"
// import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler'
// const HTML = 'Hello world';
// addEventListener('fetch', event => {
// try {
// event.respondWith(new Response('Hi world', {
// status: 200,
// }))
// } catch (e) {
// event.respondWith(new Response('Internal Error', { status: 500 }))
// }
// })
// In modules-syntax workers, we use `export default` to export our script's main event handlers.
// Here, we export one handler, `fetch`, for receiving HTTP requests. In pre-modules workers, the
// fetch handler was registered using `addEventHandler("fetch", event => { ... })`; this is just
// new syntax for essentially the same thing.
//
// `fetch` isn't the only handler. If your worker runs on a Cron schedule, it will receive calls
// to a handler named `scheduled`, which should be exported here in a similar way. We will be
// adding other handlers for other types of events over time.
export default {
async fetch(request: Request, env: EnvInterface): Promise<Response> {
return await handleErrors(request, async () => {
// We have received an HTTP request! Parse the URL and route the request.
let url = new URL(request.url);
let path = url.pathname.slice(1).split('/');
if (!path[0]) {
// Serve our HTML at the root path.
// const page = await getAssetFromKV(arguments as any, {});
//
// const response = new Response(page.body, page);
//
// response.headers.set("X-XSS-Protection", "1; mode=block");
// response.headers.set("X-Content-Type-Options", "nosniff");
// response.headers.set("X-Frame-Options", "DENY");
// response.headers.set("Referrer-Policy", "unsafe-url");
// response.headers.set("Feature-Policy", "none");
//
// return response;
return new Response('Hello world (v10)', {headers: {"Content-Type": "text/html;charset=UTF-8"}});
}
switch (path[0]) {
case "api":
// This is a request for `/api/...`, call the API handler.
return handleApiRequest(path.slice(1), request, env);
default:
return new Response("Not found", {status: 404});
}
});
}
}
async function handleApiRequest(path: string[], request: Request, env: EnvInterface) {
// We've received at API request. Route the request based on the path.
switch (path[0]) {
case "room": {
// Request for `/api/room/...`.
if (!path[1]) {
// The request is for just "/api/room", with no ID.
if (request.method == "POST") {
// POST to /api/room creates a private room.
//
// Incidentally, this code doesn't actually store anything. It just generates a valid
// unique ID for this namespace. Each durable object namespace has its own ID space, but
// IDs from one namespace are not valid for any other.
//
// The IDs returned by `newUniqueId()` are unguessable, so are a valid way to implement
// "anyone with the link can access" sharing. Additionally, IDs generated this way have
// a performance benefit over IDs generated from names: When a unique ID is generated,
// the system knows it is unique without having to communicate with the rest of the
// world -- i.e., there is no way that someone in the UK and someone in New Zealand
// could coincidentally create the same ID at the same time, because unique IDs are,
// well, unique!
let id = env.rooms.newUniqueId();
return new Response(id.toString(), {headers: {"Access-Control-Allow-Origin": "*"}});
} else {
// If we wanted to support returning a list of public rooms, this might be a place to do
// it. The list of room names might be a good thing to store in KV, though a singleton
// Durable Object is also a possibility as long as the Cache API is used to cache reads.
// (A caching layer would be needed because a single Durable Object is single-threaded,
// so the amount of traffic it can handle is limited. Also, caching would improve latency
// for users who don't happen to be located close to the singleton.)
//
// For this demo, though, we're not implementing a public room list, mainly because
// inevitably some trolls would probably register a bunch of offensive room names. Sigh.
return new Response("Method not allowed", {status: 405});
}
}
// OK, the request is for `/api/room/<name>/...`. It's time to route to the Durable Object
// for the specific room.
let name = path[1];
// Each Durable Object has a 256-bit unique ID. IDs can be derived from string names, or
// chosen randomly by the system.
let id;
if (name.match(/^[0-9a-f]{64}$/)) {
// The name is 64 hex digits, so let's assume it actually just encodes an ID. We use this
// for private rooms. `idFromString()` simply parses the text as a hex encoding of the raw
// ID (and verifies that this is a valid ID for this namespace).
id = env.rooms.idFromString(name);
} else if (name.length <= 32) {
// Treat as a string room name (limited to 32 characters). `idFromName()` consistently
// derives an ID from a string.
id = env.rooms.idFromName(name);
} else {
return new Response("Name too long", {status: 404});
}
// Get the Durable Object stub for this room! The stub is a client object that can be used
// to send messages to the remote Durable Object instance. The stub is returned immediately;
// there is no need to await it. This is important because you would not want to wait for
// a network round trip before you could start sending requests. Since Durable Objects are
// created on-demand when the ID is first used, there's nothing to wait for anyway; we know
// an object will be available somewhere to receive our requests.
let roomObject = env.rooms.get(id);
// Compute a new URL with `/api/room/<name>` removed. We'll forward the rest of the path
// to the Durable Object.
let newUrl = new URL(request.url);
newUrl.pathname = "/" + path.slice(2).join("/");
// Send the request to the object. The `fetch()` method of a Durable Object stub has the
// same signature as the global `fetch()` function, but the request is always sent to the
// object, regardless of the request's URL.
return roomObject.fetch(newUrl.toString(), request);
}
default:
return new Response("Not found", {status: 404});
}
}
|
b7e746b23cc887c28a68da2c55f067f4c3b43a4c | TypeScript | framptonjs/frampton | /packages/core/src/main/utils/is-empty.ts | 3.578125 | 4 | import isNothing from './is-nothing';
/**
* Returns a boolean telling us if a given value doesn't exist or has length 0
*
* @name isEmpty
* @method
* @memberof Frampton.Utils
* @param {*} obj
* @returns {Boolean}
*/
export default function is_empty(obj: any): boolean {
if (typeof obj === 'string') {
return obj.trim().length === 0;
} else {
return (
isNothing(obj) ||
!obj.length ||
obj.length === 0
);
}
} |
26f4faa2eb18b7204368791db3c91c9817a9ca84 | TypeScript | YasminElbahar/Eia2Aufgaben | /Canvas/Canvas_script.ts | 2.640625 | 3 | namespace Canvas {
document.addEventListener("DOMContentLoaded", init);
let canvas: HTMLCanvasElement;
let crc2: CanvasRenderingContext2D;
interface Canvas {
x: number;
y: number;
width: number;
height: number;
}
interface Point {
x: number;
y: number;
}
function generateRandomCluster(_area: Canvas, _count: number): Point[] {
let returnValue = new Array();
for (let i: number = 0; i < _count; i++) {
let newPoint: Point = {
x: Math.random() * _area.width + _area.x,
y: Math.random() * _area.height + _area.y
};
returnValue.push(newPoint);
}
return returnValue;
}
function init(): void {
canvas = <HTMLCanvasElement>document.querySelector("canvas");
crc2 = <CanvasRenderingContext2D>canvas.getContext("2d");
drawBackground();
let areaHumanCell: Canvas = {
x: 0, y: 50, width: window.innerWidth, height: window.innerHeight / 3
};
let humanCellLocations = generateRandomCluster(areaHumanCell, 15);
humanCellLocations.forEach(function (item) {
drawHumanCell(item.x, item.y);
});
let areaAntiBody: Canvas = {
x: 0, y: 50 + window.innerHeight / 3, width: window.innerWidth, height: window.innerHeight / 3
};
let antiPositionMin: Vector = { "x": 1000, "y": 300 };
let antiPositionMax: Vector = { "x": 300, "y": 600 };
for (let i: number = 0; i < 10; i++) {
let X: number = Math.random() * (antiPositionMax.x - antiPositionMin.x) + antiPositionMin.x;
let Y: number = Math.random() * (antiPositionMax.y - antiPositionMin.y) + antiPositionMin.y;
drawAntiBody({ "x": X, "y": Y }, { "x": 20, "y": 20 });
}
let areaCorona: Canvas = {
x: 0, y: innerHeight * 2 / 3, width: window.innerWidth, height: window.innerHeight / 8
};
let coronaLocations = generateRandomCluster(areaCorona, 10);
coronaLocations.forEach(function (item) {
drawVirus(item.x, item.y);
});
}
function drawBackground(): void {
let gradient: CanvasGradient = crc2.createLinearGradient(0, 0, 0, 500);
gradient.addColorStop(1, "rgb(128,0,0)");
gradient.addColorStop(0, "rgb(255,182,193)");
crc2.fillStyle = gradient;
crc2.fillRect(0, 0, canvas.width, canvas.height);
let pattern: CanvasRenderingContext2D = <CanvasRenderingContext2D>document.createElement("canvas").getContext("2d");
pattern.canvas.width = 40;
pattern.canvas.height = 20;
pattern.fillStyle = "Transparent";
pattern.fillRect(0, 0, pattern.canvas.width, pattern.canvas.height);
pattern.moveTo(0, 10);
pattern.lineTo(10, 10);
pattern.lineTo(20, 0);
pattern.lineTo(30, 0);
pattern.lineTo(40, 10);
pattern.lineTo(30, 20);
pattern.lineTo(20, 20);
pattern.lineTo(10, 10);
pattern.stroke();
crc2.fillStyle = <CanvasPattern>crc2.createPattern(pattern.canvas, "repeat");
crc2.fillRect(3, 5, canvas.width, canvas.height);
}
function drawHumanCell(_x: number, _y: number): void {
let cell: Path2D = new Path2D();
cell.arc(_x, _y, 60, 0, 10 * Math.PI);
crc2.fillStyle = "rgb(0,191,255)";
crc2.fill(cell);
crc2.stroke(cell);
let inner: Path2D = new Path2D();
inner.arc(_x, _y, 25, 0, 7 * Math.PI);
crc2.strokeStyle = "black";
crc2.fillStyle = "rgb(142,229,238)";
crc2.lineWidth = 4;
crc2.strokeStyle = "grey";
crc2.fill(inner);
crc2.stroke(inner);
}
function drawVirus(_x: number, _y: number): void {
let Corona: Path2D = new Path2D();
for (let i: number = 0; i < 10; i++) {
Corona.moveTo(_x + 5, _y - 5);
Corona.lineTo(_x + 40, _y + 20);
Corona.moveTo(_x + 5, _y - 5);
Corona.lineTo(_x - 40, _y - 20);
Corona.moveTo(_x - 25, _y + 40);
Corona.lineTo(_x + 5, _y - 5);
Corona.lineTo(_x + 25, _y - 40);
Corona.lineTo(_x + 5, _y - 5);
Corona.lineTo(_x + 25, _y + 40);
Corona.lineTo(_x + 5, _y - 5);
Corona.lineTo(_x - 25, _y + 40);
Corona.lineTo(_x + 5, _y - 5);
Corona.lineTo(_x - 25, _y - 40);
Corona.lineTo(_x + 5, _y - 5);
Corona.lineTo(_x - 40, _y + 20);
Corona.lineTo(_x + 5, _y - 5);
Corona.lineTo(_x + 40, _y - 20);
Corona.lineTo(_x + 5, _y - 5);
Corona.lineTo(_x - 25, _y + 40);
Corona.lineTo(_x + 5, _y - 5);
Corona.lineTo(_x + 25, _y - 40);
Corona.lineTo(_x + 5, _y - 5);
Corona.lineTo(_x + 40, _y - 20);
crc2.closePath();
crc2.strokeStyle = "darkgreen";
crc2.lineWidth = 7;
crc2.fill(Corona);
crc2.stroke(Corona);
}
let virusOutline: Path2D = new Path2D();
virusOutline.arc(_x, _y, 30, 0, 4 * Math.PI);
crc2.fillStyle = "rgb(127,255,0)";
crc2.fill(virusOutline);
crc2.stroke(virusOutline);
let virus: Path2D = new Path2D();
virus.arc(_x, _y, 20, 0, 2 * Math.PI);
crc2.fillStyle = "rgb(50,205,50)";
crc2.fill(virus);
crc2.stroke(virus);
}
function drawAntiBody(_position: Vector, _size: Vector): void {
crc2.strokeStyle = "rgb(209,188,138)";
crc2.lineWidth = 3;
crc2.save();
crc2.translate(_position.x, _position.y);
crc2.beginPath();
crc2.moveTo(-7, 0);
crc2.lineTo(-7, -25);
crc2.moveTo(-7, -25);
crc2.lineTo(-17, -35);
crc2.moveTo(-15, -23);
crc2.lineTo(-25, -33);
crc2.moveTo(7, 0);
crc2.lineTo(7, -25);
crc2.moveTo(7, -25);
crc2.lineTo(17, -35);
crc2.moveTo(15, -23);
crc2.lineTo(25, -33);
crc2.stroke();
crc2.closePath();
crc2.restore();
}
}
|
77b15eb8031d99f3eb7d1cdfa720a5e1359818b6 | TypeScript | shunwuyu/lesson_md | /interview/basic_know/datastructor/link/link_test.ts | 3.515625 | 4 | import LinkedList from "./lib/linked_list";
const linkedList = new LinkedList();
linkedList.push(12);
linkedList.push(13);
linkedList.push(14);
linkedList.push(15);
linkedList.push(16);
linkedList.push(17);
linkedList.push(18);
linkedList.push(19);
// 移除索引为2的元素
linkedList.removeAt(2);
// 获取0号元素
console.log(linkedList.getElementAt(0));
// 查找19在链表中的位置
console.log(linkedList.indexOf(19));
// 在2号位置添加22元素
linkedList.insert(22,2);
// 获取链表中的所有元素
console.log(linkedList.toString()); |
34f4c7dee351d980df311cf9dfc5dd1468a7c9cc | TypeScript | Maarkis/ADI6-PORTAL | /src/app/models/response/base-response.ts | 2.609375 | 3 | export class BaseResponse<T> {
public success: boolean;
public message: string;
public result: T;
}
|
578cdbc2b6aa91e8c92e5bc0bca084a6d767c90d | TypeScript | Manogel/eprint-nestjs | /src/modules/section/section.service.ts | 2.546875 | 3 | import { Injectable } from '@nestjs/common';
import { CreateSectionDto } from './dto/create-section.dto';
import { UpdateSectionDto } from './dto/update-section.dto';
@Injectable()
export class SectionService {
create(createSectionDto: CreateSectionDto) {
return 'This action adds a new section';
}
findAll() {
return `This action returns all section`;
}
findOne(id: number) {
return `This action returns a #${id} section`;
}
update(id: number, updateSectionDto: UpdateSectionDto) {
return `This action updates a #${id} section`;
}
remove(id: number) {
return `This action removes a #${id} section`;
}
}
|
f04f9e2967f3345b1ba1a5032e5e47e53b310c53 | TypeScript | cisikawa/dojo-protractor | /integration/features/data/testability.data.ts | 2.578125 | 3 | export class TestabilityData {
private readonly testabilityHeader;
private readonly testabilityBody;
constructor() {
this.testabilityHeader = 'Testability';
this.testabilityBody = 'The Testability service provides testing hooks that can be accessed ' +
'from the browser and by services such as Protractor. Each ' +
'bootstrapped Angular application on the page will have an instance of Testability.';
}
getTestabilityHeader() {
return this.testabilityHeader;
}
getTestabilityBody() {
return this.testabilityBody;
}
}
|
b588ab4df8f69d19d6b340411f3229f1c4e3c587 | TypeScript | svatal/plovouci-filmoteka | /tvScraper/src/eventsMerger.ts | 2.859375 | 3 | import {
ITvEventInfo,
ITvMovie,
ITvEvent,
IBasicTvEventInfo,
IExtendedEventInfo,
isSameMovie
} from "shared/event";
export function merge(events: ITvEventInfo[]): ITvMovie[] {
return events.reduce(tryAppendEventToMovies, <ITvMovie[]>[]);
}
function tryAppendEventToMovies(
movies: ITvMovie[],
e: ITvEventInfo
): ITvMovie[] {
for (let i = 0; i < movies.length; i++) {
if (tryAppendEventToMovie(movies[i], e)) return movies;
}
return [...movies, toMovie(e, e)];
}
function tryAppendEventToMovie(m: ITvMovie, e: ITvEventInfo): ITvMovie | null {
if (!isSameMovie(m, e)) return null;
m.events.push(toEvent(e));
return m;
}
function toEvent(e: IBasicTvEventInfo, groupName?: string): ITvEvent {
return {
channelName: e.channelName,
durationInMinutes: e.durationInMinutes,
id: e.id,
startTime: e.startTime,
name:
groupName === undefined || groupName === e.name
? undefined
: e.name.substr(groupName.length + 1)
};
}
function toMovie(
ee: IExtendedEventInfo,
be: IBasicTvEventInfo,
groupName?: string
): ITvMovie {
return {
description: ee.description,
// groupName === undefined || groupName === be.name ? ee.description : "",
mdbs: ee.mdbs,
name: groupName || be.name,
posterUrl: ee.posterUrl,
year: ee.year,
tags: ee.tags,
events: [toEvent(be, groupName)]
};
}
export function mergeToOne(
events: IBasicTvEventInfo[],
extended: IExtendedEventInfo,
groupName: string
): ITvMovie {
const movie = toMovie(extended, events[0], groupName);
events.slice(1).forEach(e => movie.events.push(toEvent(e, groupName)));
return movie;
}
|
27ee3edcca50b1a4ebb3ba1d4de588f167045ade | TypeScript | JGdijk/ng-rds | /src/rds/statements/orderby-statement.ts | 3.34375 | 3 | export class OrderByStatement {
private statement;
constructor(statement){
this.statement = statement;
}
public order(data: any[]): any[] {
// todo we have to throw a big error when the key of the order doesn't exist on the object
let statement = this.statement;
if (statement.order.toLowerCase() !== 'desc' && statement.order.toLowerCase() !== 'asc') return; // todo trow big error
let desc = (statement.order.toLowerCase() === 'desc');
return data.sort((obj1, obj2) => {
if (Number.isInteger(obj1[statement.key]) && Number.isInteger(obj2[statement.key])) {
return (desc)
? obj2[statement.key] - obj1[statement.key]
: obj1[statement.key] - obj2[statement.key];
}
if (Number.isInteger(obj1[statement.key])) return (desc) ? -1 : 1;
if (Number.isInteger(obj2[statement.key])) return (desc) ? 1 : -1;
return (desc)
? obj2[statement.key].localeCompare(obj1[statement.key])
: obj1[statement.key].localeCompare(obj2[statement.key]);
});
}
} |
30b2e3a71fab90caaf7f836ad3b5ee9ce4416abb | TypeScript | melquisedecfelipe/magrathea | /backend/src/controllers/SignInController.ts | 2.609375 | 3 | import axios from 'axios';
import { Request, Response } from 'express';
export default class SignInController {
public async auth(request: Request, response: Response) {
const { code } = request.params;
if (!code) {
return response.status(404).json({
message: 'Código de acesso inválido.',
});
}
try {
const responseToken = await axios.post(
'https://github.com/login/oauth/access_token',
{
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
code,
},
{
headers: {
Accept: 'application/json',
},
},
);
const token = responseToken.data.access_token;
const responseUser = await axios.get('https://api.github.com/user', {
headers: {
Authorization: `token ${token}`,
},
});
const user = {
id: responseUser.data.id,
avatarUrl: responseUser.data.avatar_url,
name: responseUser.data.name,
login: responseUser.data.login,
followers: responseUser.data.followers,
following: responseUser.data.following,
};
return response.status(200).json({ token, user });
} catch (error) {
return response.status(404).json({ error });
}
}
}
|
799b0cd0c48a000327bc07c6ef8c4267ac5dc113 | TypeScript | zachmart/distriprob | /src/outward/FloatUtil.ts | 2.6875 | 3 | "use strict";
/**
* (C) Copyright Zachary Martin 2018.
* Use, modification and distribution are subject to the
* Boost Software License:
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
export class FloatUtil {
public static className: string;
public static constructorFloat;
public static methodNames: Array<string>;
public static init0(): void {
FloatUtil.className = "FloatUtil";
}
public static init(): void {
class Float {
constructor(private readonly f: float) {}
public static getfloat(x: Float): float {
return x.f;
}
}
for (let fw of Library.getAllFloatMethodFWs()) {
Float.prototype[fw.name] = fw.method();
}
FloatUtil.constructorFloat = Float;
FloatUtil.getfloat = Float.getfloat;
FloatUtil.methodNames = Library.getAllFloatMethodNames();
}
public static createFloat(f: float): Float {
return new FloatUtil.constructorFloat(f);
}
public static isFloat(x: any): x is Float {
if (typeof x === "undefined") {
return false;
}
// if (x instanceof FloatUtil.constructorFloat) {
// console.log("heyo");
// return true;
// }
if (Core.instance(x.f)) {
for (let methodName of FloatUtil.methodNames) {
console.log("checking method:", methodName);
if (typeof x[methodName] !== "function") {
return false;
}
}
return true;
}
return false;
}
public static getfloat(x: Float): float {
return FloatUtil.constructorFloat.getfloat(x);
}
public static dependencies(): Set<Class> {
return new Set([
Core, Library,
]);
}
}
// *** imports come at end to avoid circular dependency ***
// interface/type imports
import {float} from "../interfacesAndTypes/float";
//import {Float} from "./Float";
import {Class} from "../interfacesAndTypes/Class";
// functional imports
import {Core as CoreAlias} from "../core/Core";
const Core = CoreAlias;
import {Library as LibraryAlias} from "../core/Library";
const Library = LibraryAlias; |
8d56d8087d8b033b8a186cdc1d6fc28851ef4fe8 | TypeScript | fabig4da/ts-node-server | /src/middleware/users/userMiddleware.ts | 2.578125 | 3 | import { CustomValidator} from "express-validator";
import User from "../../models/users/user";
export const emailExist: CustomValidator = async(email: string)=>{
try {
const user = await User.findOne({email})
console.log(user)
if(user)
return Promise.reject('Email already exist');
} catch (error) {
return Promise.reject('Server error');
}
} |
193b671a3c8154bf6702f5abedb4ee642c694c5a | TypeScript | ysabri/GitDrive | /src/git-drive/app/sync.ts | 2.734375 | 3 | import {
GRepository,
User,
WorkSpace,
} from "../../model/app";
import { Commit } from "../../model/git";
import { writeRepoInfo } from "../../util/metafile";
import {
commit,
fetchAll,
getCommit,
getStatus,
pushBranch,
} from "../git";
/**
* The big sync function, assumes very little but demands a lot.
* @param repo Repo where the commit, push, fetch will happen
* @param user The user committing
* @param workspace The workspace that the commit will be created in
* @param summary The commit summary
* @param body The commit message
*/
export async function sync(
repo: GRepository,
workspace: WorkSpace,
user: User,
summary: string,
body: string,
): Promise<WorkSpace> {
// TODO: add this back with the new array
// get the branch and check if user owns it
// const userBranch = getVal(user.workSpaces, workspace.name);
// if (!userBranch) {
// throw new Error("[sync] User: " + user.name + " does not own the WorkSpace: "
// + workspace.name);
// }
// see if branch exists by getting its tip commit, I could do the same
// thing using for-each-ref
// check if the tip commit belongs to user, something got really messed up
// if this error gets thrown.
if (workspace.tip.committer.name !== user.name) {
throw new Error("[sync] Based on the tip commit, user: " + user.name +
" doesn't own workspace: " + workspace.name);
}
// check if the current checked out branch is the one that belong to user
// i.e check if the caller messed up
const status = await getStatus(repo);
if (status.currentBranch !== workspace.name) {
throw new Error("[sync] The current checked-out branch is not the one "
+ "that belongs to user: " + user.name);
}
await writeRepoInfo(repo);
await commit(repo, user.name, user.email, summary, body);
const newCommitArr: Commit[] = workspace.commits as Commit[];
const newTip = await getCommit(repo, workspace.name);
if (newTip && newTip.SHA === workspace.tip.SHA) {
throw new Error(`[sync] Could not commit on ${user.name}'s branch`);
} else if (newTip) {
newCommitArr.push(newTip);
} else {
throw new Error("[sync] Branch: " + workspace.name + " doesn't exit" +
" or was deleted from repository: " + repo.name +
" right after committing");
}
// this only looks at the current branch, maybe add a check for other
// branches as the user's branch might not have a remote but other branches
// do and the user wants to know what was added on them.
if (workspace.remoteUpstream) {
// push the changes
await pushBranch(repo, workspace.name);
// download the other branches
await fetchAll(repo);
}
return new WorkSpace(workspace.name,
workspace.remoteUpstream, newTip, newCommitArr, workspace.changeList,
workspace.originCommit);
}
|
dd4ef98301ccc9085b36922759ddae115c9b62ca | TypeScript | EmiliaNica/boilerplate | /frontend/src/app/teacherRecords.ts | 2.625 | 3 |
export class teacherRecords{
constructor(public student:string, public grade:number){
this.student = student;
this.grade = grade;
}
} |
f5bc1f002e479947a7d1266403ed0520c50ba514 | TypeScript | HappyCerberus/streambot | /src/backbone/backbone.ts | 2.5625 | 3 | import * as zmq from "zeromq"
import { MessageTypes } from "../lib/types"
import { PublisherQueue } from "../lib/publisher_queue"
async function listen(name: string, sub: zmq.Subscriber, pub: PublisherQueue) {
let id = 0;
for await (const [topic, msg] of sub) {
console.log(`BACKBONE | ${name} | received a message id: ${++id} related to: ${topic} containing message: ${msg.toString()}`);
pub.send(topic, msg);
}
}
export async function producer_connect(hostport: string): Promise<zmq.Publisher> {
return new Promise((resolve, reject) => {
const pub = new zmq.Publisher;
pub.bind(hostport).then(() => {
const sock = new zmq.Request;
sock.connect("tcp://127.0.0.1:6666");
sock.send(hostport).then(() => {
sock.receive().then(([msg]) => {
if (msg.toString() !== "ACK") {
throw new Error(`Unexpected response from backend for inbound module at ${hostport}.`);
} else {
console.log(`Module at ${hostport} connected successfully.`);
resolve(pub);
}
});
});
});
});
}
export async function run() {
const sock = new zmq.Reply;
const pub = new zmq.Publisher
await sock.bind("tcp://127.0.0.1:6666");
await pub.bind("tcp://127.0.0.1:6667");
let retransmitter = new PublisherQueue(pub);
retransmitter.run();
for await (const [msg] of sock) {
const sub = new zmq.Subscriber;
try {
sub.connect(msg.toString());
sub.subscribe();
} catch (err) {
console.error(`BACKBONE | Backbone received a malformed message : ${err}`);
}
listen(msg.toString(), sub, retransmitter);
await sock.send("ACK").catch(err => {
console.error(`BACKBONE | Failed to confirm connection of module ${err}`);
});
}
} |
fb9b2dd369207bf895cbd37d113ad2699f589359 | TypeScript | aniket1101/xcode-projects | /TicTacToe/cloud-functions/functions/src/onGameCreate.ts | 2.765625 | 3 | import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
interface StartGame {
player: "x" | "o"
uid: string
}
const gamesPath = "/games"
const path = "/start/{gameId}"
const handler = async (snapshot: functions.database.DataSnapshot, context: functions.EventContext) => {
const gameId = context.params.gameId
const gameData: StartGame = snapshot.val()
const players = gameData.player == 'x' ? { x: gameData.uid } : { o: gameData.uid }
await snapshot.ref.remove().catch(() => {
console.log('An error occured whilst deleting the reference')
})
return admin.database().ref(gamesPath).child(gameId).set({
id: gameId,
startedAt : admin.database.ServerValue.TIMESTAMP,
nextMove : gameData.uid,
players
})
}
export const onGameCreate = functions.database.ref(path).onCreate(handler) |
e60f5112f061316892df1f57e0e1a6c55a58b351 | TypeScript | lukkerr/PraticaSistemaBancario | /app/ts/model/cliente.ts | 2.890625 | 3 | class Cliente {
private _nome : string;
private _cpf : string;
private _conta : Conta;
constructor (nome : string, cpf : string, conta : Conta) {
this._nome = nome;
this._cpf = cpf;
this._conta = conta;
}
get nome() : string {
return this._nome;
}
set nome( nome:string ) {
this._nome = nome;
}
get cpf() : string {
return this._cpf;
}
set cpf( cpf:string ) {
this._cpf = cpf;
}
get conta() : Conta {
return this._conta;
}
set conta( conta:Conta ) {
this._conta = conta;
}
toString() : string {
return `Nome: ${this.nome} - CPF: ${this.cpf} - Numero: ${this.conta.numero} - Saldo ${this.conta.saldo}`;
}
} |
0f465a8ec58b1e60c8628de4dc4297b9dcc62727 | TypeScript | duytrantlu/stl-test | /src/configs/auth/basic-auth.lib.ts | 2.515625 | 3 | /**
* @module auth
* @author DuyTM
* @description basic authenticate library
* @version 1.0.0
*/
import * as jwt from 'jsonwebtoken';
import { pick, omitBy, isNil } from 'lodash';
import { Request, Response, NextFunction, RequestHandler } from 'express';
import { AuthConfig } from './auth.config';
import { ConstLib } from '../common/consts';
import { Strategy, ApiOption } from '../common/models';
import { expressJwt } from './';
import { ConfigBase } from '../common/config.base';
export default class BasicAuthLib {
/**
* @method verifyToken
* @description Check if token is valid
* @param options
* @return {e.RequestHandler}
*/
public static verifyToken(options?: ApiOption & any): RequestHandler {
return function (req: Request, res: Response, next: NextFunction) {
return expressJwt.handler(Object.assign({}, options, {
secret: ConfigBase.SECURE.JWT.JWT_SECRET
}))(req, res, next);
};
}
/**
* @method verifyTokenBase
* @description same as verifyToken. But function not attach response failed when token not invalid
* @param {e.Request} req
* @param {e.Response} res
* @param {e.NextFunction} next
* @return {e.RequestHandler}
*/
public static verifyTokenBase(req: Request, res: Response, next: NextFunction): void {
const clientSecret: string = <string>req.headers[Strategy.ClientSecret];
if (clientSecret && clientSecret.length >= 71 && ConfigBase.SECURE.API_RESTRICT.CLIENT_SECRET.indexOf(clientSecret) > -1) {
return next();
}
let token: string = <string>req.headers.authorization;
jwt.verify(token ? token.substring(7) : '', ConfigBase.SECURE.JWT.JWT_SECRET,
{ algorithms: ['HS512'] }, function (err, decoded) {
if (err) return next();
req.user = decoded as any;
return next();
});
}
/**
* @method signToken
* @description create new token
* @param {object} user
* @param {string[]} fields
* @param {number} expiresIn
* @return {string}
*/
public static signToken(
user: any
, fields: string[] = [
...AuthConfig.JWT.FIELD,
]
, expiresIn: number = ConfigBase.SECURE.JWT.TOKEN_EXPIRE) {
user = omitBy(user, isNil);
return jwt.sign(
pick(user, fields),
ConfigBase.SECURE.JWT.JWT_SECRET,
{
algorithm: ConstLib.JWT_SECRET_ALGORITHM,
expiresIn: expiresIn
}
);
}
}
|
3e5a1a0d093fd0fbe3dc3562b07b56be58035a5e | TypeScript | joaquinenriquez/Proyecto-vacio-Angular-con-Router-Bootstrap-y-Fontawersome | /src/app/services/auth.service.ts | 2.640625 | 3 | import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { IUsuario } from '../models/iusuario';
// Firebase
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { AngularFireAuth } from '@angular/fire/auth';
@Injectable({
providedIn: 'root'
})
// Servicio que va a tener todo lo relacionado con los usuarios (creación, login, etc)
export class AuthService {
/* #region Atributos */
public usuarioActual: IUsuario = {
email: '',
password: '',
tipoUsuario: ''
};
/* #endregion */
/* #region Constructor */
constructor(private afsAuth: AngularFireAuth, private afs: AngularFirestore) { }
/* #endregion */
/* #region Métodos de clase */
registrarUsuario(email: string, password: string, tipo: string) {
return new Promise((resolve, reject) => {
this.afsAuth.auth.createUserWithEmailAndPassword(email, password) // Damos de alta el usuario
.then(datosUsuario => {
resolve(datosUsuario);
this.updateDatosUsuario(datosUsuario.user, tipo); // Lo agregamos a la coleccion de usuarios
})
.catch(err => {
console.log(err.message);
reject(err);
});
});
}
loginConEmail(email: string, password: string) {
return new Promise((resolve, reject) => {
this.afsAuth.auth.signInWithEmailAndPassword(email, password)
.then(datosUsuario => {
this.usuarioActual.email = datosUsuario.user.email;
resolve(datosUsuario);
}, err => {
reject(err);
});
});
}
updateDatosUsuario(datosUsuario, tipo: string) {
const userRef: AngularFirestoreDocument<any> = this.afs.doc(`usuarios/${datosUsuario.uid}`);
const data: IUsuario = {
id: datosUsuario.uid,
email: datosUsuario.email,
tipoUsuario: tipo
};
return userRef.set(data, { merge: true });
}
logoutUsuario() {
return this.afsAuth.auth.signOut();
}
isLogeado() {
return this.afsAuth.authState.pipe(map(auth => auth)); // Operamos sobre el flujo de datos del observable.
}
isAdmin(id) {
return this.afs.doc<IUsuario>(`usuarios/${id}`).valueChanges();
}
getUsuarioActual(): IUsuario {
return this.usuarioActual;
}
/* #endregion */
}
|
e57bfe45240f97180d678ac6a92304915b28be2c | TypeScript | home-assistant/probot-home-assistant | /src/util/text_parser.ts | 2.859375 | 3 | import { GitHubAPI } from "probot/lib/github";
import { fetchIssueWithCache } from "./issue";
import { fetchPRWithCache } from "./pull_request";
interface PullOrBodyTask {
checked: boolean;
description: string;
}
interface IntegrationDocumentationLink {
link: string;
integration: string;
}
export class ParsedGitHubIssueOrPR {
public owner: string;
public repo: string;
public number: number;
constructor(owner: string, repo: string, number: number) {
this.owner = owner;
this.repo = repo;
this.number = number;
}
issue() {
return {
owner: this.owner,
repo: this.repo,
issue_number: this.number,
};
}
pull() {
return {
owner: this.owner,
repo: this.repo,
pull_number: this.number,
};
}
async fetchIssue(github: GitHubAPI) {
return await fetchIssueWithCache(
github,
this.owner,
this.repo,
this.number
);
}
async fetchPR(github: GitHubAPI) {
return await fetchPRWithCache(github, this.owner, this.repo, this.number);
}
}
export const extractPullRequestURLLinks = (body: string) => {
const re = /https:\/\/github.com\/([\w-\.]+)\/([\w-\.]+)\/pull\/(\d+)/g;
let match;
const results: ParsedGitHubIssueOrPR[] = [];
do {
match = re.exec(body);
if (match) {
results.push(
new ParsedGitHubIssueOrPR(match[1], match[2], Number(match[3]))
);
}
} while (match);
return results;
};
export const extractIssuesOrPullRequestMarkdownLinks = (body: string) => {
const re = /([\w-\.]+)\/([\w-\.]+)#(\d+)/g;
let match;
const results: ParsedGitHubIssueOrPR[] = [];
do {
match = re.exec(body);
if (match) {
results.push(
new ParsedGitHubIssueOrPR(match[1], match[2], Number(match[3]))
);
}
} while (match);
return results;
};
export const extractTasks = (body: string) => {
const matchAll = /- \[( |)(x|X| |)(| )\] /;
const matchChecked = /- \[( |)(x|X)(| )\] /;
let tasks: PullOrBodyTask[] = [];
body.split("\n").forEach((line: string) => {
if (!line.trim().startsWith("- [")) {
return;
}
const lineSplit = line.split(matchAll);
const checked: boolean = matchChecked.test(line);
const description: string = lineSplit[lineSplit.length - 1]
.trim()
.replace(/\\r/g, "");
tasks.push({ checked, description });
});
return tasks;
};
export const extractIntegrationDocumentationLinks = (
body: string
): IntegrationDocumentationLink[] => {
const re = /https:\/\/(www.|rc.|next.|)home-assistant.io\/integrations\/(?:\w+\.)?(\w+)/g;
let match;
let results: IntegrationDocumentationLink[] = [];
do {
match = re.exec(body);
if (match) {
results.push({ link: match, integration: match[2] });
}
} while (match);
return results;
};
export const extractDocumentationSectionsLinks = (body: string): string[] => {
const re = /https:\/\/(www.|rc.|next.|)home-assistant.io\/(.*)\//g;
let match;
let results: string[] = [];
do {
match = re.exec(body);
if (match) {
const sections = match[2].split("/");
results = results.concat(sections);
}
} while (match);
return [...new Set(results)];
};
|
b0051e76d042b64d0d775930eaeef17da58c8469 | TypeScript | montalvomiguelo/cli | /packages/cli-kit/src/public/common/function.test.ts | 2.78125 | 3 | import {debounce, memoize} from './function.js'
import {describe, test, expect} from 'vitest'
describe('memoize', () => {
test('memoizes the function value', () => {
// Given
let value = 0
function functionToMemoize() {
value += 1
return value
}
const memoizedFunction = memoize(functionToMemoize)
// When/Then
expect(memoizedFunction()).toEqual(1)
expect(memoizedFunction()).toEqual(1)
})
})
describe('debounce', () => {
test('debounces the function', async () => {
// Given
let value = 0
await new Promise<void>((resolve, reject) => {
const debounced = debounce(() => {
value += 1
resolve()
}, 200)
debounced()
debounced()
debounced()
})
// Then
expect(value).toEqual(1)
})
})
|
f0afd38a3e888d0e00bf431c27227644e2583f9d | TypeScript | vcing/leetcode-ts | /1-100/88.merge-sorted-array.ts | 4.0625 | 4 | /*
* @lc app=leetcode id=88 lang=javascript
*
* [88] Merge Sorted Array
*
* https://leetcode.com/problems/merge-sorted-array/description/
*
* algorithms
* Easy (33.99%)
* Total Accepted: 318.8K
* Total Submissions: 922.7K
* Testcase Example: '[1,2,3,0,0,0]\n3\n[2,5,6]\n3'
*
* Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as
* one sorted array.
*
* Note:
*
*
* The number of elements initialized in nums1 and nums2 are m and n
* respectively.
* You may assume that nums1 has enough space (size that is greater or equal to
* m + n) to hold additional elements from nums2.
*
*
* Example:
*
*
* Input:
* nums1 = [1,2,3,0,0,0], m = 3
* nums2 = [2,5,6], n = 3
*
* Output: [1,2,2,3,5,6]
*
*
*/
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge2 = function (nums1: number[], m: number, nums2: number[], n: number) {
let currentLength = m
const insert = (index: number, value: number) => {
for (let i = currentLength; i >= index; i--) {
nums1[i] = nums1[i - 1]
}
nums1[index] = value
currentLength++
}
let left = n
let n1Index = 0
let n2Index = 0
while (left > 0) {
if (nums1[n1Index] < nums2[n2Index]) {
n1Index++
} else {
// console.log('insert:', n1Index, nums2[n2Index], currentLength)
insert(n1Index >= nums1.length ? currentLength : n1Index, nums2[n2Index])
n2Index++
n1Index++
left--
}
}
return nums1
};
// console.log(merge([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3)) |
eed53df4fdd8ce52f9f95f6dac11fd0ee6729cbc | TypeScript | ArcticZeroo/linguistics-website | /src/api/linguistics/ipa/consonants.ts | 2.65625 | 3 | enum PlaceOfArticulation {
bilabial,
labiodental,
interdental,
alveolar,
palatal,
velar,
glottal
}
enum MannerOfArticulation {
stop,
fricative,
affricate,
nasal,
flap,
retroflexLiquid,
lateralLiquid,
glide
}
enum Voicing {
voiceless, voiced
}
interface IConsonantData {
place: PlaceOfArticulation;
manner: MannerOfArticulation;
voicing: Voicing;
}
const placeOfArticulationOrder = [PlaceOfArticulation.bilabial, PlaceOfArticulation.labiodental, PlaceOfArticulation.interdental, PlaceOfArticulation.alveolar, PlaceOfArticulation.palatal, PlaceOfArticulation.velar, PlaceOfArticulation.glottal];
const mannerOfArticulationOrder = [MannerOfArticulation.stop, MannerOfArticulation.fricative, MannerOfArticulation.affricate, MannerOfArticulation.nasal, MannerOfArticulation.flap, MannerOfArticulation.retroflexLiquid, MannerOfArticulation.lateralLiquid, MannerOfArticulation.glide];
const voicingOrder = [Voicing.voiceless, Voicing.voiced];
const consonants: { [sound: string]: IConsonantData } = {
'p': {
place: PlaceOfArticulation.bilabial,
manner: MannerOfArticulation.stop,
voicing: Voicing.voiceless
},
'b': {
place: PlaceOfArticulation.bilabial,
manner: MannerOfArticulation.stop,
voicing: Voicing.voiced
},
'w': {
place: PlaceOfArticulation.bilabial,
manner: MannerOfArticulation.glide,
voicing: Voicing.voiced
},
'm': {
place: PlaceOfArticulation.bilabial,
manner: MannerOfArticulation.nasal,
voicing: Voicing.voiced
},
'f': {
place: PlaceOfArticulation.labiodental,
manner: MannerOfArticulation.fricative,
voicing: Voicing.voiceless
},
'v': {
place: PlaceOfArticulation.labiodental,
manner: MannerOfArticulation.fricative,
voicing: Voicing.voiced
},
'θ': {
place: PlaceOfArticulation.interdental,
manner: MannerOfArticulation.fricative,
voicing: Voicing.voiceless
},
'ð': {
place: PlaceOfArticulation.interdental,
manner: MannerOfArticulation.fricative,
voicing: Voicing.voiced
},
't': {
place: PlaceOfArticulation.alveolar,
manner: MannerOfArticulation.stop,
voicing: Voicing.voiceless
},
'd': {
place: PlaceOfArticulation.alveolar,
manner: MannerOfArticulation.stop,
voicing: Voicing.voiced
},
's': {
place: PlaceOfArticulation.alveolar,
manner: MannerOfArticulation.fricative,
voicing: Voicing.voiceless
},
'z': {
place: PlaceOfArticulation.alveolar,
manner: MannerOfArticulation.fricative,
voicing: Voicing.voiced
},
'n': {
place: PlaceOfArticulation.alveolar,
manner: MannerOfArticulation.nasal,
voicing: Voicing.voiced
},
'ɾ': {
place: PlaceOfArticulation.alveolar,
manner: MannerOfArticulation.flap,
voicing: Voicing.voiced
},
'l': {
place: PlaceOfArticulation.alveolar,
manner: MannerOfArticulation.lateralLiquid,
voicing: Voicing.voiced
},
'ɹ': {
place: PlaceOfArticulation.alveolar,
manner: MannerOfArticulation.retroflexLiquid,
voicing: Voicing.voiced
},
'ʃ': {
place: PlaceOfArticulation.palatal,
manner: MannerOfArticulation.fricative,
voicing: Voicing.voiceless
},
'ʒ': {
place: PlaceOfArticulation.palatal,
manner: MannerOfArticulation.fricative,
voicing: Voicing.voiced
},
'tʃ': {
place: PlaceOfArticulation.palatal,
manner: MannerOfArticulation.affricate,
voicing: Voicing.voiceless
},
'dʒ': {
place: PlaceOfArticulation.palatal,
manner: MannerOfArticulation.affricate,
voicing: Voicing.voiced
},
'j': {
place: PlaceOfArticulation.palatal,
manner: MannerOfArticulation.glide,
voicing: Voicing.voiced
},
'k': {
place: PlaceOfArticulation.velar,
manner: MannerOfArticulation.stop,
voicing: Voicing.voiceless
},
'g': {
place: PlaceOfArticulation.velar,
manner: MannerOfArticulation.stop,
voicing: Voicing.voiced
},
'ŋ': {
place: PlaceOfArticulation.velar,
manner: MannerOfArticulation.nasal,
voicing: Voicing.voiced
},
'ɫ': {
place: PlaceOfArticulation.velar,
manner: MannerOfArticulation.lateralLiquid,
voicing: Voicing.voiced
},
'ʔ': {
place: PlaceOfArticulation.glottal,
manner: MannerOfArticulation.stop,
voicing: Voicing.voiceless
},
'h': {
place: PlaceOfArticulation.glottal,
manner: MannerOfArticulation.fricative,
voicing: Voicing.voiceless
}
};
const isConsonant = (source: string) => consonants.hasOwnProperty(source);
export {
PlaceOfArticulation, MannerOfArticulation, Voicing,
placeOfArticulationOrder, mannerOfArticulationOrder, voicingOrder,
isConsonant
};
export default consonants; |
99ffe73a31086dc09de10b66635748c65fc0bb59 | TypeScript | BEAR-finance/explorer | /kernel/packages/decentraland-ecs/src/decentraland/math/Vector2.ts | 3.875 | 4 | import { Matrix } from './Matrix'
import { FloatArray, Epsilon } from './types'
import { Scalar } from './Scalar'
/** @public */
export type ReadOnlyVector2 = {
readonly x: number
readonly y: number
}
/**
* Class representing a vector containing 2 coordinates
* @public
*/
export class Vector2 {
/**
* Creates a new Vector2 from the given x and y coordinates
* @param x - defines the first coordinate
* @param y - defines the second coordinate
*/
constructor(
/** defines the first coordinate */
public x: number = 0,
/** defines the second coordinate */
public y: number = 0
) {}
/**
* Gets a new Vector2(0, 0)
* @returns a new Vector2
*/
public static Zero(): Vector2 {
return new Vector2(0, 0)
}
/**
* Gets a new Vector2(1, 1)
* @returns a new Vector2
*/
public static One(): Vector2 {
return new Vector2(1, 1)
}
/**
* Returns a new Vector2 as the result of the addition of the two given vectors.
* @param vector1 - the first vector
* @param vector2 - the second vector
* @returns the resulting vector
*/
public static Add(vector1: ReadOnlyVector2, vector2: ReadOnlyVector2): Vector2 {
return new Vector2(vector1.x, vector1.y).addInPlace(vector2)
}
/**
* Gets a new Vector2 set from the given index element of the given array
* @param array - defines the data source
* @param offset - defines the offset in the data source
* @returns a new Vector2
*/
public static FromArray(array: ArrayLike<number>, offset: number = 0): Vector2 {
return new Vector2(array[offset], array[offset + 1])
}
/**
* Sets "result" from the given index element of the given array
* @param array - defines the data source
* @param offset - defines the offset in the data source
* @param result - defines the target vector
*/
public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector2): void {
result.x = array[offset]
result.y = array[offset + 1]
}
/**
* Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
* @param value1 - defines 1st point of control
* @param value2 - defines 2nd point of control
* @param value3 - defines 3rd point of control
* @param value4 - defines 4th point of control
* @param amount - defines the interpolation factor
* @returns a new Vector2
*/
public static CatmullRom(
value1: ReadOnlyVector2,
value2: ReadOnlyVector2,
value3: ReadOnlyVector2,
value4: ReadOnlyVector2,
amount: number
): Vector2 {
let squared = amount * amount
let cubed = amount * squared
let x =
0.5 *
(2.0 * value2.x +
(-value1.x + value3.x) * amount +
(2.0 * value1.x - 5.0 * value2.x + 4.0 * value3.x - value4.x) * squared +
(-value1.x + 3.0 * value2.x - 3.0 * value3.x + value4.x) * cubed)
let y =
0.5 *
(2.0 * value2.y +
(-value1.y + value3.y) * amount +
(2.0 * value1.y - 5.0 * value2.y + 4.0 * value3.y - value4.y) * squared +
(-value1.y + 3.0 * value2.y - 3.0 * value3.y + value4.y) * cubed)
return new Vector2(x, y)
}
/**
* Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
* If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
* If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
* @param value - defines the value to clamp
* @param min - defines the lower limit
* @param max - defines the upper limit
* @returns a new Vector2
*/
public static Clamp(value: ReadOnlyVector2, min: ReadOnlyVector2, max: ReadOnlyVector2): Vector2 {
let x = value.x
x = x > max.x ? max.x : x
x = x < min.x ? min.x : x
let y = value.y
y = y > max.y ? max.y : y
y = y < min.y ? min.y : y
return new Vector2(x, y)
}
/**
* Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
* @param value1 - defines the 1st control point
* @param tangent1 - defines the outgoing tangent
* @param value2 - defines the 2nd control point
* @param tangent2 - defines the incoming tangent
* @param amount - defines the interpolation factor
* @returns a new Vector2
*/
public static Hermite(
value1: ReadOnlyVector2,
tangent1: ReadOnlyVector2,
value2: ReadOnlyVector2,
tangent2: ReadOnlyVector2,
amount: number
): Vector2 {
let squared = amount * amount
let cubed = amount * squared
let part1 = 2.0 * cubed - 3.0 * squared + 1.0
let part2 = -2.0 * cubed + 3.0 * squared
let part3 = cubed - 2.0 * squared + amount
let part4 = cubed - squared
let x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4
let y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4
return new Vector2(x, y)
}
/**
* Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
* @param start - defines the start vector
* @param end - defines the end vector
* @param amount - defines the interpolation factor
* @returns a new Vector2
*/
public static Lerp(start: ReadOnlyVector2, end: ReadOnlyVector2, amount: number): Vector2 {
let x = start.x + (end.x - start.x) * amount
let y = start.y + (end.y - start.y) * amount
return new Vector2(x, y)
}
/**
* Gets the dot product of the vector "left" and the vector "right"
* @param left - defines first vector
* @param right - defines second vector
* @returns the dot product (float)
*/
public static Dot(left: ReadOnlyVector2, right: ReadOnlyVector2): number {
return left.x * right.x + left.y * right.y
}
/**
* Returns a new Vector2 equal to the normalized given vector
* @param vector - defines the vector to normalize
* @returns a new Vector2
*/
public static Normalize(vector: ReadOnlyVector2): Vector2 {
let newVector = new Vector2(vector.x, vector.y)
newVector.normalize()
return newVector
}
/**
* Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
* @param left - defines 1st vector
* @param right - defines 2nd vector
* @returns a new Vector2
*/
public static Minimize(left: ReadOnlyVector2, right: ReadOnlyVector2): Vector2 {
let x = left.x < right.x ? left.x : right.x
let y = left.y < right.y ? left.y : right.y
return new Vector2(x, y)
}
/**
* Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
* @param left - defines 1st vector
* @param right - defines 2nd vector
* @returns a new Vector2
*/
public static Maximize(left: ReadOnlyVector2, right: ReadOnlyVector2): Vector2 {
let x = left.x > right.x ? left.x : right.x
let y = left.y > right.y ? left.y : right.y
return new Vector2(x, y)
}
/**
* Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
* @param vector - defines the vector to transform
* @param transformation - defines the matrix to apply
* @returns a new Vector2
*/
public static Transform(vector: Vector2, transformation: Matrix): Vector2 {
let r = Vector2.Zero()
Vector2.TransformToRef(vector, transformation, r)
return r
}
/**
* Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
* @param vector - defines the vector to transform
* @param transformation - defines the matrix to apply
* @param result - defines the target vector
*/
public static TransformToRef(vector: ReadOnlyVector2, transformation: Matrix, result: Vector2) {
const m = transformation.m
let x = vector.x * m[0] + vector.y * m[4] + m[12]
let y = vector.x * m[1] + vector.y * m[5] + m[13]
result.x = x
result.y = y
}
/**
* Determines if a given vector is included in a triangle
* @param p - defines the vector to test
* @param p0 - defines 1st triangle point
* @param p1 - defines 2nd triangle point
* @param p2 - defines 3rd triangle point
* @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
*/
public static PointInTriangle(p: ReadOnlyVector2, p0: ReadOnlyVector2, p1: ReadOnlyVector2, p2: ReadOnlyVector2) {
let a = (1 / 2) * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y)
let sign = a < 0 ? -1 : 1
let s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign
let t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign
return s > 0 && t > 0 && s + t < 2 * a * sign
}
/**
* Gets the distance between the vectors "value1" and "value2"
* @param value1 - defines first vector
* @param value2 - defines second vector
* @returns the distance between vectors
*/
public static Distance(value1: Vector2, value2: Vector2): number {
return Math.sqrt(Vector2.DistanceSquared(value1, value2))
}
/**
* Returns the squared distance between the vectors "value1" and "value2"
* @param value1 - defines first vector
* @param value2 - defines second vector
* @returns the squared distance between vectors
*/
public static DistanceSquared(value1: ReadOnlyVector2, value2: ReadOnlyVector2): number {
let x = value1.x - value2.x
let y = value1.y - value2.y
return x * x + y * y
}
/**
* Gets a new Vector2 located at the center of the vectors "value1" and "value2"
* @param value1 - defines first vector
* @param value2 - defines second vector
* @returns a new Vector2
*/
public static Center(value1: ReadOnlyVector2, value2: ReadOnlyVector2): Vector2 {
let center = Vector2.Add(value1, value2)
center.scaleInPlace(0.5)
return center
}
/**
* Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
* @param p - defines the middle point
* @param segA - defines one point of the segment
* @param segB - defines the other point of the segment
* @returns the shortest distance
*/
public static DistanceOfPointFromSegment(p: Vector2, segA: Vector2, segB: Vector2): number {
let l2 = Vector2.DistanceSquared(segA, segB)
if (l2 === 0.0) {
return Vector2.Distance(p, segA)
}
let v = segB.subtract(segA)
let t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2))
let proj = segA.add(v.multiplyByFloats(t, t))
return Vector2.Distance(p, proj)
}
/**
* Gets a string with the Vector2 coordinates
* @returns a string with the Vector2 coordinates
*/
public toString(): string {
return '{X: ' + this.x + ' Y:' + this.y + '}'
}
/**
* Gets class name
* @returns the string "Vector2"
*/
public getClassName(): string {
return 'Vector2'
}
/**
* Gets current vector hash code
* @returns the Vector2 hash code as a number
*/
public getHashCode(): number {
let hash = this.x || 0
hash = (hash * 397) ^ (this.y || 0)
return hash
}
// Operators
/**
* Sets the Vector2 coordinates in the given array or FloatArray from the given index.
* @param array - defines the source array
* @param index - defines the offset in source array
* @returns the current Vector2
*/
public toArray(array: FloatArray, index: number = 0): Vector2 {
array[index] = this.x
array[index + 1] = this.y
return this
}
/**
* Copy the current vector to an array
* @returns a new array with 2 elements: the Vector2 coordinates.
*/
public asArray(): number[] {
let result = new Array<number>()
this.toArray(result, 0)
return result
}
/**
* Sets the Vector2 coordinates with the given Vector2 coordinates
* @param source - defines the source Vector2
* @returns the current updated Vector2
*/
public copyFrom(source: ReadOnlyVector2): Vector2 {
this.x = source.x
this.y = source.y
return this
}
/**
* Sets the Vector2 coordinates with the given floats
* @param x - defines the first coordinate
* @param y - defines the second coordinate
* @returns the current updated Vector2
*/
public copyFromFloats(x: number, y: number): Vector2 {
this.x = x
this.y = y
return this
}
/**
* Sets the Vector2 coordinates with the given floats
* @param x - defines the first coordinate
* @param y - defines the second coordinate
* @returns the current updated Vector2
*/
public set(x: number, y: number): Vector2 {
return this.copyFromFloats(x, y)
}
/**
* Add another vector with the current one
* @param otherVector - defines the other vector
* @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
*/
public add(otherVector: ReadOnlyVector2): Vector2 {
return new Vector2(this.x + otherVector.x, this.y + otherVector.y)
}
/**
* Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
* @param otherVector - defines the other vector
* @param result - defines the target vector
* @returns the unmodified current Vector2
*/
public addToRef(otherVector: ReadOnlyVector2, result: Vector2): Vector2 {
result.x = this.x + otherVector.x
result.y = this.y + otherVector.y
return this
}
/**
* Set the Vector2 coordinates by adding the given Vector2 coordinates
* @param otherVector - defines the other vector
* @returns the current updated Vector2
*/
public addInPlace(otherVector: ReadOnlyVector2): Vector2 {
this.x += otherVector.x
this.y += otherVector.y
return this
}
/**
* Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
* @param otherVector - defines the other vector
* @returns a new Vector2
*/
public addVector3(otherVector: ReadOnlyVector2): Vector2 {
return new Vector2(this.x + otherVector.x, this.y + otherVector.y)
}
/**
* Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
* @param otherVector - defines the other vector
* @returns a new Vector2
*/
public subtract(otherVector: ReadOnlyVector2): Vector2 {
return new Vector2(this.x - otherVector.x, this.y - otherVector.y)
}
/**
* Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
* @param otherVector - defines the other vector
* @param result - defines the target vector
* @returns the unmodified current Vector2
*/
public subtractToRef(otherVector: ReadOnlyVector2, result: Vector2): Vector2 {
result.x = this.x - otherVector.x
result.y = this.y - otherVector.y
return this
}
/**
* Sets the current Vector2 coordinates by subtracting from it the given one coordinates
* @param otherVector - defines the other vector
* @returns the current updated Vector2
*/
public subtractInPlace(otherVector: ReadOnlyVector2): Vector2 {
this.x -= otherVector.x
this.y -= otherVector.y
return this
}
/**
* Multiplies in place the current Vector2 coordinates by the given ones
* @param otherVector - defines the other vector
* @returns the current updated Vector2
*/
public multiplyInPlace(otherVector: ReadOnlyVector2): Vector2 {
this.x *= otherVector.x
this.y *= otherVector.y
return this
}
/**
* Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
* @param otherVector - defines the other vector
* @returns a new Vector2
*/
public multiply(otherVector: ReadOnlyVector2): Vector2 {
return new Vector2(this.x * otherVector.x, this.y * otherVector.y)
}
/**
* Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
* @param otherVector - defines the other vector
* @param result - defines the target vector
* @returns the unmodified current Vector2
*/
public multiplyToRef(otherVector: ReadOnlyVector2, result: Vector2): Vector2 {
result.x = this.x * otherVector.x
result.y = this.y * otherVector.y
return this
}
/**
* Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
* @param x - defines the first coordinate
* @param y - defines the second coordinate
* @returns a new Vector2
*/
public multiplyByFloats(x: number, y: number): Vector2 {
return new Vector2(this.x * x, this.y * y)
}
/**
* Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
* @param otherVector - defines the other vector
* @returns a new Vector2
*/
public divide(otherVector: ReadOnlyVector2): Vector2 {
return new Vector2(this.x / otherVector.x, this.y / otherVector.y)
}
/**
* Sets the "result" coordinates with the Vector2 divided by the given one coordinates
* @param otherVector - defines the other vector
* @param result - defines the target vector
* @returns the unmodified current Vector2
*/
public divideToRef(otherVector: ReadOnlyVector2, result: Vector2): Vector2 {
result.x = this.x / otherVector.x
result.y = this.y / otherVector.y
return this
}
/**
* Divides the current Vector2 coordinates by the given ones
* @param otherVector - defines the other vector
* @returns the current updated Vector2
*/
public divideInPlace(otherVector: ReadOnlyVector2): Vector2 {
return this.divideToRef(otherVector, this)
}
/**
* Gets a new Vector2 with current Vector2 negated coordinates
* @returns a new Vector2
*/
public negate(): Vector2 {
return new Vector2(-this.x, -this.y)
}
/**
* Multiply the Vector2 coordinates by scale
* @param scale - defines the scaling factor
* @returns the current updated Vector2
*/
public scaleInPlace(scale: number): Vector2 {
this.x *= scale
this.y *= scale
return this
}
/**
* Returns a new Vector2 scaled by "scale" from the current Vector2
* @param scale - defines the scaling factor
* @returns a new Vector2
*/
public scale(scale: number): Vector2 {
let result = new Vector2(0, 0)
this.scaleToRef(scale, result)
return result
}
/**
* Scale the current Vector2 values by a factor to a given Vector2
* @param scale - defines the scale factor
* @param result - defines the Vector2 object where to store the result
* @returns the unmodified current Vector2
*/
public scaleToRef(scale: number, result: Vector2): Vector2 {
result.x = this.x * scale
result.y = this.y * scale
return this
}
/**
* Scale the current Vector2 values by a factor and add the result to a given Vector2
* @param scale - defines the scale factor
* @param result - defines the Vector2 object where to store the result
* @returns the unmodified current Vector2
*/
public scaleAndAddToRef(scale: number, result: Vector2): Vector2 {
result.x += this.x * scale
result.y += this.y * scale
return this
}
/**
* Gets a boolean if two vectors are equals
* @param otherVector - defines the other vector
* @returns true if the given vector coordinates strictly equal the current Vector2 ones
*/
public equals(otherVector: ReadOnlyVector2): boolean {
return otherVector && this.x === otherVector.x && this.y === otherVector.y
}
/**
* Gets a boolean if two vectors are equals (using an epsilon value)
* @param otherVector - defines the other vector
* @param epsilon - defines the minimal distance to consider equality
* @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
*/
public equalsWithEpsilon(otherVector: ReadOnlyVector2, epsilon: number = Epsilon): boolean {
return (
otherVector &&
Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) &&
Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
)
}
/**
* Gets a new Vector2 from current Vector2 floored values
* @returns a new Vector2
*/
public floor(): Vector2 {
return new Vector2(Math.floor(this.x), Math.floor(this.y))
}
/**
* Gets a new Vector2 from current Vector2 floored values
* @returns a new Vector2
*/
public fract(): Vector2 {
return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y))
}
// Properties
/**
* Gets the length of the vector
* @returns the vector length (float)
*/
public length(): number {
return Math.sqrt(this.x * this.x + this.y * this.y)
}
/**
* Gets the vector squared length
* @returns the vector squared length (float)
*/
public lengthSquared(): number {
return this.x * this.x + this.y * this.y
}
// Methods
/**
* Normalize the vector
* @returns the current updated Vector2
*/
public normalize(): Vector2 {
let len = this.length()
if (len === 0) {
return this
}
let num = 1.0 / len
this.x *= num
this.y *= num
return this
}
/**
* Gets a new Vector2 copied from the Vector2
* @returns a new Vector2
*/
public clone(): Vector2 {
return new Vector2(this.x, this.y)
}
}
|
384fcc380e0c8870b373c8b397ef2347acfd1beb | TypeScript | ckesoglou/31242-AIP | /src/models/Offer.ts | 2.71875 | 3 | import { Model } from "sequelize";
import User from "./User";
// Class definition
export interface IOfferAttributes {
id: string;
author: string;
completed_by?: string;
proof_of_completion?: string;
details: string;
created_time: Date;
completion_time?: Date;
is_completed: boolean;
}
class Offer extends Model<IOfferAttributes> implements IOfferAttributes {
public id!: string;
public author!: string;
public completed_by!: string;
public proof_of_completion!: string;
public details!: string;
public created_time!: Date;
public completion_time!: Date;
public is_completed!: boolean;
}
// Offer relationships
export async function initialiseOfferRelationships() {
const AuthorForeignKey = {
foreignKey: {
name: "author",
allowNull: false,
},
};
Offer.belongsTo(User, AuthorForeignKey);
User.hasMany(Offer, AuthorForeignKey);
const CompletedByForeignKey = {
foreignKey: {
name: "completed_by",
allowNull: true,
},
};
Offer.belongsTo(User, CompletedByForeignKey);
User.hasMany(Offer, CompletedByForeignKey);
}
export default Offer;
|
43662437600fdb035ea55ee6b276b5f28daa4c69 | TypeScript | arthur791004/react-context-enhancer | /src/Subscription.ts | 2.71875 | 3 | class Subscription {
listeners: Function[] = [];
subscribe = (subscribeFn: Function) => {
this.listeners.push(subscribeFn);
};
unsubscribe = (subscribeFn: Function) => {
this.listeners = this.listeners.filter(
(listener) => listener !== subscribeFn
);
};
notify = () => {
this.listeners.forEach((listener) => listener());
};
}
export default Subscription;
|
acaf06d566bbcd9cfb45b2c656b308b9eafebe20 | TypeScript | Botvinnik94/TFG_SC2_CompetitionManager | /functions/src/dao/firebase/FirebaseBotDAO.ts | 2.546875 | 3 | import { AbstractPlayerDAO } from "../AbstractPlayerDAO";
import { Bot } from "../../model/StarcraftTournamentElements/Bot";
import { Db } from "../../firebase/Db";
import { BotFirebaseConverter } from "./Converters/BotFirebaseConverter";
export class FirebaseBotDAO extends AbstractPlayerDAO<Bot> {
async update(player: Bot): Promise<void> {
const converter = new BotFirebaseConverter();
const target = converter.toFirestore(player);
await Db.collection('bots').doc(player.id).update(target);
}
async findOne(id: string): Promise<Bot> {
const snapshot = await Db.collection('bots').doc(id).get();
const converter = new BotFirebaseConverter();
const bot = converter.fromFirestore(snapshot);
if(bot) return bot;
else throw new Error(`Bot ${id} not found in DB`);
}
} |
d6ab91a33f56707de780572c60a16ad025b4f1f0 | TypeScript | jurnvdwerk/opdracht-spel | /main.ts | 2.953125 | 3 | input.onButtonPressed(Button.A, function () {
sprite.move(-1)
})
input.onButtonPressed(Button.B, function () {
sprite.move(1)
})
let pixel: game.LedSprite = null
let sprite: game.LedSprite = null
basic.showLeds(`
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
`)
basic.showLeds(`
. # # # #
# # # # #
# # # # #
# # # # #
# # # # .
`)
basic.showLeds(`
. . # # #
# # # # #
# # # # #
# # # # #
# # # . .
`)
basic.showLeds(`
. . . # #
# # # # #
# # # # #
# # # # #
# # . . .
`)
basic.showLeds(`
. . . . #
# # # # #
# # # # #
# # # # #
# . . . .
`)
basic.showLeds(`
. . . . .
# # # # #
# # # # #
# # # # #
. . . . .
`)
basic.showLeds(`
. . . . .
# # # # #
# # # # #
. . . . .
. . . . .
`)
basic.showLeds(`
. . . . .
# # # # #
. . . . .
. . . . .
. . . . .
`)
sprite = game.createSprite(2, 4)
basic.forever(function () {
pixel = game.createSprite(randint(0, 4), 0)
while (pixel.get(LedSpriteProperty.Y) < 4) {
pixel.change(LedSpriteProperty.Y, 1)
basic.pause(500)
}
if (pixel.get(LedSpriteProperty.Y) > 3 && pixel.get(LedSpriteProperty.X) != sprite.get(LedSpriteProperty.X)) {
pixel.delete()
sprite.delete()
music.playMelody("C5 B A G F E D C ", 500)
basic.showString("LOSE")
basic.showNumber(game.score())
basic.pause(2000)
sprite = game.createSprite(2, 4)
game.setScore(0)
} else {
game.addScore(1)
pixel.delete()
music.playMelody("C E A C5 - - - - ", 900)
}
})
|
3fe24994186bf8f905da131912ec0a9625fd4183 | TypeScript | Aoi-hosizora/GithubIssueCounter_TamperMonkey | /src/ts/utils.ts | 2.859375 | 3 | import Axios from "axios";
import { Global } from "./global";
/**
* Check the url and return the username or null if this is not a repository list page.
* @param url document url
* @returns username or null
*/
export function checkUrl(url: string): string | null {
const preserveKeywords = [
'', 'pulls', 'issues', 'marketplace', 'explore', 'notifications',
'new', 'login', 'organizations', 'settings', 'dashboard',
'search', 'orgs', 'apps', 'users', 'repos', 'stars', 'account', 'assets'
];
// http://github.com/xxx?xxx#xxx
const result = /https?:\/\/github\.com\/(.*)\?(:?.*)tab=repositories/.exec(url);
if (!result) {
return null;
}
const urlContent = result[1];
if (urlContent.indexOf('/') != -1 || urlContent.indexOf('#') != -1 || preserveKeywords.indexOf(urlContent) != -1) {
return null;
}
return urlContent; // author
}
/**
* Modify the history object to dispatch pushstate, locationchange, replacestate events.
* See https://stackoverflow.com/questions/6390341/how-to-detect-if-url-has-changed-after-hash-in-javascript/52809105#52809105.
*/
export function hookHistory() {
history.pushState = (f => function pushState(data: any, title: string, url?: string | null | undefined) {
var ret = f.call(history, data, title, url);
window.dispatchEvent(new Event('pushstate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.pushState);
history.replaceState = (f => function replaceState(data: any, title: string, url?: string | null | undefined) {
var ret = f.call(history, data, title, url);
window.dispatchEvent(new Event('replacestate'));
window.dispatchEvent(new Event('locationchange'));
return ret;
})(history.replaceState);
window.addEventListener('popstate', () => {
window.dispatchEvent(new Event('locationchange'))
});
}
interface RepoInfo {
open_issues_count: number,
}
/**
* Use github api and get the repository's issue count.
* @param repoName format like `/xxx/yyy`
*/
export function getIssueCount(repoName: string, callback: (count: number) => void) {
const url = `https://api.github.com/repos${repoName}`;
const headers: any = Global.token ? { 'Authorization': `Token ${Global.token}` } : {};
const promise = Axios.request<RepoInfo>({
method: 'get',
url,
headers,
});
promise.then((response) => {
const count = response.data.open_issues_count;
if (count) {
callback(count);
}
}).catch((_) => { });
}
|
ab6e1cd3936c221f9116983c376c9ecb09f05ced | TypeScript | open-flash/avm1-decompiler | /ts/src/lib/cfg/edge.ts | 2.546875 | 3 | import { Action } from "avm1-types/raw/action";
import { PartialExpr } from "../partial-expr";
import { Cfg } from "./cfg";
export type Edge =
ActionEdge
| ConditionalEdge
| ExpressionEdge
| IfFalseEdge
| IfTestEdge
| IfTrueEdge
| MarkerEdge
| SimpleEdge
| SubCfgEdge;
export enum EdgeType {
Action,
Conditional,
Expression,
IfFalse,
IfTest,
IfTrue,
Marker,
Simple,
Sub,
}
export interface ActionEdge<A extends Action = Action> {
readonly type: EdgeType.Action;
readonly action: A;
}
export interface ExpressionEdge {
readonly type: EdgeType.Expression;
readonly expression: PartialExpr;
}
export interface IfTrueEdge {
readonly type: EdgeType.IfTrue;
}
export interface IfFalseEdge {
readonly type: EdgeType.IfFalse;
}
/**
* Represents an edge consuming the test of a `JumpIf` action.
*/
export interface IfTestEdge {
readonly type: EdgeType.IfTest;
}
export interface MarkerEdge {
readonly type: EdgeType.Marker;
readonly marker: Marker;
}
export interface SimpleEdge {
readonly type: EdgeType.Simple;
}
export interface SubCfgEdge {
readonly type: EdgeType.Sub;
}
export interface ConditionalEdge {
readonly type: EdgeType.Conditional;
readonly test: PartialExpr;
readonly ifTrue: Cfg;
readonly ifFalse: Cfg;
}
export type Marker = VariableDefinitionMarker;
export interface VariableDefinitionMarker {
tag: "variable-definition";
name: string;
}
|
d3cb47a227374779ee965e9a660e87c7e9d75d5b | TypeScript | AndrewB330/Jarvis330 | /src/telegram/api_telegram.ts | 2.6875 | 3 | import {Context, Telegraf} from "telegraf";
import {TelegramConfig} from "../config";
import {readFileSync} from "fs";
const TELEGRAM_API = new Telegraf(TelegramConfig.getBotToken());
const ADMIN_CHAT_ID = TelegramConfig.getAdminChatId();
interface KeyboardButton {
text: string;
handler: () => Promise<void>;
}
/*,
reply_markup: {
keyboard:
[[{
text: 'Hello!'
}]]
}*/
const KEYBOARD = [];
export class Telegram {
static async sendMsgToChat(msg: string, chat: number) {
await TELEGRAM_API.telegram.sendMessage(chat, msg, {parse_mode: 'HTML'});
}
static async sendMsgWithPhotoToChat(msg: string, photo: string, chat: number) {
// @ts-ignore
await TELEGRAM_API.telegram.sendPhoto(chat, {source: photo}, {caption: msg, parse_mode: 'HTML'});
}
static addKeyboardButton(button: KeyboardButton) {
KEYBOARD.push(button);
}
static async sendMsgToAdmin(msg) {
await Telegram.sendMsgToChat(msg, ADMIN_CHAT_ID);
}
static async sendMsgWithPhotoToAdmin(msg, photo) {
await Telegram.sendMsgWithPhotoToChat(msg, photo, ADMIN_CHAT_ID);
}
}
async function checkIfNotAdminAndReply(ctx: Context): Promise<boolean> {
if (ctx.chat.id !== ADMIN_CHAT_ID) {
await ctx.replyWithHTML('Sorry, I serve only to my <b>Master</b>. 🧐');
return true;
}
return false;
}
TELEGRAM_API.start(async (ctx) => {
if (await checkIfNotAdminAndReply(ctx)) {
return;
}
await ctx.replyWithHTML('Hello, my <b>Master</b>! 😎');
});
export function startTelegramBot() {
TELEGRAM_API.launch().then(() => console.log('Polling started.')).catch(console.log);
}
|
fee01beecf5cbc82417c8132dc499ee402b9d332 | TypeScript | liviambrasil/api-repoprovas | /src/entities/semesters.ts | 2.546875 | 3 | import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm";
import Subject from "./subjects";
@Entity('semester')
export default class Semester {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => Subject, subject => subject.semesterId)
subject: Subject[];
} |
48b9666beba0bbe0074831f8b3ac2b77b092f8fa | TypeScript | AlexZeitler/react-mvu-todo | /src/Types.d.ts | 2.671875 | 3 | declare type Task = {
id?: number,
title: string,
finished: boolean
}
declare type AppState = Array<Task>
declare type AppMsg = { type: 'AddTask'; task: Task } | { type: 'FinishTask', id: number }
|
f828823d6d8a1f1c21b1c77d962e7560ded6b473 | TypeScript | elzup/tools | /src/components/Kotobaru/useWordle.ts | 2.65625 | 3 | import { useState } from 'react'
import useSWR from 'swr'
import { initGame, WordleGame } from '../../utils/wordle'
type Word = {
full: string
chars: string
}
const wordParse = (text: string): Word[] =>
text
.trim()
.split('\n')
.map((line) => line.split(','))
.map(([full, chars]) => ({ full, chars }))
const fetcher = (url: string) =>
fetch(url)
.then((r) => r.text())
.then(wordParse)
export function useWordle() {
const { data: words } = useSWR('/wordles.nohead.csv', fetcher)
const [_game, _setGame] = useState<WordleGame>(initGame)
return words
}
|
e15171e90fa2f03c0094ef362bcb25964a9a3ac2 | TypeScript | joserochadocarmo/github-vsc | /extensions/github-vsc/src/d.ts/array.d.ts | 2.515625 | 3 | interface Array<T> {
compact(): Array<NonNullable<T>>;
}
|
fa2f708313f76da28962c7060d90bab636ee33a7 | TypeScript | sygnowskip/angular-dynamic-validation | /library/src/services/object-merge/object-merge.service.ts | 2.671875 | 3 | import { Injectable } from "@angular/core";
@Injectable()
export class ObjectMergeService {
public deepMerge(jsonRules: any, customRules: any) {
const isObject = (item: any) => (item && typeof item === 'object' && !Array.isArray(item));
const output = Object.assign({}, jsonRules);
if (isObject(jsonRules) && isObject(customRules)) {
Object.keys(customRules).forEach(key => {
if (isObject(customRules[key])) {
if (!(key in jsonRules)) {
Object.assign(output, { [key]: customRules[key] });
} else {
output[key] = this.deepMerge(jsonRules[key], customRules[key]);
}
} else {
Object.assign(output, { [key]: customRules[key] });
}
});
}
return output;
}
}
|
d4399c04f8e813aeb86e6e469453633dcc48ead2 | TypeScript | HelloContract/cosmos-staking-dapp | /src/__test__/validator.test.ts | 3.015625 | 3 | import { validDelegate, validUndelegate, isDecimalOverflow } from '../lib/validator'
describe('test isDecimalOverflow', () => {
const cases = [{
num: '0',
places: 6,
result: false
}, {
num: '0.00001',
places: 6,
result: false
}, {
num: '0.0000000001',
places: 6,
result: true
}, {
num: '',
places: 6,
result: false
}]
cases.forEach(c => {
it(`isDecimal: ${c.num} overflow ${c.places} => ${c.result}`, () => {
expect(isDecimalOverflow(c.num, c.places)).toEqual(c.result)
})
})
})
describe('test validDelegate', () => {
const cases = [
{
inputAmount: 'aaaa',
availableAmount: 7,
feeAmount: 1,
isRedelegate: false,
result: [false, 'invalid_number'],
},
{
inputAmount: undefined,
availableAmount: 7,
feeAmount: 1,
isRedelegate: false,
result: [false, 'invalid_number'],
}, {
inputAmount: 0,
availableAmount: 7,
feeAmount: 1,
isRedelegate: false,
result: [false, 'number_must_be_positive']
}, {
inputAmount: '0.1',
availableAmount: 7,
feeAmount: 1,
isRedelegate: false,
result: [false, 'decimal_length_must_lt_six']
}, {
inputAmount: '81000000',
availableAmount: 7000000,
feeAmount: 1000000,
isRedelegate: false,
result: [false, 'more_than_available']
}, {
inputAmount: 6100000,
availableAmount: 7000000,
feeAmount: 1000000,
isRedelegate: false,
result: [false, 'fee_not_enough']
},
{
inputAmount: 9000000,
availableAmount: 7000000,
feeAmount: 1100000,
availableBalance: 2000000,
isRedelegate: true, // redelegate
result: [false, 'more_than_available']
},
{
inputAmount: 6000000,
availableAmount: 7000000,
feeAmount: 2000000,
availableBalance: 1000000,
isRedelegate: true, // redelegate
result: [false, 'fee_not_enough']
},
{
inputAmount: 6000000,
availableAmount: 7000000,
feeAmount: 2000000,
availableBalance: 3000000,
isRedelegate: true, // redelegate
result: [true, null]
}, {
inputAmount: 4,
availableAmount: 7,
feeAmount: 1,
isRedelegate: false,
result: [true, null]
}, {
inputAmount: 6,
availableAmount: 7,
feeAmount: 1,
isRedelegate: false,
result: [true, null]
}]
cases.forEach(c => {
it(`validDelegate: ${c.inputAmount} ${c.availableAmount} ${c.feeAmount} ${c.availableBalance} => ${c.result}`, () => {
expect(validDelegate(c.inputAmount, c.availableAmount, c.feeAmount, c.isRedelegate, c.availableBalance)).toEqual(c.result)
})
})
})
describe('test validUndelegate', () => {
const cases = [
{
inputAmount: 'aaaa',
delegatedNumber: 9,
availableBalance: 7,
feeAmount: 1,
result: [false, 'invalid_number']
},
{
inputAmount: undefined,
delegatedNumber: 9,
availableBalance: 7,
feeAmount: 1,
result: [false, 'invalid_number']
}, {
inputAmount: 0,
delegatedNumber: 9,
availableBalance: 7,
feeAmount: 1,
result: [false, 'number_must_be_positive']
}, {
inputAmount: '0.000000001',
delegatedNumber: 9,
availableBalance: 7,
feeAmount: 1,
result: [false, 'decimal_length_must_lt_six']
}, {
inputAmount: 10,
delegatedNumber: 9,
availableBalance: 3,
feeAmount: 1,
result: [false, 'more_than_available']
}, {
inputAmount: 8,
delegatedNumber: 9,
availableBalance: 3,
feeAmount: 4,
result: [false, 'fee_not_enough']
}, {
inputAmount: 4,
delegatedNumber: 9,
availableBalance: 1,
feeAmount: 1,
result: [true, null]
}, {
inputAmount: 9,
delegatedNumber: 9,
availableBalance: 1,
feeAmount: 1,
result: [true, null]
}]
cases.forEach(c => {
it(`validUndelegate: ${c.inputAmount} ${c.delegatedNumber} ${c.availableBalance} ${c.feeAmount} => ${c.result}`, () => {
expect(validUndelegate(c.inputAmount, c.delegatedNumber, c.feeAmount, c.availableBalance)).toEqual(c.result)
})
})
}) |
3e9a1ffbd77a5139ceafc550bf80c479ae85c44d | TypeScript | tarepan/TheHome | /src/widgets/sleeps/domain.ts | 3.203125 | 3 | import { DateTime as dt, Duration } from "luxon";
// domain: sleepHistroy => sleep indexes
type wakeupUNIXtime = number;
// e.g. 1572534000000 for "2019-11-01T00:00:00+09:00"
type sleepLengthUNIXtime = number;
// e.g. 25200000 for "just 7 hours"
// data
export type SleepRecord = [wakeupUNIXtime, sleepLengthUNIXtime];
export type SleepHistroy = SleepRecord[];
// indexes
type latestWakeupUNIXtime = number;
type latestLengthUNIXtime = number;
type wasGoodWakeup = boolean;
// behaviors
type history2latestWakeup = (sleeps: SleepHistroy) => latestWakeupUNIXtime;
type history2latestLength = (sleeps: SleepHistroy) => latestLengthUNIXtime;
type histroy2latestEvaluation = (
sleeps: SleepHistroy,
targetHour: number,
targetMinute: number
) => wasGoodWakeup;
// implementations
export const histroy2Wakeup: history2latestWakeup = history =>
history[history.length - 1][0];
export const history2Length: history2latestLength = history =>
history[history.length - 1][1];
export const history2wasGoodWakeup: histroy2latestEvaluation = (
history,
targetWakeupHour,
targetWakeupMin
) => {
const latestSleep = history[history.length - 1];
const wakeupDT = dt.fromMillis(latestSleep[0]);
const overWakeupHour = wakeupDT.hour - targetWakeupHour;
const overWakeupMin = wakeupDT.minute - targetWakeupMin;
return overWakeupHour < 0 || (overWakeupHour == 0 && overWakeupMin <= 0);
};
// console.log(history2wasGoodWakeup([[1572562800000, 25200000]], 7, 59));
// future: sleep length evaluation
|