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
46cd2415d3fc2c2d2f363dcb1c909961062c6fe0
TypeScript
mattmazzola/interview-questions
/src/pluralsight/pimatch.ts
3.46875
3
const pi = 314 const minLength = 3 const minValue = Math.pow(10, minLength - 1) const maxLength = 12 const maxValue = Math.pow(10, maxLength - 1) export const piMatch = (n: number): number => { if (n < 100) { return 0 } if (n > maxValue) { throw new Error(`Invalid number. Number must be less than 12 digits. You passed: ${n}`) } const numbers = getNumbers(n) const differences = numbers.reduce((sum, n) => { sum += n - pi return sum }, 0) return differences / numbers.length } const getNumbers = (n: number): number[] => { const numbers: number[] = [] const nString = n.toString() for (let i = 0; i <= nString.length - 3; i++) { const number = parseInt(nString.substring(i, i + 3)) numbers.push(number) } return numbers }
69e636c3a28b2138f6bc5f6f23d83fac5a4cc15b
TypeScript
BloomBooks/comical-js
/src/lineTail.ts
2.59375
3
import { Tail } from "./tail"; import paper = require("paper"); import { TailSpec } from "./bubbleSpec"; import { Bubble } from "./bubble"; import { Comical } from "./comical"; export class LineTail extends Tail { private tailWidth: number = 1; public constructor( root: paper.Point, tip: paper.Point, lowerLayer: paper.Layer, upperLayer: paper.Layer, handleLayer: paper.Layer, spec: TailSpec, bubble: Bubble | undefined ) { super(root, tip, lowerLayer, upperLayer, handleLayer, spec, bubble); } public canUnite() { return false; } public makeShapes() { const oldStroke = this.pathstroke; this.lowerLayer.activate(); this.pathstroke = this.makeShape(this.root); if (oldStroke) { this.pathstroke.insertBelow(oldStroke); oldStroke.remove(); } } public makeShape(from: paper.Point): paper.Path { const result = new paper.Path.Line(from, this.tip); result.strokeColor = new paper.Color("black"); result.strokeWidth = this.tailWidth; return result; } public onClick(action: () => void) { this.clickAction = action; if (this.pathstroke) { // create onMouseEnter and onMouseLeave events for making it easier for a user to grab // the tail. Otherwise clicking on it is really hard. The onMouseLeave event is so that it // returns the tail to the default width (this.tailWidth) of the LineTail // Enhance: If we still want this behavior, we have to enhance it to cope with scale // this.pathstroke.onMouseEnter = () => { // this.pathstroke.strokeWidth = 4; // }; // this.pathstroke.onMouseLeave = () => { // this.pathstroke.strokeWidth = this.tailWidth; // }; Comical.setItemOnClick(this.pathstroke, action); } } }
0aac81f2a4607fa2ea726a725d50959744a8ee77
TypeScript
giacomette/super-react-hook-form
/my-app/src/@form/utils/rules/__tests__/max.test.ts
3.0625
3
import { max } from "../max"; describe("#max()", () => { test("Deve formatar um retorno de validação padrão caso uma mensagem customizada não seja informada", () => { const expected = { value: "10", message: "O valor máximo para Número de telefone é 10.", }; const result = max("10", "Número de telefone"); expect(result).toEqual(expected); }); test("Deve formatar um retorno de validação customizada", () => { const expected = { value: "10", message: "Porfavor, informe um número corretamente", }; const result = max( "10", "Número de telefone", "Porfavor, informe um número corretamente" ); expect(result).toEqual(expected); }); test("Deve formatar um retorno de validação sem uma label informada", () => { const expected = { value: "10", message: "O valor máximo para este campo é 10.", }; const result = max("10"); expect(result).toEqual(expected); }); });
cc653a08ab7ea258732a502c87e9f9081a940f98
TypeScript
thislooksfun/GMTC-Operator
/src/utils/text/greet.ts
2.671875
3
import { GuildMember } from 'discord.js'; import oneOf from '../oneOf'; const greetings = [ ['Howdy', '!'], ['Hey there', '!'], ['Sah', '.'], ['Heya', '.'], ["What's up", '?'], ['Hello', '!'], ['Hi', '!'], ['Hi there', '!'], ['How do you do', '?'], ['Howdy do', '!'], ["What's poppin'", '?!?!'], ['Cheers', '.'], ["How's it hanging", '?'], ]; export default function greet(member: GuildMember | null) { const name = member?.nickname ?? member?.displayName ?? 'my friends'; const [phrase, punctuation] = oneOf(greetings); return `${phrase}, ${name}${punctuation}`; }
495b403f2a06ccfc8d06a9fb2ec4f5ad66fe975a
TypeScript
turkaytunc/rehber-frontend
/src/types/PersonBuilder.ts
3.046875
3
import { Person } from './Person'; export class PersonBuilder { person: Person; constructor(firstname: string, phone_number: string) { this.person = new Person(firstname, phone_number); } setPersonId(personId: string): PersonBuilder { this.person.person_id = personId; return this; } setFirstname(firstname: string): PersonBuilder { this.person.firstname = firstname; return this; } setLastname(lastname: string): PersonBuilder { this.person.lastname = lastname; return this; } setNickname(nickname: string): PersonBuilder { this.person.nickname = nickname; return this; } setEmail(email: string): PersonBuilder { this.person.email = email; return this; } setPhoneNumber(phone_number: string): PersonBuilder { this.person.phone_number = phone_number; return this; } setNote(note: string): PersonBuilder { this.person.note = note; return this; } build(): Person { return this.person; } }
3e0083a8e6ae994181f68d7c8a1c88886b6325fa
TypeScript
JestVA/daily-quest
/Typescript/holistic/6-guards-and-extreme-types.ts
4.25
4
import { HasEmail } from "./1-basics"; // top types ( types that can hold any value ) let myAnyValue : any = 34; let myUnknownValue : unknown = 'Hello, unknown'; myAnyValue.foo.bar.nar; // you can do anything with any //myUnknownValue.isIt; // prop does not exist on type unknown async function logAny(p: Promise<any>) { const val = await p; console.log("Got" + p); } //myUnknownValue.split(""); // oops // built in type guards if(typeof myUnknownValue === 'string') // type string myUnknownValue.split(""); if(myUnknownValue instanceof Promise) { // type Promise<any> myUnknownValue.then(x => console.log(x)) } // use defined type guards function isEmail(x: any): x is HasEmail { return typeof x.name === 'string' && typeof x.email === 'string' } if(isEmail(myUnknownValue)) { console.log(myUnknownValue.email, myUnknownValue.name) // type email } // very common guard function isDefined<T>(arg: T | undefined): arg is T { return typeof arg !== 'undefined'; } // assertion based type guards function assertIsStringArray(arr: any[]): asserts arr is string[] { if(!arr) throw new Error("not an array!"); const strings = arr.filter(i => typeof i === 'string'); if(strings.length !== arr.length) throw new Error("Not array of strings"); } assertIsStringArray(["abc", "def"]); const arr: (string|number)[] = [3, '12', '21']; assertIsStringArray(arr); // Run this... let unknown1: unknown = 41; let unknown2: unknown = ["a", "string", "array"]; unknown1 = unknown2; // yikes // alternative to unknowns are branded types interface BrandedWithA { _this_is_branded_with_a: "a" } function brandA(brand: string): BrandedWithA { return (brand as unknown) as BrandedWithA } function unbrandBrand(brand: BrandedWithA): string { return (brand as unknown) as string; } interface BrandedB { _this_is_branded_with_b: "b" } function brandB(abc: { value: string }): BrandedB { return (abc as unknown) as BrandedB; } function unbrandB(value: BrandedB): {abc: string} { return (value as unknown) as {abc: string}; } let secretA = brandA("Secret value"); let secretB = brandB({ value: "This is another secret value"}); //secretA = secretB; // can't mix them up now unbrandBrand(secretA); unbrandB(secretB); // now have original values let revealA = unbrandBrand(secretA); let revealB = unbrandB(secretB); // bottom type: never // can hold no values //let n: never = 4; // can't assign other type to type never let x = "abc" as string | number; if(typeof x === 'string') { x.split(""); } else if(typeof x === 'number') { x++; } else { // x is never let someNever = x; } class UnreachableError extends Error { constructor(val: never, message: string) { super(`Some message: ${message}`); } } let y = 4 as string | number; if(typeof y === 'string') { y.split(", ") } else if (typeof y === 'number') { y.toFixed(2); } else { throw new UnreachableError(y, "y should be a string or a number"); }
b0c2c0544ffc73bd9812b11e27291f063252986e
TypeScript
xldc/JavaScript-test
/DictionaryTest/lib/Dictionary.ts
3.265625
3
import {defaultToString} from "../../utils/Util.ts"; import {ValuePair} from "../../utils/dictionary-list-models.ts"; interface toStrFnType { (item: string): string; } interface tableType { [propName: string]: any; } interface callbackFnType { (key: string,value: any): any; } export default class Dictionary<T>{ private toStrFn: toStrFnType; private table: tableType; constructor(toStrFn = defaultToString) { this.toStrFn = toStrFn; this.table = {}; } // 判断字典中是否包含某个key hasKey(key: string){ return this.table[this.toStrFn(key)] != null; } // 向字典中添加元素 set(key: string, value: any){ if(key != null && value != null){ // 将key转为字符串,字典中需要的key为字符串形式 const tableKey = this.toStrFn(key); this.table[tableKey] = new ValuePair(key,value); return true; } return false; } // 从字典中移除一个值 remove(key: string) { if (this.hasKey(key)){ delete this.table[this.toStrFn(key)]; return true; } return false; } // 从字典中获取一个值 Possible iteration over unexpected (custom / inherited) members, probably missing hasOwnProperty check get(key: string){ const valuePair = this.table[this.toStrFn(key)]; return valuePair == null ? undefined : valuePair.value; } // 获取字典中存储的所有对象 keyValues() { /* 使用ES2017引入的Object.values方法可以直接获取对象里存储的所有对应key的value值存进数组中 */ // return Object.values(this.table); const valuePairs = []; for (const k in this.table){ if (this.table.hasOwnProperty(k) && this.hasKey(k)){ valuePairs.push(this.table[k]); } } return valuePairs; } // 获取字典中的所有键 keys() { // 可以直接使用map获取对象的key // return this.keyValues().map(valuePair=> valuePair.key); const keys = []; const valuePairs = this.keyValues(); for (let i = 0; i < valuePairs.length; i++){ keys.push(valuePairs[i].key); } return keys; } // 获取字典中的所有值 values() { const values = []; const valuePairs = this.keyValues(); for (let i = 0; i < valuePairs.length; i++){ values.push(valuePairs[i].value); } return values; } // 迭代字典中的每个键值对 forEach(callbackFn: callbackFnType){ const valuePairs = this.keyValues(); for (let i = 0; i < valuePairs.length; i++){ const result = callbackFn(valuePairs[i].key,valuePairs[i].value); if (result === false){ break; } } } size() { return this.keyValues().length; } isEmpty() { return this.size() === 0; } clear() { this.table = {}; } // 将字典中的数据转为字符串 toString() { if (this.isEmpty()){ return ''; } const valuePairs = this.keyValues(); let objString = `${valuePairs[0].toString()}`; for (let i = 1; i < valuePairs.length; i++){ objString = `${objString},${valuePairs[i].toString()}`; } return objString; } }
58831e41724179da36dc239e9ffc1033eb9e1bba
TypeScript
gabrielVjfl/softbarber
/backendbarber/src/controllers/LatLng.ts
2.78125
3
import express, { Request, Response } from 'express' const Model = require('../database/models') const Days = Model.Days import dayjs from 'dayjs' import datefns from 'date-fns' class Teste { async testando(Request, Response) { try { //let horaminha = '09:45:00' const { horaminha } = Request.body let HourFrom = await Days.findOne({ where: { BarberId: 4, dayweek: 'Sabado'}, attributes: ['hourtoTarde'] }) let HourTo = await Days.findOne({ where: { BarberId: 4, dayweek: 'Sabado'}, attributes: ['hourfromManha'] }) let HourFromAlmoco = await Days.findOne({ where: { BarberId: 4, dayweek: 'Sabado' }, attributes: ['hourtoManha'] }) let HourToAlmoco = await Days.findOne({ where: { BarberId: 4, dayweek: 'Sabado' }, attributes: ['hourfromTarde'] }) let responseHour = HourFrom.hourtoTarde let responseHourTwo = HourTo.hourfromManha let responseHourFromAlmoco = HourFromAlmoco.hourtoManha let responseHourToAlmoco = HourToAlmoco.hourfromTarde if (horaminha > responseHour) { Response.status(400).json({errBackend: 'Passou o horario de atendimento!'}) } else if (horaminha < responseHourTwo) { Response.status(400).json({errBackend: 'Hora não pode! muito cedo!'}) } else if (horaminha > responseHourFromAlmoco && horaminha < responseHourToAlmoco) { Response.status(400).json({errBackend: 'Hora de almoço!'}) } else { Response.status(200).json({suc: 'Ok'}) } } catch (err) { console.log(err) } } async testeTrim(Request: Request, Response: Response) { try { const { number } = Request.body // remove os espaços em branco do numero let formatNumber = number.replace(/\s/g, '') Response.status(200).json(formatNumber) } catch (err) { Response.status(400).json({errBack: 'Deu erro'}) } } async dayMax(Request: Request, Response: Response) { try { const {BarberId} = Request.params // Ver dias q não atendi!! const { novodia } = Request.body let dayslist = await Days.findOne({ where: { BarberId: BarberId, dayweek: novodia} }) if (!dayslist) { Response.status(400).json({ errBackend: `Não atende ${novodia}!` }) } else { Response.status(200).json(novodia) } } catch (err) { console.log(err) Response.status(400).json({errBack: 'Deu erro'}) } } } export default new Teste
363943c11fe6680f57baabfc88aca33cd807a0f2
TypeScript
Srini-py/Hotel_Expense_Tracker
/src/app/logs/log.model.ts
2.5625
3
export class Log { constructor( public id: string, public department: 'Front Desk Department' | 'Purchase Department' | 'Human Resource Department' | 'Sales & Marketing Department', public logType: 'Expense' | 'Income', public entry: string, public value: number, public date: Date ) { } }
b1a66b1d146c399cc65e91e0e09c44118e5eefb8
TypeScript
ChromeDevTools/devtools-frontend
/front_end/third_party/diff/DiffWrapper.ts
2.796875
3
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as Common from '../../core/common/common.js'; declare global { /* eslint-disable @typescript-eslint/naming-convention */ class diff_match_patch { diff_main(text1: string, text2: string): Array<{0: number, 1: string}>; diff_cleanupSemantic(diff: Array<{0: number, 1: string}>): void; } /* eslint-enable @typescript-eslint/naming-convention */ } export const DiffWrapper = { charDiff: function(text1: string, text2: string, cleanup?: boolean): {0: number, 1: string}[] { const differ = new diff_match_patch(); const diff = differ.diff_main(text1, text2); if (cleanup) { differ.diff_cleanupSemantic(diff); } return diff; }, lineDiff: function(lines1: string[], lines2: string[]): DiffArray { const idMap = new Common.CharacterIdMap.CharacterIdMap<string>(); const text1 = lines1.map(line => idMap.toChar(line)).join(''); const text2 = lines2.map(line => idMap.toChar(line)).join(''); const diff = DiffWrapper.charDiff(text1, text2); const lineDiff = []; for (let i = 0; i < diff.length; i++) { const lines = []; for (let j = 0; j < diff[i][1].length; j++) { lines.push(idMap.fromChar(diff[i][1][j]) || ''); } lineDiff.push({ 0: diff[i][0], 1: lines }); } return lineDiff; }, convertToEditDiff: function(diff: DiffArray): number[][] { const normalized = []; let added = 0; let removed = 0; for (let i = 0; i < diff.length; ++i) { const token = diff[i]; if (token[0] === Operation.Equal) { flush(); normalized.push([Operation.Equal, token[1].length]); } else if (token[0] === Operation.Delete) { removed += token[1].length; } else { added += token[1].length; } } flush(); return normalized; function flush(): void { if (added && removed) { const min = Math.min(added, removed); normalized.push([Operation.Edit, min]); added -= min; removed -= min; } if (added || removed) { const balance = added - removed; const type = balance < 0 ? Operation.Delete : Operation.Insert; normalized.push([type, Math.abs(balance)]); added = 0; removed = 0; } } }, /** * Scores character-sequence diffs, giving higher scores for longer sequences. */ characterScore: function(item: string, against: string): number { let score = 0; const diff = DiffWrapper.charDiff(item, against); for (let i = 0; i < diff.length; ++i) { if (diff[i][0] === Operation.Equal) { score += diff[i][1].length * diff[i][1].length; } } return score; }, }; // TODO(crbug.com/1167717): Make this a const enum again // eslint-disable-next-line rulesdir/const_enum export enum Operation { Equal = 0, Insert = 1, Delete = -1, Edit = 2, } export type DiffArray = {0: Operation, 1: string[]}[];
46f06cc170d2e9f6ea708f51598eba3e1c45733d
TypeScript
raghunathsandilya/smartmarkers-react
/src/models/Bundle.ts
2.578125
3
import { IResource } from './Resource' import { IIdentifier } from './Identifier' import { IBackboneElement } from './BackboneElement' import { ISignature } from './Signature' export enum BundleType { Document = 'document', Message = 'message', Transaction = 'transaction', TransactionResponse = 'transaction-response', Batch = 'batch', BatchResponse = 'batch-response', History = 'history', Searchset = 'searchset', Collection = 'collection', } export interface IBundleLink extends IBackboneElement { relation: string // R! See http://www.iana.org/assignments/link-relations/link-relations.xhtml#link-relations-1 url: string // R! Reference details for the link } export enum SearchEntryMode { Match = 'match', Include = 'include', Outcome = 'outcome', } export interface ISearchEntry extends IBackboneElement { mode?: SearchEntryMode // match | include | outcome - why this is in the result set score?: number // Search ranking (between 0 and 1) } export enum HTTPVerb { GET = 'GET', HEAD = 'HEAD', POST = 'POST', PUT = 'PUT', DELETE = 'DELETE', PATCH = 'PATCH', } export interface IRequestEntry extends IBackboneElement { method: HTTPVerb // R! GET | HEAD | POST | PUT | DELETE | PATCH url: string // R! URL for HTTP equivalent of this entry ifNoneMatch?: string // For managing cache currency ifModifiedSince?: Date // For managing cache currency ifMatch?: string // For managing update contention ifNoneExist?: string // For conditional creates } export interface IResponseEntry extends IBackboneElement { // C? Results of execution (transaction/batch/history) status: string // R! Status response code (text optional) location?: string // The location (if the operation returns a location) etag?: string // The Etag for the resource (if relevant) lastModified?: Date // Server's date time modified outcome?: IResource // OperationOutcome with hints and warnings (for batch/transaction) } export interface IBundleEntry extends IBackboneElement { link?: IBundleLink[] // Links related to this entry fullUrl?: string // URI for resource (Absolute URL server address or URI for UUID/OID) resource?: IResource // A resource in the bundle search?: ISearchEntry request?: IRequestEntry response?: IResponseEntry } export interface IBundle extends IResource { // from Resource: id, meta, implicitRules, and language identifier?: IIdentifier // Persistent identifier for the bundle type: BundleType // R! document | message | transaction | transaction-response | batch | batch-response | history | searchset | collection timestamp?: Date // When the bundle was assembled total?: number // C? If search, the total number of matches link?: IBundleLink[] entry?: IBundleEntry[] signature?: ISignature // Digital Signature }
7213e4ee88eef9915f8421c20cc4e4bf95b693bf
TypeScript
Jacks128/tytusx
/20211SVAC/G16/app/Clases/AST/Simbolo.ts
2.71875
3
import Valor from "./Valor"; export default class Simbolo { Nombre: string; Valor: Valor; Padre: string; Linea: number; Columna: number; Posicion: number; constructor(Nombre: string, Valor: Valor, Padre: string, Linea: number, Columna: number, Posicion: number) { this.Nombre = Nombre; this.Valor = Valor; this.Padre = Padre; this.Linea = Linea; this.Columna = Columna; this.Posicion = Posicion; } }
bb264b6444b641b7f716cfdf332d4201193f2780
TypeScript
void-aurora/markdown
/packages/markdown-plugin-highlight/src/index.ts
2.59375
3
/* eslint-disable @typescript-eslint/strict-boolean-expressions */ /* eslint-disable no-param-reassign */ import { Token, MarkdownPlugin } from '@void-aurora/markdown'; import { render } from './prism'; import { normalizeInfo } from './normalize'; // hljsDefineVue(hljs); export interface PluginHighlightOptions { /** * The CSS class name of `<pre>` tag. * @default 'prism' */ className?: string | string[]; /** * The CSS class name prefix of `<pre>` tag for wrapping language name. * @default 'language-' */ classNamePrefix?: string; /** * Add line numbers to highlighted code or not. * @default false */ lineNumbers?: boolean; /** * The function for wrapping highlighted code text. * @default (attrs, highlightedCode) => `<pre ${attrs}><code>${code}</code></pre>` */ wrap?: (attrs: string, highlightedCode: string) => string; } const defaultOptions: Required<PluginHighlightOptions> = { className: 'prism', classNamePrefix: 'language-', lineNumbers: false, wrap: (attrs, highlightedCode) => `<pre ${attrs}><code>${highlightedCode}</code></pre>`, }; // TODO: Compatibility to markdown-it-container const plugin: MarkdownPlugin<PluginHighlightOptions> = { id: 'highlight', install: (it, options = {}) => { const { renderer: { rules: { fence }, }, } = it; const { className: classNameRaw, classNamePrefix, lineNumbers, wrap } = { ...defaultOptions, ...options, }; const className = Array.isArray(classNameRaw) ? classNameRaw.join(' ') : classNameRaw; it.renderer.rules.fence = (tokens, index, itOptions, env, self) => { const { [index]: token } = tokens; const { language, highlightLines, lineStart } = normalizeInfo(token.info ?? ''); token.attrJoin('class', className); token.attrJoin('class', `${classNamePrefix}${language}`); const attrs = self.renderAttrs(token); let code = render(token.content, language, { lineNumbers, lineStart, highlightLines, }); if (code === '') { code = it.utils.escapeHtml(token.content); } return `${wrap(attrs, code).trim()}\n`; }; }, }; export { plugin as PluginHighlight }; export default plugin;
89685671015dfc3484c3934840c641a1acd00f0b
TypeScript
Veetaha/basic-ts-nodejs-template
/backend/modules/discord/discord-handler.interfaces.ts
3.078125
3
import Discord from 'discord.js'; export interface DiscordCmdHandlerFnCtx { /** Command that this handler was invoked with. */ readonly cmd: string; /** Original discord message that was received. */ readonly msg: Discord.Message; /** * Array of positional parameters that were forwarded to the handler by the user. */ readonly params: string[]; } /** * Defines the type of function that implements the command buisness logic. */ export type DiscordCmdHandlerFn = (ctx: DiscordCmdHandlerFnCtx) => void | Promise<unknown>; /** * Defines the type of function that is passed to `discordClient.on('message', ...)` */ export type DiscordMsgHandlerFn = (msg: Discord.Message) => void | Promise<unknown>;
7e8a444cb09e5bdde44cdabeb02117bfd10cd2aa
TypeScript
lsegurado/poc-jobsity
/src/classes/Reminder.ts
2.6875
3
import { City, Province } from "../apiHelpers/Types"; export default class Reminder { public title: string; public date: Date; public color: string; public id?: number; public city?: City | null; public province?: Province | null; constructor(date: Date = new Date()) { this.title = ''; this.date = date; this.color = '#039be5'; this.city = undefined; this.province = undefined; } }
af9340807506c89063f7512bf128777cc071939e
TypeScript
steveukx/git-js
/simple-git/src/lib/responses/StatusSummary.ts
2.671875
3
import { StatusResult } from '../../../typings'; import { append, NULL } from '../utils'; import { FileStatusSummary } from './FileStatusSummary'; type StatusLineParser = (result: StatusResult, file: string) => void; export class StatusSummary implements StatusResult { public not_added = []; public conflicted = []; public created = []; public deleted = []; public ignored = undefined; public modified = []; public renamed = []; public files = []; public staged = []; public ahead = 0; public behind = 0; public current = null; public tracking = null; public detached = false; public isClean = () => { return !this.files.length; }; } enum PorcelainFileStatus { ADDED = 'A', DELETED = 'D', MODIFIED = 'M', RENAMED = 'R', COPIED = 'C', UNMERGED = 'U', UNTRACKED = '?', IGNORED = '!', NONE = ' ', } function renamedFile(line: string) { const [to, from] = line.split(NULL); return { from: from || to, to, }; } function parser( indexX: PorcelainFileStatus, indexY: PorcelainFileStatus, handler: StatusLineParser ): [string, StatusLineParser] { return [`${indexX}${indexY}`, handler]; } function conflicts(indexX: PorcelainFileStatus, ...indexY: PorcelainFileStatus[]) { return indexY.map((y) => parser(indexX, y, (result, file) => append(result.conflicted, file))); } const parsers: Map<string, StatusLineParser> = new Map([ parser(PorcelainFileStatus.NONE, PorcelainFileStatus.ADDED, (result, file) => append(result.created, file) ), parser(PorcelainFileStatus.NONE, PorcelainFileStatus.DELETED, (result, file) => append(result.deleted, file) ), parser(PorcelainFileStatus.NONE, PorcelainFileStatus.MODIFIED, (result, file) => append(result.modified, file) ), parser( PorcelainFileStatus.ADDED, PorcelainFileStatus.NONE, (result, file) => append(result.created, file) && append(result.staged, file) ), parser( PorcelainFileStatus.ADDED, PorcelainFileStatus.MODIFIED, (result, file) => append(result.created, file) && append(result.staged, file) && append(result.modified, file) ), parser( PorcelainFileStatus.DELETED, PorcelainFileStatus.NONE, (result, file) => append(result.deleted, file) && append(result.staged, file) ), parser( PorcelainFileStatus.MODIFIED, PorcelainFileStatus.NONE, (result, file) => append(result.modified, file) && append(result.staged, file) ), parser( PorcelainFileStatus.MODIFIED, PorcelainFileStatus.MODIFIED, (result, file) => append(result.modified, file) && append(result.staged, file) ), parser(PorcelainFileStatus.RENAMED, PorcelainFileStatus.NONE, (result, file) => { append(result.renamed, renamedFile(file)); }), parser(PorcelainFileStatus.RENAMED, PorcelainFileStatus.MODIFIED, (result, file) => { const renamed = renamedFile(file); append(result.renamed, renamed); append(result.modified, renamed.to); }), parser(PorcelainFileStatus.IGNORED, PorcelainFileStatus.IGNORED, (_result, _file) => { append((_result.ignored = _result.ignored || []), _file); }), parser(PorcelainFileStatus.UNTRACKED, PorcelainFileStatus.UNTRACKED, (result, file) => append(result.not_added, file) ), ...conflicts(PorcelainFileStatus.ADDED, PorcelainFileStatus.ADDED, PorcelainFileStatus.UNMERGED), ...conflicts( PorcelainFileStatus.DELETED, PorcelainFileStatus.DELETED, PorcelainFileStatus.UNMERGED ), ...conflicts( PorcelainFileStatus.UNMERGED, PorcelainFileStatus.ADDED, PorcelainFileStatus.DELETED, PorcelainFileStatus.UNMERGED ), [ '##', (result, line) => { const aheadReg = /ahead (\d+)/; const behindReg = /behind (\d+)/; const currentReg = /^(.+?(?=(?:\.{3}|\s|$)))/; const trackingReg = /\.{3}(\S*)/; const onEmptyBranchReg = /\son\s([\S]+)$/; let regexResult; regexResult = aheadReg.exec(line); result.ahead = (regexResult && +regexResult[1]) || 0; regexResult = behindReg.exec(line); result.behind = (regexResult && +regexResult[1]) || 0; regexResult = currentReg.exec(line); result.current = regexResult && regexResult[1]; regexResult = trackingReg.exec(line); result.tracking = regexResult && regexResult[1]; regexResult = onEmptyBranchReg.exec(line); result.current = (regexResult && regexResult[1]) || result.current; result.detached = /\(no branch\)/.test(line); }, ], ]); export const parseStatusSummary = function (text: string): StatusResult { const lines = text.split(NULL); const status = new StatusSummary(); for (let i = 0, l = lines.length; i < l; ) { let line = lines[i++].trim(); if (!line) { continue; } if (line.charAt(0) === PorcelainFileStatus.RENAMED) { line += NULL + (lines[i++] || ''); } splitLine(status, line); } return status; }; function splitLine(result: StatusResult, lineStr: string) { const trimmed = lineStr.trim(); switch (' ') { case trimmed.charAt(2): return data(trimmed.charAt(0), trimmed.charAt(1), trimmed.substr(3)); case trimmed.charAt(1): return data(PorcelainFileStatus.NONE, trimmed.charAt(0), trimmed.substr(2)); default: return; } function data(index: string, workingDir: string, path: string) { const raw = `${index}${workingDir}`; const handler = parsers.get(raw); if (handler) { handler(result, path); } if (raw !== '##' && raw !== '!!') { result.files.push(new FileStatusSummary(path.replace(/\0.+$/, ''), index, workingDir)); } } }
bec59e46490dae808a134f1acf09ebd214e6dcee
TypeScript
validitylabs/PubHub
/applications/ui/src/store/notification/notification.types.ts
2.75
3
export enum AuthActionTypes { SET_NOTIFICATION = 'SET_NOTIFICATION', REMOVE_NOTIFICATION = 'REMOVE_NOTIFICATION' } export enum NotificationType { SUCCESS = 'SUCCESS', INFO = 'INFO', WARNING = 'WARNING', ERROR = 'ERROR' } export interface INotification { message: string; type: NotificationType; } export type NotificationState = INotification | null;
3f493f6fffdde34b5194748fa6c34f18c97ef927
TypeScript
kos0ama/playwright
/index.ts
2.765625
3
import { chromium } from "playwright"; import { Parser } from "json2csv"; import * as fs from "fs"; const options = { headless: false, }; const BASE_URL = "https://cloudapi.zendesk.com/hc/ja/categories/201092361"; const PER_PAGE = 10; (async () => { const stores = []; const browser = await chromium.launch(options); const page = await browser.newPage(); const navigationPromise = page.waitForNavigation(); await page.goto(BASE_URL); // 最大ページ数を取得 const maxPage = await page.evaluate(() => { return Math.ceil( Number(document.querySelector(".smp-count").textContent) / 10 ); }); // 最大ページ数の分だけループ for (let pageNumber = 1; pageNumber <= maxPage; pageNumber++) { const currentPageUrl = `${BASE_URL}=${pageNumber}`; await page.goto(currentPageUrl); // 5行目からが店舗データなので5始まりとする for (let rowNumber = 5; rowNumber < PER_PAGE + 5; rowNumber++) { // 詳細リンクを取得 const detailLinkSelector = (rowNumber: number) => { return `#smp-table-27130 > tbody > tr.smp-row-${rowNumber}.smp-row-data .smp-cell-col-2 > a` } const detailLink = await page.$(detailLinkSelector(rowNumber)); // 詳細リンクがなければスキップ if ( !detailLink ) { continue; } // 詳細ページに遷移してデータを保存 await page.click(detailLinkSelector(rowNumber)); await navigationPromise; const store = await page.evaluate(() => { const detailContentData = (rowNumber: number) => { return document.querySelector(`body > table > tbody > tr > td > div > div.whole > table > tbody > tr:nth-child(${rowNumber}) > td`)?.textContent?.trim() || '' } return { type: detailContentData(10), name: detailContentData(3), "phone number": detailContentData(8), address: detailContentData(6).replace(/\s+/g, "") + detailContentData(7), homepage: detailContentData(9), holiday: detailContentData(11), "business hours": detailContentData(12) }; }); await page.goto(currentPageUrl); await navigationPromise; stores.push(store) } } await browser.close(); // CSVへのパース const parser = new Parser; const csv = parser.parse(stores); // ファイル書き込み fs.writeFileSync('goto-eat.csv', csv) })();
48a104a07cc19edc79da457a87efa1d39397c90b
TypeScript
arkher/CadastroProdutos
/src/utils/filter-generator.ts
3.125
3
const operationMap = { equals: ':', different: '!:', greaterThan: '>', lowerThan: '<', in: '::', notIn: '!::', contains: ':*', startsWith: '>*', endsWith: '*<', }; export type Operation = | 'equals' | 'different' | 'greaterThan' | 'lowerThan' | 'in' | 'notIn' | 'contains' | 'startsWith' | 'endsWith'; type FilterFactory = { filter: string; setFilter: ( field: string | undefined, ) => (operation: string) => (value: string | undefined) => FilterFactory; and: ( field: string | undefined, ) => (operation: string) => (value: string | undefined) => FilterFactory; or: ( field: string | undefined, ) => (operation: string) => (value: string | undefined) => FilterFactory; cleanFilter: () => void; }; const filter = ''; export const filterFactory = (): FilterFactory => ({ filter, setFilter(field: string | undefined) { return (operation: string) => ( value: string | undefined, ): FilterFactory => { const op = operationMap[`${operation}`]; this.filter = field && op && value && field + op + value; return this; }; }, and(field: string | undefined) { return (operation: string) => ( value: string | undefined, ): FilterFactory => { const op = operationMap[`${operation}`]; if (field && op && value) { this.filter = this.filter.concat('|and,').concat(field + op + value); } return this; }; }, or(field: string | undefined) { return (operation: string) => ( value: string | undefined, ): FilterFactory => { const op = operationMap[`${operation}`]; if (field && op && value) { this.filter = this.filter.concat('|or,').concat(field + op + value); } return this; }; }, cleanFilter() { this.filter = ''; }, });
f797f9914d34ea5855d2d587e8bbd8117b7385e9
TypeScript
albru/Vertical-bar-chart
/src/components/chart/utils/transformToStyles.ts
2.625
3
import { ChartData } from "../../../types"; import { ChartElementStyles } from "../types"; export const transformToStyles = (data: ChartData) => data.reduce<ChartElementStyles[]>((acc, { height, width, ...rest }) => { const chartProps = { height: height + "px", width: width + "px", ...rest, }; acc.push(chartProps); return acc; }, []);
3ca461413af19981281a2a819a95d2567ecc1326
TypeScript
Josue-Lopez/DAV
/Frontend/FrontendApp/src/app/usuario.ts
2.703125
3
export class Usuario { public codUsuario: number; public username: string; public codTipousuario: number; public nombre: string; public password:string; public email: string; public realm: string; public emailVerified:boolean; public tipoRol: string; /** * */ constructor(codUsuario: number, username: string, codTipousuario: number, nombre: string, email: string, realm: string, emailVerified:boolean, contrasenia:string) { this.codUsuario= codUsuario; this.username= username; this.codTipousuario=codTipousuario; this.nombre= nombre; this.email= email; this.realm= realm; this.emailVerified=emailVerified; this.password = contrasenia; this.tipoRol = ""; } }
222ee8767f8aafd20b16b2e64d0acce9cd9aa03d
TypeScript
khsr/angular-typescript
/src/app/shared/pipes/currency.pipe.ts
2.65625
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'currencyPipe' }) export class CurrencyPipe implements PipeTransform { transform(value: any, args?: any): any { if (value >= 1000000000) { return (value / 1000000000).toFixed(1).replace(/\.0$/, '') + 'B'; } if (value >= 1000000) { return (value / 1000000).toFixed(1).replace(/\.0$/, '') + 'M'; } if (value >= 1000) { return (value / 1000).toFixed(1).replace(/\.0$/, '') + 'K'; } return value.toString(); } }
a7260ff9889bf30cbcb8794950073182049b94ef
TypeScript
dacarley/aquarium
/src/lib/Dimmer.ts
2.5625
3
import moment from "moment"; import Config from "$lib/Config"; import * as Shutdown from "$lib/Shutdown"; import * as DimmerScheduler from "$lib/DimmerScheduler"; import * as PCA9685 from "$lib/PCA9685"; let lastUpdateTimestamp = moment("1975-11-23T00:00:00.000Z"); PCA9685.init(0x40, 1000); export async function init() { console.info("Connecting to dimmer"); try { Shutdown.register(async () => { await PCA9685.allChannelsOff(); }); console.info("Connected to dimmer"); } catch (err) { console.error("Could not connect to the lights"); throw err; } } export async function update() { const now = moment(); if (now.diff(lastUpdateTimestamp, "seconds") < 15) { return; } lastUpdateTimestamp = now; const colorBrightnesses = await DimmerScheduler.getColorBrightnesses(); await setColorBrightnesses(colorBrightnesses); } type ChannelSettings = { name: string, channel: number, percentage: number, brightness: number }; async function setColorBrightnesses(colorBrightnesses: DimmerScheduler.ColorBrightnesses) { const channelSettings: ChannelSettings[] = []; for (const [color, brightness] of Object.entries(colorBrightnesses)) { for (const [name, channel] of Object.entries(Config.ledChannels)) { if (name.startsWith(color)) { const percentage = brightness * 100; const compensatedBrightness = Math.max(1.0 / 4096, brightness ** 2); channelSettings.push({ name, channel, percentage, brightness: compensatedBrightness }); } } } const promises = channelSettings.map(async (settings) => { try { await PCA9685.setDutyCycle(settings.channel, settings.brightness); } catch (err) { console.error("Caught an error setting dimmer channel level"); throw err; } }); await Promise.all(promises); }
def3aca90c22ef76d764effb1952680ff0c9e316
TypeScript
JulioCesar82/arquitetura-fullstack
/server/src/app/user.ts
2.578125
3
import {Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn} from 'typeorm'; import * as bcrypt from 'bcrypt'; @Entity('USERS') export class User { @PrimaryGeneratedColumn() id: number; @Column({ length: 50, nullable: false }) firstname: string; @Column({ length: 50, nullable: false }) lastname: string; @Column({ length: 50, nullable: false }) username: string; @Column({ length: 250, nullable: false }) password: string; @Column({ length: 20, nullable: false }) role: string; @CreateDateColumn({type: 'timestamp'}) createdAt: Date; @UpdateDateColumn({type: 'timestamp'}) updatedAt: Date; static encryptPassword(password: string): string { return bcrypt.hashSync(password, bcrypt.genSaltSync(8)); } }
ecf44d07afd935024098c3f89018c6340fbe4bfc
TypeScript
nekitus/artibox
/packages/slate-common/src/serializers/utils/getFirstAncestor.ts
2.703125
3
import { Element } from 'slate'; import { WithElementParent } from '../typings'; export function getFirstAncestor<E extends Element>( element: Element & WithElementParent, match: (element: Element & WithElementParent) => boolean ): (E & WithElementParent) | undefined { const { parent } = element; return (parent && !match(parent) ? getFirstAncestor(parent, match) : parent) as (E & WithElementParent) | undefined; }
9bc019113f1649ce295d1ea8229ef20623c7fe5b
TypeScript
locolucco209/MongoScraper
/python/anaconda/pkgs/bokeh-0.12.5-py27_1/lib/python2.7/site-packages/bokeh/server/static/js/tree_ts/models/transforms/jitter.ts
2.5625
3
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; import { Transform } from "./transform"; import * as p from "core/properties"; import * as bokeh_math from "core/util/math"; export var Jitter = (function(superClass) { extend(Jitter, superClass); function Jitter() { return Jitter.__super__.constructor.apply(this, arguments); } Jitter.define({ mean: [p.Number, 0], width: [p.Number, 1], distribution: [p.Distribution, 'uniform'] }); Jitter.prototype.compute = function(x) { if (this.distribution === 'uniform') { return x + this.mean + ((bokeh_math.random() - 0.5) * this.width); } if (this.distribution === 'normal') { return x + bokeh_math.rnorm(this.mean, this.width); } }; Jitter.prototype.v_compute = function(xs) { var i, idx, len, result, x; result = new Float64Array(xs.length); for (idx = i = 0, len = xs.length; i < len; idx = ++i) { x = xs[idx]; result[idx] = this.compute(x); } return result; }; return Jitter; })(Transform);
dbe4838a6cd90e3cf70827637f28359e10231dc1
TypeScript
tamasc/memory-game-sch
/src/app/app/game/game.component.ts
2.609375
3
import { Component, OnInit } from '@angular/core'; import { GameService } from '../services/game.service'; @Component({ selector: 'app-game', templateUrl: './game.component.html', styleUrls: ['./game.component.scss'] }) export class GameComponent implements OnInit { private allCards = [ 'angular', 'd3', 'jenkins', 'postcss', 'react', 'redux', 'sass', 'supercharge', 'ts', 'webpack' ]; private playingCards: string[]; public currentCards: string[]; public prevoiuslyChosenCard = ''; constructor( private gameService: GameService, ) { } ngOnInit() { this.playingCards = this.getRandomCards(this.allCards, this.gameService.getDeckSize()); this.currentCards = this.shuffleCards([...this.playingCards, ...this.playingCards]); } // found from stackoverflow getRandomCards(cardsArray: string[], numberOfDecks: number): string[] { const cards = [...cardsArray]; const result = new Array(numberOfDecks); let length = cards.length; const taken = new Array(length); while (numberOfDecks--) { const x = Math.floor(Math.random() * length); result[numberOfDecks] = cards[x in taken ? taken[x] : x]; taken[x] = --length in taken ? taken[length] : length; } return result; } // found from stackoverflow shuffleCards(cardsArray: string[]): string[] { const array = [...cardsArray]; for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } chooseCard(card: any) { if (this.prevoiuslyChosenCard) { if (this.prevoiuslyChosenCard === card) { this.playingCards.filter(el => el === card); } } else { this.prevoiuslyChosenCard = card; } } }
0aec5ace0e7c47f5f8d1f6f956e0889f0f675ca5
TypeScript
SatadruBhattacharjee/monorepo-fullstack-typescript-react-express-jest-cypress
/apps/backend/api/src/app/card/card.controller.ts
2.734375
3
import * as express from 'express'; import HttpException from '../exceptions/HttpException'; import Controller from '../interfaces/controller.interface'; import cardValidationMiddleware from '../middleware/cardValidation.middleware'; import { ICreditCard } from '@test-workspace/model'; class CardController implements Controller { public path = '/api/v1/card'; public router = express.Router(); private creditCards: ICreditCard[] = [ { name: 'Satadru', number: 6885622859, limit: 100, balance: 50 }, { name: 'Bhattacharjee', number: 1344361157, limit: 200, balance: 80 } ]; constructor() { this.initializeRoutes(); } private isDuplicateCardNumber = ( cards: ICreditCard[], cardNumber: number ): boolean => { return cards.some((card: ICreditCard) => card.number == cardNumber); }; private initializeRoutes() { this.router.get(this.path, this.getAllCards); this.router.post(this.path, cardValidationMiddleware(), this.createCard); } private getAllCards = ( request: express.Request, response: express.Response ) => { response.send(this.creditCards); }; private createCard = ( request: express.Request, response: express.Response, next: express.NextFunction ) => { const cardData: ICreditCard = request.body; if (this.isDuplicateCardNumber(this.creditCards, cardData.number)) { next(new HttpException(400, `Duplicate Credit Card Number`)); } else { this.creditCards.push(cardData); response.send(cardData); } }; } export default CardController;
606335139c26a96344c102513e80f8b131cfdd6a
TypeScript
ErickVAleman/reaper-graphql
/src/controllers/src/func_filter.ts
3.734375
4
/** * * @param input String de entrada para el filtrado * @param data Array de objetos * @param nameIndex Indice de los objetos para realizar el filtrado */ export const FILTER_ARRAY_OBJECTS = async (input: string, data: object[], nameIndex: string) => { return await data.filter((el: any) => el[`${nameIndex}`].toLowerCase().indexOf(input.toLowerCase()) > -1); }; export const FILTER_SIMPLE_ARRAY = async (input: string, data: []) => { return await data.filter(async (el: string | number) => { if (typeof el === "string") { return await el.toLowerCase().indexOf(input.toLowerCase()) > - 1; } else if (typeof el === "number") { return await el.toString().toLowerCase().indexOf(input.toString().toLowerCase()) > -1; } else { throw new Error("No se ha ingresado un tipo valido: Number or String"); } }); };
03146210bdf39d3813e025963403f38fcfcbe3a6
TypeScript
agroupp/numty_bak
/packages/core/src/operators/mathematical/miscellaneous/isNumber.ts
3.390625
3
/** * Return `true` if input data is `number` * * @category Mathematical Miscellaneous * * @param value Input data */ export function isNumber(value: number): boolean { return Number(value) === value; }
23abcf7dd3700ad0a772f1b2c257bd0834d3c331
TypeScript
iwe7/ims-chain
/packages/ims-close-port/lib/index.ts
2.5625
3
import child_process = require("child_process"); const { exec } = require("shelljs"); const timeout = 1000; export function close(port: number) { return new Promise(resolve => { const child = child_process.spawn("lsof", ["-i", `:${port}`]); child.stdout.on("data", rst => { let data = rst.toString("utf8", 0, rst.length); let port = null; data.split(/[\n|\r]/).forEach(item => { if (item.indexOf("LISTEN") !== -1 && !port) { let reg = item.split(/\s+/); if (/\d+/.test(reg[1])) { port = reg[1]; } } }); if (!port) { resolve(port); return; } exec(`kill -9 ${port}`, () => { console.log(`kill -9 ${port}`); resolve(port); }); }); child.stderr.on("data", rst => { let data = rst.toString("utf8", 0, rst.length); console.log(data); resolve(data); }); child.stderr.on("end", () => { resolve(); }); child.stdout.on("end", () => { resolve(); }); setTimeout(() => { resolve(); }, timeout); }); }
16d089d9b356dd60d0a77b1faf0342e4a80c96bd
TypeScript
12138qzj/lesson
/es6/addts.ts
2.96875
3
function addts(num1 :number, num2:number):number{ return num1+num2; } console.log(addts(5,6))
241aef3f7675d08bb167c0e3408b9133e59a6d6c
TypeScript
BurakAytekin/RepoOfBinance
/Saatlik_MA_CiftHoplama-master/src/app/services/helper.service.ts
2.828125
3
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class HelperService { constructor() { } sortByProperty = function (property) { return function (x, y) { return ((x[property] === y[property]) ? 0 : ((x[property] > y[property]) ? 1 : -1)); }; }; DateToNumberStr(value: any): any { const date = new Date(value); const month = date.getMonth() + 1; // months from 1-12 const day = date.getDate(); //// console.log('day') //// console.log(day); const year = date.getFullYear(); const seconds = date.getSeconds(); const minutes = date.getMinutes(); const hour = date.getHours(); const numberDateStr = this.SetStr0(year) + this.SetStr0(month) + this.SetStr0(day) + this.SetStr0(hour) + this.SetStr0(minutes) + this.SetStr0(seconds); //// console.log('numberDateStr') //// console.log(numberDateStr) return numberDateStr; } SetStr0(number: any): string { let Str = String(number); if (Str.length === 0) { Str = '00' + Str; } if (Str.length === 1) { Str = '0' + Str; } return Str; } dateAdd(date, interval, units) { if (!(date instanceof Date)) return undefined; var ret = new Date(date); //don't change original date var checkRollover = function () { if (ret.getDate() != date.getDate()) ret.setDate(0); }; switch (String(interval).toLowerCase()) { case 'year': ret.setFullYear(ret.getFullYear() + units); checkRollover(); break; case 'quarter': ret.setMonth(ret.getMonth() + 3 * units); checkRollover(); break; case 'month': ret.setMonth(ret.getMonth() + units); checkRollover(); break; case 'week': ret.setDate(ret.getDate() + 7 * units); break; case 'day': ret.setDate(ret.getDate() + units); break; case 'hour': ret.setTime(ret.getTime() + units * 3600000); break; case 'minute': ret.setTime(ret.getTime() + units * 60000); break; case 'second': ret.setTime(ret.getTime() + units * 1000); break; default: ret = undefined; break; } return ret; } }
52a6d57460d737fde39248727b89b2a0e66a5393
TypeScript
tonghoai/typescript-restful-starter
/src/sercurity/jwt.ts
2.90625
3
import * as jwt from "jsonwebtoken"; interface InterfaceJWTService { decode(token: string): InterfaceJWTDataDecode; encode(data: object): string; } interface InterfaceJWTDataDecode { user_id: number; } class JWT implements InterfaceJWTService { private _jwt: jwt; constructor() { this._jwt = jwt; } public decode(token: string): InterfaceJWTDataDecode { try { const decoded = this._jwt.verify(token, "tonghoai"); return { user_id: decoded.id, }; } catch (e) { throw new Error("error"); } } public encode(data: object): string { const token = this._jwt.sign(data, "tonghoai", { expiresIn: 24 * 60 * 60 }); return token; } } export default JWT;
ac4c4721dce62c10fe8e728eb7ee0b522487f5aa
TypeScript
quachtridat/fdu-campushub
/lib/announcements.ts
2.53125
3
import fs from 'fs' import path from 'path' import unified from 'unified' import remarkParse from 'remark-parse' import remarkRehype from 'remark-rehype' import rehypeRaw from 'rehype-raw' import rehypeStringify from 'rehype-stringify' import rehypeSanitize from 'rehype-sanitize' import toVfile from 'to-vfile' import vfileMatter from 'vfile-matter' import Announcement, { AnnouncementMeta, AnnouncementMetaMarkdown, AnnouncementTarget, } from '@/interfaces/announcement' import { getCourse } from './courses' export async function getAnnouncementsHtml(options?: { metaPredicate?: (value: AnnouncementMeta) => boolean announcementPredicate?: (value: Announcement) => boolean }): Promise<Array<Announcement>> { let ret: Array<Announcement> = [] const dataPath = getAnnouncementsPath() const filenames = await fs.promises.readdir(dataPath) for (const [fileIdx, filename] of filenames.entries()) { const filepath = path.join(dataPath, filename) const file = await toVfile.read(filepath) vfileMatter(file, { strip: true }) const { matter: frontmatter } = file.data as { matter: AnnouncementMetaMarkdown } const metadata: AnnouncementMeta = { announcer: frontmatter.announcer, title: frontmatter.title, } metadata.target = parseAnnouncementTarget(frontmatter.target) metadata.postDate = frontmatter.postDate && new Date(frontmatter.postDate) if (options && options.metaPredicate && !options.metaPredicate(metadata)) continue let err: any = undefined const fileNoFrontmatter = await unified() .use(remarkParse) .use(remarkRehype, { allowDangerousHtml: true }) .use(rehypeRaw) .use(rehypeSanitize) .use(rehypeStringify) .process(file) .catch((error) => (err = error)) if (err) { // ret.push(err) // console.log(err) continue } else { ret.push({ id: fileIdx, content: String(fileNoFrontmatter), ...metadata, } as Announcement) } } if (options && options.announcementPredicate) ret = ret.filter(options.announcementPredicate) if (options && options.metaPredicate) ret = ret.filter(options.metaPredicate) return ret } export function getAnnouncementsPath(): string { const sampleAnnoucementsMdPath = path.join( process.cwd(), 'data', 'announcements', 'markdown' ) return process.env.ANNOUNCEMENTS_PATH || sampleAnnoucementsMdPath } export function parseAnnouncementTarget(target?: string): AnnouncementTarget { const res: AnnouncementTarget = [] if (!target || target.length < 1) return res const entityFrags = target.split(';') if (!entityFrags || entityFrags.length < 1) return res for (const entityFrag of entityFrags) { const subFrags = entityFrag.split('.') if (!subFrags || subFrags.length < 1) continue const entityType = subFrags[0] if (entityType === 'course') { if (subFrags.length < 2) continue const courseIds = subFrags[1] .split(',') .map((courseId) => Number.parseInt(courseId, 10)) for (const courseId of courseIds) { if (courseId && !isNaN(courseId)) { const course = getCourse(courseId) if (course) { res.push(course) } } } } } return res }
94f62475118b937fb4471dacc4604845d603a44c
TypeScript
wenye123/async-once
/test/test-index.ts
2.875
3
import AsyncOnce, { AsyncOnceError } from "../src/index"; import { assert } from "chai"; function sleep(ms: number) { return new Promise(resolve => { setTimeout(resolve, ms); }); } describe("AsyncOnce", function() { it("获取数据", async function() { const aonce = new AsyncOnce({ timeout: 1000 }); const ret1 = await aonce.once("a", async () => { await sleep(50); return "wenye"; }); assert.strictEqual(ret1, "wenye"); const ret2 = await aonce.once("a", async () => { await sleep(50); return "yiye"; }); assert.strictEqual(ret2, "yiye"); }); it("并发获取数据", async function() { const aonce = new AsyncOnce({ timeout: 1000 }); const tag = "test"; let counter = 0; async function getData() { counter++; await sleep(50); return "wenye"; } const ret = await Promise.all([ aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), ]); assert.strictEqual(counter, 1); assert.deepStrictEqual(ret, [ "wenye", "wenye", "wenye", "wenye", "wenye", "wenye", "wenye", "wenye", "wenye", "wenye", "wenye", ]); }); it("并发获取数据超时", async function() { const aonce = new AsyncOnce({ timeout: 50 }); const tag = "test"; let counter = 0; async function getData() { counter++; await sleep(100); return "wenye"; } let isThrowError = false; try { await Promise.all([ aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), ]); } catch (err) { isThrowError = true; assert.instanceOf(err, AsyncOnceError); } assert.strictEqual(isThrowError, true); assert.strictEqual(counter, 1); }); it("并发获取数据报错", async function() { const aonce = new AsyncOnce({ timeout: 1000 }); const tag = "test"; let counter = 0; async function getData() { counter++; await sleep(50); throw new Error("test err"); } let isThrowError = false; try { await Promise.all([ aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), aonce.once(tag, getData), ]); } catch (err) { isThrowError = true; assert.strictEqual(err.message, "test err"); } assert.strictEqual(isThrowError, true); assert.strictEqual(counter, 1); }); });
99e1c346fd25605ee9cc2a18b0838a402ea1945a
TypeScript
OpenAPITools/openapi-generator
/samples/openapi3/client/petstore/typescript/builds/inversify/services/ObjectParamAPI.ts
2.703125
3
import type { HttpFile } from '../http/http'; import type { Configuration } from '../configuration' import type * as req from "../types/ObjectParamAPI"; import type { ApiResponse } from '../models/ApiResponse'; import type { Category } from '../models/Category'; import type { Order } from '../models/Order'; import type { Pet } from '../models/Pet'; import type { Tag } from '../models/Tag'; import type { User } from '../models/User'; export abstract class AbstractObjectPetApi { /** * * Add a new pet to the store * @param param the request object */ public abstract addPet(param: req.PetApiAddPetRequest, options?: Configuration): Promise<Pet>; /** * * Deletes a pet * @param param the request object */ public abstract deletePet(param: req.PetApiDeletePetRequest, options?: Configuration): Promise<void>; /** * Multiple status values can be provided with comma separated strings * Finds Pets by status * @param param the request object */ public abstract findPetsByStatus(param: req.PetApiFindPetsByStatusRequest, options?: Configuration): Promise<Array<Pet>>; /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags * @param param the request object */ public abstract findPetsByTags(param: req.PetApiFindPetsByTagsRequest, options?: Configuration): Promise<Array<Pet>>; /** * Returns a single pet * Find pet by ID * @param param the request object */ public abstract getPetById(param: req.PetApiGetPetByIdRequest, options?: Configuration): Promise<Pet>; /** * * Update an existing pet * @param param the request object */ public abstract updatePet(param: req.PetApiUpdatePetRequest, options?: Configuration): Promise<Pet>; /** * * Updates a pet in the store with form data * @param param the request object */ public abstract updatePetWithForm(param: req.PetApiUpdatePetWithFormRequest, options?: Configuration): Promise<void>; /** * * uploads an image * @param param the request object */ public abstract uploadFile(param: req.PetApiUploadFileRequest, options?: Configuration): Promise<ApiResponse>; } export abstract class AbstractObjectStoreApi { /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * Delete purchase order by ID * @param param the request object */ public abstract deleteOrder(param: req.StoreApiDeleteOrderRequest, options?: Configuration): Promise<void>; /** * Returns a map of status codes to quantities * Returns pet inventories by status * @param param the request object */ public abstract getInventory(param: req.StoreApiGetInventoryRequest, options?: Configuration): Promise<{ [key: string]: number; }>; /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions * Find purchase order by ID * @param param the request object */ public abstract getOrderById(param: req.StoreApiGetOrderByIdRequest, options?: Configuration): Promise<Order>; /** * * Place an order for a pet * @param param the request object */ public abstract placeOrder(param: req.StoreApiPlaceOrderRequest, options?: Configuration): Promise<Order>; } export abstract class AbstractObjectUserApi { /** * This can only be done by the logged in user. * Create user * @param param the request object */ public abstract createUser(param: req.UserApiCreateUserRequest, options?: Configuration): Promise<void>; /** * * Creates list of users with given input array * @param param the request object */ public abstract createUsersWithArrayInput(param: req.UserApiCreateUsersWithArrayInputRequest, options?: Configuration): Promise<void>; /** * * Creates list of users with given input array * @param param the request object */ public abstract createUsersWithListInput(param: req.UserApiCreateUsersWithListInputRequest, options?: Configuration): Promise<void>; /** * This can only be done by the logged in user. * Delete user * @param param the request object */ public abstract deleteUser(param: req.UserApiDeleteUserRequest, options?: Configuration): Promise<void>; /** * * Get user by user name * @param param the request object */ public abstract getUserByName(param: req.UserApiGetUserByNameRequest, options?: Configuration): Promise<User>; /** * * Logs user into the system * @param param the request object */ public abstract loginUser(param: req.UserApiLoginUserRequest, options?: Configuration): Promise<string>; /** * * Logs out current logged in user session * @param param the request object */ public abstract logoutUser(param: req.UserApiLogoutUserRequest, options?: Configuration): Promise<void>; /** * This can only be done by the logged in user. * Updated user * @param param the request object */ public abstract updateUser(param: req.UserApiUpdateUserRequest, options?: Configuration): Promise<void>; }
d9a4a0a5d4ab0d47e989512b81a4747d3856ba6e
TypeScript
tcharlat/rest-api-test
/src/store/Stocks/reducer.ts
2.90625
3
import { Reducer } from "react"; import { StockState, StockActions } from "./typings"; export const defaultStocks: StockState = { data: [], fetchStatus: "INIT", dataSource: "none" }; export const stockReducer: Reducer<StockState, StockActions> = ( state = defaultStocks, action ) => { switch (action.type) { case "ADD_STOCKS": return { ...state, data: action.stocks, dataSource: action.dataSource }; case "EDIT_STOCK": if (action.value === state.data[action.index].stocks) { return state; } const newStock = { ...state.data[action.index], stocks: action.value }; const data = [...state.data]; data[action.index] = newStock; return { ...state, data }; case "FETCH_STOCKS_STATUS": return { ...state, fetchStatus: action.fetchStatus }; } return state; };
af95ddcabb774087cf5b837256d99287d8f1deaf
TypeScript
crimx/ext-saladict
/src/components/dictionaries/ahdict/engine.ts
2.671875
3
import { fetchDirtyDOM } from '@/_helpers/fetch-dom' import { HTMLString, getText, getInnerHTML, handleNoResult, handleNetWorkError, SearchFunction, GetSrcPageFunction, DictSearchResult } from '../helpers' export const getSrcPage: GetSrcPageFunction = text => { return `https://ahdictionary.com/word/search.html?q=${text}` } const HOST = 'https://ahdictionary.com' interface Idiom { title?: string eg?: string tips?: string } interface AhdictResultItem { /** word */ title: string /** pronunciation */ pron?: string /** meaning and eg */ meaning: HTMLString[] /** idiom and eg */ idioms: Idiom[] origin?: HTMLString usageNote?: string } export type AhdictResult = AhdictResultItem[] type AhdictSearchResult = DictSearchResult<AhdictResult> export const search: SearchFunction<AhdictResult> = ( text, config, profile, payload ) => { const options = profile.dicts.all.ahdict.options return fetchDirtyDOM( 'https://ahdictionary.com/word/search.html?q=' + encodeURIComponent(text.replace(/\s+/g, ' ')) ) .catch(handleNetWorkError) .then(doc => handleDOM(doc, options)) } function handleDOM( doc: Document, { resultnum }: { resultnum: number } ): AhdictSearchResult | Promise<AhdictSearchResult> { const result: AhdictResult = [] const tables = Array.from(doc.querySelectorAll('#results>table')) if (tables.length <= 0) { return handleNoResult() } for (let i = 0; i < tables.length && result.length < resultnum; i++) { const $panel = tables[i] const resultItem: AhdictResultItem = { title: '', meaning: [], idioms: [] } const $rtseg = $panel.querySelector('.rtseg') as HTMLElement if ($rtseg) { const $rtsega = $panel.querySelectorAll('.rtseg>a') if ($rtsega[1] && $rtsega[1].getAttribute('href')) { resultItem.pron = `${HOST}${$rtsega[1].getAttribute('href')}` } resultItem.title = getText($rtsega[0], 'font') } const $pseg = Array.from($panel.querySelectorAll('.pseg')) $pseg.map(item => { resultItem.meaning.push( getInnerHTML(HOST, item).replace(/<\/?(span|font)[^>]*>/g, '') ) }) const $idmseg = Array.from($panel.querySelectorAll('.idmseg')) if ($idmseg.length) { $idmseg.map(item => { const idiom = {} as Idiom idiom.title = getText(item, 'b') idiom.eg = getText(item, '.ds-single') idiom.tips = getText(item, 'span+i') resultItem.idioms.push(idiom) }) } // 获取该条信息来源 const $etyseg = $panel.querySelector('.etyseg') as HTMLElement if ($etyseg) { resultItem.origin = getInnerHTML(HOST, $etyseg).replace( /<\/?(span|font)[^>]*>/g, '' ) } // 获取使用说明 const $usen = $panel.querySelector('.usen') as HTMLElement if ($usen) { resultItem.usageNote = getInnerHTML(HOST, $usen).replace( /<\/?(span|font|i)[^>]*>/g, '' ) } result.push(resultItem) } if (result.length > 0) { return { result } } else { return handleNoResult() } }
3f446dec2286d43562c14a0f7b04cc720675b9a2
TypeScript
calebpitan/nextjs-ts-redux-template
/app/redux/cursor/types.ts
2.765625
3
import { Action } from 'redux' export enum QueryCursorActionTypes { INCRENENT_OFFSET_FACTOR = 'INCRENENT_OFFSET_FACTOR', SET_LIMIT = 'SET_LIMIT', } export interface QueryCursorOffsetFactorAction extends Action<QueryCursorActionTypes> { type: QueryCursorActionTypes.INCRENENT_OFFSET_FACTOR } export interface QueryCursorLimitAction extends Action<QueryCursorActionTypes> { type: QueryCursorActionTypes.SET_LIMIT payload: { limit: number } } export type QueryCursorAction = QueryCursorOffsetFactorAction | QueryCursorLimitAction
45f49faca112fb52e47f488e5468da4490f91c12
TypeScript
Jamyth/nest-api-generator
/src/util/createControllerMethod.ts
2.8125
3
import {Utility} from "../util"; import type {ControllerMethod, MethodParameter, RequestMethod, TransformDataType} from "../type"; import {ReflectUtil} from "../reflect"; export function createService(target: Object, methodName: string | symbol, path: string, requestMethod: RequestMethod) { /** * Get functions defined with @Get @Post @Delete @Put etc... */ const controllerMethods = ReflectUtil.getControllerMethods(target.constructor); /** * function paramter defined with @Param decorator */ const pathParameters = ReflectUtil.getMethodPathParams(target.constructor, methodName); /** * function parameter defined with @Body or @Query decorator * @expected There is only one element in this variable * Body and Query should not appear in the same time */ const bodyOrQueryParameters = ReflectUtil.getBodyOrQueryParameters(target.constructor, methodName); /** * actual function parameters, may have types of number / string / other */ const rawParameters = ReflectUtil.getFunctionParameters(target, methodName); const transformedParameters = rawParameters.map((_) => Utility.transformDataType(_)); /** * the actual parameter of type @Body | @Query */ const requestType = transformedParameters.find((_, i) => bodyOrQueryParameters?.index === i) ?? null; const {pathParams, pathParamInterface} = getPathParams(pathParameters, transformedParameters); const responseType = Utility.transformDataType(ReflectUtil.getMethodReturn(target, methodName)) ?? "void"; const service: ControllerMethod = { method: requestMethod, name: String(methodName), path, pathParams, pathParamInterface, requestType, responseType, }; controllerMethods.push(service); ReflectUtil.defineControllerMethods(controllerMethods, target.constructor); } // eslint-disable-next-line sonarjs/cognitive-complexity -- refactor later function getPathParams(pathParameters: MethodParameter[], transformedParameters: (string | TransformDataType | undefined)[]) { let pathParamInterface: string | TransformDataType | null = null; let pathParams: {name: string; type: string}[] = []; for (let i = 0; i < pathParameters.length; i++) { const param = pathParameters[i]; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- checked const parameter = transformedParameters[param.index]!; const nullableKeys = typeof parameter === "string" ? [] : parameter.nullableKeys; const propertyKey = param.property; const isNullable = propertyKey ? nullableKeys.includes(propertyKey) : false; const type = (typeof parameter === "string" ? parameter : parameter.name) + (isNullable ? "| null" : ""); if (propertyKey) { pathParams.push({name: propertyKey, type}); } else { const body = (parameter as TransformDataType).body; pathParamInterface = parameter; pathParams = Object.entries(body).map(([name, param]: [string, string | TransformDataType]) => ({ name, type: typeof param === "string" ? param : param.name, })); break; } } return { pathParams, pathParamInterface, }; }
2c617e2e69b82785bb40dc953b801f2d85efd389
TypeScript
snjanbu/TypeScript
/module.ts
3.09375
3
import {Vehicle} from './interface' class Lorry implements Vehicle{ name:string; constructor(name:string){ this.name=name; } drive(){ console.log('Driving Lorry'); } } var lorry=new Lorry('Benz'); lorry.drive();
9dd0532b9a12f3fa4a71d54fc5f3cc4d50d625a8
TypeScript
three/nand-simulator
/devices/ParallelReader.ts
2.9375
3
import {Circuit} from "../Circuit.ts"; /** * Read byte from device.inputNodes on positive clock edges when readyNode is high, and output to stdout */ export class ParallelReader { circuit: Circuit; inputNodes: number[]; readyNode: number; value: Uint8Array; ready: boolean; clockNode: number; clockPrev: boolean; constructor(circuit: Circuit, device: ParallelReaderDesc) { this.circuit = circuit; this.inputNodes = device.inputNodes; this.readyNode = device.readyNode; this.ready = false; this.value = new Uint8Array(1); this.clockNode = device.clockNode; this.clockPrev = true; } pre() { let clk = this.circuit.getBitFromFrontBuffer(this.clockNode); this.ready = ( this.circuit.getBitFromFrontBuffer(this.readyNode) && clk && !this.clockPrev ); this.clockPrev = clk; if (this.ready) { let byte = 0; for (let i=0;i<8;i++) { let v = this.circuit.getBitFromFrontBuffer(this.inputNodes[i]); if (v) { byte += 1 << i; } } this.value[0] = byte; } } late() { if (this.ready) { Deno.stdout.writeSync(this.value); } } } export interface ParallelReaderDesc { type: "PARALLEL_READER"; inputNodes: number[]; readyNode: number; clockNode: number; }
66abcef9d084b86994abe26c3222eedf0a17f399
TypeScript
liujunnan0516/a-barrage
/src/commander/css-renderer/base-fixed.ts
2.8125
3
import BaseCssCommander from './base-css' import { CommanderConfig, FixedBarrageObejct } from '../../types' import Track from '../../track' import { isEmptyArray } from '../../helper' import { createBarrage, appendChild } from '../../helper/css' export default abstract class BaseFixedCssCommander extends BaseCssCommander<FixedBarrageObejct> { protected elHeight: number constructor(el: HTMLDivElement, config: CommanderConfig) { super(el, config) this.elHeight = el.offsetHeight } add(barrage: FixedBarrageObejct): boolean { const trackId = this._findTrack() if (trackId === -1) { return false } // 创建弹幕DOM const { text, size, color, offset } = barrage const fontSize = size + 'px' let posLeft = offset + 'px' const danmu = createBarrage(text, color, fontSize, posLeft) appendChild(this.el, danmu) const width = danmu.offsetWidth // 计算位置 const track = this.tracks[trackId] const trackWidth = this.trackWidth const barrageOffset = (trackWidth - width) / 2 const normalizedBarrage = Object.assign({}, barrage, { offset: barrageOffset, duration: this.duration, width }) this.objToElm.set(normalizedBarrage, danmu) this.elmToObj.set(danmu, normalizedBarrage) track.push(normalizedBarrage) return true } _findTrack(): number { let idx = -1 for (let i = 0; i < this.tracks.length; ++i) { if (isEmptyArray(this.tracks[i].barrages)) { idx = i break } } return idx } _extractBarrage(): void { let isIntered: boolean for (let i = 0; i < this.waitingQueue.length; ) { isIntered = this.add(this.waitingQueue[i]) if (!isIntered) { break } this.waitingQueue.shift() } } _removeTopElementFromTrack(track: Track<FixedBarrageObejct>) { const barrage = track.barrages[0] if (!barrage) { return } const el = this.objToElm.get(barrage)! this.objToElm.delete(barrage) this.elmToObj.delete(el) this.removeElement(el) } }
de69f700680ae11de782e656e9ab782ce5a08373
TypeScript
Josephine19001/JustShop
/client/src/redux/reducers/cart.ts
2.953125
3
import { CartState, ProductActions, ADD_PRODUCT, INCREASE_QUANTITY, DECREASE_QUANTITY, EMPTY_CART, REMOVE_PRODUCT, ProductState, } from "../../types"; const initialState: CartState = { inCart: [], }; export default function product( state = initialState, action: ProductActions ): CartState { switch (action.type) { case ADD_PRODUCT: { const { product } = action.payload; return { ...state, inCart: [...state.inCart, product] }; } case REMOVE_PRODUCT: { const { product } = action.payload; const index = state.inCart.findIndex((p) => p.name === product.name); if (index >= 0) { state.inCart.splice(index, 1); return { ...state, inCart: [...state.inCart] }; } return state; } case INCREASE_QUANTITY: { const productId = action.payload.product._id; return { ...state, inCart: state.inCart.map((product) => product._id === productId && product.amountInCart < product.quantity ? { ...product, amountInCart: product.amountInCart + 1 } : product ), }; } case DECREASE_QUANTITY: { const productId = action.payload.product._id; return { ...state, inCart: state.inCart.map((product) => product._id === productId ? { ...product, amountInCart: product.amountInCart - 1, } : product ), }; } default: return state; } }
811d9892829a78669bf66c47509f4b24cd562bdb
TypeScript
tanay-pingalkar/replace.js
/tests/regex.test.ts
2.921875
3
import { functionRegex, keyWordRegex, arrAndObjRegex, } from "../src/utils/regex"; describe("gonna check if regex works fine", () => { const str = "<h1>{{ var }}</h1><h1>{{ (bool)=>bool? 'hello' : 'bye' }}</h1><h1>{{ arr[0] }}</h1>\n<h4>{{ obj.lol[0].lol }}</h4>"; it("should match functions", () => { expect(str.match(functionRegex("bool"))).toEqual([ "{{ (bool)=>bool? 'hello' : 'bye' }}", ]); }); it("should match keywords", () => { expect(str.match(keyWordRegex("var"))).toEqual(["{{ var }}"]); }); it("should match array", () => { expect(str.match(arrAndObjRegex("arr"))).toEqual(["{{ arr[0] }}"]); }); it("should match object", () => { expect(str.match(arrAndObjRegex("obj"))).toEqual(["{{ obj.lol[0].lol }}"]); }); });
e8562b11dbbcd62a7afdbd42067e955c122cdd24
TypeScript
wanggao/away3d-core-ts
/src/away/events/EventDispatcher.ts
3.203125
3
///<reference path="../_definitions.ts"/> /** * @module away.events */ module away.events { /** * Base class for dispatching events * * @class away.events.EventDispatcher * */ export class EventDispatcher { private listeners:Object[] = new Array<Object>(); private lFncLength:number; /** * Add an event listener * @method addEventListener * @param {String} Name of event to add a listener for * @param {Function} Callback function * @param {Object} Target object listener is added to */ public addEventListener(type:string, listener:Function, target:Object) { if (this.listeners[ type ] === undefined) { this.listeners[ type ] = new Array<EventData>(); } if (this.getEventListenerIndex(type, listener, target) === -1) { var d:EventData = new EventData(); d.listener = listener; d.type = type; d.target = target; this.listeners[ type ].push(d); } } /** * Remove an event listener * @method removeEventListener * @param {String} Name of event to remove a listener for * @param {Function} Callback function * @param {Object} Target object listener is added to */ public removeEventListener(type:string, listener:Function, target:Object) { var index:number = this.getEventListenerIndex(type, listener, target); if (index !== -1) { this.listeners[ type ].splice(index, 1); } } /** * Dispatch an event * @method dispatchEvent * @param {Event} Event to dispatch */ public dispatchEvent(event:Event) { var listenerArray:Array<EventData> = this.listeners[ event.type ]; if (listenerArray !== undefined) { this.lFncLength = listenerArray.length; event.target = this; var eventData:EventData; for (var i = 0, l = this.lFncLength; i < l; i++) { eventData = listenerArray[i]; eventData.listener.call(eventData.target, event); } } } /** * get Event Listener Index in array. Returns -1 if no listener is added * @method getEventListenerIndex * @param {String} Name of event to remove a listener for * @param {Function} Callback function * @param {Object} Target object listener is added to */ private getEventListenerIndex(type:string, listener:Function, target:Object):number { if (this.listeners[ type ] !== undefined) { var a:Array<EventData> = this.listeners[ type ]; var l:number = a.length; var d:EventData; for (var c:number = 0; c < l; c++) { d = a[c]; if (target == d.target && listener == d.listener) { return c; } } } return -1; } /** * check if an object has an event listener assigned to it * @method hasListener * @param {String} Name of event to remove a listener for * @param {Function} Callback function * @param {Object} Target object listener is added to */ //todo: hasEventListener - relax check by not requiring target in param public hasEventListener(type:string, listener?:Function, target?:Object):boolean { if (this.listeners != null && target != null) { return ( this.getEventListenerIndex(type, listener, target) !== -1 ); } else { if (this.listeners[ type ] !== undefined) { var a:Array<EventData> = this.listeners[ type ]; return ( a.length > 0 ); } return false; } return false; } } /** * Event listener data container */ class EventData { public listener:Function; public target:Object; public type:string; } }
d8b05fe578c2085cc6b0483db229258c82b588f0
TypeScript
HHHHHHHHHHHHHHHHHHHHHCS/MyTinyModeTest01
/Assets/MyFirstDemo/Scripts/LogPosition.ts
2.578125
3
namespace game { //普通的log export class LogPosition extends ut.ComponentSystem { static onlyOnce: boolean = false OnUpdate(): void { return; if (LogPosition.onlyOnce) { return } LogPosition.onlyOnce = true this.world.forEach([ut.Entity, ut.Core2D.TransformNode], (entity, transformNode) => { let worldPos = ut.Core2D.TransformService.computeWorldPosition(this.world, entity); console.log(`${this.world.getEntityName(entity)} is at (${worldPos.x},${worldPos.y})`) }) } } }
8f483552d66741404bfac5a98b3115d0b837ba14
TypeScript
MikeNats/card-manager
/src/domain/card/cardService.ts
2.96875
3
import { CardModel } from './entity' import { v4 as uuidv4 } from 'uuid'; import valid from 'card-validator'; import creditCardType from "credit-card-type"; import { ReactText } from 'react' export const createCard = (card: CardModel): CardModel => Object.freeze({ id: card && card.id ? card.id : uuidv4(), type: card && card.cardNumber ? creditCardType(`${card.cardNumber}`)[0].type : '', name: card.name, cardNumber: card.cardNumber, expiration: card.expiration, cvc: card.cvc }); export const canBeParshedToInt = (input: string): boolean => !!(input.split("").filter(el => !isNaN(parseInt(el))).length > 0) export const isValidCardName = (name: string):boolean => !!(name && /^([\w]{3,})+\s+([\w\s]{3,})+$/i.test(name)) export const isValidCardNumber = (cardNum: string): boolean => !!(cardNum && (valid.number(`${cardNum}`)).isPotentiallyValid) export const isValidDate = (date: string):boolean => !!(date && /^(0[1-9]|1[0-2])\/\d{2}$/.test(date)); export const isValidCvc = (cvc: ReactText):boolean => !!(cvc && /^\d{3}$/.test(`${cvc}`) && canBeParshedToInt(`${cvc}`)); export const addSpaceEveryFourChars = (input: string | number): string => `${input}`.replace(/[^\dA-Z]/gi, '') .replace(/(.{4})/g, '$1 ') .trim() export const addSlashEveryTwoChars= (input: string | number): string => `${input}`.replace(/[^\dA-Z]/gi, '') .replace(/(.{2})/, '$1/') .trim()
3676e2bc9f920a90480dd7df2e6d951e1ec935bc
TypeScript
jack0612/tutorial
/src/app/custom-control/text-input/text-input.component.ts
2.59375
3
import { Component, forwardRef, Input, Self, OnInit } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor, NgControl, FormControl } from '@angular/forms'; //https://github.com/profanis/angular-custom-form-elements/blob/custom-form-with-validation/src/app/app.component.ts @Component({ selector: 'text-input', templateUrl: './text-input.component.html', styleUrls: ['./text-input.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TextInputComponent), multi: true, }, ], }) export class TextInputComponent implements ControlValueAccessor { @Input() label: string; @Input() type: 'text' | 'password' | 'email' = 'text'; @Input() placeholder: string; @Input() control: FormControl; field: string; id = Math.random(); errors = { minlength: 'Min length error', required: 'Field is required', email: 'Email is invalid' }; // Function to call when change onChange = (value: any) => { } writeValue(obj: any): void { this.field = obj; } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { } setDisabledState?(isDisabled: boolean): void { } getErrors(): { type; message; }[] { if (!this.control.errors) { return; } return Object.keys(this.control.errors).map(errorType => { return { type: errorType, message: this.errors[errorType] }; } ); } }
a9fd39906d85e24b702723205df363769f73313e
TypeScript
OfirTheOne/mongo-ts
/lib/core/meta/function/static.ts
2.765625
3
import { MetadataAgent } from '../../../helpers' /** * @description * class method, decorated with '@Static', will be handled as a static model method, * 'this' key word will refer to the Model itself, not a specific document. * @warn * using 'this' at compilation time is not reflect the context of the method at run-time. */ function Static() { return (targetPrototype: Object, propertyName: string, propertyDesciptor: PropertyDescriptor): PropertyDescriptor => { if(!MetadataAgent.has(targetPrototype, 'isProcessed')) { // take the actual method (decorated by @Static) const method = targetPrototype[propertyName]; // insert the method to '$metadata.functions.statics' MetadataAgent.set(targetPrototype, [`functions.statics.${propertyName}`, method]) } return propertyDesciptor; } } export { Static };
e4e073621d14a85d2611778959930f9a2552f24f
TypeScript
robertohonda/typescript-express-mongo-boilerplate
/src/responses/APIResponse/APIResponse.ts
2.6875
3
import { OK } from "http-status"; import {OK as OK_MESSAGE} from "../../messages/standard"; import { SUCCESS } from "../../messages/types/standard"; import IAPIResponse from "./IAPIResponse"; class APIResponse implements IAPIResponse { public status: number; public message?: string; public type: string; public data?: any; public count?: number; constructor({ message = OK_MESSAGE, type = SUCCESS, status = OK, data, count, }: IAPIResponse) { this.status = status; this.type = type; this.message = message; this.data = data; this.count = count; } } export default APIResponse;
031d4209511286001557c27929b04fb8536ed287
TypeScript
alejandromz96/angular-testing.github.io
/ionic-unit-testing-example/src/pages/page-testing/components/warrior-component/warrior-component.ts
2.59375
3
import { Component } from '@angular/core'; import { WarriorInterface } from '../../interfaces/warrior.interface'; @Component({ selector: 'warrior-component', templateUrl: 'warrior-component.html' }) export class WarriorComponent { private warriorClasses: string[] = ["Luchador", "Mago", "Paladin", "Sacerdote", "Cazador"]; private weapons: string[] = ["Gran espada", "Espadas dobles", "Arco", "Maza", "Espada larga", "Hacha", "Báculo"]; private warriors: WarriorInterface[] = []; constructor() { } public getWarriorClasses(): string[] { return this.warriorClasses; } public getWeapons(): string[] { return this.weapons; } public setWarrior(warrior: WarriorInterface): void { this.warriors.push(warrior); } }
d7f5990b1cb4a2093d6e0db8bd632b4fd6efd451
TypeScript
strong-roots-capital/fp-ts-react-stable-hooks
/test/callback.test.ts
3.03125
3
import * as Eq from 'fp-ts/Eq'; import * as O from 'fp-ts/Option'; import { renderHook } from '@testing-library/react-hooks'; import { useStableCallback } from '../src/index'; const o1a = O.some(1); const o1b = O.some(1); const o2 = O.some(2); const nEq = Eq.getTupleEq(O.getEq(Eq.eqNumber)); describe('useStableCallback', () => { test('should not return a new function if the values are the same', () => { let o = o1a; const { result, rerender } = renderHook(() => useStableCallback(() => o, [o], nEq)); o = o1b; rerender(); expect(result.all[0]).toStrictEqual(result.all[1]); expect(result.current()).toStrictEqual(o1a); }); test('should return a new function if the values are different', () => { let o = o1a; const { result, rerender } = renderHook(() => useStableCallback((a: number) => O.getOrElse(() => 0)(o) + a, [o], nEq)); expect(result.current(1)).toStrictEqual(2); o = o2; rerender(); expect(result.all[0]).not.toStrictEqual(result.all[1]); expect(result.current(1)).toStrictEqual(3); }); });
85a0d83af5b5a2db45048c91bd764ea90af0cf43
TypeScript
ETM44/TPMessagerie
/src/app/modeles/messagesAdaptateur.ts
2.578125
3
import {Message} from "./Message"; import {Personne} from "./Personne"; export class messagesAdaptateur { static _idMessage: number = 1; static _idPersonne: number = 1; constructor() { } static messageAPI(listMessage: Array<any>): Array<Message> { let newListMessage: Array<Message> = new Array<Message>(); for (const message of listMessage) { newListMessage.push(new Message(this._idMessage++, new Personne(this._idPersonne++,message.auteur.pseudo), new Date(), message.textMessage)) } return newListMessage; } }
0e3db5b4d5f45f1b09083a196d24d7c8090b95a7
TypeScript
tobslob/pdfmills
/src/drawables/block.ts
3.15625
3
import { BoundingBox, Context, Element, Layout } from '../base'; import sumBy = require('lodash/sumBy'); /** * This arranges all it's element on a vertical line using the width * of its bounding box. */ export class Block implements Layout { constructor(private elements: Element[]) { if (elements.length < 2) { throw new Error("You don't need this layout"); } } width(context: Context, box: BoundingBox): number { return box.width; } height(context: Context, box: BoundingBox): number { return this.elements.reduce((h, el) => { return h + el.height(context, box); }, 0); } draw(context: Context, box: BoundingBox): void { const boxes = this.boxes(context, box); this.elements.forEach((el, i) => { el.draw(context, boxes[i]); }); const fullHeight = sumBy(boxes, b => b.height); context.reframe(0, fullHeight); } boxes(context: Context, box: BoundingBox): BoundingBox[] { const boxes: BoundingBox[] = []; for (const el of this.elements) { const height = el.height(context, box); boxes.push({ ...box, height }); box.y += height; box.height -= height; } return boxes; } }
ce2887b20572dd791c8f998eec0ee1f01eec3a86
TypeScript
snelsi/canvas-hexagons
/src/scripts/random-helpers.ts
3.25
3
export const random = (a = 1, b = 0) => { const lower = Math.min(a, b); const upper = Math.max(a, b); return lower + Math.random() * (upper - lower); }; export const randomInt = (a = 1, b = 0) => { const lower = Math.ceil(Math.min(a, b)); const upper = Math.floor(Math.max(a, b)); return Math.floor(lower + Math.random() * (upper - lower + 1)); }; const getPositionBetween = (min: number, max: number, variance: number) => random(min - variance, max + variance); const defaultHueVariance = 40; const getRandomColor = (baseHue: number, hueVariance: number = defaultHueVariance) => { const hue = randomInt(baseHue - hueVariance, baseHue + hueVariance); const saturation = randomInt(4, 55); return `hsla(${hue}, ${saturation}%, ${randomInt(30, 80)}%, ${random(0.2, 0.6)})`; }; interface getRandomHexagonProps { baseSize: number; baseHue: number; x: number | number[]; y: number | number[]; } export interface IHexagon { initialRotation: number; rotationSpeed: number; x: number; y: number; size: number; color: string; } export const getRandomHexagon = ({ baseSize, baseHue, x, y }: getRandomHexagonProps): IHexagon => { const size = randomInt(baseSize * 1.2, baseSize * 2); const positionVariance = Math.round(0.1 * baseSize); const [Xmin, Xmax] = Array.isArray(x) ? x : [x, x]; const [Ymin, Ymax] = Array.isArray(y) ? y : [y, y]; return { x: getPositionBetween(Xmin - size * 0.5, Xmax - size * 0.5, positionVariance), y: getPositionBetween(Ymin - size * 0.5, Ymax - size * 0.5, positionVariance), size, color: getRandomColor(baseHue, defaultHueVariance), initialRotation: randomInt(0, 90), rotationSpeed: random(-0.1, 0.1), }; }; interface getHexagonsToFillZoneProps { width: number; height: number; } export const getHexagonsToFillZone = ({ width, height }: getHexagonsToFillZoneProps) => { const baseHue = randomInt(200, 300); const smallerSize = Math.min(width, height); /* putting big hexagons in the screen corners */ /* so that we have the whole screen covered */ const cornerHexagons: IHexagon[] = []; for (let i = 0; i <= Math.round(width / smallerSize); i++) { for (let j = 0; j <= Math.round(height / smallerSize); j++) { cornerHexagons.push( getRandomHexagon({ baseSize: Math.max(width, height), x: i * width, y: j * height, baseHue, }), ); } } /* Then adding some more hexagons randomly on the screen */ const extraHexagons = [...new Array(randomInt(5, 10))].map(() => { return getRandomHexagon({ baseSize: smallerSize, x: [0, width], y: [0, height], baseHue, }); }); return [...cornerHexagons, ...extraHexagons]; };
e8c85edd04aa6b969175f4c70ec8add63f61d1e0
TypeScript
TW2002/twxp
/Source/Installer/TWXS27/Public/end_bd.ts
2.71875
3
#Ender's Quick Backdoor finder v1.0 #Will quickly find the back door of Terra or StarDock clientMessage "You can find back door to terra anywhere, but for the Star dock, you must be there." Send "'Ender's Quick Backdoor finder v1.0 loaded! *" clientMessage "Either scroll back up to see back door, or use the $ D - <sector> command" :info echo ANSI_13 & "*Are we finding back door to Terra or StarDock?*" getInput $type "(T)errra / (S)tarDock" If ($type = "t") or ($type = "T") send "c v 2 *" send "v 3 *" send "v 4 *" send "v 5 *" send "v 6 *" send "v 7 *" send "v 8 *" send "v 9 *" send "v 10 *" send "f 22* 1*" send "v 0* y n 2*" send "v 0* y n 3*" send "v 0* y n 4*" send "v 0* y n 5*" send "v 0* y n 6*" send "v 0* y n 7*" send "v 0* y n 8*" send "v 0* y n 9*" send "v 0* y n 10*" send "q" end If ($type = "s") or ($type = "S") :getSector Send "d" setTextLineTrigger getting :getting "Sector :" PAUSE :getting getword currentline $sector 3 getSector $sector $sectordata If ($sector = STARDOCK) else send "'Must start at stardock! *" HALT end send "c v" $sectordata.warp[1] "*" send "v" $sectordata.warp[2] "*" send "v" $sectordata.warp[3] "*" send "v" $sectordata.warp[4] "*" send "v" $sectordata.warp[5] "*" send "v" $sectordata.warp[6] "*" send "f 22*" $sector "*" send "v 0* y n" $sectordata.warp[1] "*" send "v 0* y n" $sectordata.warp[2] "*" send "v 0* y n" $sectordata.warp[3] "*" send "v 0* y n" $sectordata.warp[4] "*" send "v 0* y n" $sectordata.warp[5] "*" send "v 0* y n" $sectordata.warp[6] "*" send "q" end clientMessage "Either scroll back up to see back door, or use the $ D - <sector> command" HALT
42d0ab6895931f1bac6d9bb3e46d3a0b6ed6a2bf
TypeScript
rofl4lol/rofl4lol.github.io
/Request.ts
2.625
3
import Summoner = require("Summoner"); module Request { export class Info { Path: string; OnSuccess: (string) => void; OnError: (number) => void; constructor(path: string, onSuccess: (string) => void, onError: (number) => void) { this.Path = path; this.OnSuccess = onSuccess; this.OnError = onError; } } export class Manager { static ApiKey: string; static TotalRequests: KnockoutComputed<number>; private static _refreshQueue: KnockoutObservableArray<Info>; private static _refreshQueueWaiting: KnockoutObservableArray<Info>; private static _hiPriQueue: KnockoutObservableArray<Info>; private static _hiPriQueueWaiting: KnockoutObservableArray<Info>; private static _delayedRequestInterval: number; private static _initialized: boolean = false; private static requestStillValid(waitQueue: KnockoutObservableArray<Info>, ri: Info): boolean { var fromWaiting: Array<Info> = waitQueue.remove(ri); if (fromWaiting.length > 1) { alert("Error: Request.Manager.requestStillValid(): Removed too many from waiting queue."); return false; } else if (fromWaiting.length != 1) return false; return true; } static Start(apiKey: string) { if (!Manager._initialized) { if (!Manager._refreshQueue) Manager._refreshQueue = ko.observableArray([]); if (!Manager._refreshQueueWaiting) Manager._refreshQueueWaiting = ko.observableArray([]); if (!Manager._hiPriQueue) Manager._hiPriQueue = ko.observableArray([]); if (!Manager._hiPriQueueWaiting) Manager._hiPriQueueWaiting = ko.observableArray([]); if (!Manager.TotalRequests) { Manager.TotalRequests = ko.computed(function RequestManagerTotalRequests() { return Manager._refreshQueue().length + Manager._refreshQueueWaiting().length + Manager._hiPriQueue().length + Manager._hiPriQueueWaiting().length; }); } Manager._delayedRequestInterval = setInterval(sendNextRequest, 1250); // 50ms wiggle room to avoid rate limit Manager._initialized = true; } Manager.ApiKey = apiKey; function sendNextRequest() { if (Manager._hiPriQueue().length > 0) { var info = Manager._hiPriQueue.shift(); Manager._hiPriQueueWaiting.push(info); Manager.sendRequest( info.Path, (function ManagerHiPriSuccessWrapper(ri: Info) { return function ManagerHiPriSuccess(responseText: string) { if (Manager.requestStillValid(Manager._hiPriQueueWaiting, ri)) ri.OnSuccess(responseText); // else it wasn't in waiting queue so it was cancelled } })(info), (function ManagerHiPriErrorWrapper(ri: Info) { return function ManagerHiPriError(status: number) { if (!Manager.requestStillValid(Manager._hiPriQueueWaiting, ri)) return; else if (status === 429) // rate limit exceeded, requeue and try again Manager.queueInternal(ri, Manager._hiPriQueue, Manager._hiPriQueueWaiting); // requeue and try again later else ri.OnError(status); } })(info) ); // sendRequest() } else if (Manager._refreshQueue().length > 0) { // no hi pri requests var info = Manager._refreshQueue.shift(); Manager._refreshQueueWaiting.push(info); Manager.sendRequest( info.Path, (function ManagerRefreshSuccessWrapper(ri: Info) { return function ManagerRefreshSuccess(responseText: string) { if (!Manager.requestStillValid(Manager._refreshQueueWaiting, ri)) return; Manager.queueInternal(ri, Manager._refreshQueue, Manager._refreshQueueWaiting); // requeue ri.OnSuccess(responseText); } })(info), (function ManagerRefreshErrorWrapper(ri: Info) { return function ManagerRefreshError(status: number) { if (!Manager.requestStillValid(Manager._refreshQueueWaiting, ri)) return; else if (status !== 429) // rate limit exceeded, ignore since it'll requeue ri.OnError(status); Manager.queueInternal(ri, Manager._refreshQueue, Manager._refreshQueueWaiting); // requeue } })(info) ); // sendRequest() } }; // sendNextRequest() } static GetSummonerByName( name: string, region: string, onSuccess: (string) => void, onError: (number) => void, refresh: boolean, info: Info ): Info { var path = Manager.makePath(region, "api/lol/" + region + "/v1.4/summoner/by-name/" + name); return Manager.queue(path, onSuccess, onError, refresh, info); } static GetCurrentGameBySummonerId( summonerId: number, region: string, onSuccess: (string) => void, onError: (number) => void, refresh: boolean, info: Info ): Info { var platformId = ""; switch (region) { case "na": platformId = "NA1"; break; case "euw": platformId = "EUW1"; break; case "eune": platformId = "EUN1"; break; case "kr": platformId = "KR"; break; case "oce": platformId = "OC1"; break; case "br": platformId = "BR1"; break; case "lan": platformId = "LA1"; break; case "las": platformId = "LA2"; break; case "ru": platformId = "RU"; break; case "tr": platformId = "TR1"; break; case "pbe": platformId = "PBE1"; break; default: alert("GetCurrentGameBySummonerId(): Unexpected region: " + region); } var path = Manager.makePath( region, "observer-mode/rest/consumer/getSpectatorGameInfo/" + platformId +"/" + summonerId); return Manager.queue(path, onSuccess, onError, refresh, info); } static GetSummonersByIds( summonerIds: Array<number>, region: string, onSuccess: (string) => void, onError: (number) => void, refresh: boolean, info: Info ): Info { var path = Manager.makePath( region, "api/lol/" + region + "/v1.4/summoner/" + summonerIds.join(',')); return Manager.queue(path, onSuccess, onError, refresh, info); } private static queue( path: string, onSuccess: (string) => void, onError: (number) => void, refresh: boolean, info: Info ): Info { if (!info) info = new Info(path, onSuccess, onError); Manager.queueInternal(info, Manager._hiPriQueue, Manager._hiPriQueueWaiting); if (refresh) Manager.queueInternal(info, Manager._refreshQueue, Manager._refreshQueueWaiting); return info; } private static queueInternal( info: Info, queue: KnockoutObservableArray<Info>, waitingQueue: KnockoutObservableArray<Info> ) { if (queue.indexOf(info) > -1 || waitingQueue.indexOf(info) > -1) return; // don't queue up a duplicate request queue.push(info); } private static makePath( region: string, endpoint: string ): string { return "https://" + region + ".api.pvp.net/" + endpoint; } private static sendRequest( url: string, onSuccess: (responseText: string) => void, onError: (status: number) => void ) { url += "?api_key=" + Manager.ApiKey; var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.onload = function ManagerSendRequest() { if (xhr.readyState == 4) { switch (xhr.status) { case 200: onSuccess(xhr.responseText); break; case 429: // rate limit exceeded, should be handled above alert("Error 429: Rate limit exceeded. Should have been handled."); case 404: // doesn't exist onError(xhr.status); break; case 401: // unauthorized, double check api key alert("Error 401: API key rejected, is it correct?"); onError(xhr.status); break; case 500: // server error alert("Error 500: Riot API server error, please try again."); onError(xhr.status); break; case 503: // service down alert("Error 503: Riot API service is down, please try again later."); onError(xhr.status); break; case 403: // forbidden?! default: // unexpected error var cleanUrl = url.substring(0, url.indexOf('?')); alert("Unexpected error code " + xhr.status + " for request to path: " + cleanUrl); onError(xhr.status); } } }; // xhr.onload xhr.send(null); // null: for IE bug } // sendRequest() static CancelRequest(requestInfo: Info) { if (!requestInfo) return; Manager._hiPriQueue.remove(requestInfo); Manager._hiPriQueueWaiting.remove(requestInfo); Manager._refreshQueue.remove(requestInfo); Manager._refreshQueueWaiting.remove(requestInfo); } } } export = Request;
338a02c67755acc6f152ad9a5bc72e8c663f932d
TypeScript
williamhammond/vscode-scar
/src/diagnostic/luaParserDiagnostic.ts
2.734375
3
'use strict'; import {Diagnostic, Range, Position, DiagnosticSeverity} from 'vscode'; import {ILuaParseError} from 'luaparse'; /** * Represents a Diagnostic for LuaParser errors. */ export default class LuaParserDiagnostic extends Diagnostic { /** * Creates a new instance of LuaParserDiagnostic. * @param error The error used for creating the Diagnostic item. */ constructor(error: ILuaParseError) { let errorRange = new Range( new Position(error.line - 1, error.column), new Position(error.line - 1, 1000) ); super(errorRange, `${error.name}\n${error.message.substr(error.message.indexOf(']') + 1)}`, DiagnosticSeverity.Error); } }
ce9b85295e42238cd8351b7ffcfd8fbfaa1a9970
TypeScript
hanbingleixue/TypeScript
/2-Functions/Function.ts
4.40625
4
/** * Function * 函数 */ /** * 给函数指定返回值的几种方式 * * function fnName(arg:string[指定传入string类型的数据],arg2:number[指定传入number类型的数据]):number[指定函数的返回值为number类型]{ * 函数体... * } * * var fnName = function(arg:string[指定传入string类型的数据],arg2:number[指定传入number类型的数据]):string[指定函数的返回值为string类型]{} * */ function add(x: string, y: string): string{ return "Hello TypeScript"; } let add2 = function(x: string, y: string): string{ return "Hello TypeScript"; } // 完整写法 let add3: (x: string, y: string) => string = function(x: string, y: string): string{ return "Hello TypeScript"; } /** * 可选参数和默认参数 * * function fnName(firstName?:string[指定传入string类型的数据,加?也可以不传],lastname:string[指定传入string类型的数据,加?也可以不传]]){} * * function fnName(firstName:string[指定传入String类型的数据],last="人") */ function buildName(firstName: string, lastName?: string){ console.log(lastName ? firstName + "" + lastName : firstName) } let res1 = buildName("鸣", "人"); // 鸣人 let res2 = buildName("鸣"); // 鸣 //let res3 = buildName("鸣", "人", "君"); // Supplied parameters do not match any signature of call target. function buildName2(firstName = "鸣", lastName?: string){ console.log(firstName + "" + lastName) } let res4 = buildName2("人"); // undefined人 let res5 = buildName2(undefined, "人"); // 鸣人 /** * 指定函数多个参数 * * function fnName(firstName:string[指定传入string类型的参数],...resArg:string[] [...指定多个参数,且为一个数组,取参数用数组的方式来取]){ * var arg = resArg[1]; * // 取得第三个参数 * } */ function peopleName(firstName: string, ...restArg: string[]){ console.log(firstName + "-" + restArg.join("-")) } let res6 = peopleName("my","name","is","muyy");
4d670f3f29574185de7c6c42dc57287fc7be706d
TypeScript
delesseps/newdash
/test/max.test.ts
3.234375
3
// @ts-nocheck import * as assert from 'assert'; import map from '../src/map'; import max from '../src/max'; import maxBy from '../src/maxBy'; import { falsey, noop } from './utils'; describe('max', () => { it('should return the largest value from a collection', () => { assert.strictEqual(max([1, 2, 3]), 3); }); it('should return `undefined` for empty collections', () => { const values = falsey.concat([[]]), expected = map(values, noop); const actual = map(values, (value, index) => { try { return index ? max(value) : max(); } catch (e) { } }); assert.deepStrictEqual(actual, expected); }); it('should work with non-numeric collection values', () => { assert.strictEqual(max(['a', 'b']), 'b'); }); it('should work with maxBy', () => { const items = [ { name: 'v1', age: 10 }, { name: 'v2', age: 5 } ]; assert.strictEqual(maxBy(items, 'age').name, 'v1'); }); });
776891d30eeccec3a70d38ff95f9ecc270ea9ba1
TypeScript
liyuanyuan125/mobile-front-web
/src/components/cakeChart/types.ts
2.84375
3
/** * sexItem 数据项 男女比例 */ export interface ObjData { /** 名称 */ name: string /** 数值 */ value: number } /** * AnnularItem 数据项 */ export interface DataItem { /** 名称 */ data: ObjData[] /** 数值 */ color?: any[], /** 左上角标题 */ title: string, /** 是否显示中间的文本 */ emphasisShow: boolean, /** 敏感度 */ sesnsitivity?: string, /** 是否显示标题 */ titleShow?: boolean, /** padding */ titleMargin?: any[]|number, /** 标题位置 left center right */ titleLeft?: string, /** 标题字体大小 */ titleSize?: number, /** 标题字体粗细 */ titleWeight?: string, /** legend显示几位小数 */ legendtoFixed?: number }
a507b44bdf171f2af5aa1529f9a8ddbd4ecf6258
TypeScript
BataLaSalade/site-avis-resto
/src/app/model/Resto.ts
2.515625
3
import { Rate } from "../model/Rate"; import { Geometry } from "../model/Geometry" import { Photo } from "../model/Photo" export class Resto { name?: string place_id?: string vicinity?: string geometry?: Geometry rating?: number user_ratings_total?: number ratings?: Rate[] photos?: Photo[] constructor( name?: string, vicinity?: string, geometry?: Geometry, rating?: number ) { this.name = name this.vicinity = vicinity this.geometry = geometry this.rating = rating } }
07f5fad2c15f1eb585044d423afc8a7e9da0fcfb
TypeScript
serverwizard/express-with-typescript-study
/src/controller/UserController.ts
2.78125
3
import {User} from "../entity/User"; import {DELETE, GET, Path, PathParam, POST} from "typescript-rest"; import {UserService} from "../service/UserService"; import {UserDto} from "../dto/UserDto"; import {Inject} from 'typescript-ioc'; // const validator = require('../validator/RequestValidator'); /** * TODO * 1. 스웨거 설정 확인 * 2. RequestParam 확인 */ @Path("/users") export class UserController { @Inject private userService: UserService; // TODO 한번 요청했는데 여러번 로그가 찍힘 @Path("/:userId") @GET // @PreProcessor(validator) async getUser(@PathParam('userId') userId: string): Promise<User | undefined> { console.log('path param: ' + userId); return this.userService.getUser(userId); } @GET async getUsers(): Promise<User[]> { console.log('모든 사용자 조회'); return this.userService.getUsers(); } @POST async saveUser(userDto: UserDto) { console.log('firstName: ' + userDto.firstName); console.log('lastName: ' + userDto.lastName); console.log('age: ' + userDto.age); return this.userService.saveUser(userDto); } @Path("/:userId") @DELETE async removeUser(@PathParam('userId') userId: number) { return this.userService.removeUser(userId); } }
56a66def6713b038c660c6b63fa8f26507fec79f
TypeScript
akulyk/ts29022020
/old/ajax.ts
2.546875
3
import { ajax, AjaxResponse } from "rxjs/ajax"; import { debounceTime, map } from "rxjs/operators"; import { forkJoin, fromEvent, Observable } from "rxjs"; const request$ = ajax('http://learn.javascript.ru/courses/groups/api/participants?key=1i7qske') .pipe( map((res: AjaxResponse) => res.response), ); forkJoin([request$, request$]).subscribe(([req1, req2]) => { console.log(req1, req2); }) // const input = document.querySelector('input') // const search$: Observable<string> = fromEvent<InputEvent>(input, 'input') // .pipe( // debounceTime(300), // map((e: InputEvent) => { // return (e.target as HTMLInputElement).value; // }) // ) // search$.subscribe((v) => { // console.log(v); // })
437ae2e7b97597ce9fc24279555b1c82c9396cc6
TypeScript
ArifZx/ant-serv
/index.ts
2.78125
3
import Axios, { AxiosPromise, AxiosInstance } from 'axios' export interface AntarestResult<T> { status: number, message: string, payload?: T } export interface Comparator { [field: string]: { $eq?: string | number | boolean, $gt?: number, $gte?: number, $in?: string[] | number[], $lt?: number, $lte?: number, $ne?: string | number | boolean | object, $nin?: string[] | number[] } } export interface Patcher { [filed: string]: any } export interface Config { baseUrl: string, url?: string, isSql: boolean } export default class AntarestService<T> { private _isSQL: boolean protected _server: AxiosInstance protected _baseUrl: string protected _url: string constructor(config: Config) { this._baseUrl = config.baseUrl this._url = config.url ? config.url : '' this._isSQL = config.isSql this._server = Axios.create({ baseURL: this._baseUrl, headers: { Accept: 'application/json', 'Content-type': 'application/json' } }) } public async create(objectType: T): Promise<AntarestResult<T>> { const promise = this._server.post(this._url, objectType) return await this.ResultHelper(promise, false) } public async get(options?: Comparator): Promise<AntarestResult<T[]>> { let promise if (options) { promise = this._server.post(this._url + '/search', options) } else { promise = this._server.get(this._url) } return await this.ResultHelper(promise, true) } public async update(conditions: Comparator, patch: Patcher): Promise<AntarestResult<T[]>> { const promise = this._server.patch(this._url, { conditions, patch }) return this.ResultHelper(promise, true) } public async delete(conditions: Comparator): Promise<AntarestResult<T[]>> { const promise = this._server.patch(this._url, { conditions, patch: { deletedAt: Date.now() } }) return await this.ResultHelper(promise, true) } // Manipulate by Id public async getById(id: number | string): Promise<AntarestResult<T>> { const promise = await this.get(this.getOptionsId(id)) return { status: promise.status, message: promise.message, payload: promise.payload ? promise.payload[0] : undefined } } public async updateById(id: number | string, patch: object): Promise<AntarestResult<T>> { const promise = await this.update(this.getOptionsId(id), patch) return { status: promise.status, message: promise.message, payload: promise.payload ? promise.payload[0] : undefined } } public async deleteById(id: number | string): Promise<AntarestResult<T>> { const promise = await this.delete(this.getOptionsId(id)) return { status: promise.status, message: promise.message, payload: promise.payload ? promise.payload[0] : undefined } } // Specific SQL function public async query(query: object): Promise<AntarestResult<T[]>> { if (!this._isSQL) { return { status: 403, message: 'Forbidden operation for SQL database', payload: undefined } } const promise = this._server.post(this._url, query) return await this.ResultHelper(promise, true) } // Specific noSQL function public async aggregate(aggregator: Comparator[]): Promise<AntarestResult<T[]>> { if (this._isSQL) { return { status: 403, message: 'Forbidden operation for noSQL database', payload: undefined } } const promise = this._server.post(this._url, aggregator) return await this.ResultHelper(promise, true) } // Helper private getOptionsId(id: number | string): Comparator { let options if (this._isSQL) { // SQL options = { 'id': { '$eq': id } } } else { // mongoose options = { '_id': { '$eq': id } } } return options } private async ResultHelper(promise: AxiosPromise<any>, isList: boolean) { const p = await promise if (p.status === 200) { return { status: p.data.status, message: p.data.msg, payload: isList ? p.data.payload : p.data.payload[0] } } return { status: p.status, message: p.statusText, payload: undefined } } }
8bdbb1e41ed08a3af8afa8bcc05b20120e57610e
TypeScript
kitwestneat/ati-fp-ts
/src/components/admin/module-list-utils.ts
2.640625
3
import { SECTION_TYPES } from '@/constants'; import { isDevEnv } from '@/utils'; import { ModuleSpec } from '../../types'; export interface KeyedModuleSpec extends Partial<ModuleSpec> { key: number; isNew?: boolean; } let nextKey = 0; function getModuleKey() { return nextKey++; } export function getListWithKeys<T>(list: T[]) { return list.map(i => ({ ...i, key: getModuleKey() })); } export function getNewModule() { const key = getModuleKey(); const newModule: KeyedModuleSpec = { module_opts: { type: SECTION_TYPES.NEWSLETTER }, key, isNew: true }; return newModule; } export interface ReplaceItemOpts { doDelete?: boolean; } export function replaceItem<T extends { key: any }>( list: T[], newItem: T, opts: ReplaceItemOpts = {} ) { const idx = list.findIndex(({ key }) => newItem.key === key); const newList = list.slice(0); if (opts.doDelete) { newList.splice(idx, 1); } else { newList[idx] = newItem; } return newList; } export async function saveList<T>(list: T[], tagId?: number) { const API_ENDPOINT = document.location.href; const formData = new FormData(); formData.append('module_list', JSON.stringify(list)); if (tagId) { formData.append('tag_id', '' + tagId); } await fetch(API_ENDPOINT, { method: 'POST', body: formData }); if (isDevEnv()) { return new Promise(resolve => setTimeout(resolve, 10000)); } }
833dd05e9107405a56483eb5fd1646bfe7bf29a7
TypeScript
pablohs1986/dam_pmdm
/TypeScript/Ejercicios1_soluciones/Ejercicio4_filter_con_params.ts
3.203125
3
let animales: any = [ { nombre: "Poppy", especie: "Burro", hobbies: ["Comer", "Rascarse", "Galopar"], propietario: { nombre: "Adrián", ciudad: "Avilés", tfno: "601112235" }, añoNacimiento: 2000 }, { nombre: "Pepa Pig", especie: "Cerdo", hobbies: ["Comer", "Rascarse", "Dormir"], propietario: { nombre: "Andrea", ciudad: "Avilés", tfno: "671182295" }, añoNacimiento: 2010 }, { nombre: "Luck", especie: "Perro", hobbies: ["Correr", "Jugar con la pelota"], propietario: { nombre: "Belarmino", ciudad: "Sama", tfno: "641145235" }, añoNacimiento: 2005 }, { nombre: "Srek", especie: "Burro", hobbies: ["Comer", "Rascarse", "Galopar"], propietario: { nombre: "Beatriz", ciudad: "Oviedo", tfno: "689512266" }, añoNacimiento: 2001 }, { nombre: "Pirata", especie: "Perro", hobbies: ["Correr", "Buscar cosas"], propietario: { nombre: "Adrián", ciudad: "Avilés", tfno: "601112235" }, añoNacimiento: 2005 } ]; // SOLUCIÓN 1: Usando una función flecha let tipo="Perro"; let resulAnimales=animales.filter(animal=>animal.especie===tipo); console.log(resulAnimales); // SOLUCIÓN 2: Usando una función que DEVUELVE OTRA FUNCIÓN let tipo2="Perro"; let filtroFuncion=function (parametro: string){ return function(elemento:any){ return elemento.especie===parametro; } }; let resuAnimales2=animales.filter(filtroFuncion(tipo2)); let resuAnimales3=animales.filter(filtroFuncion("Burro")); console.log(resuAnimales2); console.log(`Mis burros son: ${JSON.stringify(resuAnimales3)}`); // SOLUCIÓN 3: es la misma que la solución 2, pero usando la forma // abreviada con funciones flecha. Como hay 2 returns, hay 2 =>. // Fijaros: let filtroFuncion2=parametro => elemento => elemento.especie===parametro; let resuAnimales4=animales.filter(filtroFuncion2(tipo)); console.log(resuAnimales4);
74041c329404fb9c548bc5808e0eb6584dd5c6cf
TypeScript
xiaomingplus/type-music
/src/player.ts
2.515625
3
let findExec = require('find-exec'), cp = require('child_process'), players = ['mplayer', 'afplay', 'mpg123', 'mpg321', 'play', 'omxplayer', 'aplay', 'cmdmp3']; let spawn = cp.spawn; let globalEventId = 1; //默认为1 interface Event { id: number; exec: (data?: any) => void; } interface EventMap { [key: string]: Event[]; } class Play { private players: any; private player: any; private process: any; private playlist: string[] = []; private playIndex: number = 0; private random: boolean = false; private repeat: string = 'all'; private eventCallbackMap: EventMap = {}; constructor(opts?: any) { opts = Object.assign( { playlist: [], playIndex: 0, //默认播放的曲目 repeat: 'all', //all,one,off random: false //是否开启随机 }, opts ); if (!(opts.playlist.length > 0)) { throw new Error('No audio file specified'); } this.players = opts.players || players; this.player = opts.player || findExec(this.players); if (!this.player) { throw new Error("Couldn't find a suitable audio player"); } this.playlist = opts.playlist; this.playIndex = opts.playIndex; this.random = opts.random; this.repeat = opts.repeat; } setPlaylist(opts?: any) { opts = Object.assign( { playlist: [] }, opts ); if (!(opts.playlist.length > 0)) { throw new Error('No audio file specified'); } this.playlist = opts.playlist; this.playIndex = 0; this.stop(); } on(event: string, callback: () => void): number { let eventId = getEventId(); if (this.eventCallbackMap[event]) { this.eventCallbackMap[event].push({ id: eventId, exec: callback }); } else { this.eventCallbackMap[event] = [ { id: eventId, exec: callback } ]; } return eventId; } emit(event: string, data?: any) { if (this.eventCallbackMap[event]) { this.eventCallbackMap[event].forEach(event => { if (event.exec) { if (data) { event.exec(data); } else { event.exec(); } } }); } } off(eventId: number) { let keys = Object.keys(this.eventCallbackMap); keys.forEach(key => { for (let i = 0; i < this.eventCallbackMap[key].length; i++) { if (this.eventCallbackMap[key][i].id === eventId) { delete this.eventCallbackMap[key][i]; return; } } }); } play() { if (this.process) { this.stop(); } let options = { stdio: 'ignore' }; //执行命令的options if (this.playlist.length > 0 && this.playlist[this.playIndex]) { let args = ['-q', '1', this.playlist[this.playIndex]]; let soundProcess = spawn(this.player, args, options); this.process = soundProcess; if (!this.process) { throw new Error('Unable to spawn process with ' + this.player); } this.process.on('close', (err: any, signal: any) => { if (err && !err.killed) { this.emit('stop'); throw err; } else if (err === 0) { //next this.autoNext(); return; } else { this.emit('stop'); } this.process = null; }); this.process.on('error', (err: any) => { this.emit('stop'); this.process = null; throw new Error('Unable to spawn process with ' + this.player); }); } else { throw new Error('No audio file specified'); } } private autoNext() { if (this.random) { //index if (this.repeat !== 'one') { this.playIndex = Play.getRandomInt(0, this.playlist.length); } } else { if (this.repeat === 'all') { if (this.playlist[this.playIndex + 1]) { this.playIndex = this.playIndex + 1; } else { this.playIndex = 0; } } else if (this.repeat === 'off') { if (this.playlist[this.playIndex + 1]) { this.playIndex = this.playIndex + 1; } else { //stop this.stop(); return; } } } this.play(); //这里继续play } public next() { this.stop(); if (this.playlist[this.playIndex + 1]) { this.playIndex = this.playIndex + 1; } else { this.playIndex = 0; } } public previous() { if (this.playlist[this.playIndex - 1]) { this.playIndex = this.playIndex - 1; } else { this.playIndex = this.playlist.length - 1; } } stop() { if (this.process) { this.process.kill('SIGKILL'); } } resume() { if (this.process) { this.process.kill('SIGCONT'); } else { this.play(); } } pause() { if (this.process) { this.process.kill('SIGSTOP'); } } static getRandomInt(min: number, max: number) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive } } function getEventId(): number { return ++globalEventId; } export default Play;
cb90a471cb2ed319db960e01db469ab4718d6f18
TypeScript
pranjal930/RapidKen
/src/app/employee.service.ts
2.546875
3
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs'; import {Employee } from "./employee.model"; @Injectable({ providedIn: 'root', }) export class EmployeeService{ employeesChanged = new Subject<Employee[]>(); isFirst=true; employees:Employee[]=[ /*{ 'name':'john doe 1', 'position':'SDE', 'about':'working as angular Developer in RapidKen', 'jDate':'2018-12-10' }, { 'name':'john doe 2', 'position':'SDE', 'about':'working as angular Developer in RapidKen', 'jDate':'2018-12-10' }, { 'name':'john doe 3', 'position':'SDE', 'about':'working as angular Developer in RapidKen', 'jDate':'2018-12-10' }, */ ] addEmployee(employee:Employee){ console.log(this.employees); if(localStorage.getItem('Employees')&&this.employees!==[]){ console.log(localStorage.getItem('Employees')); this.employees=JSON.parse(localStorage.getItem('Employees')); } this.employees.push(employee); localStorage.setItem('Employees',JSON.stringify(this.employees)); } getEmployees(){ console.log('service called'); if(localStorage.getItem('Employees')) this.employees=JSON.parse(localStorage.getItem('Employees')); return this.employees.slice(); } deleteEmployee(index:number){ this.employees.splice(index,1); localStorage.setItem('Employees',JSON.stringify(this.employees)); this.employeesChanged.next(this.employees.slice()); } }
3ebaa9988c35db709a4a24556481cd0ecef173b3
TypeScript
eyalmendel/logga-ts
/src/formats/StringFormatter.ts
2.53125
3
import { StringFormattedEntry } from './../entry/StringFormattedEntry'; 'use strict' import { Formatter } from './Formatter'; import { Entry } from '../entry/Entry'; export class StringFormatter implements Formatter { format(entry: Entry): string { return new StringFormattedEntry(entry).getFormattedData(); } }
cab3b9ea9ff30e5f1118e254a48570e5586b2161
TypeScript
emmanuelnk/redis-time-series
/src/__tests__/unit/entity/timestampRange.test.ts
3.125
3
import { CommandKeyword } from "../../../enum/commandKeyword"; import { TimestampRange } from "../../../entity/timestampRange"; test("timestamp range creation with default values", () => { const tsRange = new TimestampRange(); expect(tsRange.getFrom()).toEqual(CommandKeyword.MIN_TIMESTAMP); expect(tsRange.getTo()).toEqual(CommandKeyword.MAX_TIMESTAMP); expect(tsRange.flatten()).toEqual([CommandKeyword.MIN_TIMESTAMP, CommandKeyword.MAX_TIMESTAMP]); }); test("timestamp range creation with provided values", () => { const start = new Date(2019, 11, 29, 11).getTime(); const end = start + 360000; const tsRange = new TimestampRange(start, end); expect(tsRange.getFrom()).toEqual(start); expect(tsRange.getTo()).toEqual(end); expect(tsRange.flatten()).toEqual([start, end]); }); test("timestamp range creation with default from value", () => { const end = new Date(2019, 11, 29, 11).getTime() + 360000; const tsRange = new TimestampRange(undefined, end); expect(tsRange.getFrom()).toEqual(CommandKeyword.MIN_TIMESTAMP); expect(tsRange.getTo()).toEqual(end); expect(tsRange.flatten()).toEqual([CommandKeyword.MIN_TIMESTAMP, end]); }); test("timestamp range creation with default to value", () => { const start = new Date(2019, 11, 29, 11).getTime(); const tsRange = new TimestampRange(start); expect(tsRange.getFrom()).toEqual(start); expect(tsRange.getTo()).toEqual(CommandKeyword.MAX_TIMESTAMP); expect(tsRange.flatten()).toEqual([start, CommandKeyword.MAX_TIMESTAMP]); }); test("timestamp range creation with invalid from value", () => { expect(() => { new TimestampRange(-1, Date.now()); }).toThrow(/invalid timestamp/); }); test("timestamp range creation with invalid to value", () => { expect(() => { new TimestampRange(Date.now(), -1); }).toThrow(/invalid timestamp/); });
18363ae9b0c455180d844e0978823fa1cc668932
TypeScript
uhyo/blue-eyes
/src/logic/body.ts
2.84375
3
import { Monster } from "../data/Monster"; import { RandFunction } from "./RandFunction"; import { ovalEdge } from "./baseEdge"; import { range } from "../util/range"; import { distance } from "./math/distance"; import { boxMuller } from "./math/boxMuller"; import { addPosition } from "./math/addPosition"; import { Position } from "../data/Position"; import { placeNumbers } from "./placeNumbers"; import { convertAngleToOvalAngle } from "./math/convertAngleToOvalAngle"; import { Oval } from "../data/Oval"; export type MonsterBodyResult = { /** * x of center */ x: number; /** * y of center */ y: number; /** * x radius */ xRadius: number; /** * y radius */ yRadius: number; /** * rotation */ rotation: number; }; export function decideMonsterBody( rand: RandFunction, monster: Monster ): MonsterBodyResult[] { const { base, body, position } = monster; const angles = placeNumbers( rand, (2 + body.cellNumber) >> 1, 2 * Math.PI, 0.3 ).slice(1); const baseCells: MonsterBodyResult[] = angles.map((angle) => { const ovAngle = convertAngleToOvalAngle(angle, base.xRadius, base.yRadius); const cellCenter = ovalEdge(base, ovAngle + monster.cycle, position); const { xRadius, yRadius } = cellRadius( rand, monster, cellCenter.distance, 0.25 ); const rotation = rand() * Math.PI; return { ...cellCenter, xRadius, yRadius, rotation, }; }); const otherCells: MonsterBodyResult[] = []; const lastIdx = body.cellNumber - baseCells.length - 1; for (const i of range(0, lastIdx)) { const prevCell = baseCells[i]; const nextCell = i === lastIdx ? baseCells[0] : baseCells[i + 1]; const centerPosX = (prevCell.x + nextCell.x) >> 1; const centerPosY = (prevCell.y + nextCell.y) >> 1; const circleAng = Math.atan2(centerPosY - position.y, centerPosX - position.x) - base.rotation; otherCells.push(findNiceCell(rand, monster, prevCell, nextCell, circleAng)); } return [...baseCells, ...otherCells]; } function cellRadius( rand: RandFunction, { body }: Monster, distance: number, varianceRatio: number ) { const angPerCell = (2 * Math.PI) / body.cellNumber; const baseAngle = Math.sin( boxMuller(rand, angPerCell * 0.7, angPerCell * varianceRatio) ); const baseRadius = (Math.sin(baseAngle) * distance) | 0; const xRadius = Math.max(5, baseRadius * boxMuller(rand, 1, 0.1)); const yRadius = Math.max(5, baseRadius * boxMuller(rand, 1, 0.1)); return { xRadius, yRadius }; } function findNiceCell( rand: RandFunction, monster: Monster, prevCell: MonsterBodyResult, nextCell: MonsterBodyResult, baseCenterAngle: number ): MonsterBodyResult { const { base, body, position } = monster; let result: MonsterBodyResult; let penalty = Infinity; for (let i = 0; i < 20; i++) { const centerAngle = baseCenterAngle + boxMuller(rand, 0, Math.PI / (body.cellNumber * 2)); const oAng = convertAngleToOvalAngle( centerAngle, base.xRadius, base.yRadius ); const rl = ovalEdge(base, oAng); const cellCenter = addPosition(rl, position); const siblingDistance = Math.sqrt( distance(prevCell, cellCenter) * distance(cellCenter, nextCell) ); const xRadius = Math.max(5, siblingDistance * boxMuller(rand, 0.6, 0.1)); const yRadius = Math.max(5, siblingDistance * boxMuller(rand, 0.6, 0.1)); const rotation = rand() * Math.PI; const res = { ...cellCenter, xRadius, yRadius, rotation, }; const pn = cellSizePenalty(res) + cellDistancePenalty(monster.base, prevCell, res) + cellDistancePenalty(monster.base, res, nextCell); if (penalty > pn) { result = res; penalty = pn; } } return result!; } function cellDistancePenalty( base: Oval, cell1: MonsterBodyResult, cell2: MonsterBodyResult ) { const abstAngle = Math.atan2(cell2.y - cell1.y, cell2.x - cell2.y); // cell1 -> cell2 const cell1Angle = abstAngle - cell1.rotation; // cell2 -> cell1 const cell2Angle = abstAngle - cell2.rotation + Math.PI; const cell1Edge = ovalEdge( cell1, convertAngleToOvalAngle(cell1Angle, cell1.xRadius, cell2.yRadius) ); const cell2Edge = ovalEdge( cell2, convertAngleToOvalAngle(cell2Angle, cell2.xRadius, cell2.yRadius) ); const diff = cell1Edge.distance + cell2Edge.distance - distance(cell1, cell2); if (diff < 5) { // diff is not enough, maybe not colliding return (base.xRadius + base.yRadius) * 25 - diff; } else { // too close return 5 * diff; } } function cellSizePenalty(cell: MonsterBodyResult) { return 0.01 * (cell.xRadius + cell.yRadius); // return 0; }
d54c1282585e54dfbd78af8c787646e1f3d087e5
TypeScript
maksym-plotnikov/ably-nest
/src/test/test.controller.ts
2.546875
3
import { Body, Controller, Get, Param, Post, UseGuards, UseInterceptors, UsePipes, } from '@nestjs/common'; import { TestService } from './test.service'; import { CreateDto } from '../dto/create.dto'; // Pipes import { ValidationPipe } from '../pipes/validation.pipe'; import { ParseIntPipe } from '../pipes/parse-int.pipe'; // Guards import { AuthGuard } from '../guards/auth.guard'; // Interceptors import { LoggingInterceptor } from '../interceptors/logging.interceptor'; // Custom decorator import { Roles } from '../decorators/roles.decorator'; @Controller('test') @UseGuards(AuthGuard) export class TestController { constructor(private testService: TestService) {} @Get(':id') @UseInterceptors(LoggingInterceptor) async findOne(@Param('id', new ParseIntPipe()) id) { return await this.testService.findOne(id); } @Post() // Can also be used with reflection for RolesGuard // @SetMetadata('roles', ['admin']) or we will use custom decorator @Roles('admin') @UsePipes(ValidationPipe) async create(@Body() createDto: CreateDto) { this.testService.create(createDto); } }
b6f570889ba86e464e7163eb5b0c2dd079e98ba7
TypeScript
amyhung/idlejs
/src/idle.spec.ts
2.765625
3
import { Idle } from './idle'; const testFactor = 1000; describe('Idle', () => { let idle: Idle; afterEach(() => { idle.stop(); }); it('should call do method when not interactive', done => { let called = false; idle = new Idle() .whenNotInteractive() .within(1, testFactor) .do(() => (called = true)) .start(); setTimeout(() => { expect(called).toBe(true); done(); }, 1.1 * testFactor); }); it('should call do method when not interactive, with more timeout', done => { let called = false; idle = new Idle() .whenNotInteractive() .within(2, testFactor) .do(() => (called = true)) .start(); setTimeout(() => { expect(called).toBe(true); done(); }, 2.1 * testFactor); }); it('should keep calling do method after interactive', done => { let callCount = 0; idle = new Idle() .whenNotInteractive() .within(1, testFactor) .do(() => callCount++) .start(); setTimeout(() => { document.dispatchEvent(new Event('click')); }, 1.2 * testFactor); setTimeout(() => { expect(callCount).toBe(2); done(); }, 2.5 * testFactor); }); it('should not call do method when not interactive for short time', done => { let called = false; idle = new Idle() .whenNotInteractive() .within(1, testFactor) .do(() => (called = true)) .start(); setTimeout(() => { expect(called).toBe(false); done(); }, 0.9 * testFactor); }); it('should not call do method when interactive: document.click', done => { let called = false; idle = new Idle() .whenNotInteractive() .within(1, testFactor) .do(() => (called = true)) .start(); setTimeout(() => { document.dispatchEvent(new Event('click')); }, 0.5 * testFactor); setTimeout(() => { expect(called).toBe(false); done(); }, 1.1 * testFactor); }); it('should not call do method when interactive: custom', done => { let called = false; const button = document.createElement('button') as HTMLButtonElement; idle = new Idle() .whenNot({ events: ['click'], target: button, }) .within(1, testFactor) .do(() => (called = true)) .start(); setTimeout(() => { button.dispatchEvent(new Event('click')); }, 0.5 * testFactor); setTimeout(() => { expect(called).toBe(false); done(); }, 1.1 * testFactor); }); it('should not call do method when interactive: multiple custom + default', done => { let called = false; const button = document.createElement('button') as HTMLButtonElement; const input = document.createElement('input') as HTMLInputElement; idle = new Idle() .whenNot([ { events: ['click', 'hover'], target: button, }, { events: ['click', 'input'], target: input, }, ]) .whenNotInteractive() .within(1, testFactor) .do(() => (called = true)) .start(); setTimeout(() => { input.dispatchEvent(new Event('input')); }, 0.5 * testFactor); setTimeout(() => { expect(called).toBe(false); done(); }, 1.1 * testFactor); }); it('should not call do method when stopped', done => { let called = false; idle = new Idle() .whenNotInteractive() .within(1, testFactor) .do(() => (called = true)) .start(); setTimeout(() => { idle.stop(); }, 0.5 * testFactor); setTimeout(() => { expect(called).toBe(false); done(); }, 1.1 * testFactor); }); it('should not call do method when restarted', done => { let called = false; idle = new Idle() .whenNotInteractive() .within(1, testFactor) .do(() => (called = true)) .start(); setTimeout(() => { idle.restart(); }, 0.5 * testFactor); setTimeout(() => { expect(called).toBe(false); done(); }, 1.1 * testFactor); }); it('should repeat calling do method foreach timeout amount, if repeatitive', done => { let callCount = 0; idle = new Idle() .whenNotInteractive() .within(1, testFactor) .do(() => callCount++) .repeat() .start(); setTimeout(() => { expect(callCount).toBe(2); done(); }, 2.1 * testFactor); }); it('should not repeat calling do method foreach timeout amount, if not repeatitive', done => { let callCount = 0; idle = new Idle() .whenNotInteractive() .within(1, testFactor) .do(() => callCount++) .start(); setTimeout(() => { expect(callCount).toBe(1); done(); }, 2.1 * testFactor); }); });
cefcc1c8213e0e859514636b31ea461ff5027954
TypeScript
theednaffattack/create-project
/src/templates/project-templates/backend/src/entity/Image.ts
2.59375
3
import { BaseEntity, Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"; import { Field, ID, ObjectType } from "type-graphql"; import { User } from "./User"; import { Message } from "./Message"; @ObjectType() @Entity() export class Image extends BaseEntity { @Field(() => ID) @PrimaryGeneratedColumn("uuid") id: string; @Field() @Column() uri: string; @Field(() => Message, { nullable: true }) @ManyToOne( () => Message, message => message.images, { nullable: true } ) message?: Message; @Field(() => User) @ManyToOne( () => User, user => user.images ) user: User; // @Field(() => Post) // @ManyToOne( // () => Post, // post => post.images // ) // post: Post; }
cfc4c7622be536408bc7f86818ed5ca0a22f6d1b
TypeScript
darwin1224/nest_test
/src/article/article.controller.ts
2.734375
3
import { Controller, Get, NotFoundException, Param, Body, BadRequestException, Post, Delete, Put, } from '@nestjs/common'; import { ArticleService } from './article.service'; import { Article } from './article.entity'; import { UpdateResult, DeleteResult } from 'typeorm'; import { ArticleDto } from './article.dto'; @Controller('article') export class ArticleController { /** * Constructor * * @param {ArticleService} article * @returns {void} */ public constructor(private readonly article: ArticleService) {} /** * Get all resources in storage * * @returns {Promise<Article[]>} */ @Get() public async index(): Promise<Article[]> { try { return await this.article.getAllArticle(); } catch (err) { throw new NotFoundException(err.message); } } /** * Get resource by id from storage * * @param {number} id * @returns {Promise<Article>} */ @Get('/:id') public async show(@Param('id') id: number): Promise<Article> { try { return await this.article.getArticleById(id); } catch (err) { throw new NotFoundException(err.message); } } /** * Insert resource to the storage * * @param {Article} params * @returns {Promise<Article>} */ @Post() public async store(@Body() params: ArticleDto): Promise<Article> { try { return await this.article.insertArticle(params); } catch (err) { throw new BadRequestException(err.message); } } /** * Update a single resource from storage * * @param {number} id * @param {Article} params * @returns {Promise<UpdateResult>} */ @Put('/:id') public async update(@Param('id') id: number, @Body() params: Article): Promise<UpdateResult> { try { return this.article.updateArticle(id, params); } catch (err) { throw new BadRequestException(err.message); } } /** * Delete a single resource from storage * * @param {number} id * @returns {Promise<DeleteResult>} */ @Delete('/:id') public async destroy(@Param('id') id: number): Promise<DeleteResult> { try { return this.article.deleteArticle(id); } catch (err) { throw new BadRequestException(err.message); } } }
36a5adf4cc49374c895d646b901684762fedfb8f
TypeScript
ezavile/postcss-typescript-css
/src/buildFile.ts
2.5625
3
const camelCase = require('camelcase'); const path = require('path'); import { PostcssTypescriptCss } from './namespace/PostcssTypescriptCss'; const build = (file: PostcssTypescriptCss.Options) => { const extension = path.extname(file.cssFileName); const filename = path.basename(file.cssFileName, extension); return ( `export const ${filename}Style = { ${ file.content instanceof Array ? ( file.content.map((c: string, index: number) => { const value: string = `${camelCase(c)}: '${c}'\n`; if (index === 0) { return `${value}`; } else { return ` ${value}`; } }) ) : ( Object.keys(file.content).map((c: string, index: number) => { const value: string = `${camelCase(c)}: '${(<{[key: string]: string }>file.content)[c]}'\n`; if (index === 0) { return `${value}`; } else { return ` ${value}`; } }) ) }, }; ` ); }; export default build;
4c6424fc56939504ddee127c5a4df8b50eca13e7
TypeScript
csstools/postcss-plugins
/plugins/postcss-image-set-function/src/index.ts
2.75
3
import valueParser from 'postcss-value-parser'; import { processImageSet } from './lib/process-image-set'; import type { PluginCreator } from 'postcss'; import { handleInvalidation } from './lib/handle-invalidation'; import { hasFallback } from './has-fallback-decl'; const imageSetValueMatchRegExp = /(^|[^\w-])(-webkit-)?image-set\(/i; const imageSetFunctionMatchRegExp = /^(-webkit-)?image-set$/i; /** postcss-image-set-function plugin options */ export type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean, /** * Determine how invalid usage of `image-set()` should be handled. * By default, invalid usages of `image-set()` are ignored. * They can be configured to emit a warning with `warn` or throw an exception with `throw`. * default: 'ignore' */ onInvalid?: 'warn' | 'throw' | 'ignore' | false }; const creator: PluginCreator<pluginOptions> = (opts?: pluginOptions) => { // prepare options const preserve = 'preserve' in Object(opts) ? Boolean(opts?.preserve) : true; const oninvalid = 'onInvalid' in Object(opts) ? opts?.onInvalid : 'ignore'; if ('oninvalid' in Object(opts)) { throw new Error('"oninvalid" was changed to "onInvalid" to match other plugins with similar options'); } return { postcssPlugin: 'postcss-image-set-function', Declaration(decl, { result, postcss }) { const value = decl.value; // if a declaration likely uses an image-set() function if (!imageSetValueMatchRegExp.test(value.toLowerCase())) { return; } if (hasFallback(decl)) { return; } let valueAST; try { valueAST = valueParser(value); } catch (error) { decl.warn( result, `Failed to parse value '${value}' as an image-set function. Leaving the original value intact.`, ); } if (typeof valueAST === 'undefined') { return; } // process every image-set() function const imageSetFunctions: Array<{ imageSetFunction: valueParser.FunctionNode, imageSetOptionNodes: Array<valueParser.Node>, }> = []; valueAST.walk((node) => { if (node.type !== 'function') { return; } if (!imageSetFunctionMatchRegExp.test(node.value.toLowerCase())) { return; } let foundNestedImageSet = false; valueParser.walk(node.nodes, (child) => { if ( child.type === 'function' && imageSetFunctionMatchRegExp.test(child.value.toLowerCase()) ) { foundNestedImageSet = true; } }); if (foundNestedImageSet) { handleInvalidation({ decl, oninvalid, result: result, }, 'nested image-set functions are not allowed', valueParser.stringify(node)); return false; } const relevantNodes = node.nodes.filter((x) => { return x.type !== 'comment' && x.type !== 'space'; }); imageSetFunctions.push({ imageSetFunction: node, imageSetOptionNodes: relevantNodes, }); }); processImageSet(imageSetFunctions, decl, { decl, oninvalid, preserve, result: result, postcss: postcss, }); }, }; }; creator.postcss = true; export default creator;
806a981922eb322818e56845a39269cf263b3dc8
TypeScript
rudy3091/cau-rainbowsystem-data
/test/excur.test.ts
2.671875
3
import request from "supertest"; import app from "../src"; describe("GET /api/rainbow/excur", () => { test("should return every data by default rows and page number", (done) => { request(app) .get("/api/rainbow/excur") .then((res) => { const data = res.text; const defaultRows = 20; expect(JSON.parse(data).length).toBe(defaultRows); done(); }); }); }); describe("GET /api/rainbow/excur?rows=3", () => { test("should return only 3 items", (done) => { request(app) .get("/api/rainbow/excur?rows=3") .then((res) => { const data = res.text; expect(JSON.parse(data).length).toBe(3); done(); }); }); }); describe("GET /api/rainbow/excur?rows=10", () => { test("should return only 10 items", (done) => { request(app) .get("/api/rainbow/excur?rows=10") .then((res) => { const data = res.text; expect(JSON.parse(data).length).toBe(10); done(); }); }); }); describe("GET /api/rainbow/excur?page=2", () => { test("should return different data from page 1", (done) => { request(app) .get("/api/rainbow/excur?page=2") .then((res) => { const data = res.text; const defaultRows = 20; for (let i = 0; i < defaultRows; i++) expect(JSON.parse(data)[i]).not.toBe(data[i]); done(); }); }); });
5b3d214ed5d63ac5e79e6c194ce527214b205618
TypeScript
tianlugang/poorest
/packages/bom/src/contains.ts
2.65625
3
export function contains(root: HTMLElement, el: HTMLElement) { var node: HTMLElement | null = el; while (node) { if (node === root) { return true; } node = node.parentElement; } return false; }
40c24b435c3e7e3156010d1cd0b5eb112bf77809
TypeScript
harshit-budhraja/react-admin
/packages/ra-core/src/form/useInitializeFormWithRecord.ts
2.625
3
import { useEffect } from 'react'; import { useForm } from 'react-final-form'; import merge from 'lodash/merge'; /** * Restore the record values which should override any default values specified on the form. */ const useInitializeFormWithRecord = record => { const form = useForm(); useEffect(() => { if (!record) { return; } const initialValues = form.getState().initialValues; const initialValuesMergedWithRecord = merge({}, initialValues, record); // Disable this option when re-initializing the form because in this case, it should reset the dirty state of all fields // We do need to keep this option for dynamically added inputs though which is why it is kept at the form level form.setConfig('keepDirtyOnReinitialize', false); // Since the submit function returns a promise, use setTimeout to prevent the error "Cannot reset() in onSubmit()" in final-form // It will not be necessary anymore when the next version of final-form will be released (see https://github.com/final-form/final-form/pull/363) setTimeout(() => { // Ignored until next version of final-form is released. See https://github.com/final-form/final-form/pull/376 // @ts-ignore form.restart(initialValuesMergedWithRecord); form.setConfig('keepDirtyOnReinitialize', true); }); }, [form, JSON.stringify(record)]); // eslint-disable-line react-hooks/exhaustive-deps }; export default useInitializeFormWithRecord;
94b9a4991fd67b0b46c9c98cfae4e864014d881a
TypeScript
arfedulov/typeorm-jsonapi-serializer
/src/Serializer/__tests__/Serializer.test.ts
2.765625
3
import { Entity, PrimaryGeneratedColumn, ManyToOne, OneToMany, Column } from 'typeorm'; import assert from 'assert'; const serializeEntityMock = jest.fn( (resourceType: string, entity: any, options: any) => {} ); jest.setMock('../serializeEntity', { serializeEntity: serializeEntityMock, }); import { Serializer } from '../Serializer'; import { Serializable } from '../../decorators/Serializable'; import { Skip } from '../../decorators/Skip'; test('Serializer()(): call serializeEntity() with correct arguments', async () => { @Entity() @Serializable('zoos') class Zoo { @PrimaryGeneratedColumn() id: number; @OneToMany((type) => Animal, (animal) => animal.zoo) animals?: Promise<Animal[]>; constructor(id: number) { this.id = id; } } @Entity() @Serializable('animals') class Animal { @PrimaryGeneratedColumn() id: number; @Column() name = 'bear'; @Column() @Skip() secretName: string; @ManyToOne((type) => Zoo, (zoo) => zoo.animals) zoo: Promise<Zoo>; constructor(id: number, secretName: string, zoo: Zoo) { this.id = id; this.secretName = secretName; this.zoo = Promise.resolve(zoo); } } const zoo = new Zoo(0); const animal = new Animal(1, '^(-.-)^', zoo); const EXPECT_ARGS = [ 'animals', animal, { relationshipsTypes: { zoo: 'zoos', }, exclude: ['secretName'], }, ]; await Serializer()(animal); const actualArgs = serializeEntityMock.mock.calls[0]; EXPECT_ARGS.forEach((EXPECT_ARG, i) => { assert.deepStrictEqual(actualArgs[i], EXPECT_ARG); }); });
2d70b96b7451368c9ccedea3c4d84d4fa5bc51c2
TypeScript
Henrixounez/ScanEat-Backend
/src/routes/Category/controller.ts
2.6875
3
import { Request, Response } from "express"; import { getRepository } from "typeorm"; import { StatusCodes } from 'http-status-codes'; import { Restaurant } from "../../entities/Restaurant"; import { Category } from "../../entities/Category"; import { DishReturn, formatDishReturn } from "../Dish/controller"; import { User, UserType } from "../../entities/User"; import { Dish } from "../../entities/Dish"; export interface CategoryReturn { id: number; name: string; dishes?: Array<DishReturn>; } export const formatCategoryReturn = (category: Category): CategoryReturn => ({ id: category.id, name: category.name, dishes: category.dishes?.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()).map(formatDishReturn) || [], }); // GET // Get categories for a Restaurant export async function get(req: Request, res: Response<CategoryReturn[]>): Promise<void> { const restaurantRepository = getRepository(Restaurant); const { id } = req.params; try { const restaurant = await restaurantRepository.findOneOrFail({ where: { id: id }, relations: ['categories'] }); res.status(StatusCodes.OK).json( restaurant.categories.map(formatCategoryReturn) ); } catch (e) { res.sendStatus(StatusCodes.NOT_FOUND); } } // POST // Create Category export async function create(req: Request, res: Response<CategoryReturn>): Promise<void> { const restaurantRepository = getRepository(Restaurant); const categoryRepository = getRepository(Category); const { name, restaurantId } = req.body; try { const restaurant = await restaurantRepository.findOneOrFail({ where: { id: restaurantId } }); const category = await categoryRepository.save( categoryRepository.create({ name, }) ); category.restaurant = restaurant; await categoryRepository.save(category); res.status(StatusCodes.OK).json(formatCategoryReturn(category)); } catch (e) { console.log(e); res.sendStatus(StatusCodes.NOT_FOUND); } } // PUT // Update a Category export async function update(req: Request, res: Response<CategoryReturn>): Promise<void> { const categoryRepository = getRepository(Category); const { id } = req.params; const { name } = req.body; try { const category = await categoryRepository.findOneOrFail(id, { relations: ['restaurant', 'restaurant.owner'] }); const user: User = res.locals.user; if (user.type === UserType.ADMIN || user.id === category.restaurant.owner.id) { category.name = name === undefined ? category.name : name; await categoryRepository.save(category); res.status(StatusCodes.OK).json(formatCategoryReturn(category)); } else { res.sendStatus(StatusCodes.FORBIDDEN); } } catch (e) { console.log(e); res.sendStatus(StatusCodes.NOT_FOUND); } } // DELETE // Delete a Category export async function del(req: Request, res: Response<CategoryReturn>): Promise<void> { const categoryRepository = getRepository(Category); const dishRepository = getRepository(Dish); const { id } = req.params; try { const category = await categoryRepository.findOneOrFail(id, { relations: ['restaurant', 'restaurant.owner', 'dishes'] }); const user: User = res.locals.user; if (user.type === UserType.ADMIN || user.id === category.restaurant.owner.id) { await Promise.all(category.dishes.map(async (dish) => { await dishRepository.delete(dish.id); })); await categoryRepository.delete(category.id); res.sendStatus(StatusCodes.OK); } else { res.sendStatus(StatusCodes.FORBIDDEN); } } catch (e) { console.log(e); res.sendStatus(StatusCodes.NOT_FOUND); } }
888918f457a9427b3dbcf13c12590f9632289124
TypeScript
iceyang/data_structure_and_algorithm_code
/ts/src/stack_by_queue/stack_by_queue.ts
3.59375
4
/** * 由队列实现的栈 */ import Queue from '../lib/queue'; export default class StackByQueue<T> { private queue: Queue<T> = new Queue<T>(); length(): number { return this.queue.length(); } push(t: T) { this.queue.push(t); } pop(): T | undefined { const length = this.length(); if (length > 1) { for (let i = 0; i < length - 1; i++) { this.queue.push(<T>this.queue.poll()); } } return this.queue.poll(); } }
dd7fe27834b9c8b416012343aa0ce7481f69d0dc
TypeScript
sundarcodes/Angular-bootcamp-21-Aug
/Day-2/EmpSalary/Employee.ts
3.125
3
export class Employee { id: number; name: string; salary: number; designation: string; rating: number; constructor(id: number, name: string, currentSalary: number, desig: string, rating: number) { this.id = id; this.salary = currentSalary; this.designation = desig; this.rating = rating; } getRating() { return this.rating; } getSalary() { return this.salary; } setSalary(sal: number) { this.salary = sal; } }
2b27c24bb15e4d5bc14d0375a05b7456c3e7464b
TypeScript
MOTORIST/shri-2020-task-2
/tests/warning.invalid_button_position.test.ts
2.59375
3
import linter from '../src/index'; import { ERROR_CODE, ERROR_TEXT, } from '../src/rules/warning.invalid_button_position.rule'; import { LinterError } from '../src/types/LinterError'; describe(ERROR_CODE, () => { describe('same level', () => { const rightJson = ` { "block": "warning", "content": [ { "block": "placeholder", "mods": { "size": "m"} }, { "block": "button", "mods": { "size": "m" } } ] } `; const wrongJson = ` { "block": "warning", "content": [ { "block": "button", "mods": { "size": "m" } }, { "block": "placeholder", "mods": { "size": "m" } } ] } `; it('should return empty array, if button has right position', () => { expect(linter(rightJson)).toEqual([]); }); it('should return errors, if button has not right position', () => { const err: LinterError = { code: ERROR_CODE, error: ERROR_TEXT, location: { start: { column: 9, line: 5, }, end: { column: 55, line: 5, }, }, }; expect(linter(wrongJson)).toEqual([err]); }); }); describe('deep level', () => { const rightJson = ` { "block": "warning", "content": { "block": "container", "content": [ { "block": "placeholder", "mods": { "size": "m"} }, { "block": "button", "mods": { "size": "m" } } ] } } `; const wrongJson = ` { "block": "warning", "content": { "block": "container", "content": [ { "block": "button", "mods": { "size": "m" } }, { "block": "placeholder", "mods": { "size": "m"} } ] } } `; it('should return empty array, if button has right position', () => { expect(linter(rightJson)).toEqual([]); }); it('should return errors, if button has not right position', () => { const err: LinterError = { code: ERROR_CODE, error: ERROR_TEXT, location: { start: { column: 11, line: 7, }, end: { column: 57, line: 7, }, }, }; expect(linter(wrongJson)).toEqual([err]); }); }); });
f92d2168471b91369add69f85ce89a9d4088fec0
TypeScript
UDcebower/educational-game-project-team-9-kalloyan-s-adam-j
/src/scripts/objects/interactiveDialogBox.ts
2.953125
3
export default class InteractiveDialogBox extends Phaser.GameObjects.Container { private background: Phaser.GameObjects.Rectangle; private interactableText: Phaser.GameObjects.Text; private bgStartingX: number; private bgStartingY: number; private displayedText: Phaser.GameObjects.Text; private dialog: string[]; private num: number = 0; private dialogCount: number = 0; private timedEvent: Phaser.Time.TimerEvent; private destroyed: boolean = false; constructor(config) { super(config.scene); this.scene = config.scene; //setting the background of the dialog this.bgStartingX = this.scene.scale.width / 6; this.bgStartingY = this.scene.scale.height / 10; this.background = this.scene.add.rectangle(this.bgStartingX, this.bgStartingY, config.width, config.height, 0x000000); this.background.setOrigin(0, 0); this.add(this.background); this.scene.add.existing(this.background); //adding the interactable text this.interactableText = this.scene.add.text(this.bgStartingX + this.background.displayWidth - 20, this.bgStartingY + this.background.displayHeight - 20, config.text); this.interactableText.setOrigin(1, 1); this.interactableText.setInteractive(); this.interactableText.on('pointerover', () => { this.interactableText.setStyle({ fill: '#0f0' }); }); this.interactableText.on('pointerout', () => this.interactableText.setStyle({ fill: '#ffffff' })); this.add(this.interactableText); this.scene.add.existing(this.interactableText); } getInteractiveText(): Phaser.GameObjects.Text { return this.interactableText; } getBackground(): Phaser.GameObjects.Rectangle { return this.background; } //sets the properties of the text _setText(text: string): void { if (this.displayedText) { //this.remove(this.displayedText); //this.displayedText.destroy(); } this.displayedText = this.scene.make.text({ x: this.background.x + 20, y: this.background.y + 20, text: text, style: { wordWrap: { width: this.background.width - 20 }, fill: '#ffffff' } }); /*this.displayedText = this.scene.add.text(this.background.x + 20, this.background.y + 20, text, { wordWrap: { width: this.background.width - 20 }, fill: '#ffffff' });*/ this.add(this.displayedText); this.scene.add.existing(this.displayedText); } //runs a timer event to animate the words setText(text: string, animate: boolean): void { this.num = 0; //this.isDone = false; this.dialogCount++; this.dialog = text.split(' '); if (this.timedEvent) this.timedEvent.remove(); let tempText: string = animate ? '' : text; this._setText(tempText); if (animate) { this.interactableText.disableInteractive(); this.interactableText.setVisible(false); this.timedEvent = this.scene.time.addEvent({ delay: 200, callback: this.animateText, callbackScope: this, loop: true }); } } //displayes a new word every time it is called animateText(): void { this.num++; this.displayedText.setText(this.displayedText.text + this.dialog[this.num - 1] + " "); //I'm so glad I decided to add the space here because for the life of me I could not figure out how to get the text to wrap console.log("num: " + this.num + " length: " + this.dialog.length); if (this.num === this.dialog.length) { this.timedEvent.remove(); let timedEvent2: Phaser.Time.TimerEvent = this.scene.time.addEvent({ delay: 400, callback: this.enableText, callbackScope: this, repeat: 0 }); } } enableText(): void{ this.interactableText.setInteractive(); this.interactableText.setVisible(true); } }
5ab04177d7e15c4d29f5ab5291f74922321eaefc
TypeScript
NourDT/patreon-scraper
/types/request.ts
2.515625
3
// tslint:disable-next-line: no-empty-interface interface ICommonRequestOptions { } // tslint:disable-next-line: no-empty-interface export interface ICurrentUserRequestOptions extends ICommonRequestOptions { } export interface IStreamRequestOptions extends ICommonRequestOptions { fields?: IFieldOptions; filter?: IFilterOptions; include?: TIncludeStrings[]; "json-api-use-default-includes"?: boolean; "json-api-version"?: JsonApiVersionKey; page?: IPageOptions; } type TIncludeStrings = "recent_comments.commenter" | "recent_comments.commenter.flairs.campaign" | "recent_comments.parent" | "recent_comments.post" | "recent_comments.first_reply.commenter" | "recent_comments.first_reply.parent" | "recent_comments.first_reply.post"; enum JsonApiVersionKey { v1 = "1.0", } interface IFieldOptions { comment?: CommentFieldKey[]; flair?: FlairFieldKey[]; post?: PostFieldKey[]; user?: UserFieldKey[]; } enum FlairFieldKey { ImageTinyUrl = "image_tiny_url", Name = "name", } enum UserFieldKey { ImageUrl = "image_url", FullName = "full_name", Url = "url", } enum PostFieldKey { CommentCount = "comment_count", } enum CommentFieldKey { Body = "body", Created = "created", DeletedAt = "deleted_at", IsByPatron = "is_by_patron", IsByCreator = "is_by_creator", VoteSum = "vote_sum", CurrUserVote = "current_user_vote", ReplyCount = "reply_count", } interface IFilterOptions { is_following: boolean; } interface IPageOptions { count?: number; cursor: string | null; }
d44b7031cf8077dc0818c292e214f0410e2d4029
TypeScript
chwasiq0569/nextJS
/pages/api/login.ts
2.53125
3
import {NextApiRequest, NextApiResponse} from 'next'; import jwt from "jsonwebtoken"; const KEY = 'sajidiowuqioeklasdjasdkl'; export default (req: NextApiRequest, res: NextApiResponse) => { // console.log('REQ.BODY: ',req.body); // console.log('REQ.query: ',req.query); // res.statusCode = 200; console.log(req.body); const {username, password} = req.body; // res.end("Response Stream ahs been ended here"); res.json({ token: jwt.sign({ username: username, admin: username === 'admin' && password === 'admin' }, KEY) }) }
2f351f7031c79469a33a94692b3bc3d449199512
TypeScript
Coffeekraken/coffeekraken
/packages/tools/s-specs/src/node/SSpecs.ts
2.828125
3
import { __readJsonSync } from '@coffeekraken/sugar/fs'; import { __deepMap, __deepMerge, __get } from '@coffeekraken/sugar/object'; import type { ISSpecsSettings } from '../shared/SSpecs.js'; import __SSpecs from '../shared/SSpecs.js'; import __SSugarConfig from '@coffeekraken/s-sugar-config'; import { __isPlainObject } from '@coffeekraken/sugar/is'; import { __packageRootDir } from '@coffeekraken/sugar/path'; import __fs from 'fs'; import * as __glob from 'glob'; import __path from 'path'; /** * @name SSpecs * @namespace node * @type Class * @platform node * @status beta * * This class allows you to access with ease some specification file(s) that supports internal and external references to other files, etc... * This is usefull to build specification files in json format that make share some parts through common files, etc... * You will also have easy access to your files through "namespaces" that represent different folders on your system. This will simplify * the way you read your files by prefixing your dotpath (simple fs "/" replacement) with the namespace you want to look in. * * @param {Object} [$settings={}] Some settings to configure your instance * * @setting {Object} [namespaces={}] An object of namespace like "my.namespace" property with a simple array of folders where to search for specs files when using this namespace * @setting {Function} [previewUrl=null] A function called only when a .preview.png file exists alongside the .spec.json file that will take an object with "path", "name", "specs" and "specsObj" as input and that has to return the web accessible preview url. If not specified, no "preview" field will exists in the output spec json * @setting {Boolean} [read.metas=true] Specify if you want to get the metas back for each spec * @setting {Boolean} [read.models=true] Specigy if you want to get back the ".model.json" files that are alongside of the .spec.json file if exists * * @snippet __SSpecs($1) * const specs = new __SSpecs($1); * const spec = specs.read('sugar.views.components.card'); * * @example js * import __SSpecs from '@coffeekraken/s-specs'; * const spec = new __SSpecs({ * namespaces: { * myNamespace: [ * '/my/absolute/path/to/my/specs/directory' * ] * } * }); * * // read a spec file * const viewSpec = spec.read('myNamespace.views.mySpecFile'); * * // read a spec file and specify an internal property to get * const title = spec.read('myNamespace.views.mySpecFile:title); * * @since 2.0.0 * @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io) */ export interface ISSpecsNodeSettings extends ISSpecsSettings { namespaces: Record<string, string[]>; read?: Partial<ISSpecsReadSettings>; previewUrl?: Function; } export interface ISSpecsReadSettings { metas: boolean; models: boolean; } export interface ISSpecsListResult { name: string; filename: string; dotpath: string; namespace: string; path: string; dir: string; read: Function; } export default class SSpecs extends __SSpecs { /** * @name fromInterface * @type Function * @status beta * @static * * This method allows you to convert an SInterface class into a spec object * * @param {SInterface} int The SInterface class you want to use for your spec object * @return {Any} The requested spec object * * @since 2.0.0 * @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io) */ static fromInterface( int: __SInterface, settings: Partial<ISSpecsSettings> = {}, ): any { let specJson = { title: int.title, description: int.description, props: {}, }; for (let [prop, value] of Object.entries(int.definition)) { const repeatableStr = value.type.match(/\[\]$/) ? '[]' : value.type.match(/\{\}$/) ? '{}' : ''; let type; if (value.values && value.values.length) { type = 'Select'; } switch (value.type.toLowerCase()) { case 'boolean': specJson.props[prop] = { type: type ?? 'Checkbox', }; break; case 'number': specJson.props[prop] = { type: type ?? 'Number', }; break; case 'integer': specJson.props[prop] = { type: type ?? 'Integer', }; break; case 'string': specJson.props[prop] = { type: type ?? 'Text', }; break; default: specJson.props[prop] = { type: type ?? value.type ?? 'Text', }; break; } specJson.props[prop] = { ...(specJson.props[prop] ?? {}), ...(value.specs ?? {}), type: `${specJson.props[prop].type}${repeatableStr}`, title: value.title, description: value.description, default: value.default, required: value.required, }; if (type === 'Select') { specJson.props[prop].options = value.values.map((v) => { return { name: v, value: v, }; }); } } // take the "_specs" static property of the SInterface class // if exists if (int._specs) { specJson = __deepMerge(specJson, int._specs); } // resolve the @... const specs = new SSpecs(settings); specJson = specs.resolve(specJson); // return the new spec json return specJson; } /** * @name constructor * @type Function * * Constructor * * @since 2.0.0 * @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io) */ constructor(settings?: Partial<ISSpecsNodeSettings>) { super( __deepMerge( { read: { metas: true, models: true, }, }, __toPlainObject(__SSugarConfig.get('specs') ?? {}), settings ?? {}, ), ); if (!this.settings.namespaces) { throw new Error( '[SSpecs] You MUST at least specify some "namespaces" folders to search specs files in...', ); } const monorepoRootPath = __packageRootDir(process.cwd(), { highest: true, }); for (let [namespace, dirs] of Object.entries( this.settings.namespaces, )) { this.settings.namespaces[namespace].forEach((dir, i) => { if (dir.startsWith('./node_modules')) { this.settings.namespaces[namespace].push( `${monorepoRootPath}${dir.replace(/^\./, ``)}`, ); } if (dir.startsWith('.')) { this.settings.namespaces[namespace][i] = __path.resolve(dir); } }); } } /** * @name read * @type Function * @status beta * * This method allows you to read a spec file and/or a value inside the passed spec file. * * @param {String} specDotPath A dotpath that point to a json spec file relative to one of the registered "$settings.namespaces" folders. You can then specify an internal dotpath to get a specific value inside the passed file like so "sugar.views.props.attributes:title. Can also be an absolute path." * @return {Any} The requested spec value * * @since 2.0.0 * @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io) */ read(specDotPath: string, settings: Partial<ISSpecsReadSettings> = {}) { let finalSpecFilePath; // handle absolute file path if (specDotPath.startsWith('/')) { const fileName = __path.basename(specDotPath), dir = __path.dirname(specDotPath); // add the "absolute" namespace in the settings if (!settings.namespaces) { settings.namespaces = {}; } settings.namespaces.absolute = [dir]; // call the read method with this time the absolute namespace // prefix the fileName with the absolute namespace return this.read( `absolute.${fileName.replace('.spec.json', '')}`, settings, ); } const finalSettings: ISSpecsReadSettings = __deepMerge( // @ts-ignore this.settings.read, settings, ); let definedNamespaces = this.settings.namespaces; let definesNamespacesKeys = Object.keys(definedNamespaces); let currentNamespace = ''; for (let i = 0; i < definesNamespacesKeys.length; i++) { const namespace = definesNamespacesKeys[i]; if (specDotPath.startsWith(namespace)) { currentNamespace = namespace; break; } } if (!currentNamespace) { throw new Error( `[SSpecs.read] The passed dotpath "<cyan>${specDotPath}</cyan>" does not correspond to any registered namespaces which are: ${definesNamespacesKeys.join( '\n', )}`, ); } let dotPathParts = specDotPath.split(':'); let specFileDotPath = dotPathParts[0], internalSpecDotPath; if (dotPathParts[1]) { internalSpecDotPath = dotPathParts[1]; } // compute internal namespace dotpath let internalDotPath = specFileDotPath.replace( `${currentNamespace}.`, '', ); let internalPath = `${internalDotPath.split('.').join('/')}.spec.json`; // loop on each registered namespaces directories to check if the specDotPath // correspond to a file in one of them... const dirs = this.settings.namespaces[currentNamespace]; for (let i = 0; i < dirs.length; i++) { const dir = dirs[i]; // direct path my/path => my/path.spec.json let potentialSpecPath = `${dir}/${internalPath}`; if (__fs.existsSync(potentialSpecPath)) { finalSpecFilePath = potentialSpecPath; break; } // try from my/path => my/path/path.spec.json const parts = internalDotPath.split('.'), lastDotPart = parts[parts.length - 1]; potentialSpecPath = `${dir}/${internalPath.replace( '.spec.json', `/${lastDotPart}.spec.json`, )}`; if (__fs.existsSync(potentialSpecPath)) { finalSpecFilePath = potentialSpecPath; break; } } if (!finalSpecFilePath) { throw new Error( `[SSpecs] The requested dotpath spec "${specDotPath}" does not resolve to any existing spec file...`, ); } const specName = finalSpecFilePath .split('/') .pop() .replace('.spec.json', ''); // read the spec file let specJson = JSON.parse( __fs.readFileSync(finalSpecFilePath).toString(), ); // traverse each values to resolve them if needed specJson = __deepMap(specJson, ({ object, prop, value, path }) => { return this.resolve(value, object, finalSettings); }); specJson = __deepMap( specJson, ({ object, prop, value, path }) => { if (prop === 'extends') { if (value.startsWith('@')) { throw new Error( `The "extends": "${value}" property cannot start with an "@"`, ); } let extendsJson = this.read(value, finalSettings); const newObj = __deepMerge(extendsJson, object); Object.assign(object, newObj); } return value; }, { clone: false, }, ); // check if we have a ".preview.png" file alongside the spec file const potentialPreviewUrl = finalSpecFilePath.replace( '.spec.json', '.preview.png', ); if (__fs.existsSync(potentialPreviewUrl) && this.settings.previewUrl) { specJson.preview = this.settings.previewUrl({ path: potentialPreviewUrl, name: specName, specs: internalDotPath, specsObj: specJson, }); } // if we have an internal spec dotpath if (internalSpecDotPath) { return __get(specJson, internalSpecDotPath); } if (finalSettings.models) { const folderPath = finalSpecFilePath .split('/') .slice(0, -1) .join('/'), glob = `${folderPath}/*.${specName}.model.json`, files = __glob.sync(glob); if (files?.length) { specJson.models = {}; files.forEach((filePath) => { // read the model json const modelJson = __readJsonSync(filePath), fileName = filePath.split('/').pop(), name = fileName?.replace('.model.json', ''), modelName = name?.split('/')[0]; // handle potential "preview.png" file alongside the model one const potentialModelPreviewUrl = filePath.replace( '.model.json', '.preview.png', ); if ( __fs.existsSync(potentialModelPreviewUrl) && this.settings.previewUrl ) { modelJson.preview = this.settings.previewUrl({ path: potentialModelPreviewUrl, name, specs: internalDotPath, specsObj: specJson, modelObj: modelJson, }); } // add some metas to the model if (finalSettings.metas) { modelJson.metas = { path: filePath, dir: filePath.split('/').slice(0, -1).join('/'), name, specs: specDotPath, }; } // set the model in the json specJson.models[<string>modelName] = modelJson; }); } } // add metas about the spec file read if (finalSettings.metas) { specJson.metas = { path: finalSpecFilePath, dir: finalSpecFilePath.split('/').slice(0, -1).join('/'), name: specName, specs: internalDotPath, }; } // return the getted specJson return specJson; } /** * @name list * @type Function * @platform php * @status beta * * This method allows you to list all the available spec files inside a particular namespace(s), or simply all. * * @param {String} $namespaces An array of namespaces to list the specs from. If not set, list all the specs from all the namespaces * @return {Any} A list of all the specs files available * * @since 2.0.0 * @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io) */ list(namespaces = []) { let results: ISSpecsListResult[] = [], definedNamespaces = this.settings.namespaces, definedNamespacesKeys: string[] = Object.keys(definedNamespaces), finalNamespaces: string[] = []; if (!namespaces.length) { finalNamespaces = definedNamespacesKeys; } else { definedNamespacesKeys.forEach((definedNamespace) => { namespaces.forEach((passedNamespace) => { if (definedNamespace.startsWith(passedNamespace)) { if (!finalNamespaces.includes(definedNamespace)) { finalNamespaces.push(definedNamespace); } } }); }); } finalNamespaces.forEach((namespace) => { const folders = definedNamespaces[namespace]; folders.forEach((folder) => { const specFiles = __glob.sync(`${folder}/**/*.spec.json`); specFiles.forEach((specFilePath) => { const filename = __path.basename(specFilePath), name = filename.replace('.spec.json', ''), dotpath = `${namespace}${specFilePath .replace('.spec.json', '') .replace(folder, '') .split('/') .join('.')}`; results.push({ name, filename, dotpath, namespace, path: specFilePath, dir: __path.dirname(specFilePath), read: (settings: Partial<ISSpecsReadSettings>) => { return this.read(dotpath, settings ?? {}); }, }); }); }); }); return results; } /** * @name resolve * @type Function * @status beta * * This method allows you to pass a specJson object and resolve all the "@..." values in it * * @param {Any}  specJson The specJson to resolve * @return {Any} The resolved specJson object * * @since 2.0.0 * @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io) */ resolve(value: any, specJson: any, settings?: ISSpecsReadSettings): any { let newValue = value; if (typeof value === 'string') { if (value.startsWith('@this')) { let internalDotPath = value.replace('@this', ''); newValue = __get(specJson, internalDotPath); if (Array.isArray(newValue) || __isPlainObject(newValue)) { newValue = __deepMap(newValue, ({ value: v }) => { return this.resolve(v, newValue, settings); }); } } else if (value.startsWith('@config.')) { const dotPath = value.replace('@config.', ''), config = __SSugarConfig.get(dotPath); newValue = config; } else if (value.startsWith('@')) { const dotPath = value.replace('@', ''), spec = this.read(dotPath, { metas: false, models: false, ...(settings ?? {}), }); newValue = spec; } } return newValue; } }
2aae637ba1365ecb9fab5b0d6bb54ef5a1552c91
TypeScript
ezrafukss/money-ts
/src/NonZeroRational.ts
3
3
import { NonZeroInteger } from './NonZeroInteger' import { Natural } from './Natural' import { Option } from 'fp-ts/lib/Option' import { Setoid } from 'fp-ts/lib/Setoid' import { Ord } from 'fp-ts/lib/Ord' import { Rational } from './Rational' import * as natural from './Natural' import * as rational from './Rational' import * as nonZeroInteger from './NonZeroInteger' import { unsafeCoerce } from 'newtype-ts' export type NonZeroRational = [NonZeroInteger, Natural] export function fromRational(r: Rational): Option<NonZeroRational> { return nonZeroInteger.fromInteger(r[0]).map((n): NonZeroRational => [n, r[1]]) } export const reduce: (n: NonZeroInteger, d: Natural) => NonZeroRational = unsafeCoerce(rational.reduce) export const add: (x: NonZeroRational, y: NonZeroRational) => NonZeroRational = unsafeCoerce(rational.add) export const mul: (x: NonZeroRational, y: NonZeroRational) => NonZeroRational = unsafeCoerce(rational.mul) export const one: NonZeroRational = unsafeCoerce(rational.one) export function sub(x: NonZeroRational, y: NonZeroRational): Option<NonZeroRational> { return fromRational(rational.sub(x, y)) } export const div: (x: NonZeroRational, y: NonZeroRational) => NonZeroRational = unsafeCoerce(rational.div) export function inverse(x: NonZeroRational): NonZeroRational { const d = x[1] const n = nonZeroInteger.abs(x[0]) return nonZeroInteger.isPositive(x[0]) ? [d, n] : [natural.negate(d), n] } export const setoid: Setoid<NonZeroRational> = rational.setoid export const ord: Ord<NonZeroRational> = rational.ord export const show: (x: NonZeroRational) => string = rational.show
e77529bcb36b4bc0296f489a2a9ef6a50b85ae3d
TypeScript
yurkagon/self-education
/fundamental/design_patterns/Structural/Facade/typescript.ts
3.578125
4
class Part1 { public method1(): void { console.log("method1"); } } class Part2 { public method2(): void { console.log("method2"); } } class Part3 { public method3(): void { console.log("method3"); } } class Facade { private readonly part1: Part1; private readonly part2: Part2; private readonly part3: Part3; constructor(part1?: Part1, part2?: Part2, part3?: Part3) { this.part1 = part1 || new Part1(); this.part2 = part2 || new Part2(); this.part3 = part3 || new Part3(); } public operation1(): void { this.part1.method1(); this.part2.method2(); } public operation2(): void { this.part1.method1(); this.part3.method3(); } } const facade: Facade = new Facade(); facade.operation1(); facade.operation2();
f3ee64d9b0688a06e0b5676623fbedb7f48e0eb7
TypeScript
DGeisz/orchidv4-client
/src/routes/page/page_types/reduced_form/reduced_form.ts
2.546875
3
import { palette } from "../../../../global_styles/palette"; import { add_latex_color, create_tex_text } from "../../utils/latex_utils"; import { TexWidgetProperties } from "../../building_blocks/tex_element/building_blocks/tex_widget/tex_widget_types/tex_widget_types"; export enum ReducedFormTag { TexLine, GlobalHeader, SurroundIndent, InlineProp, LambdaProp, } export interface TexLineType { tag: ReducedFormTag.TexLine; tex: string; tex_widget_properties: TexWidgetProperties[]; } export function error_form(): ReducedFormType { return { tag: ReducedFormTag.TexLine, tex: add_latex_color(create_tex_text("ERROR"), palette.danger), tex_widget_properties: [], }; } export interface GlobalHeaderType { tag: ReducedFormTag.GlobalHeader; title: string; title_color: string; main_tex: string; main_widget_properties: TexWidgetProperties[]; label: string; label_widget_properties: TexWidgetProperties[]; pg_index: string; children: ReducedFormType[]; left_cursor_active?: boolean; right_cursor_active?: boolean; background_color?: string; } export interface SurroundIndentType { tag: ReducedFormTag.SurroundIndent; header_tex: string; header_widget_properties: TexWidgetProperties[]; children: ReducedFormType[]; footer_tex: string; footer_widget_properties: TexWidgetProperties[]; body_name: string; label?: string; pg_index?: string; } export interface InlinePropType { tag: ReducedFormTag.InlineProp; prop: string; prop_widget_properties: TexWidgetProperties[]; explanation: string; label: string; label_widget_properties: TexWidgetProperties[]; pg_index: string; } export interface LambdaPropType { tag: ReducedFormTag.LambdaProp; intro_tex: string; intro_widget_properties: TexWidgetProperties[]; label: string; label_widget_properties: TexWidgetProperties[]; pg_index: string; children: ReducedFormType[]; } export type ReducedFormType = | TexLineType | GlobalHeaderType | SurroundIndentType | InlinePropType | LambdaPropType;
5d6fc1c9bb7a8fd7f7c4afb17f4addf7dadc4cc9
TypeScript
tdurtschi/bug
/src/core/entity-manager.ts
3.046875
3
import Entity from "./entities/entity"; import Bug from "./entities/bug/bug"; import Plant from "./entities/plant/plant"; export interface IEntityManager { getEntities: () => Entity[] addEntity: (entity: Entity) => void } export default class EntityManager implements IEntityManager { private entities: Entity[] = [] constructor(initialEntities: Entity[] = []) { initialEntities.forEach(this.addEntity); } public getEntities = () => this.entities; public addEntity = (entity: Entity) => { this.entities.push(entity) if (entity instanceof Bug) { (entity as Bug).zIndexChanged.subscribe(this.sortEntities()) } } sortEntities = () => () => { const plants = this.entities.filter(entity => entity instanceof Plant).map(entity => [entity]) const climbingBugs: Bug[] = this.entities.filter(entity => entity instanceof Bug && entity.climbingOn) as Bug[] climbingBugs.forEach(bug => { const idx = plants.findIndex(plants => plants[0] === bug.climbingOn.plant) plants[idx].push(bug) }) const otherEntities = this.entities.filter(entity => !(entity instanceof Plant || entity instanceof Bug && entity.climbingOn)).map(entity => [entity]) this.entities = this.flatten([...plants, ...otherEntities].sort((a, b) => { return a[0].id - b[0].id })); window.DEBUG && console.log(this.entities) } flatten = (list: any[]): any[] => list.reduce( (a, b) => a.concat(Array.isArray(b) ? this.flatten(b) : b), [] ); }
cf620685a003973f2ea70820541398d0cfb8f8c7
TypeScript
Joe123123/yumeek
/client/src/components/interfaces/Recipe.interface.ts
2.53125
3
export interface Recipes { id: number | undefined; carbs: number; energies: number; fat: number; fiber: number; health_labels: string[]; img_url: string; ingredients: string[]; label: string; protein: number; src_url: string; steps: string | null; weekday: string | null; } export interface FormattedRecipe { recipe: { health_labels: string[]; img_url: string; ingredients: string[]; label: string; src_url: string; steps: string | null; }; nutrients: { carbs: number; energies: number; fat: number; fiber: number; protein: number; }; } export interface DashboardRecipe { weekday: string; energies: number; carbs: number; fat: number; protein: number; fiber: number; recipe: Recipes; } export interface PutRecipe { recipe: Recipes; type: string; }
818d308204837f770bae50ff10ea84133fd9f363
TypeScript
fefo-app/toggl-dashboard
/src/app/views/helpers/DateCalculator/DateCalculator.ts
3.609375
4
export enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } enum Months { January, February, March, April, May, June, July, August, September, October, November, December } export class DateCalculator { static longestMonths = [ Months.January, Months.March, Months.May, Months.July, Months.August, Months.October, Months.December ] static oneDayInMs = 86400000 static calcLastWorkday(date: Date = new Date()): string { const weekDay = date.getDay() if (weekDay === Days.Sunday) { return this.calcDay(date, 2) } if (weekDay === Days.Monday) { return this.calcDay(date, 3) } return this.calcDay(date, 1) } static calcLastWeekday(weekday: Days, date = new Date()) { const week = this.calcDatesForLastWeek(date) return week.find(([day]) => weekday === day)![1] } private static calcDatesForLastWeek(date = new Date()): [Days, string][] { return Array.from({ length: 7 }) .map((_, i) => new Date(date.getTime() - this.oneDayInMs * i)) .map((date) => [date.getDay() as Days, this.toISODate(date)]) } private static calcDay(date: Date, removeDays = 0): string { const year = date.getFullYear() const month = date.getMonth() const dayOfTheMonth = this.calcDaysToRemove(date, removeDays) if (dayOfTheMonth <= removeDays) { const lastDayOfTheMonth = this.calcLastDayOfThePreviousMonth(date) if (month === Months.January) { return `${year - 1}-12-${lastDayOfTheMonth - dayOfTheMonth}` } else { return `${year}-${month}-${lastDayOfTheMonth - dayOfTheMonth}` } } else { return `${year}-${month + 1}-${dayOfTheMonth}` } } private static calcDaysToRemove(d: Date, removeDays: number): number { return d.getDate() < removeDays ? removeDays - d.getDate() : d.getDate() - removeDays } private static calcLastDayOfThePreviousMonth(d: Date): number { const year = d.getFullYear() const month = d.getMonth() const previousMonth = this.calcPreviousMonth(month) if (previousMonth === Months.February) { return this.isLeapYear(year) ? 29 : 28 } if (this.isLongMonth(previousMonth)) { return 31 } return 30 } private static calcPreviousMonth(month: number): number { return month === Months.January ? Months.December : month - 1 } private static isLeapYear(year: number): boolean { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 } private static isLongMonth(month: number): boolean { return this.longestMonths.includes(month) } private static toISODate = (d: Date) => d.toISOString().split('T')[0] }
f75caf951f4a6165e873be62424e107f58a2a266
TypeScript
hopetonpalmer/hp_components
/projects/hp-components/src/lib/scripts/strings.ts
3.28125
3
export function splitCamelCase(value: string): string { return value.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase(); } export function splitCamelCaseProper(value: string): string { const result = value.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase(); return properCase(result); } export function properCase(value: string): string { if (value) { return value.replace(/\w\S*/g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()); } return ''; } export function camelCase(value: string): string { return value.charAt(0).toLowerCase() + value.substr(1); } export function splitToProperCase(value: string): string { return splitCamelCaseProper(camelCase(value)); } export function camelToDash(value: string): string { return value.replace(/([A-Z])/g, ($1) => '-' + $1.toLowerCase()); } export function dashToCamel(value: string): string { return value.replace(/-([a-z])/g, (g) => g[1].toUpperCase()); } export function camelToUnderscore(value: string): string { return value.replace(/([A-Z])/g, ($1) => '_' + $1.toLowerCase()); }
3a03a103a0ee6472ab0cf83eb56ce9879a72f998
TypeScript
adibahasan11/Design-Patterns
/Observer-Pattern/Task -1/180042111.ts
3.53125
4
interface Subject{ notifyObserver(): void; addObserver(display: Display): void; removeObserver(display: Display): void; } interface Display{ update(CourseNo : string, TopicName: string, TeacherName: string, date: Date): void; display(): void; } class ClassTimeData implements Subject{ private CourseNo! : string; private TopicName! : string; private TeacherName! : string; private date! : Date; private displays : Array<Display> = []; getCourseNo = (): string => { return 'Swe 45xx' } getTopicName = (): string => { return 'xyz' } getTeacherName = (): string => { return 'ABC' } getDate = (): Date => { return new Date() } addObserver(display: Display):void{ this.displays.push(display); } removeObserver(display: Display):void{ this.displays.filter(obj => obj !== display); } notifyObserver(){ this.displays.map(o => { o.update(this.CourseNo, this.TopicName, this.TeacherName, this.date) }) } measureChange(courseNo: string, time: Date, topicName: string, teacherName: string): void { this.CourseNo = courseNo this.date = time this.TopicName = topicName this.TeacherName = teacherName this.notifyObserver() } } class TeacherDisplay implements Display{ private CourseNo! : string; private TopicName! : string; private TeacherName! : string; private date! : Date; update(CourseNo : string, TopicName: string, TeacherName: string, date: Date){ this.CourseNo = CourseNo; this.TopicName = TopicName; this.TeacherName = TeacherName; this.date = date; this.display() } display(){ console.log("Teacher's Notice") console.log( "Course No.: ", this.CourseNo ); console.log( "Topic Name: ", this.TopicName); console.log( "Teacher Name: ", this.TeacherName ); console.log( "Class Time: ", this.date ); } } class StudentDisplay implements Display{ private CourseNo! : string; private TopicName! : string; private TeacherName! : string; private date! : Date; update(CourseNo : string, TopicName: string, TeacherName: string, date: Date){ this.CourseNo = CourseNo; this.TopicName = TopicName; this.TeacherName = TeacherName; this.date = date; this.display(); } display(){ console.log("Students Notice:") console.log( "Course No.: ", this.CourseNo ); console.log( "Topic Name: ", this.TopicName); console.log( "Teacher Name: ", this.TeacherName ); console.log( "Class Time: ", this.date ); } } let classTimeData = new ClassTimeData(); classTimeData.addObserver(new StudentDisplay()) classTimeData.addObserver(new TeacherDisplay()) classTimeData.measureChange('SWE-4501', new Date(), 'Observer Pattern', 'Nazmul Haque')