Datasets:

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
92a5ffa3c0f770c630cd7b0b9808c3694bc4a87a
TypeScript
bakesaled/avocado
/src/services/coordinate.service.ts
3.265625
3
import { Vehicle } from '../models/vehicle'; import { Coordinate } from '../models/coordinate'; import { Direction } from '../models/direction'; export class CoordinateService { public static moveVehicle(vehicle: Vehicle) { vehicle.move(this.getNextCoordinate(vehicle.currentCoordinate, vehicle.currentDirection)); } public static getNextCoordinate(currentCoordinate: Coordinate, direction: Direction) { switch (direction) { case Direction.Up: return new Coordinate(currentCoordinate.x, currentCoordinate.y - 1); case Direction.Down: return new Coordinate(currentCoordinate.x, currentCoordinate.y + 1); case Direction.Left: return new Coordinate(currentCoordinate.x - 1, currentCoordinate.y); case Direction.Right: return new Coordinate(currentCoordinate.x + 1, currentCoordinate.y); } } }
e319b080220706c48c3f8e3304c09442a7d1aa78
TypeScript
pokatomnik/file-server
/src/server.ts
2.53125
3
// Imports import type { KindResponse, Request, Response } from "./types.ts"; import { serve, serveTLS, resolve, extname, join, ms, renderFileToString, html } from "./deps.ts"; import { Cache } from "./Cache.ts"; import { Logger } from "./Logger.ts"; import { canRead, fileType, toReadableSize } from "./util.ts"; import { bundle } from "./bundler.ts"; async function findIndexInDirectory (path: string, indexes: string[]): Promise<string | void> { if (await canRead(path)) { const stat = await Deno.lstat(path); if (stat.isDirectory) { for (let indexFile of indexes) { const p = await findIndexInDirectory(resolve(join(path, indexFile)), indexes); if (p) return p; } } else { return path; } } } async function getEntries (dir: string): Promise<({ name: string, size?: string })[]> { const directories: ({ name: string })[] = [ ]; const files: ({ name: string, size: string })[] = [ ]; for await (let entry of Deno.readDir(dir)) { if (entry.isFile) files.push({ name: entry.name, size: toReadableSize((await Deno.lstat(join(dir, entry.name))).size) }); if (entry.isDirectory) directories.push({ name: entry.name }); } return [ { name: "." }, { name: ".." }, ...directories.sort((a, b) => a.name.localeCompare(b.name)), ...files.sort((a, b) => a.name.localeCompare(b.name)) ]; } async function indexDirectory (req: Request) { const body = html` <!DOCTYPE html5> <html> <head> <meta charset="UTF-8" /> <title>${req.url.pathname}</title> </head> <body> <h1>Directory Listing</h1> <p>${req.url.pathname}</p> <ul> ${(await getEntries(req.path)).map(entry => `<li><a href="${resolve(join(req.url.pathname, entry.name))}">${entry.name}</a>${entry.size !== undefined ? ` (${entry.size})` : ""}</li>`).join("")} </ul> </body> </html> `; await req.respond({ body, status: 200, headers: { "Content-Type": fileType("_.html") } }); } export async function server ( { directory, port, host, cert, key, cache, lifetime, cors, indexing, indexes, ejs, typescript, logging, debug, colors }: { directory: string, port: number, host: string, cert?: string, key?: string, cache: boolean, lifetime: number, cors: boolean, indexing: boolean, indexes: string[], ejs: boolean, typescript: boolean, logging: boolean, debug: boolean, colors: boolean } ) { // Init. const logger = new Logger({ colors, debug, output: logging }); const cached = new Cache(cache, lifetime); // Verify that the directory is readable and // is indeed a directory. if (!await canRead(directory)) { logger.error("Cannot read from directory %s", directory); Deno.exit(1); } if (!(await Deno.lstat(directory)).isDirectory) { logger.error("Path must be a directory!"); Deno.exit(1); } // Verify that both cert and key is readable. let useTLS: boolean = false; if (cert || key) { if (cert === "" || key === "") { logger.error("Both cert and key must be defined to use TLS!"); Deno.exit(1) } if (!await canRead(cert!)) { logger.error("Cannot read certificate file!"); Deno.exit(1); } if (!await canRead(key!)) { logger.error("Cannot read key file!"); Deno.exit(1); } useTLS = true; } // Create a server object. const s = !useTLS ? serve({ port, hostname: host }) : serveTLS({ port, hostname: host, certFile: cert!, keyFile: key! }); // Address details. const _host: string = (s.listener.addr as any).hostname; const _port: number = (s.listener.addr as any).port; const _usePort = (useTLS && _port !== 443) || (!useTLS && _port !== 80); const _origin: string = "http" + (useTLS ? "s" : "") + "://" + _host + (_usePort ? ":" + _port : ""); logger.info("Server listening on %s", _origin); // Listen for requests. for await (let _request of s) { const start = Date.now(); // Build a new request object. const req: Request = _request as any as Request; req.url = new URL(_origin + _request.url); req.path = resolve(join(directory, resolve("/", req.url.pathname))); req.__respond__ = _request.respond; let hasResponded: boolean = false; req.respond = async (response: KindResponse) => { if (hasResponded) throw new Error("A response has already been sent!"); hasResponded = true; if (!(response.headers instanceof Headers)) { if (typeof response.headers === "object" && response.headers !== null) { const h = new Headers(); for (let key in response.headers!) h.set(key, (response.headers as any)![key]!); response.headers = h; } else { response.headers = new Headers(); } } response.headers.set("Content-Length", response.body?.toString().length.toString() || "".length.toString()); if (cors) response.headers.set("Access-Control-Allow-Origin", req.headers.get("origin") || req.headers.get("Origin") || "*"); if (response.cache === true) { response.cache = true; cached.save(req, response as Response); } const _ = ms(Date.now() - start) as string; if (response.body instanceof Uint8Array) response.body = response.body.reduce((str, char) => str += String.fromCharCode(char), ""); const sizeStr = debug ? " (" + toReadableSize((response.body as string || "").length) + ")" : ""; await req.__respond__({ body: response.body, headers: response.headers, status: response.status, trailers: response.trailers }).then(() => { logger.info( "%s %s %d %s %s%s" + ((response.status!||0) >= 500 ? " - %s" : ""), ...[ req.method, (req.conn.remoteAddr as any).hostname, response.status || 200, _, req.url.pathname, sizeStr, ...((response.status!||0) >= 500 ? [ response.body! ] : []) ] ); }).catch(error => { logger.error( "%s %s %d %s %s%s - %s", req.method, (req.conn.remoteAddr as any).hostname, response.status || 0, _, req.url.pathname, sizeStr, debug ? error.stack : error.message ); }); }; // logger.debug( // "%s %s %s", // req.method, // (req.conn.remoteAddr as any).hostname, // req.url.pathname // ); // Check if the cache already has a response // for this request. let cachedResponse = cached.response(req); if (cachedResponse) { await req.respond(cachedResponse); } else { try { const path = await findIndexInDirectory(req.path, indexes); if (path) { req.path = path; const ext = extname(path).toLowerCase(); if (ejs && ext === ".ejs") { const data = { req, headers: { "Content-Type": fileType("_.html") } }; const body = await renderFileToString(path, data); await req.respond({ body, status: 200, headers: data.headers }); } else if ( typescript && ( ext === ".ts" || ext === ".js" || ext === ".tsx" || ext === ".jsx" ) ) { try { let _ = await bundle(directory, path); _.output = _.output.replaceAll(directory, "/"); if (_.error) throw new Error(_.output); await req.respond({ body: _.output, status: 200, headers: { "Content-Type": fileType("_.js") }, cache: true }); } catch (error) { await req.respond({ body: error.message, status: 500 }); } } else { const body = await Deno.readTextFile(path); await req.respond({ body, status: 200, headers: { "Content-Type": fileType(path) }, cache: true }); } } else if (indexing && await canRead(req.path) && (await Deno.lstat(req.path)).isDirectory) { await indexDirectory(req); } } catch (error) { await req.respond({ body: debug ? error.stack : error.message, status: 500 }); } if (!hasResponded) { const htmlPath = resolve(directory, "404.html"); const ejsPath = resolve(directory, "404.ejs"); if (await canRead(htmlPath)) { const body = await Deno.readTextFile(htmlPath); await req.respond({ body, status: 404, headers: { "Content-Type": fileType(htmlPath) } }); } else if (ejs && await canRead(ejsPath)) { const data = { req, headers: new Headers() }; data.headers.set("Content-Type", fileType(htmlPath)); const body = await renderFileToString(ejsPath, data); await req.respond({ body, status: 404, headers: data.headers }); } else { await req.respond({ body: `Cannot get ${req.url.pathname}!`, status: 404, headers: { "Content-Type": fileType(htmlPath) } }); } } } } }
5a5bff969b22336cf26028b55ec73464ef0660bb
TypeScript
hardfist/stackoverflow
/packages/typescript/src/polymorphism/ad_hoc/adt/expr.ts
3.84375
4
type Expr = Add | Mult | Num type Num = { kind: 'num', val: number } type Add = { kind: 'add', left: Expr, right: Expr } type Mult = { kind: 'mult', left: Expr, right: Expr } function add(left: Expr, right: Expr){ return { kind: 'add', left, right } as const; } function mult(left: Expr, right: Expr){ return { kind: 'mult', left, right } as const; } function num(val: number){ return { kind: 'num', val } as const; } export function eval_expr(expr: Expr): number{ switch(expr.kind){ case 'num': return expr.val; case 'add': return eval_expr(expr.left) + eval_expr(expr.right); case 'mult': return eval_expr(expr.left) * eval_expr(expr.right) } } console.log(eval_expr( add( mult( num(1), num(2) ), mult( num(3), num(4) ) ) ));
679d37a8438ebcc6daed015916404b3396ccaa08
TypeScript
cunvoas/ecoledirecte.js
/lib/accounts/Teacher.ts
2.515625
3
import { Account } from "./Account"; import { Session } from "../Session"; import { loginResSuccess, teacherAccount, isTeacherAccount, } from "ecoledirecte-api-types/v3"; import { getMainAccount, fetchPhoto } from "../util"; export class Teacher extends Account { public type: "teacher" = "teacher"; private account: teacherAccount; constructor(private session: Session) { super(session); const mainAccount = getMainAccount( (session.loginRes as loginResSuccess).data.accounts ); if (!isTeacherAccount(mainAccount)) throw new Error("Teacher class's main account is wrong"); if (!session.token) throw new Error("Account class MUST have token"); this.account = mainAccount; this.token = session.token; } private _photo?: Buffer; private _photoUri?: string; async getPhoto(): Promise<Buffer | undefined> { const r = await fetchPhoto(this); if (!r) return; const [buf, str] = r; this._photo = buf; this._photoUri = str; return buf; } get photo(): { buffer?: Buffer; uri?: string; } { return { buffer: this._photo, uri: this._photoUri, }; } get _raw(): teacherAccount { return this.account; } }
2feb7bbae9597063455978a505522ef3a8bf4d11
TypeScript
snewell92/newhotness
/public/src/app/app.component.ts
2.609375
3
import { Component, ElementRef, Type } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1>Hello {{name}}</h1><p>In angular world and we see this page is {{page}}</p>` }) export class AppComponent { name = 'Angular'; page: string; constructor(elm: ElementRef) { this.page = elm.nativeElement.attributes["page"].value; // dynamically load component based on name to load page content /* var factories = Array.from(this.resolver['_factories'].keys()); var factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp); const factory = this.resolver.resolveComponentFactory(factoryClass); const compRef = this.vcRef.createComponent(factory); */ // above code belongs in its own service. Since this is the main bootstrapped component, this will be responsible for // grabbing the page name and loading the correct component, using the aforementioned service. // There's a plunker here demonstrating that http://plnkr.co/edit/AhUmUZwNIqnM0EraDVVB?p=preview // there's also this similar way, but cleaner service API http://stackoverflow.com/a/38467952/2378943 } }
edeafe670e36348449a0a6358b839487091cb074
TypeScript
abnerFCR/OLC2-P2
/src/interprete/Expresion/AccesoTipo.ts
2.9375
3
import { Instruccion } from '../Abstracto/Instruccion'; import { Expresion } from '../Abstracto/Expresion'; import { Entorno } from '../Simbolo/Entorno'; import { Retorno, Tipo } from '../Abstracto/Retorno'; import { Type_ } from '../Objetos/Type_'; import { Error_ } from '../Errores/Error'; export class AccesoTipo extends Expresion{ private id1:string; private id2:string; private anterior:Expresion |null; constructor(id1:string, id2:string, anterior:Expresion|null, fila:number, columna:number){ super(fila, columna); this.id1 = id1; this.id2 = id2; this.anterior = anterior; } public ejecutar(entorno: Entorno): Retorno { if(this.anterior == null){ let variableId1 = entorno.getVar(this.id1); if(variableId1 == null){ throw new Error_(this.linea, this.columna, "Semantico", "El tipo '"+this.id1+"' no existe"); } if(variableId1?.valor instanceof Type_){ let valorId1 = variableId1.valor as Type_; if(valorId1.getAtributo(this.id2) == null){ throw new Error_(this.linea, this.columna, "Semantico", "La variable '"+this.id2+"' no existe"); } let respuesta= valorId1.getAtributo(this.id2).valor; if(respuesta == null){ return {valor:null, tipo:Tipo.TYPE} } if(respuesta instanceof Type_){ //return {valor:valorId1.getAtributo(this.id2).valor, tipo:valorId1.getAtributo(this.id2).valor.tipo}; } return {valor:valorId1.getAtributo(this.id2).valor, tipo:valorId1.getAtributo(this.id2).tipo}; }else{ throw new Error_(this.linea, this.columna, "Semantico", "No es una instancia de tipo"); } }else{ let anterior = this.anterior.ejecutar(entorno); let x = anterior.valor as Type_; if(x == null){ throw new Error_(this.linea, this.columna, "Semantico", "Error al acceder a los parametros del tipo"); } let z = x.getAtributo(this.id1); if(z == null){ throw new Error_(this.linea, this.columna, "Semantico", "No existe el parametro '"+this.id1+"' en este tipo"); } return {valor: z?.valor, tipo:z?.tipo}; } return null; } }
dfc569bd3afcfb05cab0274d8586551108935060
TypeScript
ahmetikrdg/TypeScript-Tutorial
/1.3-Function/function.ts
3.578125
4
//Ortalama hesaplaması yapan fonksiyon function getAverage(a:number,b:number,c:number):string{//dışarıdan a,b,c değerlerini number olarak aldım ve geriye bunları hesaplama sonucu string olarak dön dedim const result=(a+b+c)/3;// gelen paremetre toplanır 3'e bölünür return 'result: '+result;//daha sonra ise sonucumu döndürdüm } /*Aklımıza şu soru gelebilir a:number yazmak ne işimize yaradı? eğer a,b,c şeklinde verseydik sayı gönderseydik sıkıntı olmazdı fakat harfte versen başta hata vermezdi. a:number ... diyerek ben aşağıda fonksiyonuma harf verirsem artık anında hata verecektir uyaracaktır.*/ getAverage(10,20,30);//fonksiyonun beklediği sayısal değerleri gönderdim. /* ŞİMDİİ BİR ÖRNEK DAHA YAPALIM EĞER 3 SAYI VERMEK İSTESEYDİK */ function getAverage2(a:number,b:number,c?:number):string{ //(a:number,b:number,c?:number) cden sonra "?" koydum.Bu şu demek istersen c'ye değer atamayabilirsin hata vermez let total=a+b;// a değer ile b değerini topladım örn: 10+20=30. 30 sonucunu total değeri içine attım. let count=2;// a,b count 2. henüz 2 değer geldi. if (typeof c!=='undefined') {//c değeri undefined yani tanımsız belirsiz değilse içinde değer varsa total =total+c;// yukarıdaki total ile c'nin içindeki değeri topla count++;//count değerinide bir arttır 3 yap } const result=total/count;//daha sonra toplamı kaç değer gönderildiyse ona böl. return 'result: '+result; } getAverage2(10,20); /* PEKİ DİLEDİĞİMİZ KADAR SAYI GÖNDERMEK İSTESEYDİK İŞTE BURADA KONUYA REST PARAMETERS DAHİL OLUR */ function getAverage3(...a:number[]):string{//gelecek değere a dedim değerinide number dizisi olarak belirttim let total=0;//çünkü ne geleceğini bilmiyoruz 0'dan başlattık let count=0; for (let i = 0; i < a.length; i++) {//0 dan başla a'ya kaç değer gönderdiysem toplam sayısını al 10 değer gönderdim. bir bir arttır. total =total+a[i];//a'nın içindeki değerleri bir bir arttırarak totala at orada ise toplamına işlemi olur. count++;//ve her for döndüğünde burayıda bir arttır. } const result=total/count; //total 550 count ise 10 return 'result: '+result;//sonuç: 55 } //getAverage3(10,20,30,40,50,60,70,80,90,100); //isterseniz sonucu görelim bunun için fonksiyonu consta atıp daha sonra bunu console.logla yazdıracağım. const Result=getAverage3(10,20,30,40,50,60,70,80,90,100); console.log(Result); //Console çıktısı: 55
bd22b9981816ccb6b6c6bf7b1a417c624011b48b
TypeScript
rbuetzer/kinder
/src/redux/sagas.ts
2.609375
3
import { call, put, select, takeEvery } from "redux-saga/effects"; import { TActionType } from "./types"; import { nameListActions } from "./nameListStore"; import { getNameIdsInStack, stackStoreActions } from "./stackStore"; import { pickRandomElement } from "../utils/array"; import { Action } from "redux"; import { appAction } from "./appStore"; import { SubPage } from "../models/SubPage"; const ACTION_IMPORT_FILE = "importFile"; const ACTION_IMPORT_NAMES = "importNames"; const ACTION_UPVOTE = "upvote"; const ACTION_DOWNVOTE = "downvote"; const ACTION_NEXT_CARD = "nextCard"; export const sagaActions = { importFile: (fileContent: string) => ({ type: ACTION_IMPORT_FILE, fileContent }), importNames: (names: string[]) => ({ type: ACTION_IMPORT_NAMES, names }), upvote: () => ({ type: ACTION_UPVOTE }), downvote: () => ({ type: ACTION_DOWNVOTE }), nextCard: () => ({ type: ACTION_NEXT_CARD }) }; type TAction = TActionType<typeof sagaActions>; export function* importFileSaga( action: ReturnType<typeof sagaActions.importFile> ) { const array = action.fileContent .split("\n") .map(string => string.replace(/^\s+|\s+$/g, "")) .filter(string => string.length > 0); yield put(sagaActions.importNames(array)); yield put(appAction.selectSubPage(SubPage.Voting)); } export function* importNamesSaga( action: ReturnType<typeof sagaActions.importNames> ) { yield put(nameListActions.importNames(action.names)); yield put(stackStoreActions.init(action.names.map((_, i) => i))); yield put(sagaActions.nextCard()); } function* nextCardSaga(action: ReturnType<typeof sagaActions.importNames>) { const nameIds = yield select(getNameIdsInStack); const pickedCardId = yield call(pickRandomElement(), nameIds); yield put(stackStoreActions.pickCard(pickedCardId)); } function* voteSaga(voteActionCreator: (id: number) => Action) { const id = yield select(state => state.stack.currentNameId); yield put(voteActionCreator(id)); yield put(sagaActions.nextCard()); } function* upvoteSaga() { yield voteSaga(nameListActions.upvote); } function* downvoteSaga() { yield voteSaga(nameListActions.downvote); } export function* sagas() { yield takeEvery(ACTION_IMPORT_FILE, importFileSaga); yield takeEvery(ACTION_IMPORT_NAMES, importNamesSaga); yield takeEvery(ACTION_NEXT_CARD, nextCardSaga); yield takeEvery(ACTION_UPVOTE, upvoteSaga); yield takeEvery(ACTION_DOWNVOTE, downvoteSaga); }
b55385b727916ea66d5e797458bb5d44b5ebd640
TypeScript
AlogyStudy/v-ts
/src/utils/sha1.ts
3.109375
3
// base64(sha1(base64(sha1($password)) + $salt)) function Encode(this: any) { var _ = this; var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // 内部使用 var _utf8_encode = function (string: any) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }; // base64加密,公共可对外调用 this.encodeBase64 = function (input: any) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = _utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); } return output; }; // sha1 this.encodeSha1 = function (inp: any) { return b64_sha1(inp); }; // encode password -- base64(sha1(base64(sha1($password)) + $salt)) -- this.encodePsw = function (psw: any) { var salt = new Date().getTime(); return { salt: salt, token: _.encodeSha1(_.encodeSha1(psw) + salt) }; }; this.hex_sha1 = hex_sha1; } // sha1 /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ var b64pad = "="; /* base-64 pad character. "=" for strict RFC compliance */ var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function hex_sha1(s: any) { return binb2hex(core_sha1(str2binb(s), s.length * chrsz)); } function b64_sha1(s: any) { return binb2b64(core_sha1(str2binb(s), s.length * chrsz)); } function str_sha1(s: any) { return binb2str(core_sha1(str2binb(s), s.length * chrsz)); } function hex_hmac_sha1(key: any, data: any) { return binb2hex(core_hmac_sha1(key, data)); } function b64_hmac_sha1(key: any, data: any) { return binb2b64(core_hmac_sha1(key, data)); } function str_hmac_sha1(key: any, data: any) { return binb2str(core_hmac_sha1(key, data)); } /* * Perform a simple self-test to see if the VM is working */ function sha1_vm_test() { return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d"; } /* * Calculate the SHA-1 of an array of big-endian words, and a bit length */ function core_sha1(x: any, len: any) { /* append padding */ x[len >> 5] |= 0x80 << (24 - len % 32); x[((len + 64 >> 9) << 4) + 15] = len; var w = Array(80); var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var e = -1009589776; for (var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; var olde = e; for (var j = 0; j < 80; j++) { if (j < 16) w[j] = x[i + j]; else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1); var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = rol(b, 30); b = a; a = t; } a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); e = safe_add(e, olde); } return Array(a, b, c, d, e); } /* * Perform the appropriate triplet combination function for the current * iteration */ function sha1_ft(t: any, b: any, c: any, d: any) { if (t < 20) return (b & c) | ((~b) & d); if (t < 40) return b ^ c ^ d; if (t < 60) return (b & c) | (b & d) | (c & d); return b ^ c ^ d; } /* * Determine the appropriate additive constant for the current iteration */ function sha1_kt(t: any) { return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514; } /* * Calculate the HMAC-SHA1 of a key and some data */ function core_hmac_sha1(key: any, data: any) { var bkey = str2binb(key); if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz); var ipad = Array(16), opad = Array(16); for (var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz); return core_sha1(opad.concat(hash), 512 + 160); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x: any, y: any) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function rol(num: any, cnt: any) { return (num << cnt) | (num >>> (32 - cnt)); } /* * Convert an 8-bit or 16-bit string to an array of big-endian words * In 8-bit function, characters >255 have their hi-byte silently ignored. */ function str2binb(str: any) { var bin = Array(); var mask = (1 << chrsz) - 1; for (var i = 0; i < str.length * chrsz; i += chrsz) bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i % 32); return bin; } /* * Convert an array of big-endian words to a string */ function binb2str(bin: any) { var str = ""; var mask = (1 << chrsz) - 1; for (var i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i >> 5] >>> (32 - chrsz - i % 32)) & mask); return str; } /* * Convert an array of big-endian words to a hex string. */ function binb2hex(binarray: any) { var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var str = ""; for (var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF); } return str; } /* * Convert an array of big-endian words to a base-64 string */ function binb2b64(binarray: any) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var str = ""; for (var i = 0; i < binarray.length * 4; i += 3) { var triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF); for (var j = 0; j < 4; j++) { if (i * 8 + j * 6 > binarray.length * 32) str += b64pad; else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F); } } return str; } export default Encode
3d34e5dc5ad9d42426835e5d322520a9c90f7e26
TypeScript
mayacoda/CS370
/demo/common/gui.ts
2.84375
3
import {GameScene} from "../../engine-lib/data"; import {randomRangeInt} from "../../engine-lib/utilities"; import {createElement} from "./gui-util"; import {createHighScoreButton, createPausePlayButton, createRestartButton} from "./gui-footer"; let timeout: number; export function initGui(scene: GameScene, callbacks: { pausePlayCallback: (state: boolean) => void, restartCallback: () => void }) { const gui = scene.getGUI(); gui.setDefaultGuiStyle('flex-direction: column; justify-content: space-between') const header = createElement('header'); header.appendChild(createElement('time')); const scoreElement = createElement('score'); header.appendChild(scoreElement); const {pausePlayCallback, restartCallback} = callbacks; const footer = createElement('footer'); footer.appendChild(createHighScoreButton(scene)) footer.appendChild(createPausePlayButton(pausePlayCallback)) footer.appendChild(createRestartButton(restartCallback)) gui.addElement(header); gui.addElement(createElement('exclamation')) gui.addElement(footer); } export function showInstructions(scene: GameScene, text: string[], onFinish: () => void, buttonText: string = 'Woof! Woof! (Continue)') { if (text.length === 0) { onFinish(); return; } const gui = scene.getGUI(); const overlay = createElement('full-screen-overlay'); const instructions = createElement('instructions'); const instructionsText = createElement('instructions-text', 'p'); const continueButton = createElement('continue', 'button'); overlay.classList.add('instructions-overlay'); overlay.appendChild(instructions) instructions.appendChild(instructionsText); instructions.appendChild(continueButton) gui.addElement(overlay); instructionsText.innerHTML = text[0] let page = 0; continueButton.textContent = buttonText; continueButton.addEventListener('click', () => { page++; if (page >= text.length) { onFinish() gui.removeElement(overlay) } else { instructionsText.innerHTML = text[page]; } }) } export function restartGui(scene: GameScene) { const gui = scene.getGUI(); gui.getElement('.time').innerHTML = ''; gui.getElement('.score').innerHTML = ''; } export function showExclamation(scene: GameScene, text: string) { const exclamation = scene.getGUI().getElement('.exclamation'); exclamation.innerHTML = text if (timeout) window.clearTimeout(timeout); timeout = window.setTimeout(() => { exclamation.innerHTML = '' }, 3000); } export function writeNewScore(scene: GameScene, score: number) { const scoreElement = scene.getGUI().getElement('.score'); scoreElement.innerHTML = score.toString(); } export function getExclamationText(score: number, maxScore: number) { if (score === Math.floor(maxScore / 2)) return 'Half way there!' if (score === maxScore - 1) return 'One more to go!' return ['Score!', 'Awesome!', 'Keep Going!'][randomRangeInt(0,2)] }
51e4dacec8211055c0fead14cc46fbda8008152c
TypeScript
mshivam76/image-filter-starter-code
/src/server.ts
2.984375
3
import express from 'express'; import bodyParser from 'body-parser'; import {filterImageFromURL, deleteLocalFiles} from './util/util'; (async () => { // Init the Express application const app = express(); // Set the network port const port = process.env.PORT || 8082; // Use the body parser middleware for post requests app.use(bodyParser.json()); const { expressCspHeader, INLINE, NONE, SELF } = require('express-csp-header'); app.use(expressCspHeader({ directives: { 'default-src': [SELF], 'img-src': ['data:', 'images.com'], 'worker-src': [NONE], 'block-all-mixed-content': true } })); // @TODO1 IMPLEMENT A RESTFUL ENDPOINT // GET /filteredimage?image_url={{URL}} // endpoint to filter an image from a public url. // IT SHOULD // 1 // 1. validate the image_url query // 2. call filterImageFromURL(image_url) to filter the image // 3. send the resulting file in the response // 4. deletes any files on the server on finish of the response // QUERY PARAMATERS // image_url: URL of a publicly accessible image // RETURNS // the filtered image file [!!TIP res.sendFile(filteredpath); might be useful] /**************************************************************************** */ app.get("/filteredimage",async(req,res)=>{ let image_url:string = req.query.image_url; //Validate url const isValideUrl:any = image_url.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g); if(isValideUrl == null) return res.status(401).send(`Inavlid url! Try again with valid url`); else{ //Process Image const filteredImage:string =await filterImageFromURL(image_url); console.log(filteredImage); if(filteredImage===undefined||filteredImage===null) return res.status(401).send(`Unable to filter image`); else{ res.on('finish', function() { deleteLocalFiles([filteredImage]); }); return res.status(200).sendFile(''+filteredImage); } } }) //! END @TODO1 // Root Endpoint // Displays a simple message to the user app.get( "/", async ( req, res ) => { res.send("try GET /filteredimage?image_url={{}}") } ); // Start the Server app.listen( port, () => { console.log( `server running http://localhost:${ port }` ); console.log( `press CTRL+C to stop server` ); } ); })();
3ce90137d22883631048253d5502a0659c0b6abb
TypeScript
Alvin-MXK/TypeScript
/高级类型/4索引类型.ts
3.984375
4
let obj = { a: 1, b: 2, c: 3, }; // function getValue(obj: any,keys: string[]){ // return keys.map(key => obj[key]); // } // console.log(getValue(obj,["a","b"])); // console.log(getValue(obj,["c","f"])); // 使用索引类型 function getValue<T,K extends keyof T>(obj: T, keys: K[]): T[K][] { // T[k][]表示,返回值必须是obj中的值组成的列表 return keys.map(key => obj[key]); // 此时keys中的元素只能是obj中的键 } console.log(getValue(obj,["a","b"])); console.log(getValue(obj,["c","f"]));
f14b084dcb2692ef25c148ac65331143586e58b2
TypeScript
matheusmoreira12/TypeScript-LINQ
/Linq/OrderedEnumerator.ts
3.203125
3
/// <reference path="../_references.ts" /> namespace TS { export namespace Linq { /** * @class TS.Linq.OrderedEnumerator<T, TKey> * * @description The 'TS.Linq.OrderedEnumerator' class is used by the Linq sort functions where every subsequent call * to a sort function operate on the partitions of the enumerator elements without changing the order of previous * sorting. * * @implements {BaseEnumerator<T} * @implements {TS.Linq.IOrderedEnumerator<T>} */ export class OrderedEnumerator<T, TKey> extends BaseEnumerator<T> implements TS.Linq.IOrderedEnumerator<T> { /** * @private */ private keySelector: (item: T) => TKey; /** * @private */ private comparer: (first: TKey, second: TKey) => number; /** * @private */ private orderedEnumerator: IOrderedEnumerator<T>; /** * @description Property which returns an empty 'OrderedEnumerator'. * * @get {TS.Liny.OrderedEnumerator<any, any>} Empty */ public static get Empty(): OrderedEnumerator<any, any> { return new OrderedEnumerator(Enumerator.Empty, (item: any) => item, (first: any, second: any) => 0); } /** * @implements {TS.Linq.BaseEnumerator<T>} * * @returns {Iterator<T>}, An instance of the iterator type. */ public [Symbol.iterator](): Iterator<T> { let flatArray: Array<T> = this.flatPartitions(this.partitionIterator()); return new ArrayIterator(flatArray); } /** * @implements {TS.Linq.IOrderedEnumerator<T>} * * @returns {Iterator<Iterator<T>}, An instance of the partitioned iterator type. */ public partitionIterator(): Iterator<Iterator<T>> { return new PartitionIterator(this.orderedEnumerator, this.keySelector, this.comparer); } ////Handled by extension function ///** // * @description Flattens the current ordered enumeration and returns the elements in array which reflects the current order. // * // * @returns {Array<T>} // */ //public toArray() : Array<T> //{ // return Array.from(this); //} ////Handled by extension function ///** // * @description Flattens the current ordered enumeration and returns the elements in a list which reflects the current order. // * // * @returns TS.Collections.List<T>} // */ //public toList(): TS.Collections.List<T> //{ // return new TS.Collections.List(true, this); //} /** * @private * * @param { Iterator<Iterator<T>>} partitionIterator * * @returns Array<T> */ private flatPartitions(partitionIterator: Iterator<Iterator<T>>): Array<T> { let resultArray: Array<T>; let outerIterator: Iterator<Iterator<T>> = partitionIterator; let sourceArray: Array<T> = new Array<T>(); let outerResult: IteratorResult<Iterator<T>>; let innerResult: IteratorResult<T>; resultArray = new Array<T>(); do { outerResult = outerIterator.next(); if (!outerResult.done) { do { innerResult = outerResult.value.next(); if (!innerResult.done) { resultArray.push(innerResult.value); } } while (!innerResult.done); } } while (!outerResult.done); return resultArray; } /** * @constructor * * @param {Iterable<T> | IOrderedEnumerator<T>} enumerator * @param {(item: T) => TKey} keySelector * @param {(first: TKey, second: TKey) => number} comparer * * @throws {TS.InvalidTypeException} * @throws {TS.ArgumentNullOrUndefinedException} */ constructor(enumerator: Iterable<T> | IOrderedEnumerator<T>, keySelector: (item: T) => TKey, comparer: (first: TKey, second: TKey) => number) { TS.Utils.checkIterableParameter("enumerator", enumerator, "TS.Linq.OrderedEnumerator constructor"); TS.Utils.checkFunctionParameter("keySelector", keySelector, "TS.Linq.OrderedEnumerator constructor"); TS.Utils.checkFunctionParameter("comparer", comparer, "TS.Linq.OrderedEnumerator constructor"); super(); if ((enumerator as IOrderedEnumerator<T>).partitionIterator == undefined) { this.orderedEnumerator = new BaseOrderedEnumerator((enumerator as Iterable<T>)); } else { this.orderedEnumerator = (enumerator as IOrderedEnumerator<T>); } this.keySelector = keySelector; this.comparer = comparer; } //*********************************************************************** // Implementing the extension functions 'thenByDescending', and 'thenBy' // from TS.Linq.Extensions. // Function 'thenBy' and 'thenByDescending' are only available on // 'TS.Linq.OrderedEnumerator' objects for obvious reasons. //*********************************************************************** /** * @description Performs a subsequent ordering of the elements in a sequence in ascending order according to a key. * This function uses a default comparer. The result may differ from the C# counterpart * because of the different implementations of the default comparer. * @description Extension function. * @description Deferred execution. * * @see {@link https://msdn.microsoft.com/en-us/library/bb534743.aspx | MSDN} * * @param { (item: T) => TKey } keySelector * * @returns {TS.Linq.OrderedEnumerator<T, TKey>} * * @throws {TS.ArgumentNullOrUndefinedException} * @throws {TS.InvalidTypeException} */ public thenBy<TKey>(keySelector: (item: T) => TKey): TS.Linq.OrderedEnumerator<T, TKey> /** * @description Performs a subsequent ordering of the elements in a sequence in ascending order by using a specified comparer. * @description Extension function. * @description Deferred execution. * * @see {@link https://msdn.microsoft.com/en-us/library/bb534500.aspx | MSDN} * * @param { (item: T) => TKey } keySelector * @param {(first: TKey, second: TKey) => number} comparer * * @returns {TS.Linq.OrderedEnumerator<T, TKey>} * * @throws {TS.ArgumentNullOrUndefinedException} * @throws {TS.InvalidTypeException} */ public thenBy<TKey>(keySelector: (item: T) => TKey, comparer: (first: TKey, second: TKey) => number): TS.Linq.OrderedEnumerator<T, TKey> public thenBy<TKey>(keySelector: (item: T) => TKey, comparer?: (first: TKey, second: TKey) => number): TS.Linq.OrderedEnumerator<T, TKey> { return TS.Linq.Extensions.thenBy(this, keySelector, comparer as (first: TKey, second: TKey) => number); } /** * @description Performs a subsequent ordering of the elements in a sequence in descending order, according to * the specified key. This function uses a default comparer. The result may differ from the C# counterpart * because of the different implementations of the default comparer. * @description Extension function. * @description Deferred execution. * * @see {@link https://msdn.microsoft.com/en-us/library/bb534736.aspx | MSDN} * * @param { (item: T) => TKey } keySelector * * @returns {TS.Linq.OrderedEnumerator<T, TKey>} * * @throws {TS.ArgumentNullOrUndefinedException} * @throws {TS.InvalidTypeException} */ public thenByDescending<TKey>(keySelector: (item: T) => TKey): TS.Linq.OrderedEnumerator<T, TKey> /** * @description Performs a subsequent ordering of the elements in a sequence in descending order, according to the * specified key and comparer. * @description Extension function. * @description Deferred execution. * * @see {@link https://msdn.microsoft.com/en-us/library/bb534489.aspx | MSDN} * * @param { (item: T) => TKey } keySelector * @param {(first: TKey, second: TKey) => number} comparer * * @returns {TS.Linq.OrderedEnumerator<T, TKey>} * * @throws {TS.ArgumentNullOrUndefinedException} * @throws {TS.InvalidTypeException} */ public thenByDescending<TKey>(keySelector: (item: T) => TKey, comparer: (first: TKey, second: TKey) => number): TS.Linq.OrderedEnumerator<T, TKey> public thenByDescending<TKey>(keySelector: (item: T) => TKey, comparer?: (first: TKey, second: TKey) => number): TS.Linq.OrderedEnumerator<T, TKey> { return TS.Linq.Extensions.thenByDescending(this, keySelector, comparer as (first: TKey, second: TKey) => number); } //*********************************************************************** // END OF extension function binding //*********************************************************************** }//END class OrderedEnumerator /*************************************************************************/ /* Inner class: BaseOrderedEnumerator<T> */ /*************************************************************************/ /** * @class BaseOrderedEnumerator<T> * * @implements {TS.Linq.IOrderedEnumerator<T>} * * @internal */ class BaseOrderedEnumerator<T> implements TS.Linq.IOrderedEnumerator<T> { private enumerator: Iterable<T>; private done: boolean; /** * @constructor * * @param {Iterable<T>} enumerator */ constructor(enumerator: Iterable<T>) { this.enumerator = enumerator; this.done = false; } /** * @imploements {TS.Linq.IOrderedEnumerator<T>} * * @returns {Iterator<Iterator<T>>} */ public partitionIterator(): Iterator<Iterator<T>> { return new ArrayIterator([this.enumerator[Symbol.iterator]()]); } }//END class /*************************************************************************/ /* Inner class: PartitionIterator<T, TKey> */ /*************************************************************************/ /** * @class PartitionIterator<T, TKey> * * @description The 'PartitionIterator<T>' class is returned by the 'OrderedEnumerator' class and all derived * classes in order to iterate over the class elements. During iteration the 'next' function of this class is * called. If the iteration passed the end of the result set, every subsequent call to next will return a * 'IteratorResult<T>' object which has the 'done' flag set. * * @implements {Iterator<Iterator<T>>} * * @internal */ class PartitionIterator<T, TKey> implements Iterator<Iterator<T>> { private orderedEnumerator: IOrderedEnumerator<T> private keySelector: (item: T) => TKey; private comparer: (first: TKey, second: TKey) => number; private initalized: boolean = false; private resultArray: Array<Array<T>>; /** * @constructor * * @param source, The source object or collection used in this iterator. * @param selector, A selector function which determines the result set. */ constructor(orderedEnumerator: IOrderedEnumerator<T>, keySelector: (item: T) => TKey, comparer: (first: TKey, second: TKey) => number) { this.orderedEnumerator = orderedEnumerator; this.keySelector = keySelector; this.comparer = comparer; this.initalized = false; } /** * @private */ private init() : void { this.resultArray = this.createPartions(this.orderedEnumerator, this.keySelector, this.comparer); this.initalized = true; } /** * @private * * @param {TS.Linq.IOrderedEnumerator<T>} orderedEnumerator * @param {(item: T) => TKey} keySelector * @param {(first: TKey, second: TKey) => number} comparer * * @returns {Array<Array<T>>} */ private createPartions(orderedEnumerator: TS.Linq.IOrderedEnumerator<T>, keySelector: (item: T) => TKey, comparer: (first: TKey, second: TKey) => number): Array<Array<T>> { let partitionedArray: Array<Array<T>>; let orderedIterator: Iterator<Iterator<T>>; let orderedIteratorResult: IteratorResult<Iterator<T>>; partitionedArray = new Array<Array<T>>(); orderedIterator = orderedEnumerator.partitionIterator(); do { orderedIteratorResult = orderedIterator.next(); if (!orderedIteratorResult.done) { partitionedArray = partitionedArray.concat(sort(orderedIteratorResult.value)); } } while (!orderedIteratorResult.done); return partitionedArray; function sort(iterator: Iterator<T>): Array<Array<T>> { let iteratorResult: IteratorResult<T>; let sourceArray: Array<T>; let partition: Array<T>; let resultArray: Array<Array<T>>; let lastElement: T | null = null; sourceArray = new Array<T>(); do { iteratorResult = iterator.next(); if (!iteratorResult.done) { sourceArray.push(iteratorResult.value); } } while (!iteratorResult.done); sourceArray = sourceArray.sort((first, second) => { return comparer(keySelector(first), keySelector(second)); }) partition = new Array<T>(); resultArray = new Array<Array<T>>(); while (sourceArray.length > 0) { //new partition if ((lastElement != null) && (keySelector(lastElement) != keySelector(sourceArray[0]))) { resultArray.push(partition); partition = new Array<T>(); } lastElement = sourceArray.shift() as T; partition.push(lastElement); } resultArray.push(partition); return resultArray; } } /** * @description This is the implementation of the 'Iterator<Iterator<T>>' interface. * * @returns {IteratorResult<Iterator<T>>} */ public next(): IteratorResult<Iterator<T>> { if (!this.initalized) { this.init(); } while (this.resultArray.length > 0) { return { done: false, value: new ArrayIterator<T>(this.resultArray.shift() as Array<T>) }; } return { done: true, value: null as any }; } }//END class ///*************************************************************************/ ///* Inner class: ArrayIterator<T> */ ///*************************************************************************/ /** * @class ArrayIterator<T> * * @implements {Iterator<T>} * * @internal */ class ArrayIterator<T> implements Iterator<T> { private innerArray: Array<T>; private initalized: boolean = false; private index: number = -1; /** * @constructor * * @param { Array<T>} source, The source object or collection used in this iterator. * * @throws {TS.ArgumentNullOrUndefinedException} * @throws {TS.InvalidTypeException} */ constructor(source: Array<T>) { TS.Utils.checkArrayParameter("source", source, "TS.Linq.OrderedEnumerator.TArrayIterator.constructor"); this.innerArray = TS.Utils.compactArray(source); } /** * @implements {Iterator<T>} * * @returns {IteratorResult<T>} */ public next(): IteratorResult<T> { if (this.innerArray.length > 0) { return { done: false, value: this.innerArray.shift() } as IteratorResult<T>; } return { done: true, value: undefined as any } as IteratorResult<T> } }//END class }//END namespace }//END namespace
d811c1571e51e626ff2052498efa2ab2507d314b
TypeScript
ammobinDOTca/ammobin-classifer
/build/get-counts.d.ts
2.640625
3
/** * parse a store listing to determine the item quantity * @param {string} str * @returns {number} determined quantity, returns 0 if not found */ export declare function getItemCount(str: string): number;
ec704bec9800c715da44db64bf502df7d9fb080c
TypeScript
dhmw/dynamo-easy
/src/decorator/impl/model/model.decorator.ts
2.75
3
/** * @module decorators */ import * as DynamoDB from 'aws-sdk/clients/dynamodb' import { kebabCase } from '../../../helper/kebab-case.function' import { ModelMetadata } from '../../metadata/model-metadata.model' import { PropertyMetadata } from '../../metadata/property-metadata.model' import { SecondaryIndex } from '../index/secondary-index' import { KEY_PROPERTY } from '../property/key-property.const' import { modelErrors } from './errors.const' import { KEY_MODEL } from './key-model.const' import { ModelData } from './model-data.model' /** * decorator to define a model for dynamo easy */ export function Model(opts: ModelData = {}): ClassDecorator { // tslint:disable-next-line:ban-types return (constructor: Function) => { const type = constructor as any // get all the properties with @Property() annotation (or @PartitionKey(),...) // if given class has own properties, all inherited properties are already set and we can get the properties with 'getOwnMetadata'. // otherwise when the given class does not have own properties, there's no 'ownMetadata' but we need to get them from the class it extends with 'getMetadata' const properties: Array<PropertyMetadata<any>> = (Reflect.hasOwnMetadata(KEY_PROPERTY, constructor) ? Reflect.getOwnMetadata(KEY_PROPERTY, constructor) : Reflect.getMetadata(KEY_PROPERTY, constructor)) || [] // get partition key const partitionKeys = properties.filter((property) => property.key && property.key.type === 'HASH') const partitionKeyName: string | null = partitionKeys.length ? partitionKeys[0].nameDb : null /* * get the local and global secondary indexes */ const globalSecondaryIndexes: any = getGlobalSecondaryIndexes(properties) const localSecondaryIndexes: any = getLocalSecondaryIndexes(partitionKeyName, properties) const indexes: Map<string, SecondaryIndex<any>> = new Map([...globalSecondaryIndexes, ...localSecondaryIndexes]) const transientProperties = properties.length ? properties.filter((property) => property.transient === true).map((property) => property.name) : [] const metaData: ModelMetadata<any> = { clazz: constructor, clazzName: type.name, tableName: `${kebabCase(type.name)}s`, properties, transientProperties, indexes, ...opts, } // console.log(`Decorating: ${metaData.clazzName}`, metaData); Reflect.defineMetadata(KEY_MODEL, metaData, constructor) } } /** * @hidden */ function testForGSI<T>( property: PropertyMetadata<T>, ): property is PropertyMetadata<T> & { keyForGSI: Record<string, DynamoDB.KeyType> } { return !!(property.keyForGSI && Object.keys(property.keyForGSI).length) } /** * @hidden */ function testForLSI<T>(property: PropertyMetadata<T>): property is PropertyMetadata<T> & { sortKeyForLSI: string[] } { return !!(property.sortKeyForLSI && property.sortKeyForLSI.length) } /** * @hidden */ function getGlobalSecondaryIndexes(properties: Array<PropertyMetadata<any>>): Map<string, SecondaryIndex<any>> { return properties.filter(testForGSI).reduce((map, property): Map<string, SecondaryIndex<any>> => { let gsi: SecondaryIndex<any> Object.keys(property.keyForGSI).forEach((indexName) => { if (map.has(indexName)) { gsi = map.get(indexName) } else { gsi = <SecondaryIndex<any>>{} } switch (property.keyForGSI[indexName]) { case 'HASH': if (gsi.partitionKey) { throw new Error(modelErrors.gsiMultiplePk(indexName, property.nameDb)) } gsi.partitionKey = property.nameDb break case 'RANGE': if (gsi.sortKey) { throw new Error(modelErrors.gsiMultipleSk(indexName, property.nameDb)) } gsi.sortKey = property.nameDb break } map.set(indexName, gsi) }) return map }, new Map()) } /** * @hidden */ function getLocalSecondaryIndexes( basePartitionKey: string | null, properties: Array<PropertyMetadata<any>>, ): Map<string, SecondaryIndex<any>> { return properties.filter(testForLSI).reduce((map, property): Map<string, SecondaryIndex<any>> => { let lsi: SecondaryIndex<any> property.sortKeyForLSI.forEach((indexName) => { if (map.has(indexName)) { throw new Error(modelErrors.lsiMultipleSk(indexName, property.nameDb)) } if (!basePartitionKey) { throw new Error(modelErrors.lsiRequiresPk(indexName, property.nameDb)) } lsi = { partitionKey: basePartitionKey, sortKey: property.nameDb, } map.set(indexName, lsi) }) return map }, new Map()) }
b4bde34512635ee40b5858ca914646b8dcc68107
TypeScript
kristerkari/observable-redux-json-api
/src/utils.ts
2.765625
3
import { __assign } from "./assign"; import { AjaxResponse, Observable } from "./rxjs-imports"; export { __assign }; // workaround to stop TS removing __assign import as unused export const jsonContentTypes = [ "application/json", "application/vnd.api+json" ]; export const apiRequest = (url: string, options = {}): Observable<any> => { return Observable.ajax({ url, ...options, responseType: "json" }).map((res: AjaxResponse) => { if (res.status >= 200 && res.status < 300) { if (res.status === 204) { return res; } const header = res.xhr.getResponseHeader("Content-Type"); if ( typeof header === "string" && jsonContentTypes.some(contentType => header.indexOf(contentType) > -1) ) { return res.response; } } return res; }); }; export const hasOwnProperties = (obj, propertyTree) => { if (obj instanceof Object === false) { return false; } const property = propertyTree[0]; const hasProperty = obj.hasOwnProperty(property); if (hasProperty) { if (propertyTree.length === 1) { return hasProperty; } return hasOwnProperties(obj[property], propertyTree.slice(1)); } return false; }; export function find(array: any, predicate: Function) { for (let i = 0; i < array.length; i += 1) { if (predicate(array[i], i, array)) { return array[i]; } } return undefined; } export function findIndex(array: any, predicate: Function) { if (array.length === 0) { return -1; } for (let i = 0; i < array.length; i++) { if (predicate(array[i], i, array)) { return i; } } return -1; }
f87d972cc5b4bdeb0fb0d7e20145036bc3f5e831
TypeScript
IoanaLaz/Catalog-Online
/frontend/src/app/entry-details-student.ts
2.640625
3
export class EntryDetailsStudent{ constructor(public courseName:string, public teacherName:string, public grade:number){ this.courseName = courseName; this.teacherName = teacherName; this.grade = grade; } }
b5f813e3324a2b391e1e4c8fc90afa5cb8e453d2
TypeScript
otaviohenrique1/curso-javascript-school-of-net
/javascript_estrutura_de_dados/typescript_recursividade/fila_com_prioridade.ts
3.921875
4
class FilaComPrioridade { private elementos: Array<any> = []; // LILO // O último a entrar é o último a sair // Inserir no final do array // Remover no ínicio constructor() { this.elementos = []; } public inserir(dado: any, prioridade: number) { var elementoDaFila = { dado: '', prioridade: 0 }; elementoDaFila.dado = dado; elementoDaFila.prioridade = prioridade; if (this.estaVazia()) { this.elementos.push(elementoDaFila) } else { var adicionado = false; for (let i = 0; i < this.elementos.length; i++) { if (elementoDaFila.prioridade > this.elementos[i].prioridade) { this.elementos.splice(i, 0, elementoDaFila); adicionado = true; break; } if (!adicionado) { this.elementos.push(elementoDaFila); } } } } public remover() { // Removo no ínicio return this.elementos.shift(); } public imprimir() { for (let i = 0; i < this.elementos.length; i++) { console.log(i, "Dado: " + this.elementos[i].dado, "Prioridade: " + this.elementos[i].prioridade); } } public primeiro() { return this.elementos[0]; } public ultimo() { // A quantidade de elementos em um array - 1 // 0 1 2 // Ex: [10,20,40] //3-1 = 2 return this.elementos[this.elementos.length-1]; } public estaVazia() { return this.elementos.length == 0; } public limpar() { this.elementos = []; } } var filaDeHospital = new FilaComPrioridade(); filaDeHospital.inserir("Paciente 101",3); filaDeHospital.inserir("Paciente 97",5); filaDeHospital.inserir("Paciente 1400",4); filaDeHospital.inserir("Paciente 10",6); console.log(filaDeHospital.remover()); filaDeHospital.imprimir();
67ec9f4ab7e18af00a3bff06fe73ad2e90d1bb3a
TypeScript
lydiacupery/leet-code
/add-two-numbers/add-two-numbers.test.ts
3.765625
4
import {Solution, ListNode} from './add-two-numbers' /* You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. */ describe('add two numbrs', () => { it("1", () => { const val1 = new ListNode(2) val1.next = new ListNode(4) val1.next.next = new ListNode(3) const val2 = new ListNode(5) val2.next = new ListNode(6) val2.next.next = new ListNode(4) const res = Solution.addNumbers(val1, val2) expect(res.val).toEqual(7) expect(res.next!.val).toEqual(0) expect(res.next!.next!.val).toEqual(8) }) })
a02ec41253af73d1e55b361ba007e32a8fe5a30f
TypeScript
dhamotharang/filink-build3
/src/app/business-module/trouble/share/model/trouble-areaCodes.model.ts
2.625
3
/** * 批量指派责任单位区域集合 */ export class TroubleAreaCodesModel { /** * 标识位 */ public flag: boolean; /** * 区域code集合 */ public areaCodes: string[]; constructor() { this.flag = true; this.areaCodes = []; } }
fc853aee93d8e22d4c47af27b6990aee979f7755
TypeScript
gcali/duetto
/fe/src/services/auth.ts
2.6875
3
const baseUrl = "https://localhost:5001/api/auth" export class AuthService { public async login(username: string, password: string): Promise<boolean> { const endpoint = `${baseUrl}`; const response = await fetch(endpoint, { method: "POST", body: JSON.stringify({username, password}), headers: { 'Content-Type': 'application/json' }, redirect: "follow", cache: "no-cache", mode: "cors", credentials: "include" }); return response.status === 200; } public async logout(): Promise<void> { const endpoint = `${baseUrl}/logout`; await fetch(endpoint, { method: "POST", body: JSON.stringify({}), headers: { 'Content-Type': 'application/json' }, redirect: "follow", cache: "no-cache", mode: "cors", credentials: "include" }); } public async whoAmI(): Promise<string | null> { const endpoint = `${baseUrl}`; const response = await fetch(endpoint, { credentials: "include", redirect: "follow", cache: "no-cache", mode: "cors", }); if (response.status !== 200) { return null; } const body = await response.json(); return body.name; } }
00a44fce3c541e8844c79d786a85177704aea642
TypeScript
silky/morpheus-graphql
/scripts/local/hie.ts
2.640625
3
import { join } from "path"; import { StackPackage } from "../lib/check-packages/types"; import { readYAML, writeYAML } from "../lib/utils/file"; type Pkg = { path: string } & StackPackage; const getPath = (path: string, src: StackPackage["library"]) => "./" + join(path, src["source-dirs"]); const scanSub = ( configs: Pkg[], type: string, key: "tests" | "executables" | "benchmarks" ) => configs.flatMap((pkg) => Object.entries(pkg[key] ?? {}).map(([sub, lib]) => ({ path: getPath(pkg.path, lib), component: [pkg.name, type, sub].join(":"), })) ); const scanLib = (configs: Pkg[]) => configs.flatMap(({ path, name, library }) => library ? [ { path: getPath(path, library), component: `${name}:lib`, }, ] : [] ); export const hie = async (sources: string[]) => { const packages = await Promise.all( sources.map(async (name) => { return { ...(await readYAML<StackPackage>(join(name, "package.yaml"))), path: name, }; }) ); writeYAML("hie.yaml", { cradle: { stack: { stackYaml: "./stack.yaml", components: [ ...scanLib(packages), ...scanSub(packages, "test", "tests"), ...scanSub(packages, "exe", "executables"), ...scanSub(packages, "bench", "benchmarks"), ], }, }, }); };
827399a4ac462ac28f5e8b40287a8ab2508c4546
TypeScript
tsigel/waves-frontent-meetups
/2019-04-29/interface.d.ts
3.03125
3
export interface IToPairs { <T extends Record<keyof any, any>>(data: T): Array<[keyof T, T[keyof T]]>; } interface IPipe { <A, B, R>(cb1: (a: A) => B, cb2: (b: B) => R): (a: A) => R; <A, B, C, R>(cb1: (a: A) => B, cb2: (b: B) => C, cb3: (c: C) => R): (a: A) => R; <A, B, C, D, R>(cb1: (a: A) => B, cb2: (b: B) => C, cb3: (c: C) => D, cb4: (c: D) => R): (a: A) => R; <A, B, C, D, E, R>(cb1: (a: A) => B, cb2: (b: B) => C, cb3: (c: C) => D, cb4: (c: D) => E, cb5: (data: E) => R): (a: A) => R; } export interface ICompose { <A, B, R>(cb2: (b: B) => R, cb1: (a: A) => B): (a: A )=> R; <A, B, C, R>(cb3: (c: C) => R, cb2: (B: B) => C, cb1: (a: A) => B): (a: A) => R; <A, B, C, D, R>(cb1: (a: D) => R, cb2: (b: C) => D, cb3: (c: B) => C, cb4: (c: A) => B): (a: A) => R; <A, B, C, D, E, R>(cb1: (a: E) => R, cb2: (b: D) => E, cb3: (c: C) => D, cb4: (c: B) => C, cb5: (data: A) => B): (a: A) => R; } export interface IFilter { <T>(callback: (item: T) => boolean, list: Array<T>): Array<T>; <T>(callback: (item: T) => boolean): (list: Array<T>) => Array<T>; } export interface IWhereEq { <T extends Record<keyof any, any>>(data: Partial<T>, item: T): boolean; <T extends Record<keyof any, any>>(data: Partial<T>): (item: T) => boolean; } export interface ICurry { <A, B, R>(cb: (a: A, b: B) => R): (a: A, b: B) => R; <A, B, R>(cb: (a: A, b: B) => R): (a: A) => (b: B) => R; <A, B, C, R>(cb: (a: A, b: B, c: C) => R): (a: A, b: B, c: C) => R; <A, B, C, R>(cb: (a: A, b: B, c: C) => R): (a: A, b: B) => (c: C) => R; <A, B, C, R>(cb: (a: A, b: B, c: C) => R): (a: A) => (b: B) => (c: C) => R; }
6b23ee9c569db8382a40ff7851b6014dace5cf1d
TypeScript
ruffythepirate/the-octopus-battle
/packages/common/src/dtos/PlayerControls.ts
3.078125
3
import {PlayerAction, PlayerControlsEventDto} from "../logic/events/GameEventDto"; export class PlayerControls { left: boolean = false; right: boolean = false; up: boolean = false; down: boolean = false; constructor() { this.left = false; this.right = false; this.up = false; this.down = false; } applyEvent(event: PlayerControlsEventDto) { switch (event.action) { case PlayerAction.LEFT: this.left = event.pressed; break; case PlayerAction.RIGHT: this.right = event.pressed; break; case PlayerAction.UP: this.up = event.pressed; break; case PlayerAction.DOWN: this.down = event.pressed; break; } } } export function applyControlEvent(playerControls: PlayerControls, event: PlayerControlsEventDto): PlayerControls { return {...playerControls, [getPropertyName(event.action)]: event.pressed} as PlayerControls; } function getPropertyName(action: PlayerAction) { switch (action) { case PlayerAction.LEFT: return 'left'; case PlayerAction.RIGHT: return 'right'; case PlayerAction.UP: return 'up'; case PlayerAction.DOWN: return 'down'; case PlayerAction.SHOOT: return 'fire'; default: throw new Error('Unknown action: ' + action); } }
1ac4f86caa27baae2c1371a3e6fe354993f37b2c
TypeScript
XeroAPI/xero-node
/src/gen/model/payroll-au/payRun.ts
2.59375
3
import { PayRunStatus } from '././payRunStatus'; import { PayslipSummary } from '././payslipSummary'; import { ValidationError } from '././validationError'; export class PayRun { /** * Xero identifier for pay run */ 'payrollCalendarID': string; /** * Xero identifier for pay run */ 'payRunID'?: string; /** * Period Start Date for the PayRun (YYYY-MM-DD) */ 'payRunPeriodStartDate'?: string; /** * Period End Date for the PayRun (YYYY-MM-DD) */ 'payRunPeriodEndDate'?: string; 'payRunStatus'?: PayRunStatus; /** * Payment Date for the PayRun (YYYY-MM-DD) */ 'paymentDate'?: string; /** * Payslip message for the PayRun */ 'payslipMessage'?: string; /** * Last modified timestamp */ 'updatedDateUTC'?: Date; /** * The payslips in the payrun */ 'payslips'?: Array<PayslipSummary>; /** * The total Wages for the Payrun */ 'wages'?: number; /** * The total Deductions for the Payrun */ 'deductions'?: number; /** * The total Tax for the Payrun */ 'tax'?: number; /** * The total Super for the Payrun */ '_super'?: number; /** * The total Reimbursements for the Payrun */ 'reimbursement'?: number; /** * The total NetPay for the Payrun */ 'netPay'?: number; /** * Displays array of validation error messages from the API */ 'validationErrors'?: Array<ValidationError>; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "payrollCalendarID", "baseName": "PayrollCalendarID", "type": "string" }, { "name": "payRunID", "baseName": "PayRunID", "type": "string" }, { "name": "payRunPeriodStartDate", "baseName": "PayRunPeriodStartDate", "type": "string" }, { "name": "payRunPeriodEndDate", "baseName": "PayRunPeriodEndDate", "type": "string" }, { "name": "payRunStatus", "baseName": "PayRunStatus", "type": "PayRunStatus" }, { "name": "paymentDate", "baseName": "PaymentDate", "type": "string" }, { "name": "payslipMessage", "baseName": "PayslipMessage", "type": "string" }, { "name": "updatedDateUTC", "baseName": "UpdatedDateUTC", "type": "Date" }, { "name": "payslips", "baseName": "Payslips", "type": "Array<PayslipSummary>" }, { "name": "wages", "baseName": "Wages", "type": "number" }, { "name": "deductions", "baseName": "Deductions", "type": "number" }, { "name": "tax", "baseName": "Tax", "type": "number" }, { "name": "_super", "baseName": "Super", "type": "number" }, { "name": "reimbursement", "baseName": "Reimbursement", "type": "number" }, { "name": "netPay", "baseName": "NetPay", "type": "number" }, { "name": "validationErrors", "baseName": "ValidationErrors", "type": "Array<ValidationError>" } ]; static getAttributeTypeMap() { return PayRun.attributeTypeMap; } }
cc8341e9d178b5310cdcde75efc964bc8e9cb399
TypeScript
CollaboratorsCoding/saas-express-ts
/src/models/user.model.ts
3.015625
3
import * as mongoose from "mongoose"; import { UserAttrs, UserDoc, UserModel } from "../interfaces/user.interface"; const userSchema = new mongoose.Schema({ email: { type: String, required: true, }, password: { type: String, required: true, }, }); userSchema.statics.build = (attrs: UserAttrs) => { return new User(attrs); }; const User = mongoose.model<UserDoc, UserModel>("User", userSchema); // Error example - password missing // User.build({email: 'test'}); // Error example - email type not string // User.build({email: 123, password: "wweqe"}) // const newUser = User.build({email: "test@test.test", password: "wweqe"}) // newUser.e --- type mail or newUser.pass --- type word export { User };
8937dbb84a82fe69a3a7d7e8d45ab68786095cd9
TypeScript
hijiangtao/LeetCode-with-JavaScript
/src/house-robber/res.ts
3.3125
3
function rob(nums: number[]): number { if (!nums.length) { return 0; } const dp: number[] = new Array(nums.length).fill(0); for (let i = 0; i < nums.length; i++) { if (i === 0) { dp[i] = nums[i]; } else if (i === 1) { dp[i] = Math.max(nums[i], dp[i-1]); } else { dp[i] = Math.max(nums[i] + dp[i-2], dp[i-1]); } } return dp[nums.length-1]; };
da97e55240ee46859a7b03cc4aa30e124438212d
TypeScript
wwlee94/typescript-book-rental-assignment
/src/entity/Rental.ts
2.71875
3
import { BaseEntity, Column, CreateDateColumn, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm'; import { Book } from './Book'; import { User } from './User'; @Entity() export class Rental extends BaseEntity { @PrimaryGeneratedColumn() id!: number; // Rental(*) <-> User(1) @ManyToOne(type => User, user => user.rentals, { onDelete: 'CASCADE' }) user!: User; // Rental(1) <-> Book(1) @ManyToOne(type => Book, book => book.rentals, { onDelete: 'CASCADE' }) book!: Book; // 대여 일자 @CreateDateColumn({ type: 'timestamp' }) rentalDateAt!: Date; // 반납 일자 @Column({ type: 'timestamp', default: null }) returnDateAt!: Date; }
b97d4f49894149ac6588f7c2f4ae88c7576509a0
TypeScript
airhorns/superpro
/app/javascript/types/skip_list.d.ts
2.875
3
declare module "skip_list" { class NodeData<T> { key: string; value: T; level: number; prevKey: string[]; nextKey: string[]; prevCount: number[]; nextCount: number[]; } class Node<T> extends NodeData<T> { constructor(key: string, value: T, level: number, prevKey: string, nextKey: string, prevCount: number, nextCount: number); setValue(key: string, value: T): Node<T>; insertAfter(newKey: string, newLevel: number, fromLevel: number, distance: number): Node<T>; insertBefore(newKey: string, newLevel: number, fromLevel: number, distance: number): Node<T>; removeAfter(fromLevel: number, removedLevel: number, newKeys: string[], distances: number[]): Node<T>; removeBefore(fromLevel: number, removedLevel: number, newKeys: string[], distances: number[]): Node<T>; } type RandomGenerator = () => { next(): { value: number; done: boolean } }; type IteratorMode = "keys" | "values" | "entries"; interface IteratorResult<T> { next(): { value: string | T | [string, T]; done: boolean; }; [Symbol.iterator](): IteratorResult<T>; } export class SkipList<T> { _nodes: Map<string, T>; _randomSource: RandomGenerator; constructor(randomSource?: RandomGenerator); headNode: Node<T>; length: number; predecessors(predecessor: Node<T>, maxLevel: number): { preKeys: string[]; preCounts: number[] }; successors(successor: Node<T>, maxLevel: number): { sucKeys: string[]; sucCounts: number[] }; insertAfter(predecessor: string, key: string, value: T): SkipList<T>; insertIndex(index: number, key: string, value: T): SkipList<T>; removeKey(key: string): SkipList<T>; removeIndex(index: number): SkipList<T>; indexOf(key: string): number; keyOf(index: number): string; getValue(key: string): T; setValue(key: string, value: T): SkipList<T>; iterator(mode: IteratorMode): IteratorResult<T>; [Symbol.iterator](): IteratorResult<T>; } }
7e1e1f86dbc9e8019bbd240efc90a87cf3175f25
TypeScript
future4code/Joao-Moura
/semana15/projeto-backend-todolist/src/utils/utils.ts
2.828125
3
export enum STATUS { "TODO" = "To_Do", "DOING" = "Doing", "DONE" = "Done" } export type user = { id: number, name: string, nickname: string, email: string, } export type task = { id: number, title: string, limitDate: string, creatorUserId: string, status: STATUS } export const formattedDate = (date: string): Date =>{ const [dd, mm, yyyy] = date.split("/") const newDate: Date = new Date(`${yyyy}-${mm}-${dd}`) return newDate }
42baa923ab21d7779bbf33e4c155c6256bab371a
TypeScript
YonaBenReuven/socket.io-react
/hooks/useStateOn.ts
2.703125
3
import { useState } from "react"; import { useOn } from "."; const useStateOn = (event: string, initialState: any): [any, React.Dispatch<any>] => { const stateTuple = useState<any>(initialState); const [, setState] = stateTuple; useOn(event, (nextState: any) => { setState(nextState); }); return stateTuple; }; export default useStateOn;
58ef14967d0a42bf79b7cef2f69f72897376e3a3
TypeScript
falconmick/testable-typescript
/src/ManualDiMethod/AddressAutofillController.ts
3.421875
3
import { AddressSearchResult, AddressSearchType } from "./AddressSearchService"; import { UpdateAddressType } from "./AddressAutofillActions"; import { Address } from "./Address"; // All testable services are created with the following type // type InjectableService = (...injectables: any[]) => (...args: any[]) => any; // This is basically: // function 1: List of injectables that returns another function // function 2: Any function (this is our service) // // in the bellow example the injectables are addressSearch, updateAddress and some random json object // next is the function which is the function which accepts a dispatch and returns another function // this is acceptable as an InjectablService's second function's return value is any // and thus another function is a.O.K! export const __attemptAutofill = ( _addressSearch: AddressSearchType, _updateAddress: UpdateAddressType, _NOT_FOUND_SEARCH_RESULT: AddressSearchResult ) => (dispatch: (action: object) => void) => (address: Address): Address => { const { address: addressSearchResult, foundMatch } = _addressSearch(address) || _NOT_FOUND_SEARCH_RESULT; if (foundMatch) { dispatch(_updateAddress(addressSearchResult)); return addressSearchResult; } return address; }; // This is how we do the manual DI, currently we don't have the // dependencies defined so we cannot make it avaliable // export const attemptAutofill = __attemptAutofill( // addressSearch, // updateAddress, // NOT_FOUND_SEARCH_RESULT // ); // bellow shows how once you have setup the DI, the three dependancies would // be defined normally in other files, but I am just making fake ones here // so that we can see an example how how you would setup the DI const exampleAddressSearchFnc: AddressSearchType = address => ({ foundMatch: false, address: { postcode: "2222" }, }); const exampleAddressfnc: UpdateAddressType = address => ({}); const exampleAddressSearchResult: AddressSearchResult = { foundMatch: false, address: { postcode: "2222" }, }; export const attemptAutofill: ReturnType< typeof __attemptAutofill > = __attemptAutofill( exampleAddressSearchFnc, exampleAddressfnc, exampleAddressSearchResult ); // this is then how you would call the injected service attemptAutofill(action => "my dispatcher")({ postcode: "example request!" });
f7412dd19df4f46e63e52dfa250c4756b8a7b47b
TypeScript
marcusbalbi/study
/udemy/typescript-the-complete-developers-guide/server/src/controllers/LoginController.ts
2.75
3
import { Request, Response } from "express"; import { requireAuth } from "../middlewares/requireAuth"; import { get, controller, post, use, bodyValidator } from "./decorators"; @controller("") export class LoginController { // @get("/add") // add(a: number, b: number) {} @get("/") main(req: Request, res: Response): void { if (req.session?.loggedIn) { res.send(` <div> <div>You are LoggedIn</div> <a href="/logout">Logout!</a> </div> `); } else { res.send(` <div> <div>You are not LoggedIn</div> <a href="/login">Login!</a> </div> `); } } @get("/login") loginPage(req: Request, res: Response): void { res.send(` <form method="POST"> <div> <label>Email</label> <input name="email" /> </div> <div> <label>Password</label> <input name="password" type="password" /> </div> <button>Submit!</button> </form> `); } @post("/login") @bodyValidator("email", "password") login(req: Request, res: Response): void { const { email, password } = req.body; if (email === "balbimarcus@gmail.com" && password === "abc123") { req.session = { loggedIn: true }; // res.send(`${email.toUpperCase()}:${password}`); res.redirect("/"); } else { res.status(422).send("Error: Invalid email or passord!"); } } @get("/logout") logout(req: Request, res: Response): void { req.session = undefined; res.redirect("/"); } @get("/protected") @use(requireAuth) protectedRoute(req: Request, res: Response): void { res.send(` <h1>Welcome!!</h1> `); } }
832d2371de3b40822b02869ae38d4f21065ace69
TypeScript
JessicaBunyan/todo-list
/back/todo-list/todo-list.service.ts
2.890625
3
import { TodoList } from "./todo-list.model"; import { mockData } from "./todo-list-mock-data"; export class TodoListService { private static instance: TodoListService; private lists: { [key: string]: TodoList } = mockData; public static getInstance() { if (TodoListService.instance) { return TodoListService.instance; } TodoListService.instance = new TodoListService(); return TodoListService.instance; } public reset() { this.lists = {}; } public async saveList(list: TodoList) { list.id = list.id || getId(); list.items.forEach((i) => (i.id = i.id || getId())); this.lists[list.id] = list; return list; } public async deleteList(id: string) { const list = this.lists[id]; if (!list) { return Promise.reject("No Such List"); } this.lists[id] = undefined; return Promise.resolve("OK"); } public async getAllListDetails() { const val = Object.values(this.lists) .filter((l) => l) .map((l) => ({ id: l.id, name: l.name, numItems: l.items.length, numCompletedItems: l.items.filter((i) => i.done).length, })); return Promise.resolve(val); } public async getList(id: string) { const val = this.lists[id]; return Promise.resolve(val); } public updateListItemState(listId: string, itemId: string, state: boolean) { const list = this.lists[listId]; if (!list) { return Promise.reject("No such list"); } const item = list.items.find((i) => i.id == itemId); if (!item) { return Promise.reject("Invalid update - list item does not exist"); } item.done = state; return Promise.resolve(list); } } // Would be generated by mongo / DB in real app function getId() { return Math.random().toString(36).substring(2, 9); }
0f748881a5083c663bb54ef6727f02f68265198c
TypeScript
wraith13/vertical-line-vscode
/src/extension.ts
2.609375
3
'use strict'; // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from 'vscode'; /* import localeEn from "../package.nls.json"; import localeJa from "../package.nls.ja.json"; interface LocaleEntry { [key : string] : string; } const localeTableKey = <string>JSON.parse(<string>process.env.VSCODE_NLS_CONFIG).locale; const localeTable = Object.assign(localeEn, ((<{[key : string] : LocaleEntry}>{ ja : localeJa })[localeTableKey] || { })); const localeString = (key : string) : string => localeTable[key] || key; */ export module VerticalLine { //let pass_through; const applicationKey = "vertical-line"; const getConfiguration = <type>(key? : string, section : string = applicationKey) : type => { const configuration = vscode.workspace.getConfiguration(section); return key ? configuration[key] : configuration; }; const setEnabled = (enabled : boolean) : void => { vscode.workspace.getConfiguration().update("enabled", enabled, true); }; let color : string = "dummy"; let enabled : boolean = false; let decorator : vscode.TextEditorDecorationType = vscode.window.createTextEditorDecorationType({}); export function initialize(context : vscode.ExtensionContext): void { context.subscriptions.push ( // コマンドの登録 vscode.commands.registerCommand(`${applicationKey}.show`, show), vscode.commands.registerCommand(`${applicationKey}.hide`, hide), // イベントリスナーの登録 vscode.workspace.onDidChangeConfiguration(() => onDidChangeConfiguration()), vscode.window.onDidChangeTextEditorSelection(() => update()), vscode.window.onDidChangeActiveTextEditor(() => update()) ); onDidChangeConfiguration(); } export const show = () : void => setEnabled(true); export const hide = () : void => setEnabled(false); const calcWidth = (text : string) : number => { return text.length; }; const substrByWidth = (text : string, width : number) : string | null => { return text.length < width ? null: text.substr(0, width); } ; export function update() : void { const editor = vscode.window.activeTextEditor; if (editor) { var decorations = []; if (editor.selection.isEmpty && enabled) { const width = calcWidth(editor.document.lineAt(editor.selection.start.line).text.substr(0, editor.selection.start.character)); for (var i = 0; i < editor.document.lineCount; i++) { //if (editor.selection.end.character <= editor.document.lineAt(i).text.replace(/(^ +).*$/, "$1").length) var sub = substrByWidth(editor.document.lineAt(i).text, width); if (null !== sub) { decorations.push(new vscode.Range(i, sub.length,i, sub.length)); } } } editor.setDecorations(decorator, decorations); } } export const onDidChangeConfiguration = () => { vscode.window.visibleTextEditors.forEach(editor => editor.setDecorations(decorator, [])); color = getConfiguration<string>("color"); enabled = getConfiguration<boolean>("enabled"); decorator.dispose(); decorator = vscode.window.createTextEditorDecorationType ( { borderColor: color, borderStyle: 'none none none solid', borderWidth: '1px' } ); update(); }; } export function activate(context: vscode.ExtensionContext) : void { VerticalLine.initialize(context); } export function deactivate() : void { }
1952b0bd4f6b532447ae3e1ca90c8ac702a414f6
TypeScript
iconic-king/chess-bet-functions
/functions/src/domain/ServiceAccount.ts
2.546875
3
export class ServiceAccount { public id!: string; public name!: string; public accountId!: number; public userId!: string; public phoneNumber!: string; public email!: string; } export interface ServiceAccountDTO { userId: string, email: string, name: string, phoneNumber: string, serviceId: number } export enum Status { ACTIVE = 'ACTIVE', SUSPENDED = 'SUSPENDED', PENDING = 'PENDING', CLOSED = 'CLOSED' } /** * Structure data from payments */ export interface PaymentAccount { id: number; userId: string, email: string, name: string, phoneNumber: string, balance: number; termsOfServiceAccepted : boolean; status: Status; }
a71ec4b313d08fe147cc0ed6f7c9924b32a7fb6d
TypeScript
ChiantiYZY/hw06-city-generation
/src/Building.ts
2.5625
3
import { vec2, vec3, mat4, mat3 } from 'gl-matrix'; import Turtle from './Turtle'; import Expansion from './Expansion'; import Draw from './Draw'; import { readTextFile } from './globals'; import Mesh from './geometry/Mesh'; export default class Building { cubeCount: number; cubeHeight: number; translateArray:Array<any> = []; meshArray: Array<Mesh> = []; heightArray: Array<any> = []; radiusArray: Array<any> = []; cubeSize: number; position: vec3; constructor(t: number, s: number, position: vec3) { // this.cubeCount = 0; this.cubeHeight = t; this.cubeSize = s; this.position = position; } drawCube(cube: Mesh, trans: vec3, ColorsArray: vec3, r: number, height: number) { //let ColorsArray: number[] = [0.2196, 0.1333, 0.0235, 1.0]; // brown //let rotate = vec3.fromValues(0, r, 0); let rotation = mat4.create(); mat4.fromRotation(rotation, r, vec3.fromValues(0, 1, 0)); let tran = vec3.fromValues(trans[0], this.cubeHeight, trans[2]); let translate = mat4.create(); let scalar = vec3.fromValues(this.cubeSize, height, this.cubeSize); let scalation = mat4.create(); mat4.fromTranslation(translate, tran); mat4.fromScaling(scalation, scalar); let transform = mat4.create(); // mat4.multiply(transform, position, transform); mat4.multiply(transform, rotation, transform); mat4.multiply(transform, scalation, transform); //mat4.multiply(transform, movePivot, transform); mat4.multiply(transform, translate, transform); cube.colorsArray.push(ColorsArray[0]); cube.colorsArray.push(ColorsArray[1]); cube.colorsArray.push(ColorsArray[2]); cube.colorsArray.push(1); cube.transArray1.push(transform[0]); cube.transArray1.push(transform[1]); cube.transArray1.push(transform[2]); cube.transArray1.push(transform[3]); cube.transArray2.push(transform[4]); cube.transArray2.push(transform[5]); cube.transArray2.push(transform[6]); cube.transArray2.push(transform[7]); cube.transArray3.push(transform[8]); cube.transArray3.push(transform[9]); cube.transArray3.push(transform[10]); cube.transArray3.push(transform[11]); cube.transArray4.push(transform[12]); cube.transArray4.push(transform[13]); cube.transArray4.push(transform[14]); cube.transArray4.push(transform[15]); cube.numbs++; } drawCubeBuilding(cube: Mesh) { //this.translateArray.push(0.0); // this.meshArray.push(cube); var trans = 0; var i = 0; // while(i < 4) // { while(this.cubeHeight > -18.0) { i++; var randObj = Math.random() ; let obj0: string; if(randObj <= 0.33) { obj0 = readTextFile('./src/prism.obj'); } else if(randObj <= 0.67) obj0 = readTextFile('./src/cube.obj'); else obj0 = readTextFile('./src/pentagon.obj'); let newMesh = new Mesh(obj0, vec3.fromValues(0, 0, 0)); newMesh.create(); this.meshArray.push(newMesh); var radius = (Math.random() - 0.5); this.radiusArray.push(radius); var y = Math.random() * 5.0; if(this.cubeHeight - y < -18.0) { y = this.cubeHeight + 18.0; } this.cubeHeight -= y; var x = (Math.random() - 0.5) * 2.0 * this.cubeSize; trans += x; var tran = vec3.fromValues(trans, y, 0); vec3.add(tran, tran, this.position); this.translateArray.push(tran); for(var j = 0; j < i; j++) { var r = Math.random(); var g = Math.random(); var b = Math.random(); let ColorsArray = vec3.fromValues(r, g, b); // brown this.drawCube(this.meshArray[j], this.translateArray[j], ColorsArray, this.radiusArray[j], y); } } // console.log(this.meshArray); for(var i = 0; i < this.meshArray.length; i++) { let col1: Float32Array = new Float32Array(this.meshArray[i].transArray1); let col2: Float32Array = new Float32Array(this.meshArray[i].transArray2); let col3: Float32Array = new Float32Array(this.meshArray[i].transArray3); let col4: Float32Array = new Float32Array(this.meshArray[i].transArray4); let colors: Float32Array = new Float32Array(this.meshArray[i].colorsArray); this.meshArray[i].setInstanceVBOs(col1, col2, col3, col4, colors); this.meshArray[i].setNumInstances(this.meshArray[i].numbs); } return this.meshArray; } drawStoreBuilding(cube: Mesh) { //this.translateArray.push(0.0); // this.meshArray.push(cube); var trans = 0; var i = 0; // while(i < 4) // { while(this.cubeHeight > -18.0) { i++; var randObj = Math.random() ; let obj0: string; if(randObj <= 0.5) obj0 = readTextFile('./src/cube.obj'); else obj0 = readTextFile('./src/pentagon.obj'); let newMesh = new Mesh(obj0, vec3.fromValues(0, 0, 0)); newMesh.create(); this.meshArray.push(newMesh); var radius = (Math.random() - 0.5); this.radiusArray.push(radius); var y = Math.random() * 8.0; if(this.cubeHeight - y < -18.0) { y = this.cubeHeight + 18.0; } this.cubeHeight -= y; if(radius < 0.0) trans = -trans - this.cubeSize; else trans += this.cubeSize; var tran = vec3.fromValues(trans, y, 0); vec3.add(tran, tran, this.position); this.translateArray.push(tran); for(var j = 0; j < i; j++) { var r = Math.random(); var g = Math.random(); var b = Math.random(); let ColorsArray = vec3.fromValues(r, g, b); // brown this.drawCube(this.meshArray[j], this.translateArray[j], ColorsArray, this.radiusArray[j], y); } } // console.log(this.meshArray); for(var i = 0; i < this.meshArray.length; i++) { let col1: Float32Array = new Float32Array(this.meshArray[i].transArray1); let col2: Float32Array = new Float32Array(this.meshArray[i].transArray2); let col3: Float32Array = new Float32Array(this.meshArray[i].transArray3); let col4: Float32Array = new Float32Array(this.meshArray[i].transArray4); let colors: Float32Array = new Float32Array(this.meshArray[i].colorsArray); this.meshArray[i].setInstanceVBOs(col1, col2, col3, col4, colors); this.meshArray[i].setNumInstances(this.meshArray[i].numbs); } return this.meshArray; } };
bcee74895d5003cec5c931947c7d0e89b965f239
TypeScript
dOrgTech/mutations
/packages/mutations/src/__tests__/mutations.test.ts
2.5625
3
import gql from 'graphql-tag' import 'cross-fetch/polyfill' import { createMutations, Mutations, MutationContext, MutationStates, } from '../' import { MutationStatesSubject } from '../mutationState' const schema = ` type Mutation { testResolve: Boolean! secondTestResolve: Boolean! dispatchStateEvent: Boolean! testConfig: String! testError: Boolean! testQuery: Boolean! } ` const invalidSchema = ` type Mutationsss { testResolve: Boolean! } ` const resolvers = { Mutation: { testResolve: () => { return true }, secondTestResolve: () => { return true }, dispatchStateEvent: async (_: any, __: any, context: MutationContext<Config>) => { await context.graph.state.dispatch('PROGRESS_UPDATE', { value: .5 }) return true }, testConfig: (_: any, __: any, context: MutationContext<Config>) => { return context.graph.config.value }, testError: () => { throw Error(`I'm an error...`) }, testQuery: async (_: any, __: any, context: MutationContext<Config>) => { try { await context.graph.client.query({ query: gql` query testQuery { testQuery { id } } ` }) return false } catch (e) { return e.message.indexOf('ECONNREFUSED') > -1 } }, }, } type Config = typeof config const config = { value: (arg: string) => arg, } describe('Mutations', () => { let mutations: Mutations<Config> let observer = new MutationStatesSubject({} as MutationStates) let latestState: MutationStates = {} beforeAll(() => { mutations = createMutations({ mutations: { resolvers, config, schema, }, subgraph: 'test', node: 'http://localhost:5000', config: { value: '...', }, }) observer.subscribe((value: MutationStates) => { latestState = value }) }) const getSetContext = () => { let context = { } return { setContext: (newContext: any) => { context = newContext return context }, getContext: () => context } } it('Successfully creates mutations and executes. No observer provided', async () => { const { data } = await mutations.execute({ query: gql` mutation testResolve { testResolve } `, ...getSetContext() }) expect(data && data.testResolve).toEqual(true) }) it('Fails when type Mutation is missing from the schema', async () => { try { createMutations({ mutations: { resolvers, config, schema: invalidSchema, }, subgraph: 'test', node: 'http://localhost:5000', config: { value: '...', }, }) expect('').toBe('This should never happen...') } catch (e) { expect(e.message).toBe( `type Mutation { ... } missing from the mutations module's schema` ) } }) it('Correctly wraps resolvers and formats observer results to object with mutation name as key and state as value', async () => { await mutations.execute({ query: gql` mutation testResolve { testResolve } `, ...getSetContext(), stateSubject: observer, }) expect(latestState).toHaveProperty('testResolve') expect(latestState.testResolve.events).toBeTruthy() }) it('Executes multiple mutations in the same mutation query and dispatches object with different states for each', async () => { const { data } = await mutations.execute({ query: gql` mutation testResolve { testResolve secondTestResolve } `, ...getSetContext(), stateSubject: observer, }) if (!data) { throw Error('data is undefined...') } expect(data).toHaveProperty('testResolve') expect(data.testResolve).toBeTruthy() expect(data).toHaveProperty('secondTestResolve') expect(data.secondTestResolve).toBeTruthy() expect(latestState).toHaveProperty('testResolve') expect(latestState.testResolve.events).toBeTruthy() expect(latestState).toHaveProperty('secondTestResolve') expect(latestState.secondTestResolve.events).toBeTruthy() expect(latestState.testResolve).not.toEqual(latestState.secondTestResolve) }) it('Executes the same mutation several times in the same query and dispatches object with different states for each', async () => { const { data } = await mutations.execute({ query: gql` mutation testResolve { testResolve testResolve } `, ...getSetContext(), stateSubject: observer, }) if (!data) { throw Error('data is undefined...') } expect(data).toHaveProperty('testResolve') expect(data.testResolve).toBeTruthy() expect(data).toHaveProperty('testResolve_1') expect(data.testResolve_1).toBeTruthy() expect(latestState).toHaveProperty('testResolve') expect(latestState.testResolve.events).toBeTruthy() expect(latestState).toHaveProperty('testResolve_1') expect(latestState.testResolve_1.events).toBeTruthy() expect(latestState.testResolve).not.toEqual(latestState.testResolve_1) }) it('Calls custom mutationExecutor', async () => { let called = false const mutations = createMutations({ mutations: { resolvers, config, schema, }, subgraph: '', node: '', config: { value: '...', }, mutationExecutor: (query) => { called = true return new Promise((resolve) => resolve({ data: { testResolve: true } })) } }) await mutations.execute({ query: gql` mutation testResolve { testResolve } `, ...getSetContext(), }) expect(called).toBeTruthy() }) it('Catches resolver execution errors', async () => { const { errors } = await mutations.execute({ query: gql` mutation testError { testError } `, ...getSetContext(), }) if (!errors) { throw Error('errors is undefined...') } expect(errors[0].message).toBe(`I'm an error...`) }) it('State is correctly updated', async () => { const observer = new MutationStatesSubject({}) let context = { graph: { rootSubject: observer, }, } let progress = 0 const subject = observer.subscribe((state: MutationStates) => { if (state.dispatchStateEvent) { progress = state.dispatchStateEvent.progress } }) await mutations.execute({ query: gql` mutation TestResolve { dispatchStateEvent } `, variables: {}, getContext: () => context, setContext: (newContext: any) => { context = newContext return context }, stateSubject: observer, }) expect(progress).toEqual(.5) subject.unsubscribe() }) it('Correctly queries using the remote executor', async () => { let context = {} as MutationContext<Config> const { data } = await mutations.execute({ query: gql` mutation testQuery { testQuery } `, variables: {}, getContext: () => context, setContext: (newContext: MutationContext<Config>) => { context = newContext return context }, }) expect(data && data.testQuery).toEqual(true) }) describe('mutations.configure(...)', () => { it('Correctly reconfigures the mutation module', async () => { { const { data } = await mutations.execute({ query: gql` mutation testConfig { testConfig } `, ...getSetContext(), }) if (!data) { throw Error('data is undefined...') } expect(data.testConfig).toEqual('...') } await mutations.configure({ value: 'foo', }) { const { data } = await mutations.execute({ query: gql` mutation testConfig { testConfig } `, ...getSetContext(), }) if (!data) { throw Error('data is undefined...') } expect(data.testConfig).toEqual('foo') } }) it('Detects incorrect configuration values object', async () => { try { await mutations.configure({ notValues: '' } as any) throw Error('This should never happen...') } catch (e) { expect(e.message).toBe( `Failed to find mutation configuration value for the property 'value'.`, ) } }) }) })
04886d3016b0c564f6c053b1a8007f2ea7474d99
TypeScript
sachinsinghsk13/The-Tech-Forums
/src/model/post.ts
2.6875
3
import User from "./user"; import Topic from "./topic"; import { getTime } from "../util/dateFormat"; export default class Post { public prettyDate: string | undefined; public postId: number | undefined; public content: string | undefined; public datePosted: Date | undefined; public postedBy: User | undefined; public topic: Topic | undefined; constructor(){ } setPostedDate(date: Date) { this.datePosted = date; if (this.datePosted) { this.prettyDate = getTime(this.datePosted); } } }
ec29374a4fdddd715bb95240755dc2167a3d558f
TypeScript
xiaolilir/LayaMiniGameFrame
/src/dMyGame/ConfigProxy/SkinConfigProxy.ts
2.734375
3
import { SkinConfig } from "../_config/SkinConfig"; import BaseConfigDataProxy from "../../aTGame/Config/RootDataProxy"; /** * 皮肤数据处理类 */ export default class SkinConfigProxy extends BaseConfigDataProxy<SkinConfig.config> { // private static _instance: SkinConfigProxy; /** 单例 */ public static get instance(): SkinConfigProxy { if (this._instance == null) { this._instance = new SkinConfigProxy(); } return this._instance; } // private constructor() { super(); } //初始化 protected initData() { this.m_dataList = SkinConfig.dataList; } /** * 通过皮肤名字获取皮肤数据 * @param _name 皮肤名字 */ public bySkinNameGetSkin(_name: string): SkinConfig.config { return this.m_dataList.find((item) => { return item.name == _name; }); } /** * 根据皮肤id获取数据 * @param _id 皮肤id */ public bySkinIdGetSkin(_id: number): SkinConfig.config { return this.m_dataList.find((item) => { return item.id == _id; }); } /** * 通过名字获取皮肤路径 * @param _name 皮肤名字 */ public bySkinNameGetURL(_name: string): string { let _data: SkinConfig.config = this.bySkinNameGetSkin(_name); if (_data) { return _data.ImageURL; } else { // console.warn("没有找到该皮肤!"); return ""; } } /** * 通过皮肤id获取皮肤名字 * @param _id 皮肤id */ public bySkinIdGetName(_id: number): string { let _data: SkinConfig.config = this.bySkinIdGetSkin(_id); if (_data) { return _data.name; } else { console.warn("没有找到该皮肤!"); return ""; } } }
9c7babf6b1f4104464a3a9274ed4feb64fe716eb
TypeScript
strongui/jodit
/src/core/helpers/normalize/normalize-css-value.ts
2.90625
3
/*! * Jodit Editor (https://xdsoft.net/jodit/) * Released under MIT see LICENSE.txt in the project root for license information. * Copyright (c) 2013-2023 Valeriy Chupurnov. All rights reserved. https://xdsoft.net */ /** * @module helpers/normalize */ import { isNumeric } from 'jodit/core/helpers/checker/is-numeric'; import { kebabCase } from 'jodit/core/helpers/string/kebab-case'; import { colorToHex } from 'jodit/core/helpers/color/color-to-hex'; import { isVoid } from 'jodit/core/helpers/checker/is-void'; export const NUMBER_FIELDS_REG = /^(left|top|bottom|right|width|min|max|height|margin|padding|fontsize|font-size)/i; export function normalizeCssNumericValue( key: string, value: string | number | undefined | null ): string | number | undefined | null { if ( !isVoid(value) && NUMBER_FIELDS_REG.test(key) && isNumeric(value.toString()) ) { return parseInt(value.toString(), 10) + 'px'; } return value; } export function normalizeCssValue( key: string, value: string | number ): string | number { switch (kebabCase(key)) { case 'font-weight': switch (value.toString().toLowerCase()) { case '700': case 'bold': return 700; case '400': case 'normal': return 400; case '900': case 'heavy': return 900; } return isNumeric(value) ? Number(value) : value; } if (/color/i.test(key) && /^rgb/i.test(value.toString())) { return colorToHex(value.toString()) || value; } return value; }
0ad4efb09646b9ee040000f14b694653db155aa9
TypeScript
LaKhDaR619/bangalore_challenge_backend
/src/features/timeLogs/controllers/timeLog.controller.ts
2.625
3
import { Request, Response, Router } from 'express'; import validationMiddleware from '../../../middlewares/dataValidator'; import Controller from '../../../shared/interfaces/controller.interface'; import AddTimeLogDTO from '../dtos/addTimeLog'; import TimeLogService from '../services/timeLog.service'; class TimeLogsController implements Controller { path = '/time_logs'; route = Router(); constructor() { this.initializeRoutes(); } initializeRoutes(): void { this.route.get('/', this.getAllTimeLogs); this.route.post('/', validationMiddleware(AddTimeLogDTO), this.addTimeLog); } async getAllTimeLogs(req: Request, res: Response) { const take = req.query.take || '10'; const skip = req.query.skip || '0'; const result = await TimeLogService.getAllTimeLogs( Number.parseInt(take as string), Number.parseInt(skip as string), ); res.json(result); } async addTimeLog(req: Request, res: Response) { const addTimeLogDTO: AddTimeLogDTO = req.body; if (addTimeLogDTO.startTime >= addTimeLogDTO.endTime) { return res .status(400) .json({ error: { message: 'endTime must be greater than startTime' } }); } await TimeLogService.addTimeLog(addTimeLogDTO); res.sendStatus(201); } } export default TimeLogsController;
458055167aa1df5108f10cd0f5a6bdcbc49cdc74
TypeScript
trebler/Messenger
/authservice/src/utils/respondtext.ts
2.515625
3
import { STATUS_CODES } from 'http'; import type { ServerResponse } from 'http'; export const respondText = ( res: ServerResponse, statusCode: number, extraHeaders: Record<string, string> = {} ): void => { const body = STATUS_CODES[statusCode]; return res .writeHead(statusCode, { 'Content-Length': body?.length || 0, 'Content-Type': 'text/plain', ...extraHeaders, }) .end(body); };
4ef47bae98f9612e7500c7f27d029a10f45d6da1
TypeScript
pasqualintosh/react-redux-ts-caldaiapiatto
/src/domains/watches/type.d.ts
2.828125
3
export interface IWatch { id: string; name: string; } export interface IWatchState { watches: Array<IWatch>; } export interface IWatchAction { type: string; wacth: IWatch; } export type DispatchType = (args: IWatchAction) => IWatchAction;
8e8367de8b46f452b2b57c158f5c6f7eef0dbb3a
TypeScript
blslade-neumont/agile-html5-game
/src/engine/audio-source-object.ts
2.640625
3
import { GameObject, GameObjectOptions } from './game-object'; import { GameScene } from './game-scene'; import { AudioT } from './utils/audio'; import merge = require('lodash.merge'); export interface AudioSourceObjectOptions extends GameObjectOptions { shouldLoop?: boolean } export class AudioSourceObject extends GameObject { constructor(name: string, private audio: AudioT, opts: AudioSourceObjectOptions = {}) { super(name, merge({ shouldRender: false }, opts)); if (typeof opts.shouldLoop !== 'undefined') this._shouldLoop = opts.shouldLoop; } private _shouldLoop = false; get shouldLoop() { return this._shouldLoop; } addToScene(scene: GameScene) { super.addToScene(scene); let theirAudio = this.resources.loadAudio(this.audio.src); this._myAudio = document.createElement('audio'); this._myAudio.src = theirAudio.src; this._myAudio.onended = () => { if (this._shouldLoop) this._myAudio.play(); else this.scene.removeObject(this); }; if (this.game.scene == scene) this._myAudio.play(); } private _myAudio: HTMLAudioElement; get myAudio() { return this._myAudio; } onSceneEnter() { if (this.myAudio.paused) this._myAudio.play(); } onSceneExit() { if (!this.myAudio.paused) this._myAudio.pause(); } }
58d0911f37cc3ff8662f1ae735c9dbbbd03d47e6
TypeScript
KranteshSingh/TypeScript
/04 Function Parameters/02RestParameter.ts
3.078125
3
let allPeopleIWantToInvite:string[] = [] let pushToPartyList = (...people:string[])=>{ console.log(people) let newPeopleArray = people allPeopleIWantToInvite = allPeopleIWantToInvite.concat(newPeopleArray) console.log(allPeopleIWantToInvite) return allPeopleIWantToInvite } pushToPartyList("Aditya","Sanjana","Pooja") pushToPartyList("Hena","Jaya","Shushma")
46869b973075dc57208367dd58db368ecc806d2f
TypeScript
santhoshkumarch/addressCrud
/src/app/in-memory-data.service.ts
2.875
3
import { InMemoryDbService } from 'angular-in-memory-web-api'; import { Address } from './address'; export class InMemoryDataService implements InMemoryDbService { createDb() { const add_res = [ { id: 1, firstname: 'Santhosh', lastname: 'Kumar', address1: '1299 Park Avenue', address2: 'Manhattan', city: 'Newyork City', state: "Newyork", pin: '100212' }, ]; return {add_res}; } // Overrides the genId method to ensure that a hero always has an id. // If the heroes array is empty, // the method below returns the initial number (11). // if the heroes array is not empty, the method below returns the highest // hero id + 1. genId(heroes: Address[]): number { return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11; } }
fcc012664a9ff555f99600c6ab89848998a54ef8
TypeScript
tarsupin/deno-sqlite
/mod.ts
2.765625
3
import { DB } from "./src/db.js"; import { Empty } from "./src/rows.js"; import { Status } from "./src/constants.ts"; import SqliteError from "./src/error.ts"; /** * open * * Open a new SQLite3 database. The file at * the path is read and preloaded into the database. * * ?> Unlike the SQLite3 C library, this will not * automatically write any changes to disk. Use * `db.data()` or `save(db)` to persist any changes * you make. */ async function open(path: string, ignoreNotFound = true): Promise<DB> { let bytes = undefined; try { bytes = await Deno.readFile(path); } catch (err) { if (!ignoreNotFound || !(err instanceof Deno.errors.NotFound)) { throw err; } } const db: any = new DB(bytes); db._save_path = path; return db; } /** * save * * Save database to file. If the database was opened * from a file using `open()`, the second parameter * is optional. */ async function save(db: DB, path?: string): Promise<void> { path = path || (db as any)._save_path as string; if (!db._open) { throw new SqliteError("Database was closed."); } // We obtain the data array ourselves to avoid // .data() making a copy const ptr = db._wasm.get_db_file(db._id); const len = db._wasm.get_db_file_size(db._id); const data = new Uint8Array(db._wasm.memory.buffer, ptr, len); return Deno.writeFile(path, data); } export { open, save, DB, Empty, Status };
28b7822f829a3dcd91570c69665d7bcb0744dc89
TypeScript
eoodin/shelf
/frontend/src/app/htmltext.pipe.ts
2.5625
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'htmltext' }) export class HtmltextPipe implements PipeTransform { private domPaser; transform(value: any, args?: any): any { if (value == null) { return ''; } if (typeof value !== 'string') { throw new Error('html text pipe cannot handle type ' + (typeof value)); } if (!this.domPaser) { this.domPaser = new DOMParser(); } return this.domPaser.parseFromString(value, 'text/html').documentElement.textContent; } }
23d7677e1df99cf6cef3509b230aefe30f9df5fd
TypeScript
map-c/koa-service
/src/utils/jwt.ts
2.734375
3
import Application from 'koa' import jwtGenerator, { SignOptions, TokenExpiredError, VerifyOptions } from 'jsonwebtoken' import { RouterContext } from 'koa-router' class Token { /** * 令牌的 secret 值,用于令牌加密 */ public secret: string | undefined /** * access token */ public accessExp: number = 60 * 60 /** * access token 默认的过期时间 */ public refreshExp: number = 60 * 60 * 24 constructor(secret?: string, accessExp?: number, refreshExp?: number) { secret && (this.secret = secret) refreshExp && (this.refreshExp = refreshExp) accessExp && (this.accessExp = accessExp) } public initApp( app: Application, secret: string, accessExp?: number, refreshExp?: number ) { app.context.jwt = this secret && (this.secret = secret) accessExp && (this.accessExp = accessExp) refreshExp && (this.refreshExp = refreshExp) } /** * 生成 access_token * @param identity */ public createAccessToken(identity: string | number) { if (!this.secret) { throw new Error('secret can not be empty') } let exp: number = Math.floor(Date.now() / 1000) + this.accessExp return jwtGenerator.sign( { exp, identity, scope: 'cola', type: 'access' }, this.secret ) } /** * 生成 refresh_token * @param identity 标识位 */ public createRefreshToken(identity: string | number) { if (!this.secret) { throw new Error('secret can not be empty') } let exp = Math.floor(Date.now() / 1000) + this.refreshExp return jwtGenerator.sign( { exp, identity, scope: 'cola', type: 'refresh' }, this.secret ) } public verifyToken(token: string, type = 'access') { if (!this.secret) { throw new Error('secret can not be empty') } let decode try { decode = jwtGenerator.verify(token, this.secret) } catch (error) { if (error instanceof TokenExpiredError) { if (type === 'access') { throw new Error('出错了') } } } return decode } } const jwt = new Token() export function createAccessToken( payload: string | object, options?: SignOptions ) { let exp: number = Math.floor(Date.now() / 100) + jwt.accessExp if (typeof payload === 'string') { return jwtGenerator.sign( { indentify: payload, type: 'access', exp: jwt.accessExp }, jwt.secret!, options ) } else { return jwtGenerator.sign( { ...payload, type: 'access', exp: exp }, jwt.secret!, options ) } } export function createRefreshToken( payload: string | object, opitons?: SignOptions ) { let exp: number = Math.floor(Date.now() / 1000) + jwt.refreshExp if (typeof payload === 'string') { return jwtGenerator.sign( { indentify: payload, type: 'refresh', exp: jwt.refreshExp }, jwt.secret!, opitons ) } } export function verifyAccessToken(token: string, options?: VerifyOptions) { let decode try { decode = jwtGenerator.verify(token, jwt.secret!, options) } catch (err) { throw new Error('出错了') } return decode } export function getTokens(user: any) { const accessToken = jwt.createAccessToken(user.id) const refreshToken = jwt.createRefreshToken(user.id) return { accessToken, refreshToken } } export function parseHeader(ctx: RouterContext, type = 'access') { if (!ctx.header || !ctx.header.authorization) { ctx.throw(401, new Error('没有权限')) } const parts = ctx.header.authorization.split(' ') if (parts.length === 2) { const schema = parts[0] const token = parts[1] if (/^Bearer$/i.test(schema)) { const obj = (ctx as any).jwt.verifyToken(token, type) if (!obj.type || obj.type !== type) { ctx.throw(401, '权限已过期') } return obj } } else { ctx.throw(401, '无权限') } }
b17d56b9c21bbaf0b543c153b0290f1cf3e6fd83
TypeScript
ryepup/c4-lab
/src/core/codegen.ts
2.78125
3
import * as lz from 'lz-string' import Viz from 'viz.js' type elementCreator = (tagName: string) => HTMLElement /** * convert a graph from DOT text to SVG */ export const toSvg = (dot: string) => Viz(dot, { format: 'svg', engine: 'dot' }) as string /** * convert a text representation to an URI-encoded representation */ export const uriEncode = (text: string) => lz.compressToEncodedURIComponent(text) /** * convert an URI-encoded representation to a text representation */ export const uriDecode = (uriData: string) => lz.decompressFromEncodedURIComponent(uriData) /** * convert DOT text to a png-encoded data URI */ export const toPngDataUri = (dot: string, createElement: elementCreator) => { const svg = toSvg(dot) const img = createElement('img') as HTMLImageElement return new Promise<string>((resolve) => { img.onload = () => resolve(toDataUrl(img, createElement)) img.setAttribute('src', 'data:image/svg+xml,' + encodeURIComponent(svg)) }) } function toDataUrl(img: HTMLImageElement, createElement: elementCreator) { const canvas = createElement('canvas') as HTMLCanvasElement canvas.width = img.width canvas.height = img.height const context = canvas.getContext('2d') if (context) { context.drawImage(img, 0, 0) const dataUrl = canvas.toDataURL('image/png') return dataUrl } }
4ea90867a665f5c4769008a3b78acccd55da4b63
TypeScript
aiduc93/realworld-angular
/src/app/models/user.ts
2.859375
3
export interface User { bio: string; createdAt: string; email: string; id: number; image: string; token: string; updatedAt: string; username: string; password?: string; } export class UserResponse implements User { bio: string; createdAt: string; email: string; id: number; image: string; token: string; updatedAt: string; username: string; password: string; constructor(user: User) { if (user) { this.bio = user.bio; this.createdAt = user.createdAt; this.email = user.email; this.id = user.id; this.image = user.image; this.token = user.token; this.updatedAt = user.updatedAt; this.username = user.username; this.password = user.password; } } } export class UserPost { user: UserResponse constructor(user: UserResponse) { if (user) { this.user = user; } } }
894613232c89d836426bd4f63537a1f7484d8462
TypeScript
bgruening/ngl
/dist/declarations/utils/netcdf-reader.d.ts
2.859375
3
/** * @file Netcdf Reader * @author Alexander Rose <alexander.rose@weirdbyte.de> * @private * * Adapted from https://github.com/cheminfo-js/netcdfjs * MIT License, Copyright (c) 2016 cheminfo */ import IOBuffer from './io-buffer'; export interface NetCDFRecordDimension { length: number; id?: number; name?: string; recordStep?: number; } export interface NetCDFHeader { recordDimension: NetCDFRecordDimension; version: number; dimensions: any[]; globalAttributes: any[]; variables: any[]; } export interface NetCDFDimension { name: string; size: number; } /** * Reads a NetCDF v3.x file * https://www.unidata.ucar.edu/software/netcdf/docs/file_format_specifications.html */ declare class NetcdfReader { header: Partial<NetCDFHeader>; buffer: IOBuffer; /** * @param {ArrayBuffer} data - ArrayBuffer or any Typed Array with the data */ constructor(data: ArrayBuffer); /** * @return {string} - Version for the NetCDF format */ get version(): "classic format" | "64-bit offset format"; /** * @return {object} - Metadata for the record dimension * * `length`: Number of elements in the record dimension * * `id`: Id number in the list of dimensions for the record dimension * * `name`: String with the name of the record dimension * * `recordStep`: Number with the record variables step size */ get recordDimension(): NetCDFRecordDimension | undefined; /** * @return {Array<object>} - List of dimensions with: * * `name`: String with the name of the dimension * * `size`: Number with the size of the dimension */ get dimensions(): any[] | undefined; /** * @return {Array<object>} - List of global attributes with: * * `name`: String with the name of the attribute * * `type`: String with the type of the attribute * * `value`: A number or string with the value of the attribute */ get globalAttributes(): any[] | undefined; /** * @return {Array<object>} - List of variables with: * * `name`: String with the name of the variable * * `dimensions`: Array with the dimension IDs of the variable * * `attributes`: Array with the attributes of the variable * * `type`: String with the type of the variable * * `size`: Number with the size of the variable * * `offset`: Number with the offset where of the variable begins * * `record`: True if is a record variable, false otherwise */ get variables(): any[] | undefined; /** * Checks if a variable is available * @param {string|object} variableName - Name of the variable to check * @return {Boolean} - Variable existence */ hasDataVariable(variableName: string): boolean; /** * Retrieves the data for a given variable * @param {string|object} variableName - Name of the variable to search or variable object * @return {Array} - List with the variable values */ getDataVariable(variableName: string | {}): any[]; } export default NetcdfReader;
e4c12e89b47171dcbcd77e570f7a0dee136ff8a3
TypeScript
Auggustos/sistema-gestao-vidracaria
/projeto-vidracaria/backend/src/modules/products/services/CreateProductService.ts
2.625
3
import Product from '@modules/products/infra/typeorm/entities/Product'; import IStorageProvider from '@shared/container/providers/StorageProvider/models/IStorageProvider'; import AppError from '@shared/errors/AppError'; import { injectable, inject } from 'tsyringe'; import IProductsRepository from '../repositories/IProductsRepository'; interface IRequest { description: string; imageFileName: any; quantity: number; name: string; } @injectable() class CreateProductService { constructor( @inject('ProductsRepository') private productsRepository: IProductsRepository, @inject('StorageProvider') private storageProvider: IStorageProvider, ) { } public async execute({ description, imageFileName, quantity, name, }: IRequest): Promise<Product> { const product = await this.productsRepository.create({ description, imageFileName, quantity, name, }); if (quantity < 0) { throw new AppError( 'Não é possível criar um produto com quantidade negativa.' ); } const filename = await this.storageProvider.saveFile(imageFileName); product.image = filename await this.productsRepository.save(product); return product; } } export default CreateProductService;
2c52281aa588372fa0f5aebf9468ee701bc24693
TypeScript
Sid12869/mikaela
/src/commands/fun/lonely.ts
2.640625
3
import { Command } from '../../classes/Command'; const koroneLink = 'https://cdn.discordapp.com/attachments/702091543514710027/820638857396617226/Korone_you_are_lonely_lonely_lonely.mp4'; export const command: Command = { name: 'lonely', description: 'Posts a video of Korone telling you how lonely you are 😢', aliases: ['alone', 'korone'], execute(message, args: string[]) { message.channel.send(koroneLink); } };
147b9adbe124fe05e5d5e489338f787dbdcd14d0
TypeScript
samdiano/book-a-meal-api
/v2/src/orders/order.model.ts
2.59375
3
import { AllowNull, BelongsTo, BelongsToMany, Column, DataType, Default, ForeignKey, HasMany, IsUUID, Model, PrimaryKey, Table } from 'sequelize-typescript'; import { User } from '../users/user.model'; import { Meal } from '../meals/meal.model'; import { OrderItem } from './orderItem.model'; import { Notification } from '../notifications/notification.model'; enum ORDER_STATUS { started = 'started', pending = 'pending', delivered = 'delivered', canceled = 'canceled' } @Table export class Order extends Model<Order | any> { @IsUUID(4) @PrimaryKey @AllowNull(false) @Default(DataType.UUIDV4) @Column(DataType.UUID) orderId: string; @Column(DataType.TEXT) deliveryAddress: string; @Column deliveryPhoneNo: string; @Default('started') @Column(DataType.ENUM('started', 'pending', 'delivered', 'canceled')) status: ORDER_STATUS; @IsUUID(4) @ForeignKey(() => User) @Column(DataType.UUID) userId: string; @BelongsTo(() => User, 'userId') customer: User; @BelongsToMany(() => Meal, () => OrderItem, 'orderId') meals: Meal[]; @HasMany(() => Notification, 'orderId') notifications: Notification[]; };
fa1259320c08fc9eca7c7aa1375b1082e1e64307
TypeScript
FunCloud/NodeRocket2
/server/sys/util/stringUtil.ts
3.203125
3
/** * 字符串处理工具类 * @author dapaer */ export default class stringUtil{ /** *获取Action名称 *url url **/ static getActionName(url) { var expStr = url.split('!'); var tempArr = expStr[0].split('/'); return tempArr[tempArr.length - 1]; } /** *获取Action名称 *url url **/ static getMethodName(url) { var arr = url.split('!'); return arr[arr.length - 1].split('?')[0]; } /** * 转换成驼峰命名 * @param str 要转换的字符串 * @returns {string} * @author dapaer */ static changeToHump(str){ var firstChat = str[0].toLocaleLowerCase(); if(str.length==1){ return firstChat; } return firstChat.toLocaleLowerCase()+str.substr(1,str.length-1); } }
e1ec73a71967128ac2e003754e7214d94ae7d067
TypeScript
MrZhouZh/awesome-validator
/test/rules/contains.ts
2.90625
3
import { assert } from 'chai'; import { AbstractRule } from '../../src/rules/abstract-rule'; import { Contains } from '../../src/rules/contains'; describe('Contains', () => { class Foo { /** * bar */ public bar: string = 'foobar'; } it('is rule', () => { assert.instanceOf(new Contains(), AbstractRule); }); it('values is valid', () => { assert.isTrue(new Contains('foo').validate('FOO')); assert.isTrue(new Contains('FOO').validate('foo')); assert.isTrue(new Contains('foo').validate(['FOO'])); assert.isTrue(new Contains('foo').validate('foobar')); assert.isTrue(new Contains('foo').validate(String('foobar'))); assert.isTrue(new Contains(1).validate([1, 2, 3])); assert.isTrue(new Contains('1').validate([1, 2, 3])); assert.isTrue(new Contains('foo').validate(new Array('foo', 'bar', 'foobar'))); assert.isTrue(new Contains(1).validate(new Set([1, 2, 3]))); assert.isTrue(new Contains('foo').validate(new Set(['foo', 'bar', 'foobar']))); assert.isTrue(new Contains(1).validate(new Map().set(1, 'bar'))); assert.isTrue(new Contains('foo').validate(new Map().set('foo', 'bar'))); assert.isTrue(new Contains('foo').validate({foo: 'bar'})); assert.isTrue(new Contains('foo').validate(Object({foo: 'bar'}))); assert.isTrue(new Contains('foo', false).validate('Foo')); assert.isTrue(new Contains('FOO', false, true).validate('FOO')); assert.isTrue(new Contains(null).validate(null)); const foo: Foo = new Foo(); assert.isTrue(new Contains(foo).validate(foo)); assert.isTrue(new Contains('bar').validate(foo)); }); it('values is not valid', () => { assert.isFalse(new Contains('bar').validate('foo')); assert.isFalse(new Contains(String('bar')).validate('foo')); assert.isFalse(new Contains(0).validate([1, 2, 3])); assert.isFalse(new Contains('foobar').validate(new Array('foo', 'bar'))); assert.isFalse(new Contains(0).validate(new Set([1, 2, 3]))); assert.isFalse(new Contains('foobar').validate(new Set(['foo', 'bar']))); assert.isFalse(new Contains(0).validate(new Map().set(1, 'bar'))); assert.isFalse(new Contains('foobar').validate(new Map().set('foo', 'bar'))); assert.isFalse(new Contains('bar').validate({foo: 'bar'})); assert.isFalse(new Contains('bar').validate(Object({foo: 'bar'}))); assert.isFalse(new Contains().validate(null)); assert.isFalse(new Contains('foo', false).validate('foobar')); assert.isFalse(new Contains('foo', false, true).validate('FOO')); assert.isFalse(new Contains().validate(null)); assert.isFalse(new Contains(new Foo()).validate(new Foo())); assert.isFalse(new Contains('foobar').validate(new Foo())); assert.isFalse(new Contains(1, false, true).validate('1')); assert.isFalse(new Contains(1, false, true).validate(['1', 2, 3])); }); });
570c86590b06f5bf712cd7fa3756e6b2e7e328dd
TypeScript
wandyezj/standard-node
/src/lib/equivalentLists.ts
3.84375
4
/** * checks if two lists have the same values in the same order using the default comparison operator. * @public * @param a - a list * @param b - a list * @returns true if both lists have the same values in the same order. */ export function equivalentLists(a: string[], b: string[]): boolean { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; }
ed8f2b2944938d159bad57cc25fbc083789a50d1
TypeScript
Nesci28/PubAuCochonFume
/server/helpers/jwt.helper.ts
2.765625
3
import * as jwt from "jsonwebtoken"; import { User } from "../interfaces/user.interface"; const JWT_SECRET = process.env.JWT_SECRET; class JWTHelpers { constructor() {} async getId(token: string): Promise<string> { token = this.cleanToken(token); return new Promise<string>((resolve, _) => { resolve((jwt.verify(token, JWT_SECRET) as any).id); }); } async getUsername(token: string): Promise<string> { token = this.cleanToken(token); return new Promise<string>((resolve, _) => { resolve((jwt.verify(token, JWT_SECRET) as any).username); }); } async getRole(token: string): Promise<string> { token = this.cleanToken(token); return new Promise<string>((resolve, _) => { resolve((jwt.verify(token, JWT_SECRET) as any).role); }); } async validateJWTToken(token: string): Promise<boolean> { token = this.cleanToken(token); return new Promise<boolean>((resolve, _) => { try { jwt.verify(token, JWT_SECRET); resolve(true); } catch (_) { resolve(false); } }); } cleanToken(token: string): string { if (token.startsWith("Bearer ")) { token = token.split("Bearer ")[1]; } return token; } createJWTToken(user: User): string { return jwt.sign( { id: user._id, username: user.username, role: "admin", }, JWT_SECRET, { expiresIn: "30d" } ); } } export default new JWTHelpers();
815bdf66edaa40323206982a3a9e30baae1595bd
TypeScript
Li357/WHS
/packages/app/src/reducers/elearningPlans.ts
2.53125
3
import { ELearningPlansState, ELearningPlansAction, ELearningPlansActions } from '../types/store'; import { initialELearningPlansState } from '../constants/store'; export default function elearningPlansReducer( state: ELearningPlansState = initialELearningPlansState, action: ELearningPlansAction, ) { switch (action.type) { case ELearningPlansActions.SET_PLANS: return action.payload; default: return state; } }
d8a2c8457cc7fc03bf742201a24a54ea70718727
TypeScript
Aakashdeveloper/May_ang_mrng
/firstapp/src/app/shared/star.component.ts
2.8125
3
import { Component, OnChanges, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-star', templateUrl: './star.component.html', styleUrls: ['./star.component.css'] }) export class StarComponent implements OnChanges, OnInit, OnDestroy { // this is always get call first and // only one time starWidth: number; @Input() rating: number; @Output() ratingClicked: EventEmitter<string> = new EventEmitter<string>(); constructor() { console.log('inside Constructor'); } // This work on change detection ngOnChanges() { console.log(this.rating); this.starWidth = this.rating * 86 / 5.2; } // This fires after onchanges ngOnInit() { console.log('inside oninit'); } // when you looose context ngOnDestroy() { console.log('inside on destroy'); } onStarClick(): void { this.ratingClicked.emit(`Rating clicked is ${this.rating}`); } }
8f3b0b9583ec23a2f8fe28bc4e5a29322f6f7f19
TypeScript
fwpushan/fresh-forms
/packages/web/src/store/modules/student/student.ts
2.984375
3
export class StudentState { profile!: StudentProfile; } export class StudentProfile { name?: string; age?: string; birthdate?: string; givenNames?: string; lastName?: string; email?: string; emailVerified?: string; familyName?: string; gender?: string; givenName?: string; middleName?: string; } const initialState: StudentState = { profile: new StudentProfile(), }; export const student = { namespaced: true, state: initialState, mutations: { SET_STUDENT_PROFILE_DATA(state: StudentState, parsedToken: any) { state.profile.name = parsedToken.name; state.profile.age = parsedToken.age; state.profile.birthdate = parsedToken.birthdate; state.profile.givenNames = parsedToken.givenNames; state.profile.lastName = parsedToken.lastName; state.profile.email = parsedToken.email; state.profile.emailVerified = parsedToken.email_verified; state.profile.familyName = parsedToken.family_name; state.profile.gender = parsedToken.gender; state.profile.middleName = parsedToken.middle_name; }, }, actions: { setStudentProfileData({ commit }: { commit: Function }, token: any) { commit("SET_STUDENT_PROFILE_DATA", token.tokenParsed); }, }, };
c7223d9fd4be4ebc2e9b5a78a3fc45f7bc26c816
TypeScript
ndf1997/whentomeet
/frontend/src/types/Member.ts
2.75
3
import PropTypes from 'prop-types'; import { Day, DayPropType } from './Day'; import { days as d } from './constants'; export class Member { meeting_id: string; member_id: string; name: string; days: Day[]; pollingChoice?: number; constructor(meeting_id: string = '', member_id: string = '', name: string = '', days: Day[] = []) { this.meeting_id = meeting_id; this.member_id = member_id; this.name = name; this.days = days; if (days.length === 0) { this.days = d.map(day => new Day(day)); } } } export const MemberPropType = PropTypes.shape({ meeting_id: PropTypes.string.isRequired, member_id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, days: PropTypes.arrayOf(DayPropType.isRequired).isRequired, });
cc2b48dc79b535557c279908d348213cacce421b
TypeScript
azael1412/angular-input-image
/src/app/hello.component.ts
2.671875
3
import { Component, forwardRef, HostBinding, Input, HostListener, ElementRef, OnInit } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; @Component({ template: ' <input class="file-input" type="file">', selector: 'app-custom-input', providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => HelloComponent ), multi: true } ] }) export class HelloComponent implements ControlValueAccessor, OnInit { constructor(private host: ElementRef) { } ngOnInit(): void { console.log('HelloComponent initialized'); } onChange: Function; onTouch: any = () => {} private file: File | null = null; base64textString : string = ""; @HostListener('change', ['$event.target.files']) emitFiles( event: FileList ) { console.log(event); const file = event && event.item(0); console.log(file) if (file) { const reader = new FileReader(); reader.onload = this.handleReaderLoaded.bind(this); reader.readAsBinaryString(file); } console.log(this.base64textString); //this.onChange(file); //this.onChange(this.base64textString); this.file = file; //const file = evt.target.files[0]; } val= "" // this is the updated value that the class accesses /*set value(val){ // this value is updated by programmatic changes if( val !== undefined && this.val !== val){ this.val = val this.onChange(val) this.onTouch(val) }*/ // this method sets the value programmatically writeValue(value: any){ this.host.nativeElement.value = ''; this.val = value this.file = null; //this.value = value } // upon UI element value changes, this method gets triggered registerOnChange(fn: any){ console.log('registerOnChange called') console.log(fn); this.onChange = fn if(this.onChange) { console.log(this.onChange) } } // upon touching the element, this method gets triggered registerOnTouched(fn: any){ this.onTouch = fn } handleReaderLoaded(e) { this.base64textString = 'data:image/png;base64,' + btoa(e.target.result); console.log('HE HANDLEADO EL EVENTO LOAD xd') console.log(this.base64textString) this.onChange(this.base64textString); } }
04ac8eec5cc68e4af92b9f602deebda744632a9b
TypeScript
AStaroverov/minesweeperonline
/lib/Renderer/examples/triangles/worker.ts
2.5625
3
import { scheduler, TaskQueue, Task } from '../../../Scheduler'; import { render } from '../../src/render'; import { TComponentData } from '../../src/types'; import { BaseComponent } from '../../src/BaseComponent'; import { createElement, withDeclarativeSetChildren } from '../../src/mixins/withDeclarativeSetChildren'; import { getInitData } from '../../src/worker/getInitData'; import { getWorkerScope } from '../../src/worker/getWorkerScope'; main(); type TContext = { x: number y: number angle: number }; async function main (): Promise<void> { const workerScope = await getWorkerScope(); const { canvases } = await getInitData(workerScope); const canvas = canvases[0]; const ctx = canvas.getContext('2d')!; const queue = new TaskQueue(); scheduler.add(queue); (function tick () { scheduler.traverse(); requestAnimationFrame(tick); })(); const targetSize = 24; class Dot extends BaseComponent<TContext> { constructor ( protected props: { x: number y: number s: number } ) { super(); } p1: { x: number, y: number } = { x: 0, y: 0 }; p2: { x: number, y: number } = { x: 0, y: 0 }; p3: { x: number, y: number } = { x: 0, y: 0 }; render (): void { const props = this.props; const halfS = props.s / 2; const x = props.x + halfS; const y = props.y + halfS; this.p1.x = x; this.p1.y = y; this.p2.x = x - halfS; this.p2.y = y + halfS; this.p3.x = x + halfS; this.p3.y = y + halfS; rotatePoint(this.p1, this.context, this.context.angle); rotatePoint(this.p2, this.context, this.context.angle); rotatePoint(this.p3, this.context, this.context.angle); ctx.moveTo(this.p1.x, this.p1.y); ctx.lineTo(this.p2.x, this.p2.y); ctx.lineTo(this.p3.x, this.p3.y); ctx.lineTo(this.p1.x, this.p1.y); } } class Triangle extends withDeclarativeSetChildren(BaseComponent) { constructor ( protected props: { x: number y: number s: number } ) { super(); } protected connected (): void { super.connected(); this.setChildren(this.updateChildren()); } updateChildren (): TComponentData[] { let { s, x, y } = this.props; if (s <= targetSize) { return [ createElement(Dot, { x: x - (targetSize / 2), y: y - (targetSize / 2), s: targetSize }) ]; } s /= 2; return [ createElement( Triangle, { x, y: y - (s / 2), s } ), createElement( Triangle, { x: x - s, y: y + (s / 2), s } ), createElement( Triangle, { x: x + s, y: y + (s / 2), s } ) ]; } } class Fill extends BaseComponent { protected render (): void { ctx.closePath(); ctx.fill(); } } class Root extends withDeclarativeSetChildren(BaseComponent)<TContext> { constructor () { super(); queue.add(new Task(() => { // eslint-disable-next-line @typescript-eslint/restrict-plus-operands this.context.angle = this.context.angle + 0.01; this.requestUpdate(); })); } protected connected (): void { super.connected(); this.context = { x: canvas.width / 2, y: canvas.height / 2, angle: 0 }; this.setChildren(this.updateChildren()); } protected render (): void { ctx.fillStyle = 'blue'; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); } protected updateChildren (): TComponentData[] { return [ createElement( Triangle, { x: this.context.x, y: this.context.y, s: 800 } ), createElement(Fill) ]; } } render(workerScope, new Root()); } function rotatePoint<T extends { x: number, y: number }> (point: T, pivotPoint: T, angle: number): T { const s: number = Math.sin(angle); const c: number = Math.cos(angle); // translate point back to origin: point.x -= pivotPoint.x; point.y -= pivotPoint.y; // rotate point const newX: number = point.x * c - point.y * s; const newY: number = point.x * s + point.y * c; // translate point back: point.x = newX + pivotPoint.x; point.y = newY + pivotPoint.y; return point; }
dea47add6a46e357b353cc21d882c50b5b6486d5
TypeScript
annapoliswu/CISC474-Backend
/backend/src/security/userModel.ts
3.09375
3
import bcrypt from 'bcrypt'; //represents a user in the system export class UserModel{ id?=''; email = ''; private _password=''; favorites:Array<string> = []; //["test", "5eb5a1fbe2e28b1d9c2aafc2"] listings:Array<string> = []; //when user password is set through here, it is stored encrypted set password(val:string){ this._password=UserModel.encryptString(val); } //returns encrypted password get password():string{return this._password;} //encrypts password public constructor(email:string,password:string,favorites:Array<string>,listings:Array<string>){ this.email=email; this.password=password; this.favorites = favorites; this.listings = listings; } //does not encrypt password, expects already encrypted password static fromObject=(obj:any):UserModel=>{ const mdl=new UserModel(obj.email,'',obj.favorites, obj.listings); mdl._password=obj.password; return mdl; } //includes encrypted password toObject=(): any=> ({email: this.email,password: this.password, favorites: this.favorites, listings: this.listings}); //compares unencrypted password to encrypted password validatePassword(password:string):boolean{ if (this.password==='*') {return false;} return bcrypt.compareSync(password,this.password); } //encrypt a string using the bcrypt library static encryptString(inval:string):string{ try { var salt = bcrypt.genSaltSync(10); return bcrypt.hashSync(inval, salt); }catch (err){ return '*'; } } }
5705f88e1e8b82d961ab91b5637f72907ea41a5c
TypeScript
benhawley7/FUT-DB
/src/players/types.ts
2.90625
3
/** * @file Contains types and constants relevant to the players * @package fut-db * @author Ben Hawley * @copyright Ben Hawley 2020 */ /** * List of Numeric Fields for Player Objects */ export const numFields = [ "rating", "pace", "shooting", "passing", "dribbling", "defending", "physicality", "diving", "handling", "kicking", "reflexes", "speed", "positioning" ]; /** * Shared Player Properties between Outfield and Goalkeepers * @interface */ export interface Player { [key: string]: string | number; name: string; club: string; position: string; revision: string; league: string; rating: number; } /** * Main stats of an outfield player * @interface */ export interface OutfieldPlayer extends Player { pace: number; shooting: number; passing: number; dribbling: number; defending: number; physicality: number; } /** * Main stats of a goalkeeper player * @interface */ export interface GoalkeeperPlayer extends Player { diving: number; handling: number; kicking: number; reflexes: number; speed: number; positioning: number; }
7aa83504098cbffa08d7883be411c1c20de9f8ba
TypeScript
LaserFlash/qcyc-usagemaintenancetracker
/src/app/core/constants/known-boats/known-boats.service.ts
2.515625
3
import { Injectable } from '@angular/core'; import { Boat, BoatID } from '../../objects/boat'; import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore'; import { Observable } from 'rxjs/Observable'; import { map } from 'rxjs/operators'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable({ providedIn: 'root' }) export class KnownBoatsService { private itemsCollection: AngularFirestoreCollection<Boat>; private boats: BoatID[]; public boatInformation: BehaviorSubject<BoatID[]> = new BehaviorSubject([]); constructor(private db: AngularFirestore) { this.itemsCollection = db.collection<Boat>('/boats', ref => ref.orderBy('name', 'asc')); let items: Observable<BoatID[]>; items = this.itemsCollection.snapshotChanges().pipe( map(actions => { return actions.map(action => { const data = action.payload.doc.data() as BoatID; const id = action.payload.doc.id; return { ...data, id }; }); }) ); items.subscribe((doc) => { const currentBoats: BoatID[] = []; doc.forEach(element => { currentBoats.push(element); }); this.boatInformation.next(currentBoats); }); this.boatInformation.subscribe((boats) => { this.boats = boats; }); } public addOrUpdateDoc(boat: BoatID): string { if (!boat.id) { boat.id = this.db.createId(); } this.itemsCollection.doc(boat.id).set({ name: boat.name, selectable: boat.selectable }, { merge: true }); return boat.id; } public restore(boat: BoatID) { if (boat.name === '') { this.deleteDoc(boat); } else { this.itemsCollection.doc(boat.id).set({ name: boat.name, selectable: boat.selectable }, { merge: true }); } } public deleteDoc(boat: BoatID) { this.itemsCollection.doc(boat.id).delete(); } getBoatName(key: string): string { const boatFound = this.boats.find((boat) => { return boat.id === String(key); }); if (boatFound) { return boatFound.name; } else { return 'Unknown Name'; } } }
2957c5b049122f5a0b9ef6ad7d8f499b4fc61c19
TypeScript
AlexCovizzi/vscode-sqlite
/tests/fixtures/index.ts
2.53125
3
import { join, basename } from "path"; import { randomString } from "../../src/utils/utils"; export namespace Fixture { export const DATABASE_MAIN = "main"; export const DATABASE_EMPTY = "empty"; export interface Database { name: string; path: string; tables: { name: string; columns: { name: string; type: string; notnull: boolean; pk: number }[] records: string[][] }[]; } export function getMainDatabase(): Database { return getDatabase(DATABASE_MAIN); } export function getEmptyDatabase(): Database { return getDatabase(DATABASE_EMPTY); } function getDatabase(name: string): Database { name = name.endsWith(".json")? name : name+".json"; let obj = require(join(__dirname, "database", name)); let fixture = JSON.parse(JSON.stringify(obj)); if (!fixture.name) { if (fixture.path) fixture.name = basename(fixture.path); else fixture.name = randomString(6) + ".db"; } if (!fixture.path) { fixture.path = join(__dirname, fixture.name); } return fixture; } }
64ba8e245530b51674a840d9e043dfb3cc69240a
TypeScript
tracernz/igniter
/src/Renderer.ts
2.8125
3
import { Task } from './Library/Contracts/Task'; export default async (task: Task, refreshRate = 100) => { const spinner = ['◜', '◠', '◝', '◞', '◡', '◟']; const render = () => { process.stdout.write('\x1Bc'); const spinnerChar = spinner.shift(); spinner.push(spinnerChar); const view = task.render().replaceAll('⊙', spinnerChar); console.log(view); // eslint-disable-line no-console }; // If refreshRate is zero we just want to run the root task. // Then we'll render ONCE to get the final output, and return. if (refreshRate === 0) { await task.run(); render(); return; } const interval = setInterval(render, refreshRate); await task.run(); clearInterval(interval); render(); };
971113b2fa252f8d22af98e3e62b99950aedbfbf
TypeScript
SamuelDrews/wirvsvirus_diy_masks
/src/ts/react/pudos/formatDistance.ts
2.53125
3
export default (x: number) => { if (x < 1) { return Math.floor(x * 1000) + ' m' } return Math.floor(x * 10) / 10 + ' km' }
39c1137c166cdffd36c969b266fcb748cfaac6a9
TypeScript
Fice/jst
/src/encodeToken.ts
3.625
4
// The `encodeToken` function encodes a string for use as a JSON pointer token // replacing the values '~' with '~0' and '/' with '~1'. // ## Usage // // ```javascript // import { encodeToken } from '@jdw/jst'; // // encodeToken('~/home') // '~0~1home' // ``` // // **Arguments** // - `token: string A string to encode // // **Returns** // - `string`: The escaped string // // **Throws** // - {Error}: If something went wrong. // ## Implementation const encodeToken = (pointer: string) => { return pointer .replace(new RegExp('~', 'g'), '~0') .replace(new RegExp('/', 'g'), '~1'); }; export { encodeToken, };
aff7149bf062465998ace9e4f09368c51562af18
TypeScript
dralc/ng-pipes
/src/app/sort.pipe.ts
2.6875
3
import { Pipe, PipeTransform, ElementRef } from '@angular/core'; import { ServerInfo } from './serverInfo.model'; @Pipe({ name: 'sort', pure: false }) export class SortPipe implements PipeTransform { /** * Sorts an Array of Objects by the object <key>'s value * @returns The sorted <inputAr> */ transform(inputAr: Array<Object>, key: string): Array<Object> { if (!key) { return inputAr; } inputAr.sort((a, b) => { let valA = a[key]; let valB = b[key]; if (typeof valA === 'string' && typeof valB === 'string') { valA = valA.toUpperCase(); valB = valB.toUpperCase(); } return valA < valB ? -1 : (valA > valB ? 1 : 0); }); return inputAr; } }
f95f836a7d6b7718746510e6f9edc73be7d00b7f
TypeScript
ksanman/bike-estimator
/src/app/part.service.ts
2.578125
3
import { Injectable } from '@angular/core'; import { Part } from './part'; import { BehaviorSubject, Observable, of } from 'rxjs'; @Injectable() export class PartService { private parts: Part[] = [ {id: 0, category: { id: 1, name: 'Frame'}, name: 'Santa Cruz Blur', price: '$2999.99', weight: '2700'} ]; private partsSubject: BehaviorSubject<Part[]> = new BehaviorSubject<Part[]>([]); constructor() { this.updateSubject(); } parts$: Observable<Part[]> = this.partsSubject.asObservable(); addPart(part: Part): void { part.id = this.parts.length > 0 ? Math.max(...this.parts.map(p => p.id)) + 1 : 1; this.parts.push(part); this.updateSubject(); } updateSubject(): void { this.partsSubject.next(this.parts.map(p => Object.assign({}, p))); } }
212013d93d59129d9c68f5b101e088103867992a
TypeScript
ecologylab/BigSemanticsJavaScript
/src/downloaders/ServiceRepoLoader.ts
2.578125
3
/** * Helper for caching repository from BigSemantics web service. */ import * as Promise from 'bluebird'; import ParsedURL from '../core/ParsedURL'; import { Repository } from '../core/types'; import RepoMan, { RepoOptions } from '../core/RepoMan'; import { Downloader } from '../core/Downloader'; import { RepoLoader } from '../core/RepoLoader'; import ServiceHelper from "./ServiceHelper"; /** * */ export interface ServiceRepoLoaderOptions { appId?: string; appVer?: string; serviceBase: string | ParsedURL; repoFileName?: string; repoOptions?: RepoOptions; /** * Format: "1d", "1d12h", "5h30m", "100m" * Minimum: 10 min * Default value: 1d. * @type {[type]} */ cacheRepoFor?: string; disableRepoCaching?: boolean; requesterFactory?: ()=>Downloader; } /** * Helper for caching repository from BigSemantics web service. */ export class ServiceRepoLoader implements RepoLoader { private options: ServiceRepoLoaderOptions; private serviceHelper: ServiceHelper; private repoMan: RepoMan; private repoManLife: number = 0; private repoManTimer: any = undefined; getOptions(): ServiceRepoLoaderOptions { return this.options; } getServiceHelper(): ServiceHelper { return this.serviceHelper; } load(options: ServiceRepoLoaderOptions): void { this.options = options; this.serviceHelper = new ServiceHelper(); this.serviceHelper.load(options); if (!options.disableRepoCaching) { let cacheRepoFor = options.cacheRepoFor || '1d'; let match = cacheRepoFor.match(/((\d+)d)?((\d+)h)?((\d+)m)?/i); if (!match) { throw new Error("Invalid cache life: " + options.cacheRepoFor); } let d = match[2] ? Number(match[2]) : 0; let h = match[4] ? Number(match[4]) : 0; let m = match[6] ? Number(match[6]) : 0; this.repoManLife = d*86400000 + h*3600000 + m*60000; if (this.repoManLife < 3600000) { console.warn("Minimal repository cache life: 10min"); this.repoManLife = 600000; } this.getRepoMan(); } else { console.log("Repository caching disabled."); } } /** * If repository is cached, this will force repository to be reloaded from the * last used service. */ reload(): void { if (this.repoMan) { this.reloadRepoMan(); } } getRepoMan(): Promise<RepoMan> { if (this.repoMan && !this.options.disableRepoCaching) { return Promise.resolve(this.repoMan); } return this.reloadRepoMan(); } reloadRepoMan(): Promise<RepoMan> { if (this.repoMan) { this.repoMan.reset(); } else { this.repoMan = new RepoMan(); } let filename = 'mmdrepository.json'; if (this.options.repoFileName) { filename = this.options.repoFileName; } return this.serviceHelper.callJSONService(filename).then(result => { if (result['meta_metadata_repository']) { result.repository = result['meta_metadata_repository'] } if (!result.repository) { throw new Error("Missing repository in server response"); } this.repoMan.load(result.repository, this.options.repoOptions); if (this.repoManLife > 0) { if (this.repoManTimer) { clearTimeout(this.repoManTimer); } this.repoManTimer = setTimeout(() => { this.reloadRepoMan(); }, this.repoManLife); } return this.repoMan.onReadyP(); }).catch(err => { this.repoMan.setError(err); throw new Error(`Failed to load repository with base ${this.options.serviceBase}`); }); } } export default ServiceRepoLoader;
1c5d2e089b8ecc5f61052a005f73627975d77d6c
TypeScript
cvimbert/reverted-template
/src/reverted-template.class.ts
2.921875
3
import {Expressions} from "./expressions.class"; import {TemplateGroup} from "./template-group.class"; import {GroupType} from "./group-type.enum"; export class RevertedTemplate { private groups: TemplateGroup[] = []; constructor( templateText: string, contentFormat: string = "([A-Za-z0-9]+)" ) { let groupLines = this.getGroups(templateText); groupLines.forEach((line: string) => { this.groups.push(new TemplateGroup(line, contentFormat)); }); } private getGroups(text: string): string[] { text = text.replace(Expressions.leftBracket, "["); text = text.replace(Expressions.rightBracket, "]"); return this.splitGroups(text); } private splitGroups(text: string): string[] { return text.split(Expressions.groupSplitter).filter((line: string) => { return line !== ""; }); } extract(text: string): Object[] { let result: Object[] = []; let lineIndex: number = 0; let lines: string[] = this.splitGroups(text); let currentLine: string; for (let group of this.groups) { if (group.type === GroupType.BASIC) { currentLine = lines[lineIndex]; if (group.test(currentLine)) { result.push(group.extractFirstMatchingContent(currentLine)); lineIndex++; } else { this.incomplete(lineIndex, result); } } else if (group.type === GroupType.ARRAY) { let groupArray:Object[] = []; currentLine = lines[lineIndex]; while (group.test(currentLine)) { groupArray.push(group.extractFirstMatchingContent(currentLine)); lineIndex++; currentLine = lines[lineIndex]; } if (groupArray.length > 0) { result.push(groupArray); } else { this.incomplete(lineIndex, result); } } } return result; } incomplete(lineIndex:number, result:Object) { console.warn(`Error parsing template line ${ lineIndex + 1 }, incomplete result`); return result; } }
31309107857d5f58392f5a7266d3a0d3f8802e3e
TypeScript
Aszparuh/Design-Patterns
/StructuralPatterns/Facade/Player.ts
3.140625
3
import IPlayer from "./IPlayer"; import MediaEntry from "./MediaEntry"; class Player implements IPlayer { private readonly playList!: MediaEntry[]; private currentIndex: number = 0; constructor() { this.playList = new Array<MediaEntry>(); } Play(): void { if (this.playList.length === 0) { throw Error("Playlist is empty"); } let currentItem = this.playList[this.currentIndex]; if (currentItem === null) { throw Error("Item does not exist"); } console.log(`Playing ${currentItem.title} - Duration: ${currentItem.durationSeconds} seconds`); } Stop(): void { console.log("Stop"); } Next(): void { this.currentIndex++; if (this.currentIndex >= this.playList.length) { this.currentIndex = 0; } console.log("Switching to next item...") } Previous(): void { this.currentIndex--; if (this.currentIndex < this.playList.length) { this.currentIndex = this.playList.length - 1; } console.log("Switching to previous item...") } LoadMedia(mediaEntry: MediaEntry): void { this.playList.push(mediaEntry); console.log(`Media Added ${mediaEntry.title}`); } } export default Player;
f7037555c946ede0d2d96aec972f9c7d2c7038b5
TypeScript
zxhfighter/measure
/src/component/overlay/dynamic-component.service.ts
2.75
3
import { Injector, Injectable, TemplateRef, ViewRef, ElementRef, EmbeddedViewRef, ViewContainerRef, Renderer2, RendererFactory2, ComponentRef, ComponentFactory, ComponentFactoryResolver } from '@angular/core'; import { ConnectionPosition } from './position.interface'; import { Subscription } from 'rxjs'; /** * Class that allows for inserting Text or TemplateRef. */ export class ContentRef { constructor(public nodes: any[], public viewRef?: ViewRef, public _componentRef?: ComponentRef<any>) { } } @Injectable() export class DynamicComponentService<T> { /** It’s not a good idea to inject Renderer2 in Service. so create it in constructor */ private _renderer: Renderer2; /** created component reference */ private _componentRef: ComponentRef<T> | null; /** places a new component as the content */ private _contentRef: ContentRef | null; /** places a new component at this container */ private _viewContainerRef: ViewContainerRef; /** Subscription to viewport resize events. */ private _resizeSubscription = Subscription.EMPTY; /** attachment element's calculated position */ originPos: ConnectionPosition; /** overlay element's calculated position */ overlayPos: ConnectionPosition; /** overlay element's original position such as 'bottom-top' */ placement: string; constructor( private _injector: Injector, private rendererFactory: RendererFactory2, private _componentFactoryResolver: ComponentFactoryResolver) { this._renderer = this.rendererFactory.createRenderer(null, null); } /** * create the given component or text to DOM element using the ComponentFactoryResolver. * * @param { any } type * @param { string | TemplateRef<any> } content * @param { Element } hostDomElement * @param { any } context * @return { ComponentRef<T> } _componentRef */ createDynamicComponent( viewContainerRef: ViewContainerRef, type: any, content: string | TemplateRef<any>, hostDomElement?: Element, context?: any): ComponentRef<T> { this._viewContainerRef = viewContainerRef; let windowFactory: ComponentFactory<T>; if (!this._componentRef) { this._contentRef = this._getContentRef(content, context); windowFactory = this._componentFactoryResolver.resolveComponentFactory<T>(type); this._componentRef = this._viewContainerRef.createComponent(windowFactory, 0, this._injector, this._contentRef.nodes); } if (hostDomElement) { let overlayRootNode = this.getComponentRootNode(this._componentRef); hostDomElement.appendChild(overlayRootNode); } return this._componentRef; } /** * dispose the created component and remove from the body and unsubscribe event */ dispose() { if (this._componentRef) { this._viewContainerRef.remove(this._viewContainerRef.indexOf(this._componentRef.hostView)); this._componentRef = null; let viewRef = this._contentRef!.viewRef; if (viewRef) { this._viewContainerRef.remove(this._viewContainerRef.indexOf(viewRef)); this._contentRef = null; } } this._resizeSubscription.unsubscribe(); } /** * get content from given content * @param { string | TemplateRef<any> } content * @param { any } context * @return { ContentRef } */ private _getContentRef(content?: string | TemplateRef<any>, context?: any): ContentRef { if (!content) { return new ContentRef([]); } else if (content instanceof TemplateRef) { const viewRef = this._viewContainerRef.createEmbeddedView(<TemplateRef<T>>content, context); return new ContentRef([viewRef.rootNodes], viewRef); } else { return new ContentRef([[this._renderer.createText(`${content}`)]]); } } /** * get component's root node for appending given element * @param { string | TemplateRef<any> } content * @return { HTMLElement } */ getComponentRootNode(_componentRef: ComponentRef<any>): HTMLElement { return (_componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement; } }
85fed01ddc0e2888573059a8a781d28c2336f46a
TypeScript
MingZhang-PS/product
/src/app/actions/products.action.ts
2.59375
3
import { Action } from '@ngrx/store'; import { Product } from '../models/Product'; export enum ProductsActionTypes { LoadProducts = '[Products] LoadProducts', AddProduct = '[Products] AddProduct', AddProductSuccess = '[Products] AddProductSuccess', DeleteProduct = '[Products] DeleteProduct', UpdateProduct = '[Products] UpdateProduct', SelectProduct = '[Products] SelectProduct', LoadProductsSuccess = '[Products] LoadProductsSuccess', SearchProduct = '[Products] SearchProduct' } export class LoadProducts implements Action { readonly type = ProductsActionTypes.LoadProducts; } export class AddProduct implements Action { readonly type = ProductsActionTypes.AddProduct; constructor(public payload: Product) {} } export class AddProductSuccess implements Action { readonly type = ProductsActionTypes.AddProductSuccess; constructor(public payload: Product) {} } export class DeleteProduct implements Action { readonly type = ProductsActionTypes.DeleteProduct; constructor(public productId: number) {} } export class UpdateProduct implements Action { readonly type = ProductsActionTypes.UpdateProduct; constructor(public payload: Product) {} } export class SearchProduct implements Action { readonly type = ProductsActionTypes.SearchProduct; constructor(public searchTerm: string) {} } export class LoadProductsSuccess implements Action { readonly type = ProductsActionTypes.LoadProductsSuccess; constructor(public payload: Product[]) {} } export class SelectProduct implements Action { readonly type = ProductsActionTypes.SelectProduct; constructor(public payload: Product) {} } export type ProductsActions = LoadProducts | LoadProductsSuccess | AddProduct | AddProductSuccess | DeleteProduct | UpdateProduct | SearchProduct | SelectProduct;
e00f682f0fd978f0bb98260724da0e3ac55be23d
TypeScript
guryanov-a/d3-heat-map
/src/stores/HeatMapStore.ts
2.640625
3
interface MonthlyVarianceInterface { year: number; } interface HeatMapDataInterface { monthlyVariance: MonthlyVarianceInterface[]; baseTemperature: number; } class HeatMapStore { data: HeatMapDataInterface; } export const heatMapStore = new HeatMapStore();
740d4f944e7ff4ee3c8190fd93e65882aa3b7aab
TypeScript
austinevov/sage-tour-studio
/src/packages/sage-tour/src/core/lod/LODManager.ts
2.828125
3
import LODNode from './LODNode'; export default class LODManager { private isPreloaded: boolean; private lod: LODNode; private gl: WebGLRenderingContext; constructor(id: number) { this.lod = new LODNode(id, 512, 0, 5); this.lod.next = new LODNode(id, 1024, 1, 5); } public initialize = (gl: WebGLRenderingContext): void => { this.gl = gl; this.lod.initialize(gl); this.lod.next.initialize(gl); }; public update = (): void => { if (this.lod.next && this.lod.next.isBuffered()) { this.lod = this.lod.next; } }; public isCompletelyBuffered = (): boolean => { return !this.lod.next && this.lod.isBuffered(); }; public buffer = (): void => { const oldTexture = this.gl.getParameter(this.gl.TEXTURE_BINDING_2D); const oldActive = this.gl.getParameter(this.gl.ACTIVE_TEXTURE); this.lod.buffer(); if (this.lod.isBuffered() && this.lod.next) { this.lod.next.buffer(); } if (oldTexture) { this.gl.activeTexture(oldActive); this.gl.bindTexture(this.gl.TEXTURE_2D, oldTexture); } }; public bind = (): void => { const oldTexture = this.gl.getParameter(this.gl.TEXTURE_BINDING_2D); const oldActive = this.gl.getParameter(this.gl.ACTIVE_TEXTURE); this.lod.bind(); if (oldTexture) { this.gl.activeTexture(oldActive); //this.gl.bindTexture(this.gl.TEXTURE_2D, oldTexture); } }; public preload = (imagePathRoot: string): Promise<any> => { if (!this.isPreloaded) { this.isPreloaded = true; return this.lod.load(imagePathRoot); } else { } return new Promise((resolve, reject) => { resolve(); }); }; public getBestTexture = (): number => { return this.lod.getTextureOffset(); }; public load = (imagePathRoot: string): Promise<any> => { let current = this.lod; const promises: Promise<any>[] = []; while (current !== null && current !== undefined) { promises.push(current.load(imagePathRoot)); current = current.next; } return Promise.all(promises); }; }
0a80463b2c2a1ce5299a8528341da6a115d76b06
TypeScript
ShahriyarSheikh/Safe-quote-commenting
/Backend/src/model/request-models/user/userForgotPassword.model.ts
2.796875
3
import { IsEmail } from "class-validator"; export class UserForgotPassword { @IsEmail() private _email: string; get email(): string { return this._email; } set email(name: string) { this._email = name.toLowerCase(); } }
d2faa224c4c2bd531aa428601c6fc3a17406810f
TypeScript
sunyang-629/the-movie-db-react
/src/client/actions/movies.ts
2.828125
3
import { IAction, IGetMoviesResponse, IProcessedMoviesResponse, } from '../interfaces/actions'; import fetch from '../../common/utils/fetch'; // action types export const ERROR_RECEIVING_MOVIES = 'ERROR_RECEIVING_MOVIES'; export const GET_MOVIES = 'GET_MOVIES'; export const HANDLE_INPUT_CHANGE = 'HANDLE_INPUT_CHANGE'; export const LOAD_MORE = 'LOAD_MORE'; export const RECEIVE_MOVIES = 'RECEIVE_MOVIES'; // action creators export function errorReceivingMoviesAction(error: Error) { return { error, type: ERROR_RECEIVING_MOVIES, }; } export function getMoviesAction(): IAction { return { type: GET_MOVIES }; } export function handleInputChangeAction(input: string) { return { input, type: HANDLE_INPUT_CHANGE }; } export function loadMoreAction() { return { type: LOAD_MORE }; } export function receiveMoviesAction(response: IProcessedMoviesResponse): IAction { return { movies: response.results, page: response.page, query: response.query, totalPages: response.total_pages, totalResults: response.total_results, type: RECEIVE_MOVIES, }; } // async actions export function getMovies(pageNumber: number = 1) { return (dispatch, getState) => { const input = getState().movies.input; const path = input ? '/search/movie' : '/movie/popular'; const query = input ? `&query=${encodeURI(input)}` : ''; const queryParameter = `?page=${pageNumber}${query}`; const url = `/api${path}${queryParameter}`; dispatch(getMoviesAction()); return fetch(url) .then((response: IGetMoviesResponse) => ( dispatch(receiveMoviesAction({ ...response, query: input, })) )) .catch(err => dispatch(errorReceivingMoviesAction(err))); }; } export function loadNextPage() { return (dispatch, getState) => { dispatch(loadMoreAction()); const nextPage = getState().movies.page + 1; return getMovies(nextPage)(dispatch, getState); }; }
8e17da3ea202e33f98ed8be902842b83d52b35bd
TypeScript
shk1993/DynamicUI
/src/util/NextQuestionParser.ts
2.765625
3
import { Grammar, Parser } from 'nearley'; import { IAnswers } from '../interfaces/answers'; import { ICondition, IConditional, IDEIDFunction, INextQuestion, IQuestionReturn, IQuestionValue, } from '../interfaces/nextQuestion'; import { map } from '../state/stateHandler'; let grammar: Grammar; let parser: Parser; // tslint:disable-next-line:no-var-requires grammar = Grammar.fromCompiled(require('../grammar/nextQuestion')); const isConditionTrue = (condition: ICondition) => { const result = map[condition.condEval.state][condition.expr]( condition.condEval.QID, condition.AID, ); return result !== undefined ? result : true; }; const evaluateNextQuestionFunction = (deid: IDEIDFunction) => { const nextQuestion = map.loop.peek(deid.state.QID); map.loop.pop(deid.state.QID); return nextQuestion; }; const evaluateConditional = (conditional: IConditional): INextQuestion => { return conditional.condition.every(isConditionTrue) ? conditional.trueNextQuestion : conditional.falseNextQuestion; }; const parseNextQuestion = (nextQuestion: string) => { parser = new Parser(grammar); parser.feed(nextQuestion); return parser.results[0]; }; const getNextQuestion = (nextQuestion: IQuestionValue): IQuestionReturn => { return typeof nextQuestion.QID === 'string' ? (nextQuestion as IQuestionReturn) : { modifier: nextQuestion.modifier, QID: evaluateNextQuestionFunction(nextQuestion.QID), }; }; /** * This function is the function called by the NextQuestion function. It returns an IQuestionReturn object * for the NextQuestion function to return. * @param value Currently submited value for the current question * @param answers All the possible answer choices for the current question * @returns An IQuestionReturn object NextQuestion to return back to QuestionSet */ export const getNextQuestionOfString = (value: string, answers: IAnswers) => { const nextQuestion = value in answers ? answers[value].nextQuestion : answers.noKey.nextQuestion; let nextQuestionParsed = parseNextQuestion(nextQuestion); while (nextQuestionParsed.type !== 'nextQuestion') { nextQuestionParsed = evaluateConditional( nextQuestionParsed.value as IConditional, ); } if (nextQuestionParsed.value.length) { const next = []; for (const val of nextQuestionParsed.value) { next.push(getNextQuestion(val.DEID)); } return next; } else { return [getNextQuestion(nextQuestionParsed.value as IQuestionReturn)]; } };
dc9c6b5104840b4b42f8cb8e7c3cd1310fbcbe0f
TypeScript
dogstarYT/BeatBox
/TS/model.ts
2.578125
3
let model = { positions: [] as Array<{ x: number, y: number, fileName: string, beat: number }>, files: [] as Array<{ fileName: string, beats: Array<boolean>, audio: HTMLAudioElement }>, lenght: 0, steps: 0, heightS: 0, widthS: 0, leftShift: 200, reLoadModule: ((beatCanvasId: string) => { model.files.forEach(f => { while (f.beats.length < model.steps) { f.beats.push(false); } while (f.beats.length > model.steps) { f.beats.pop(); } }); model.redraw(beatCanvasId); }), redraw: ((beatCanvasId: string) => { if (model.files.length > 0) { if (!beatCanvas || !ctxBeat) { beatCanvas = document.getElementById(beatCanvasId) as HTMLCanvasElement; ctxBeat = beatCanvas.getContext('2d'); } ctxBeat.clearRect(0, 0, beatCanvas.width, beatCanvas.height); beatCanvas.width = beatCanvas.clientWidth; beatCanvas.height = beatCanvas.clientHeight; model.heightS = beatCanvas.height / (model.files.length + 1); model.widthS = (beatCanvas.width - model.leftShift) / (model.steps + 1); //draw rows for (let i = 1; i <= model.files.length; i++) { ctxBeat.beginPath(); ctxBeat.moveTo(model.leftShift, (model.heightS + 1) * i); ctxBeat.lineTo(beatCanvas.width, (model.heightS + 1) * i); ctxBeat.stroke(); ctxBeat.font = "30px Arial"; ctxBeat.fillText(model.files[i - 1].fileName, 0, (model.heightS + 1) * i + 10); } //draw colums model.positions = []; for (let j = 0; j <= model.files.length - 1; j++) { for (let i = 0; i <= model.steps - 1; i++) { let obj = { x: (model.widthS * (i + 1)) + model.leftShift, y: (model.heightS + 1) * (j + 1), fileName: model.files[j].fileName, beat: i } model.positions.push(obj) if (model.files[j].beats[i]) { ctxBeat.beginPath(); ctxBeat.arc(obj.x, obj.y, 20, 0, 2 * Math.PI); ctxBeat.fillStyle = "black"; ctxBeat.fill(); } } } model.positions.forEach(p => { ctxBeat.beginPath(); ctxBeat.moveTo(p.x, p.y + 10) ctxBeat.lineTo(p.x, p.y - 10) ctxBeat.stroke(); }); //text } }), ClickCauculation: ((clickX: number, clickY: number) => { //console.log("click at " + clickX + " " + clickY); let pos = model.positions.find(p => { let a = p.x - clickX; let b = p.y - clickY; let c = Math.sqrt(a * a + b * b); return (c < 30) }); if (pos) { model.SelectBeat(pos.beat, pos.fileName) } }), SelectBeat: ((beat: number, fileName: string) => { let locationBeat = model.files.find(f => { return (f.fileName == fileName); }); if (locationBeat) { locationBeat.beats[beat] = !(locationBeat.beats[beat]) model.redraw("beatCanvas"); } }) };
6554b27aded39b1984994da944e5e8c59cd5c78b
TypeScript
ddaras/dropzone
/src/hooks/useApi.ts
2.53125
3
import { useMutation, useQuery } from '@apollo/client'; interface IOptions { variables?: object; hasInput?: boolean; onSuccess?: (res: any) => void; onCompleted?: (data: any) => void; } interface IResponse { call: (options?: object) => any; data?: any; loading?: boolean; } const useApi = (mutationOrQuery: any, options?: IOptions) => { const response: IResponse = { call: () => {} }; switch (mutationOrQuery.definitions[0].operation) { case 'query': const { data: queryData, loading: loadingQuery } = useQuery( mutationOrQuery, options ); response.data = queryData; response.loading = loadingQuery; break; case 'mutation': const [call, { data: mutationData, loading: loadingMutation }] = useMutation(mutationOrQuery, options); response.call = call; response.data = mutationData; response.loading = loadingMutation; break; default: } return response; }; export default useApi;
f295a5162ff3aa7fa55f252059e5c2c982277eae
TypeScript
luorixiangyang/Blog-code
/front_end/scheme/scheme_event_emitter/src/observable/index.ts
3.015625
3
import EventEmitter from '../emitter'; import { Observable, ObservableListener } from './interface'; /** * 创建一个可观察对象 * 内部使用 Proxy 代理 * @param obj * @returns */ const createObservable = <T extends Object>(obj: T): T & Observable<T> => { const ON_DATA_UPDATE = 'ON_DATA_UPDATE'; const emitter = new EventEmitter<string, T>(); const proxy = new Proxy( Object.assign(obj, { subscribe(listener: ObservableListener<T>) { emitter.on(ON_DATA_UPDATE, listener); }, }), { set(target, propKey, value, receiver) { const res = Reflect.set(target, propKey, value, receiver); emitter.emit(ON_DATA_UPDATE, target); return res; }, } ); return proxy; }; export default createObservable;
c2acf25bf756f6f0a13dec1baeee532dc654707d
TypeScript
rands0n/hoje-tem-live
/src/services/lives.ts
2.625
3
import {chunk, removeDuplicates} from 'utils/array'; import {getRandomInt} from 'utils/number'; import {Genre, GenreMapping, Live, LivesHub} from 'schemas/api'; import {getBaseData} from 'services/_base'; // Utils const mapLives = (allLives: Live[], allGenres: Genre[]) => { // Featured Lives const validLives = allLives.filter((live) => live.active); const livesChunks = chunk(validLives, 10); const randomFeatured1 = getRandomInt(0, livesChunks[0].length); const randomFeatured2 = getRandomInt(0, livesChunks[1].length); const randomFeatured3 = getRandomInt(0, livesChunks[2].length); const featured1 = validLives[randomFeatured1]; const featured2 = validLives[randomFeatured2]; const featured3 = validLives[randomFeatured3]; const featured = [featured1, featured2, featured3]; // Lives per genre const genres = allGenres.map((genre) => genre.id); const genresMapping = {} as GenreMapping; genres.forEach((id) => { genresMapping[id] = allLives.filter((item) => { const hasItem = !!item.genres.find((genre) => genre.id === id); return hasItem; }); }); // Final response const livesHub = { featured, genres: genresMapping, }; return livesHub as LivesHub; }; // Exported export const getLivesHub = async () => { const allLives = await getBaseData(); const rawGenres = allLives.map((item) => item.genres).flat(); const allGenres = removeDuplicates(rawGenres); const lives = mapLives(allLives, allGenres); return lives; }; export const getLive = async (liveId: string) => { const id = Number(liveId); const allLives = await getBaseData(); const live = allLives.find((item) => item.id === id); return live; };
2c03412aa8ef6832804a8ad7ad0811c79e683264
TypeScript
codestothestars/react-pivot-table
/src/aggregation/DefaultAggregators.ts
2.578125
3
import { Aggregator } from './Aggregator'; /** * The default aggregators provided for use in the pivot table. */ export interface DefaultAggregators { /** * Sums numeric metrics. */ sum: Aggregator<number>; }
cbefcafb7fd06e702f6f668f1e6c150d4e1cc5d2
TypeScript
rafaneri/phychips-rcp
/lib/rcp-manager.ts
2.546875
3
import { Packet } from './packet'; import { Util } from "."; import { EventEmitter } from 'events'; export class RcpManager extends EventEmitter { private preamble: number = 0xBB; private endMark: number = 0x7E; private byteRxPkt: Buffer; private rcpReceivedPacket: boolean; private rcpReceivedPacketCrcError: boolean; private static instance: RcpManager; constructor() { super(); this.byteRxPkt = Buffer.from([]); this.rcpReceivedPacket = false; this.rcpReceivedPacketCrcError = false; } dataReceived(data: Buffer): void { if (data.length != 0) { this.byteRxPkt = Buffer.concat([this.byteRxPkt, data], this.byteRxPkt.length + data.length); let num = 0; for (num = 0; num < this.byteRxPkt.length && this.byteRxPkt[num] != this.preamble; num++) { } if (num != 0) { this.byteRxPkt = Buffer.from(this.byteRxPkt.subarray(num, this.byteRxPkt.length - num)); } while (true) { if (this.byteRxPkt.length > 8) { let num2 = (this.byteRxPkt[3] << 8) + this.byteRxPkt[4]; if (this.byteRxPkt[num2 + 5] == this.endMark) { this.rcpReceivedPacket = true; let bytePkt2 = Buffer.from(this.byteRxPkt.subarray(0, num2 + 8)); this.parseRxData(bytePkt2); bytePkt2 = Buffer.from([]); if (this.byteRxPkt.length - (num2 + 8) > 0) { bytePkt2 = Buffer.from(this.byteRxPkt.subarray(num2 + 8, this.byteRxPkt.length - (num2 + 8))); } this.byteRxPkt = Buffer.from(bytePkt2); continue; } this.byteRxPkt = Buffer.from([]); continue; } return; } } } private parseRxData(buffer: Buffer): void { switch (buffer[1]) { case 1: case 2: case 3: case 4: this.emit('packet', Packet.from(buffer)); break; } } }
0b6fd9f6b2854b7dd69d5ab1195f00b38bf9e109
TypeScript
LucasAurelio/alocca
/alocca/src/app/requests/request-access/request-access.component.ts
2.53125
3
import { Component, OnInit } from '@angular/core'; import { FirebaseService } from '../../services/firebase.service'; import { Request } from '../request.model'; import { Router } from '@angular/router'; import { SnackbarService } from '../../services/snackbar.service'; @Component({ selector: 'app-request-access', templateUrl: './request-access.component.html', styleUrls: ['./request-access.component.css'] }) export class RequestAccessComponent implements OnInit { /** * Email of the access request to be saved. */ email: string; /** * Name of the access request to be saved. */ name: string; /** * SIAPE number of the access request to be saved. */ SIAPE: string; /** * Message to display when the access request is saved. */ SAVED_SUCCESSFULLY_MESSAGE: string = "Sua solicitação foi enviada!"; /** * Timeout for the message displayed in the snackbar * * when the access request is saved. */ TIMEOUT_SAVED_MESSAGE = 2500; /** * Message to display when the access request is not saved. */ NOT_SAVED_MESSAGE: string = "Opa! Parece que você já enviou uma solicitação com o email fornecido."; /** * Timeout for the message displayed in the snackbar * * when the access request is not saved. */ TIMEOUT_NOT_SAVED_MESSAGE = 5000; constructor( private FBservice: FirebaseService, private router: Router, private snackService: SnackbarService ) { } /** * Saves a new access request (object) on form submission. */ onAddNewRequest(){ let request = new Request ( this.SIAPE, this.name, this.email ) let savedSuccessfully: boolean = this.FBservice.addNewRequest(request); this.SIAPE = null; this.email = null; this.name = null; if(savedSuccessfully){ this.snackService.openSnackBar(this.SAVED_SUCCESSFULLY_MESSAGE, this.TIMEOUT_SAVED_MESSAGE); this.router.navigate(['/home']); } else{ this.snackService.openSnackBar(this.NOT_SAVED_MESSAGE, this.TIMEOUT_NOT_SAVED_MESSAGE); } } /** * Sets necessary elements on the start of the page. */ ngOnInit() { let initiateRequests: any[]; this.FBservice.getRequestsEmails().valueChanges().subscribe(requests =>{ initiateRequests = requests; }); } }
cfc77cc3f83cce592e1a0bf859a2763808710d82
TypeScript
oanaariana/office-portofolio
/src/app/office-portofolio/models/building-vm.model.ts
2.71875
3
// Interface for the buildings. export interface Building { address: string; code: string; id: number; latitude: number; longitude: number; }
1d5a6d10198775b140ff47b56b0c7d448f179d32
TypeScript
laogong5i0-2/turbox
/packages/reactivity/src/decorators/mutation.ts
2.765625
3
import { store } from '../core/store'; import { CURRENT_MATERIAL_TYPE, EMPTY_ACTION_NAME } from '../const/symbol'; import { bind, convert2UniqueString, isPromise } from '../utils/common'; import { Mutation, BabelDescriptor } from '../interfaces'; import { invariant, fail } from '../utils/error'; import { quacksLikeADecorator } from '../utils/decorator'; import { materialCallStack, Domain } from '../core/domain'; import { EMaterialType } from '../const/enums'; interface MutationConfig { immediately: boolean; displayName: string; } function createMutation(target: Object | undefined, name: string | symbol | number, original: Mutation, config: MutationConfig) { const stringMethodName = convert2UniqueString(name); return function (...payload: any[]) { let _this = this; if (!target) { _this = new Domain(); } _this[CURRENT_MATERIAL_TYPE] = EMaterialType.MUTATION; materialCallStack.push(_this[CURRENT_MATERIAL_TYPE]); if (!store) { fail('store is not ready, please init first.'); } const result = store.dispatch({ name: stringMethodName, displayName: config.displayName || EMPTY_ACTION_NAME, payload, type: EMaterialType.MUTATION, domain: _this, original: bind(original, _this) as Mutation, immediately: !!config.immediately, }); if (isPromise(result)) { return new Promise((resolve) => { (result as Promise<any>).then((res) => { materialCallStack.pop(); const length = materialCallStack.length; _this[CURRENT_MATERIAL_TYPE] = materialCallStack[length - 1] || EMaterialType.DEFAULT; resolve(res); }); }); } materialCallStack.pop(); const length = materialCallStack.length; _this[CURRENT_MATERIAL_TYPE] = materialCallStack[length - 1] || EMaterialType.DEFAULT; if (result && result instanceof Error) { throw result; } return result; }; } export function mutation(target: Object, name: string | symbol | number, descriptor?: BabelDescriptor<Mutation>): any; export function mutation(name?: string, immediately?: boolean): (target: Object, name: string | symbol | number, descriptor?: BabelDescriptor<Mutation>) => any; export function mutation(name: string | symbol | number, original: Mutation, config?: MutationConfig): (...payload: any[]) => any; /** * decorator @mutation, update state by mutation styling. */ export function mutation(...args: any[]) { const config: MutationConfig = { immediately: false, displayName: '', }; if (typeof args[0] === 'string' && typeof args[1] === 'function') { if (args[2] !== void 0) { config.displayName = args[2].displayName; config.immediately = args[2].immediately; } return createMutation(undefined, args[0], args[1], config); } const decorator = (target: Object, name: string | symbol | number, descriptor?: BabelDescriptor<Mutation>): BabelDescriptor<Mutation> => { // typescript only: @mutation method = () => {} if (descriptor === void 0) { let mutationFunc: Function; return Object.defineProperty(target, name, { enumerable: true, configurable: true, get: function () { return mutationFunc; }, set: function (original: Mutation) { mutationFunc = createMutation(target, name, original, config); }, }); } // babel/typescript: @mutation method() {} if (descriptor.value !== void 0) { const original: Mutation = descriptor.value; descriptor.value = createMutation(target, name, original, config); return descriptor; } // babel only: @mutation method = () => {} const { initializer } = descriptor; descriptor.initializer = function () { invariant(!!initializer, 'The initializer of the descriptor doesn\'t exist, please compile it by using babel and correspond decorator plugin.'); return createMutation(target, name, (initializer && initializer.call(this)) as Mutation, config); }; return descriptor; } if (quacksLikeADecorator(args)) { // @mutation return decorator.apply(null, args as any); } // @mutation(args) config.displayName = args[0] || ''; config.immediately = args[1] !== void 0 ? args[1] : false; return decorator; }
e38ba2735c10595735b4d713b5407a1441d36e8d
TypeScript
fernandomiras1/UDEMY
/CLARO/guardias-angular/src/app/pipes/truncate.pipe.ts
2.65625
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'truncate' }) export class TruncatePipe implements PipeTransform { transform(str: string, limit = 10): string { if(str.length > limit) { str = str.substring(0,limit) + '...'; } return str; } }
7c63320d9dff881a85bb738aabf4100538cfbb86
TypeScript
bngesp/angular
/src/app/list-person/list-person.component.ts
2.65625
3
import { Component, OnInit } from '@angular/core'; // @ts-ignore import {Personne} from '../classe/personne'; @Component({ selector: 'app-list-person', templateUrl: './list-person.component.html', styleUrls: ['./list-person.component.css'] }) export class ListPersonComponent implements OnInit { personnes = [ new Personne('Ndiaye', 'Modou', 17, 'M', [9, 14, 15, 8]), new Personne('Diop', 'Anta', 18, 'F', [19, 10, 1, 8]), new Personne('Dieng', 'Fallou', 20, 'M', [19, 10, 1, 8]), new Personne('Samb', 'Ousmane', 8, 'M', [19, 10, 1, 8]), new Personne('Fall', 'Coumba', 28, 'F', [19, 10, 1, 8]), ]; constructor() { } ngOnInit(): void { console.log(this.personnes); } changerSexe(sex: string){ let person: Personne[] = [] ; this.personnes.forEach(p => { p.sexe = sex; person.push(p); } ); this.personnes = person; } }
72e87e15cd483a1c61cb54092738b08293ceb0a4
TypeScript
vicsmr/payment-gateway
/src/PGateway.ts
2.671875
3
import { PaymentMethod } from "../models/PaymentMethod"; import { Price } from "../models/Price"; export abstract class PGateway { private price: Price; private paymentMethod: PaymentMethod; abstract pay(); abstract reimburse(); getPrice(): Price { return this.price; } setPrice(price: Price): void { this.price = price; } getPaymentMethod(): PaymentMethod { return this.paymentMethod; } setPaymentMethod(paymentMethod: PaymentMethod): void { this.paymentMethod = paymentMethod; } }
626a06bea449a14185c0f1ac6e9ace39cf72a592
TypeScript
Sharky666/setClient
/src/app/common/interfaces/common.d.ts
2.578125
3
export interface ApiResponse <T> { result: T; error: string; }
c7f3d974ffb747ca2fba111f19d302a512d97fa6
TypeScript
azizj1/advent-of-code
/src/2020/4b.ts
2.890625
3
import { timer } from '~/util/Timer'; import { getSimulations, Passport, Simulation } from './4'; interface Rule { isValid(passport: Passport): boolean; } class YearRule implements Rule { constructor( private readonly key: string, private readonly minYear: number, private readonly maxYear: number ) {} isValid(passport: Passport) { if (passport.has(this.key)) { const val = Number(passport.get(this.key)!); return !isNaN(val) && val >= this.minYear && val <= this.maxYear; } return false; } } class BirthYearRule extends YearRule { constructor() { super('byr', 1920, 2002); } } class IssueYearRule extends YearRule { constructor() { super('iyr', 2010, 2020); } } class ExpirationYearRule extends YearRule { constructor() { super('eyr', 2020, 2030); } } class HeightRule implements Rule { private readonly KEY = 'hgt'; isValid(passport: Passport) { if (passport.has(this.KEY)) { const val = passport.get(this.KEY)!; const matches = val.match(/^(\d+)(cm|in)/) ?? []; const measurement = Number(matches[1]); const unit = matches[2]; if (unit === 'cm' && measurement >= 150 && measurement <= 193) { return true; } else if (unit === 'in' && measurement >= 59 && measurement <= 76) { return true; } return false; } return false; } } class HairColorRule implements Rule { private readonly KEY = 'hcl'; private readonly REGEX = /^#[0-9A-Fa-f]{6}$/; isValid(passport: Passport) { if (passport.has(this.KEY)) { return this.REGEX.test(passport.get(this.KEY)!); } return false; } } class EyeColorRule implements Rule { private readonly KEY = 'ecl'; private readonly VALID_COLORS = new Set(['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']); isValid(passport: Passport) { if (passport.has(this.KEY)) { return this.VALID_COLORS.has(passport.get(this.KEY)!); } return false; } } class PassportIdRule implements Rule { private readonly KEY = 'pid'; private readonly REGEX = /^\d{9}$/; isValid(passport: Passport) { if (passport.has(this.KEY)) { return this.REGEX.test(passport.get(this.KEY)!); } return false; } } class AndRule implements Rule { constructor(private readonly rules: Rule[]) {} isValid(passport: Passport) { return this.rules.every((r) => r.isValid(passport)); } } function and(...rules: Rule[]): Rule { return new AndRule(rules); } function buildRules() { return and( new BirthYearRule(), new IssueYearRule(), new ExpirationYearRule(), new HeightRule(), new HairColorRule(), new EyeColorRule(), new PassportIdRule() ); } function getValidCount(rule: Rule) { return ({ passports }: Simulation) => passports.filter((p) => rule.isValid(p)).length; } export function run() { const rules = buildRules(); const simulation = getSimulations()[0]; timer.run(getValidCount(rules), 'day 4b', simulation); }
4cb0668f30991e53454a7175485cf4adf5ed856b
TypeScript
IvanJosipovic/AutoSPInstallerOnlineGithubPage
/App/Directives/stringToNumberDirective.ts
2.546875
3
/// <reference path="../../typings/tsd.d.ts" /> (function () { "use strict"; class StringToNumber implements angular.IDirective { restrict = "A"; require = "ngModel"; link = (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs, ngModelController: angular.INgModelController) => { ngModelController.$parsers.push(function (value) { if (value === null) { return ""; } return "" + value; }); ngModelController.$formatters.push(function (value) { return parseFloat(value); }); } static factory(): angular.IDirectiveFactory { let directive = () => new StringToNumber(); return directive; } } angular .module("ASPIO") .directive("stringToNumber", StringToNumber.factory()); })();