blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
120
| path
stringlengths 5
328
| src_encoding
stringclasses 19
values | length_bytes
int64 23
6.41M
| score
float64 2.52
5.16
| int_score
int64 3
5
| detected_licenses
listlengths 0
99
| license_type
stringclasses 2
values | text
stringlengths 23
6.04M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
e1ee9937a6912b8ff2b19f3e9b4de1e08568695e
|
TypeScript
|
jiangwenyang/front-end-assistant
|
/src/translate.ts
|
UTF-8
| 2,797 | 3.046875 | 3 |
[] |
no_license
|
var TKK = ((function () {
var a = 561666268
var b = 1526272306
return 406398 + '.' + (a + b)
})())
function hexCharAsNumber(xd: string) {
return (xd >= 'a') ? xd.charCodeAt(0) - 87 : Number(xd)
}
function shiftLeftOrRightThenSumOrXor(num: number, opArray: Array<string>) {
return opArray.reduce((acc, opString) => {
var op1 = opString[1] // '+' | '-' ~ SUM | XOR
var op2 = opString[0] // '+' | '^' ~ SLL | SRL
var xd = opString[2] // [0-9a-f]
var shiftAmount = hexCharAsNumber(xd)
var mask = (op1 === '+') ? acc >>> shiftAmount : acc << shiftAmount
return (op2 === '+') ? (acc + mask & 0xffffffff) : (acc ^ mask)
}, num)
}
function transformQuery(query: string) {
for (var e = [], f = 0, g = 0; g < query.length; g++) {
var l = query.charCodeAt(g)
if (l < 128) {
e[f++] = l // 0{l[6-0]}
} else if (l < 2048) {
e[f++] = l >> 6 | 0xC0 // 110{l[10-6]}
e[f++] = l & 0x3F | 0x80 // 10{l[5-0]}
} else if (0xD800 === (l & 0xFC00) && g + 1 < query.length && 0xDC00 === (query.charCodeAt(g + 1) & 0xFC00)) {
// that's pretty rare... (avoid ovf?)
l = (1 << 16) + ((l & 0x03FF) << 10) + (query.charCodeAt(++g) & 0x03FF)
e[f++] = l >> 18 | 0xF0 // 111100{l[9-8*]}
e[f++] = l >> 12 & 0x3F | 0x80 // 10{l[7*-2]}
e[f++] = l & 0x3F | 0x80 // 10{(l+1)[5-0]}
} else {
e[f++] = l >> 12 | 0xE0 // 1110{l[15-12]}
e[f++] = l >> 6 & 0x3F | 0x80 // 10{l[11-6]}
e[f++] = l & 0x3F | 0x80 // 10{l[5-0]}
}
}
return e
}
function normalizeHash(encondindRound2: number) {
if (encondindRound2 < 0) {
encondindRound2 = (encondindRound2 & 0x7fffffff) + 0x80000000
}
return encondindRound2 % 1E6
}
function calcHash(query: string, windowTkk: string) {
// STEP 1: spread the the query char codes on a byte-array, 1-3 bytes per char
var bytesArray = transformQuery(query)
// STEP 2: starting with TKK index, add the array from last step one-by-one, and do 2 rounds of shift+add/xor
var d = windowTkk.split('.')
var tkkIndex = Number(d[0]) || 0
var tkkKey = Number(d[1]) || 0
var encondingRound1 = bytesArray.reduce((acc, current) => {
acc += current
return shiftLeftOrRightThenSumOrXor(acc, ['+-a', '^+6'])
}, tkkIndex)
// STEP 3: apply 3 rounds of shift+add/xor and XOR with they TKK key
var encondingRound2 = shiftLeftOrRightThenSumOrXor(encondingRound1, ['+-3', '^+b', '+-f']) ^ tkkKey
// STEP 4: Normalize to 2s complement & format
var normalizedResult = normalizeHash(encondingRound2)
return normalizedResult.toString() + "." + (normalizedResult ^ tkkIndex)
}
function genTK(query: string) {
return calcHash(query, TKK)
}
| true |
90a54e8adcde3c4a777e42047508ec9d734d92e0
|
TypeScript
|
MartinSka/chat
|
/src/app/models/user.model.ts
|
UTF-8
| 376 | 3.140625 | 3 |
[] |
no_license
|
export interface User {
/**
* User ID.
*/
id: string;
/**
* User name.
*/
name: string;
/**
* List of users and their respective chats ID.
*/
contacts: Contacts;
}
/**
* List of users that the sender can talk to
* and the chat ID that corresponds to that conversation.
*/
export interface Contacts {
[key: string]: { chatId: string; };
}
| true |
548d5b2d5b10d5f3483c2c9731eaccf496eae470
|
TypeScript
|
Wiggins-zsz/typescript
|
/src/interface.ts
|
UTF-8
| 519 | 3.0625 | 3 |
[] |
no_license
|
import {Singleton} from './index';
interface Type {
name: string,
age: number,
address?: string
}
interface ReadOnly {
readonly x: string,
readonly y: number
}
export function Type(param: Type) {
let c = Singleton.getInstance({name: 'third', className: 'third class', content: 'third address', callBack: () =>{}});
let {name, age, address} = param;
console.log(age, name, address);
return [name, age, address];
}
export function Read(param: ReadOnly): {} {
return param;
}
| true |
7127bd8e9f0d6078707157b263ba787c6901bcc7
|
TypeScript
|
taonylu/egretproject
|
/EgretProjects/llk_old/src/net/ClientSocket.ts
|
UTF-8
| 2,583 | 2.671875 | 3 |
[] |
no_license
|
/**
* 文 件 名:ClientSocket.ts
* 功 能: 客户端Socket
* 内 容:
* 作 者: 羊力大仙
* 生成日期:2015/9/14
* 修改日期:2015/9/14
* 修改日志:
*/
class ClientSocket {
private static instance: ClientSocket;
private webSocket: egret.WebSocket;
private tempMsg: string = ""; //临时数据
private callBack: ISocketCallBack; //socket回调
private IP: string = "192.168.1.50";
private port: number = 12345;
public static getInstance(): ClientSocket {
if(this.instance == null) {
this.instance = new ClientSocket();
}
return this.instance;
}
public connect(): void {
console.log("start connect socket...");
if(this.webSocket == null) {
this.webSocket = new egret.WebSocket();
this.webSocket.addEventListener(egret.ProgressEvent.SOCKET_DATA,this.onSocketData,this);
this.webSocket.addEventListener(egret.Event.CONNECT,this.onSocketConnect,this);
this.webSocket.addEventListener(egret.IOErrorEvent.IO_ERROR,this.onSocketError,this);
this.webSocket.addEventListener(egret.Event.CLOSE,this.onSocketClose,this);
}
this.webSocket.connect(this.IP,this.port);
}
private onSocketConnect(): void {
console.log("socket connect success...");
if(this.tempMsg != "") {
this.send(this.tempMsg);
this.tempMsg = "";
}
this.callBack.onSocketConnect();
}
private onSocketData(e: egret.Event): void {
var data = this.webSocket.readUTF();
console.log("socket rev data:" + data);
var json = JSON.parse(data);
this.callBack.onSocketData(json);
}
private onSocketError(e:egret.IOErrorEvent): void {
console.log("socket connent error...");
this.callBack.onSocketError();
}
public send(jsonMsg:string): void {
console.log("socket send msg:" + jsonMsg);
if(this.webSocket && this.webSocket.connected) {
this.webSocket.writeUTF(jsonMsg);
this.webSocket.flush();
} else {
console.log("socket is close,can't send msg...");
this.tempMsg = jsonMsg;
this.connect();
}
}
public onSocketClose(): void {
console.log("close socket...");
this.tempMsg = "";
this.callBack.onSocketClose();
}
public setCallBack(callBack: ISocketCallBack) {
this.callBack = callBack;
}
}
| true |
d0d8d5ac61f02b734480391f21d6db5eace02edc
|
TypeScript
|
cns-iu/ngx-dino
|
/projects/core/src/lib/fields/factories/simple-field.ts
|
UTF-8
| 598 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
import { Seq } from 'immutable';
import { Operator } from '../../operators';
import { BaseFieldArgs, Field } from '../field';
export interface SimpleFieldArgs<T> extends BaseFieldArgs {
bfieldId?: string;
operator: Operator<any, T>;
}
export function simpleField<T>(args: SimpleFieldArgs<T>): Field<T> {
const {bfieldId, operator} = args;
const bidSeq = bfieldId ? {[bfieldId]: operator} : {};
const mapping = Seq.Keyed<string, Operator<any, T>>({
[Field.defaultSymbol]: operator
}).concat(bidSeq).toSeq();
const newArgs = {...args, mapping};
return new Field(newArgs);
}
| true |
5a712cff0d7c386996b188bf4c418c4768442b8e
|
TypeScript
|
MagnetronGame/magnetron-client
|
/src/components/magnetron_game/MagnetronGame3d/boardGroupAnim.ts
|
UTF-8
| 3,737 | 2.84375 | 3 |
[] |
no_license
|
import * as THREE from "three"
import { StaticBoard } from "./board"
import { resetBoardObjectCellPositions, VisBoardPlate } from "./boardVisObject"
import { range } from "../../../utils/arrayUtils"
import { Anim } from "./animation/animationTypes"
const positionCells = (
staticBoard: StaticBoard,
boardObject: VisBoardPlate,
distanceFactor: number,
rotation: number,
) => {
range(staticBoard.cellCount.x).forEach((x) => {
range(staticBoard.cellCount.y).forEach((y) => {
const cellStaticPos = staticBoard.cellsCenterPosition[x][y]
const cellMesh = boardObject.cells[x][y]
const cellStaticRelPos = new THREE.Vector2().subVectors(
cellStaticPos,
staticBoard.center,
)
const cellPos = cellStaticRelPos
.clone()
.multiplyScalar(distanceFactor)
.rotateAround(staticBoard.center, rotation)
.add(staticBoard.center)
cellMesh.position.x = cellPos.x
cellMesh.position.z = cellPos.y
})
})
}
export default (staticBoard: StaticBoard, boardObject: VisBoardPlate): Anim => ({
name: "group board pieces",
duration: 4,
update: ({ durationRatio, durationRatioInv }) => {
const durationRatioSquared = Math.pow(durationRatio, 20)
const distanceFactor = 10 * (1 - durationRatioSquared) + 1
const rotation = (Math.PI / 2) * durationRatioInv
positionCells(staticBoard, boardObject, distanceFactor, rotation)
},
end: () => resetBoardObjectCellPositions(staticBoard, boardObject),
})
//
// export class BoardGroupAnimation extends Animation {
// private readonly boardObject: VisBoardPlate
// private readonly staticBoard: StaticBoard
//
// constructor(staticBoard: StaticBoard, boardObject: VisBoardPlate) {
// super(4, false)
// this.staticBoard = staticBoard
// this.boardObject = boardObject
// }
//
// public update = (game: Magnetron, deltaTime: number) => {
// this.currDuration += deltaTime
// const durationFactor = this.currDuration / this.duration
// const durationFactorSquared = Math.pow(durationFactor, 10)
//
// const distanceFactor = 10 * (1 - durationFactorSquared) + 1
// const rotation = (Math.PI / 2) * (1 - durationFactor)
// this.positionCells(distanceFactor, rotation)
//
// if (this.currDuration >= this.duration) {
// resetBoardObjectCellPositions(this.staticBoard, this.boardObject)
// return false
// } else {
// return true
// }
// }
//
// private positionCells = (distanceFactor: number, rotation: number) => {
// range(this.staticBoard.cellCount.x).forEach((x) => {
// range(this.staticBoard.cellCount.y).forEach((y) => {
// const cellStaticPos = this.staticBoard.cellsCenterPosition[x][y]
// const cellMesh = this.boardObject.cells[x][y]
//
// const cellStaticRelPos = new THREE.Vector2().subVectors(
// cellStaticPos,
// this.staticBoard.center,
// )
// const cellPos = cellStaticRelPos
// .clone()
// .multiplyScalar(distanceFactor)
// .rotateAround(this.staticBoard.center, rotation)
// .add(this.staticBoard.center)
//
// cellMesh.position.x = cellPos.x
// cellMesh.position.z = cellPos.y
// })
// })
// }
//
// protected start(game: Magnetron): void {}
// protected end(game: Magnetron): void {}
// }
| true |
be0f1304de6fcf40810b2987d5340b3c2ad1b989
|
TypeScript
|
madfish-solutions/quipuswap-webapp
|
/src/core/operation.ts
|
UTF-8
| 2,194 | 2.53125 | 3 |
[] |
no_license
|
import { BlockResponse, OperationEntry } from "@taquito/rpc";
import { TezosToolkit } from "@taquito/taquito";
export const SYNC_INTERVAL = 10_000;
export const CONFIRM_TIMEOUT = 60_000 * 5;
export type ConfirmOperationOptions = {
initializedAt?: number;
fromBlockLevel?: number;
signal?: AbortSignal;
};
export async function confirmOperation(
tezos: TezosToolkit,
opHash: string,
{ initializedAt, fromBlockLevel, signal }: ConfirmOperationOptions = {}
): Promise<OperationEntry> {
if (!initializedAt) initializedAt = Date.now();
if (initializedAt && initializedAt + CONFIRM_TIMEOUT < Date.now()) {
throw new Error("Confirmation polling timed out");
}
const startedAt = Date.now();
let currentBlockLevel;
try {
const currentBlock = await tezos.rpc.getBlock();
currentBlockLevel = currentBlock.header.level;
for (
let i = fromBlockLevel ?? currentBlockLevel;
i <= currentBlockLevel;
i++
) {
const block =
i === currentBlockLevel
? currentBlock
: await tezos.rpc.getBlock({ block: i as any });
const opEntry = await findOperation(block, opHash);
if (opEntry) {
let status;
try {
status = (opEntry.contents[0] as any).metadata.operation_result
.status;
} catch {}
if (status && status !== "applied") {
throw new FailedOpError(`Operation ${status}`);
}
return opEntry;
}
}
} catch (err) {
if (err instanceof FailedOpError) {
throw err;
}
}
if (signal?.aborted) {
throw new Error("Cancelled");
}
const timeToWait = Math.max(startedAt + SYNC_INTERVAL - Date.now(), 0);
await new Promise(r => setTimeout(r, timeToWait));
return confirmOperation(tezos, opHash, {
initializedAt,
fromBlockLevel: currentBlockLevel ? currentBlockLevel + 1 : fromBlockLevel,
signal,
});
}
export async function findOperation(block: BlockResponse, opHash: string) {
for (let i = 3; i >= 0; i--) {
for (const op of block.operations[i]) {
if (op.hash === opHash) {
return op;
}
}
}
return null;
}
class FailedOpError extends Error {}
| true |
c712cdb2629197c6620a0c56fd7224059ea51884
|
TypeScript
|
igoralvesantos/backend-food4u
|
/src/business/usecases/user/updateUser.ts
|
UTF-8
| 1,280 | 2.734375 | 3 |
[] |
no_license
|
import { UserGateway } from "../../gateways/userGateway";
import { JWTAutenticationGateway } from "../../gateways/jwtAutenticationGateway";
import { ValidatorsGateway } from "../../gateways/validatorsGateway";
export class UpdateUserUC {
constructor(
private db: UserGateway,
private jwtAuth: JWTAutenticationGateway,
private validators: ValidatorsGateway
) {}
public async execute(input: updateUserUCInput): Promise<updateUserUCOutput> {
try {
this.validators.validateUpdateUserInput(input);
const userId = this.jwtAuth.verifyToken(input.token);
if(input.email) {
await this.db.changeEmail(input.email, userId);
}
if(input.name) {
await this.db.changeName(input.name, userId);
}
if(input.birthDate) {
await this.db.changeBirthDate(input.birthDate, userId);
}
return {
message: "User updated successfully",
};
} catch (err) {
throw {
code: err.statusCode || 400,
message: err.message || "An error occurred while trying to update the user",
};
}
}
}
export interface updateUserUCInput {
token: string;
email?: string;
name?: string;
birthDate?: Date;
}
export interface updateUserUCOutput {
message: string;
}
| true |
ec8338deef9aca3ba706b11851a6b989ee0e10b3
|
TypeScript
|
changchangge/chang-request
|
/src/types/object-type.ts
|
UTF-8
| 169 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
/**
* @interface ObjectType
*/
interface ObjectType {
/**
* obj definition
* 对象定义
*/
[key: string]: unknown;
}
export type ObjType = ObjectType;
| true |
21d77c6812a4fb48f2fb460de2abe5a03d277fda
|
TypeScript
|
rodrigodsluz/dashboard-app
|
/src/utils/validation/index.ts
|
UTF-8
| 1,189 | 2.84375 | 3 |
[] |
no_license
|
export function checkEmailValid(value: string): boolean {
if (value.length > 0) {
const exclude = /[^@\-\\.\w]|^[_@\\.\\-]|[\\._\\-]{2}|[@\\.]{2}|(@)[^@]*\1/;
const check = /@[\w\\-]+\./;
const checkend = /\.[a-zA-Z]{2,3}$/;
if (
value.search(exclude) !== -1 ||
value.search(check) === -1 ||
value.search(checkend) === -1
) {
return false;
}
return true;
}
return false;
}
export function checkEmpty(value: string): boolean {
const valeuInput = value.trim();
if (valeuInput.length === 0) {
return true;
}
return false;
}
export function checkRangeMin(value: string, min: number): boolean {
return !(value.length > 1 && value.length >= min);
}
export const clear = (value: string) => {
const emptyMask = value.replace(/[\\[\].!'@,><|://\\;&*()_+=-]/g, '');
return emptyMask.replace(/\.|\\-|\/|[()]|\W+/g, '');
};
export const setMaskMobile = (value: string): string => {
const array = value.split('');
if (array.length > 2) {
array.splice(0, 0, '(');
array.splice(3, 0, ')');
array.splice(4, 0, ' ');
}
if (array.length > 10) {
array.splice(10, 0, '-');
}
return array.join('');
};
| true |
c409077afe1d3e1ad46000cc5c34e1c3a005b4ed
|
TypeScript
|
romaannaeem/unofficial-notion-api-v2
|
/src/lib/helpers.ts
|
UTF-8
| 5,702 | 3.046875 | 3 |
[] |
no_license
|
import { NotionObject, Options, Attributes, PageDTO, formatter, htmlResponse } from './types';
import slugify from 'slugify';
// Seperator for good-looking HTML ;)
const SEPERATOR = '';
// HTML Tag types
const types = {
page: 'a',
text: 'p',
header: 'h1',
sub_header: 'h3',
sub_sub_header: 'h5',
divider: 'hr',
break: 'br',
numbered_list: 'ol',
bulleted_list: 'ul',
image: 'img'
};
/**
* Method that parses a Notion-Object to HTML
* @param {*} ObjectToParse The Notion-Object
* @param {*} options Options for parsing
*/
function formatToHtml(
ObjectToParse: NotionObject,
options: Options,
index: number
) {
let { type, properties, format } = ObjectToParse;
// Get color
const color = format && format.block_color;
// Replace color with custom color if passed
const customColor =
color &&
options.colors &&
((options.colors as any)[color.split('_')[0]] || color);
// Set content
const content =
properties &&
properties.title &&
properties.title[0][0].replace(/\[.*\]:.{1,}/, '');
const source =
properties &&
properties.source;
const tags = (content && content[0] ? content[0][0] : '').match(
/\[.{1,}\]: .{1,}/
);
const attrib = tags && tags[0].replace(/(\[|\])/g, '').split(':');
if (attrib && attrib.length == 2) {
return {
[attrib[0]]: attrib[1].trim()
};
}
// Only set Style if passed
const property =
customColor && color.includes('background')
? `style="background-color:${customColor.split('_')[0]}"`
: `style="color:${customColor}"`;
// Use ternary operator to return empty string instead of undefined
const style = color ? ` ${property}` : '';
// Set type to break if no content is existent
if (!content && type !== 'divider' && !source) {
type = 'break';
}
// Create HTML Tags with content
switch (types[type]) {
case types.page: {
if (index === 0) {
return `<h1 ${style}>${content}</h1>`;
}
return null;
}
case types.divider: {
return `<${types.divider}${style}/>`;
}
case types.break: {
return `<${types.break} />`;
}
case types.numbered_list:
case types.bulleted_list: {
return `<li${style}>${content}</li>`;
}
case types.image: {
return `<${types.image}${style} src="${source}" />`;
}
default: {
if (types[type])
return `<${types[type]}${style}>${content}</${types[type]}>`;
return null;
}
}
}
/**
* Formats a List of objects to HTML
* @param {*} ObjectList List of Notion-Objects
* @param {*} options Options for parsing
* @param {*} htmlFormatter html renderer
*/
function formatList(ObjectList: Array<NotionObject>, options: Options, htmlFormatter?: formatter) {
const items = [];
const attributes: Attributes = {};
for (let index = 0; index < ObjectList.length; index += 1) {
const element = ObjectList[index];
let html: htmlResponse;
if (htmlFormatter) {
html = htmlFormatter(element, options, index, ObjectList);
} else {
html = formatToHtml(element, options, index);
}
if (html && typeof html === 'object') {
const keys = Object.keys(html as Attributes);
keys.forEach(key => {
attributes[key] = (html as Attributes)[key];
});
} else if (
element &&
element.type.includes('list') &&
!element.type.includes('column')
) {
// If it the element is the first ul or ol element
if (
ObjectList[index - 1] &&
!ObjectList[index - 1].type.includes('list')
) {
html = `<${types[element.type]}>${SEPERATOR}${html}`;
}
if (
index + 1 >= ObjectList.length ||
(ObjectList[index + 1] && !ObjectList[index + 1].type.includes('list'))
) {
html = `${html}${SEPERATOR}</${types[element.type]}>`;
}
}
if (typeof html === 'string') {
items.push(html);
}
}
const { format, properties } = ObjectList[0];
const title = (properties && properties.title && properties.title[0][0]) || '';
const cover =
format && format.page_cover
? format.page_cover.includes('http')
? format.page_cover
: `https://www.notion.so${format.page_cover}`
: null;
return {
items,
attributes: {
...attributes,
title,
slug: slugify(title, { lower: true }),
cover,
teaser: items
.map(i =>
i
.replace(/\[.{1,}\]: .{1,}/g, '')
.replace(/\<a.*\>*\<\/a\>/g, '')
.replace(/<[^>]*>/g, '')
)
.filter(i => i)
.join(' ')
.trim()
.substring(0, 200),
icon: format ? format.page_icon : null
}
};
}
/**
* Creates a HTML Page out of a List of Notion-Objects
* @param {*} ObjectList List of Notion-Objects
* @param {*} options Options for parsing
* @param {*} htmlFormatter html renderer
*/
function toHTMLPage(
ObjectList: Array<NotionObject>,
options: Options,
htmlFormatter?: formatter
): PageDTO {
const { items, attributes } = formatList(ObjectList, options, htmlFormatter);
const elementsString = items.join('');
return {
HTML: elementsString ? `<div>${elementsString}</div>` : '',
Attributes: { ...attributes, id: ObjectList[0].id }
};
}
export function handleNotionError(err: Error) {
if (err.message.includes('block')) {
console.error('Authentication Error: Please check your token!');
} else {
console.error(err);
}
}
export function isNotionID(id: string) {
const idRegex = new RegExp(
/[a-z,0-9]{8}-[a-z,0-9]{4}-[a-z,0-9]{4}-[a-z,0-9]{4}-[a-z,0-9]{12}/g
);
return idRegex.test(id);
}
export default toHTMLPage;
| true |
c48ecc2bb1d398fc1254edba5357b7c252438f23
|
TypeScript
|
rajivnayanc/Shoot_the_Balloons_HTML5_canvas
|
/shoot-the-balloon/src/game/Objects/ProjectileLine.ts
|
UTF-8
| 2,430 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
import { BulletPosition } from './Bullet';
import { Position2D } from './common-intf';
import { LIGHT_THEME } from './consts';
import RenderableObject from './renderable-object';
import { distance, getQuadraticRoots } from './utils';
class ProjectileLine extends RenderableObject {
start:Position2D;
end:Position2D;
controlPoints:Position2D;
gravity:number;
color: string;
constructor(canvas: HTMLCanvasElement, c: CanvasRenderingContext2D, theme:string){
super(canvas, c);
this.start = {x:0,y:0};
this.end = {x:0,y:0};
this.controlPoints = {x:0,y:0};
this.gravity = 0.3;
this.color = theme===LIGHT_THEME?"black":"gray";
}
draw(): void {
this.c.save();
this.c.lineWidth = 1;
this.c.beginPath();
this.c.setLineDash([10,15])
this.c.moveTo(this.start.x, this.start.y);
this.c.quadraticCurveTo(this.controlPoints.x, this.controlPoints.y, this.end.x, this.end.y);
this.c.strokeStyle = this.color;
this.c.stroke();
this.c.restore();
}
update(bull_start:BulletPosition): void {
this.start.x = bull_start.x;
this.start.y = bull_start.y;
const dist = bull_start.dist/distance(0,0,this.canvas.width, this.canvas.height);
const velocity = Math.min(150 * dist,40);
let ux = Math.cos(bull_start.angle) * velocity;
let uy = Math.sin(bull_start.angle) * velocity;
let t_x = (this.canvas.width-this.start.x)/ux;
let t_y = getQuadraticRoots(this.gravity, 2*uy, -2 * (this.canvas.height - this.start.y));
let t_y_top = getQuadraticRoots(this.gravity, 2*uy, -2 * (0 - this.start.y));
let timeArray = [t_x, t_y, t_y_top].filter(a=>a!=null) as number[];
let min_time = Math.min(...timeArray);
this.end.x = this.start.x + ux*min_time;
this.end.y = this.start.y + uy*min_time + (this.gravity * min_time * min_time)/2;
const a = this.gravity/(2*ux*ux);
const b = uy/ux - (this.gravity*this.start.x)/(ux*ux);
const c = this.start.y - uy*this.start.x/ux + this.gravity*this.start.x*this.start.x/(2*ux*ux);
this.controlPoints = this.getQuadraticBezierControlPoints( a, b, c );
this.draw();
}
getQuadraticBezierControlPoints(a:number, b:number, c:number):Position2D{
let out:Position2D = {x:0,y:0};
out.x = (this.start.x+this.end.x)/2;
out.y = ((this.end.x-this.start.x)/2) * (2*a*this.start.x + b) + (a*this.start.x*this.start.x + b*this.start.x + c);
return out;
}
}
export default ProjectileLine;
| true |
9a5e278ebc1c1e5c951ff8e2f8ab83c1e85be194
|
TypeScript
|
awoimbee/TGVmax
|
/server/src/routes/StationRouter.ts
|
UTF-8
| 939 | 2.625 | 3 |
[] |
no_license
|
import { Context } from 'koa';
import * as Router from 'koa-router';
import StationController from '../controllers/StationController';
import { HttpStatus } from '../Enum';
import { authenticate } from '../middlewares/authenticate';
import { IStation } from '../types';
/**
* Autocomplete router for train stations
*/
class StationRouter {
/**
* http router
*/
public readonly router: Router;
constructor() {
this.router = new Router<{}>();
this.router.prefix('/api/v1/stations');
this.init();
}
/**
* Add a travel to database
*/
private readonly getStations = async(ctx: Context): Promise<void> => {
const stations: IStation[] = await StationController.getStations();
ctx.body = stations;
ctx.status = HttpStatus.OK;
}
/**
* init router
*/
private init(): void {
this.router.get('/', authenticate(), this.getStations);
}
}
export default new StationRouter().router;
| true |
f4a0d55145e80540b8e4b3837712e48238c22258
|
TypeScript
|
LisaLoop/typescript-demo
|
/src/examples/use-cases.ts
|
UTF-8
| 1,016 | 3.140625 | 3 |
[] |
no_license
|
export default {}
type User = {
id: string;
name: string;
};
type ServerUser = {
userData: {
userEmployeeId: string;
userName: string;
userMeta: {
userMetaId: string;
userMetaLastLogin: string;
userMetaDetails: [];
};
};
};
const getUser = (id: string) => fetch(`/api/users/${id}`)
.then((res) => res.json())
.then((data: unknown): Promise<User> => {
return isValidUserData(data)
? Promise.resolve(makeUser(data))
: Promise.reject(data);
});
const makeUser = (data: ServerUser): User => {
const user: User = {
id: data.userData.userMeta.userMetaId,
name: data.userData.userName
};
return user;
};
const isValidUserData = (data: unknown): data is ServerUser => {
const name = (data as ServerUser)?.userData?.userName;
const id = (data as ServerUser)?.userData?.userMeta.userMetaId;
const isValid =
(typeof name === "string" && name.length > 0)
&& (typeof id === "string" && id.length > 0);
return isValid;
};
| true |
1667a0421c54830665d252157b96102546074010
|
TypeScript
|
lanrehnics/park-campus
|
/src/providers/buildings.ts
|
UTF-8
| 1,296 | 2.90625 | 3 |
[] |
no_license
|
import {Injectable} from '@angular/core';
import {Api} from './api';
import {Building} from '../models/building';
import 'rxjs/add/operator/map';
@Injectable()
/**
* Used by the application to interact with the buildings stored in the database on the server.
*/
export class BuildingProvider {
/**
* @param {Api} api the class containing methods which facilitate interaction with the server
*/
constructor(public api: Api) {
}
/**
* Retrieves either all buildings stored on the server, or the building matching the specified ID.
*
* @param {Number} id used to specify the unique identifier of the building
* @returns {Promise} contains the buildings retrieved from the server
*/
queryBuildings(id?: Number) {
return new Promise((resolve, reject) => {
this.api.getEntity("buildings", id).map(res => res.json()).subscribe((values) => {
let buildings = [];
if (values != null && values.length > 0) {
for (let i = 0; i < values.length; i++) {
buildings.push(new Building(values[i].building_id, values[i].building_code, values[i].building_name, values[i].building_lat, values[i].building_lng));
}
}
resolve(buildings);
}, (error) => {
reject(error);
});
});
}
}
| true |
cf50613daf2616efa12d1f952da59dfeeb866099
|
TypeScript
|
IronOnet/codebases
|
/codebases/anchor.fm/client/modules/AnchorAPI/v3/stations/fetchImportStatus.ts
|
UTF-8
| 932 | 2.65625 | 3 |
[] |
no_license
|
import { getApiUrl } from '../../../Url';
type ImportStatusParameters = {
stationId: string;
};
type Item = {
rssImportItemId: number;
state: 'waiting' | 'started' | 'finished' | 'failed';
kind: 'item' | 'channel';
title: string;
};
type ImportStatusResponse = {
state: 'processing' | 'complete';
percentageComplete: number;
items: Item[];
};
const getEndpointUrl = (stationId: string) =>
getApiUrl({ path: `stations/webStationId:${stationId}/importStatus` });
export const fetchImportStatus = async ({
stationId,
}: ImportStatusParameters): Promise<ImportStatusResponse> => {
const url = getEndpointUrl(stationId);
try {
const response = await fetch(url, {
credentials: 'same-origin',
});
if (response.ok) {
return response.json();
}
throw new Error(`unable to fetch import status for station: ${stationId}`);
} catch (err) {
throw new Error(err.message);
}
};
| true |
993e7a13b02214d1444ef8b77e915534d6f7fb6c
|
TypeScript
|
CodersCamp2020-HK/CodersCamp2020.Project.FullStack-Node-React
|
/src/infrastructure/postgres/PostgresQueries.ts
|
UTF-8
| 3,041 | 2.765625 | 3 |
[] |
no_license
|
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Client } from 'pg';
import { parse } from 'pg-connection-string';
interface PostgresConnectionConfig {
host: string;
user: string;
password: string;
port: number;
database: string | undefined;
}
interface PostgresUrl {
url: string;
}
type PostgresConnectionOptions = PostgresConnectionConfig | PostgresUrl;
function isPostgresUrl(value: any): value is PostgresUrl {
return 'url' in value && typeof value.url === 'string';
}
function parsePostgresUrl({ url }: PostgresUrl): PostgresConnectionConfig {
const options = parse(url);
const config = { ...options, port: Number(options.port) };
const getOrThrowIfNull = <T>(param: keyof typeof config, value: T | null | undefined) => {
if (value === undefined || value === null) {
throw new Error(`Invalid postgres url (${param})`);
}
return value;
};
return {
host: getOrThrowIfNull('host', config.host),
user: getOrThrowIfNull('user', config.user),
password: getOrThrowIfNull('password', config.password),
port: getOrThrowIfNull('port', config.port),
database: config.database as string | undefined,
};
}
async function singleQueryConnection<T>(
options: PostgresConnectionOptions,
query: (client: Client) => Promise<T>,
): Promise<T> {
const config = isPostgresUrl(options) ? parsePostgresUrl(options) : options;
const client = new Client(config);
await client.connect();
try {
return await query(client);
} finally {
await client.end();
}
}
async function createDatabaseIfNotExists(options: PostgresConnectionOptions, defaultDatabase = 'postgres') {
const config = isPostgresUrl(options) ? parsePostgresUrl(options) : options;
const query = async (client: Client) => {
try {
const existingDb = await client.query(`
SELECT datname
FROM pg_catalog.pg_database
WHERE lower(datname) = lower('${config.database}');`);
if (existingDb.rowCount <= 0) {
return await client.query(`CREATE DATABASE "${config.database}";`);
}
} catch (e) {
console.warn(e);
}
return;
};
return singleQueryConnection({ ...config, database: defaultDatabase }, query);
}
async function createSchemaIfNotExists(options: PostgresConnectionOptions, schema: string) {
const query = (client: Client) => client.query(`CREATE SCHEMA IF NOT EXISTS "${schema}";`);
return singleQueryConnection(options, query);
}
async function dropSchemaIfExists(options: PostgresConnectionOptions, schema: string) {
const query = (client: Client) => client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE;`);
return singleQueryConnection(options, query);
}
export { singleQueryConnection, createDatabaseIfNotExists, createSchemaIfNotExists, dropSchemaIfExists };
| true |
d0dbeca763055ab137b531b1c0be8a2d8ffd5c89
|
TypeScript
|
mikeparisstuff/amplify-cli
|
/packages/graphql-relational-schema-transformer/src/RelationalDBSchemaTransformerUtils.ts
|
UTF-8
| 7,440 | 2.96875 | 3 |
[
"Apache-2.0"
] |
permissive
|
import { Kind, print, ObjectTypeDefinitionNode, NonNullTypeNode, DirectiveNode, NameNode,
OperationTypeNode, FieldDefinitionNode, NamedTypeNode, InputValueDefinitionNode, ValueNode,
OperationTypeDefinitionNode, SchemaDefinitionNode, ArgumentNode, ListValueNode, StringValueNode,
InputObjectTypeDefinitionNode, DocumentNode} from 'graphql'
const intTypes = [`INTEGER`, `INT`, `SMALLINT`, `TINYINT`, `MEDIUMINT`, `BIGINT`, `BIT`]
const floatTypes = [`FLOAT`, `DOUBLE`, `REAL`, `REAL_AS_FLOAT`, `DOUBLE PRECISION`, `DEC`, `DECIMAL`, `FIXED`, `NUMERIC`]
/**
* Creates a non-null type, which is a node wrapped around another type that simply defines it is non-nullable.
*
* @param typeNode the type to be marked as non-nullable.
* @returns a non-null wrapper around the provided type.
*/
export function getNonNullType(typeNode: NamedTypeNode): NonNullTypeNode {
return {
kind: Kind.NON_NULL_TYPE,
type: typeNode
}
}
/**
* Creates a named type for the schema.
*
* @param name the name of the type.
* @returns a named type with the provided name.
*/
export function getNamedType(name: string): NamedTypeNode {
return {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: name
}
}
}
/**
* Creates an input value definition for the schema.
*
* @param typeNode the type of the input node.
* @param name the name of the input.
* @returns an input value definition node with the provided type and name.
*/
export function getInputValueDefinition(typeNode: NamedTypeNode | NonNullTypeNode, name: string): InputValueDefinitionNode {
return {
kind: Kind.INPUT_VALUE_DEFINITION,
name: {
kind: Kind.NAME,
value: name
},
type: typeNode
}
}
/**
* Creates an operation field definition for the schema.
*
* @param name the name of the operation.
* @param args the arguments for the operation.
* @param type the type of the operation.
* @param directives the directives (if any) applied to this field. In this context, only subscriptions will have this.
* @returns an operation field definition with the provided name, args, type, and optionally directives.
*/
export function getOperationFieldDefinition(name: string, args: InputValueDefinitionNode[], type: NamedTypeNode, directives: ReadonlyArray<DirectiveNode>): FieldDefinitionNode {
return {
kind: Kind.FIELD_DEFINITION,
name: {
kind: Kind.NAME,
value: name
},
arguments: args,
type: type,
directives: directives
}
}
/**
* Creates a field definition node for the schema.
*
* @param fieldName the name of the field to be created.
* @param type the type of the field to be created.
* @returns a field definition node with the provided name and type.
*/
export function getFieldDefinition(fieldName: string, type: NonNullTypeNode | NamedTypeNode): FieldDefinitionNode {
return {
kind: Kind.FIELD_DEFINITION,
name: {
kind: Kind.NAME,
value: fieldName
},
type
}
}
/**
* Creates a type definition node for the schema.
*
* @param fields the field set to be included in the type.
* @param typeName the name of the type.
* @returns a type definition node defined by the provided fields and name.
*/
export function getTypeDefinition(fields: ReadonlyArray<FieldDefinitionNode>, typeName: string): ObjectTypeDefinitionNode {
return {
kind: Kind.OBJECT_TYPE_DEFINITION,
name: {
kind: Kind.NAME,
value: typeName
},
fields: fields
}
}
/**
* Creates an input type definition node for the schema.
*
* @param fields the fields in the input type.
* @param typeName the name of the input type
* @returns an input type definition node defined by the provided fields and
*/
export function getInputTypeDefinition(fields: ReadonlyArray<InputValueDefinitionNode>, typeName: string): InputObjectTypeDefinitionNode {
return {
kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
name: {
kind: Kind.NAME,
value: typeName
},
fields: fields
}
}
/**
* Creates a name node for the schema.
*
* @param name the name of the name node.
* @returns the name node defined by the provided name.
*/
export function getNameNode(name: string): NameNode {
return {
kind: Kind.NAME,
value: name
}
}
/**
* Creates a list value node for the schema.
*
* @param values the list of values to be in the list node.
* @returns a list value node containing the provided values.
*/
export function getListValueNode(values: ReadonlyArray<ValueNode>): ListValueNode {
return {
kind: Kind.LIST,
values: values
}
}
/**
* Creates a simple string value node for the schema.
*
* @param value the value to be set in the string value node.
* @returns a fleshed-out string value node.
*/
export function getStringValueNode(value: string): StringValueNode {
return {
kind: Kind.STRING,
value: value
}
}
/**
* Creates a directive node for a subscription in the schema.
*
* @param mutationName the name of the mutation the subscription directive is for.
* @returns a directive node defining the subscription.
*/
export function getDirectiveNode(mutationName: string): DirectiveNode {
return {
kind: Kind.DIRECTIVE,
name: this.getNameNode('aws_subscribe'),
arguments: [this.getArgumentNode(mutationName)]
}
}
/**
* Creates an operation type definition (subscription, query, mutation) for the schema.
*
* @param operationType the type node defining the operation type.
* @param operation the named type node defining the operation type.
*/
export function getOperationTypeDefinition(operationType: OperationTypeNode, operation: NamedTypeNode): OperationTypeDefinitionNode {
return {
kind: Kind.OPERATION_TYPE_DEFINITION,
operation: operationType,
type: operation
}
}
/**
* Creates an argument node for a subscription directive within the schema.
*
* @param argument the argument string.
* @returns the argument node.
*/
export function getArgumentNode(argument: string): ArgumentNode {
return {
kind: Kind.ARGUMENT,
name: this.getNameNode('mutations'),
value: this.getListValueNode([this.getStringValueNode(argument)])
}
}
/**
* Given the DB type for a column, make a best effort to select the appropriate GraphQL type for
* the corresponding field.
*
* @param dbType the SQL column type.
* @returns the GraphQL field type.
*/
export function getGraphQLTypeFromMySQLType(dbType: string): string {
const normalizedType = dbType.toUpperCase().split("(")[0]
if (`BOOL` == normalizedType) {
return `Boolean`
} else if (`JSON` == normalizedType) {
return `AWSJSON`
} else if (`TIME` == normalizedType) {
return `AWSTime`
} else if (`DATE` == normalizedType) {
return `AWSDate`
} else if (`DATETIME` == normalizedType) {
return `AWSDateTime`
} else if (`TIMESTAMP` == normalizedType) {
return `AWSTimestamp`
} else if (intTypes.indexOf(normalizedType) > -1) {
return `Int`
} else if (floatTypes.indexOf(normalizedType) > -1) {
return `Float`
}
return `String`
}
| true |
0cb6c287dbc85d7e197dd1a2f83a71472060f8af
|
TypeScript
|
lifaon74/common-classes
|
/src/debug/observables-v4/observable/from/from-iterable/from-array.ts
|
UTF-8
| 533 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
import { IObservable, IObservableUnsubscribeFunction, Observable } from '../../../core/observable';
import { IObserver } from '../../../core/observer';
export function fromArray<GValue>(array: ArrayLike<GValue>): IObservable<GValue> {
return new Observable<GValue>((observer: IObserver<GValue>): IObservableUnsubscribeFunction => {
let running: boolean = true;
for (let i = 0, l = array.length; (i < l) && running; i++) {
observer.emit(array[i]);
}
return (): void => {
running = false;
};
});
}
| true |
409f530b31dabea057b2ae948dd33ce98085a3cb
|
TypeScript
|
atmajs/memd
|
/src/persistance/StoreWorker.ts
|
UTF-8
| 1,088 | 2.765625 | 3 |
[] |
no_license
|
import { ICacheEntry, ICacheOpts } from '../Cache';
import { IStore } from './IStore';
export class StoreWorker <T = any> {
public isAsync = false;
private doNotWaitSave = false;
constructor (private store: IStore, public options: ICacheOpts = {}) {
this.isAsync = this.store.getAsync != null
this.doNotWaitSave = options?.doNotWaitSave === true;
}
get?(key: string, ...args): ICacheEntry<T> {
return this.store.get(key);
}
getAsync?(key: string, ...args): Promise<ICacheEntry<T>> {
return this.store.getAsync(key, ...args);
}
save?(key: string, val: ICacheEntry<T>): void {
this.store.save(key, val);
}
saveAsync?(key: string, val: ICacheEntry<T>): Promise<void> {
let promise = this.store.saveAsync(key, val);
if (this.doNotWaitSave === true) {
return null;
}
return promise;
}
clear?(key: string): void {
this.store.clear(key);
}
clearAsync?(key: string): Promise<void> {
return this.store.clearAsync(key);
}
}
| true |
8cdf812a17d9278bd1bc5909f0ebc34f8c743bab
|
TypeScript
|
daimananshen/ProAngularExamples
|
/JavaScriptPrimer/usingTuples.ts
|
UTF-8
| 261 | 2.890625 | 3 |
[] |
no_license
|
import { TempConverter } from "./tempConverter";
let tuple: [string, string, string];
tuple = ["London", "raining", TempConverter.convertFtoC("38")];
console.log("----Using Tuples----");
console.log(`It is ${tuple[2]} degrees C and ${tuple[1]} in ${tuple[0]}`);
| true |
f03fe954e4ec4dc174fcfeee7b774c149238d57c
|
TypeScript
|
JVB-Dev/crud-users
|
/Node/server/src/controllers/UsersController.ts
|
UTF-8
| 2,999 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
import { json, Request, Response } from "express";
import { User } from "../models/User";
import query from "../database/DB";
class UsersController {
async Index(req: Request, res: Response) {
try {
const result = await query("SELECT * FROM usuarios ORDER BY ID");
return res.status(200).json(result.rows);
} catch (error) {
return res
.status(400)
.json({ message: `Occurred an error: ${error}`, error });
}
}
async Show(req: Request, res: Response) {
const id = req.params.id;
try {
const user: User = (
await query("SELECT * FROM usuarios WHERE ID = $1", [id])
).rows[0];
if (!user.id)
return res
.status(404)
.json({ message: `User with id: ${id} not found.` });
return res.status(200).json(user);
} catch (error) {
return res
.status(400)
.json({ message: `Occurred an error: ${error}`, error });
}
}
async Create(req: Request, res: Response) {
const { email, password, name } = req.body;
try {
const result = await query(
"INSERT INTO usuarios (EMAIL, PASSWORD, NAME) VALUES ($1, $2, $3)",
[email, password, name]
);
if (result.rowCount === 0)
return res
.status(400)
.json({ message: `An error was occurred, try again later.` });
return res.status(200).json({ message: "User has been created successfully." });
} catch (error) {
return res
.status(400)
.json({ message: `Occurred an error: ${error}`, error });
}
}
async Update(req: Request, res: Response) {
const id = req.params.id;
try {
let queryText = "UPDATE usuarios SET ";
let setParams: string[] = [];
let valueParams: any[] = [];
Object.keys(req.body).forEach(function (key, i) {
setParams.push(`${key} = $${i + 1}`);
valueParams.push(req.body[key]);
});
queryText += `${setParams.join(", ")} WHERE ID = ${id}`;
const result = await query(queryText, valueParams);
if (result.rowCount === 0)
return res
.status(400)
.json({ message: `An error was occurred, try again later.` });
return res.status(200).json({message: `User has been updated successfully.`});
} catch (error) {
return res
.status(400)
.json({ message: `Occurred an error: ${error}`, error });
}
}
async Delete(req: Request, res: Response) {
const id = req.params.id;
try {
const result = await query(`DELETE FROM usuarios WHERE ID = $1`, [id]);
if (result.rowCount === 0)
return res
.status(404)
.json({ message: `User with id: ${id} not found.` });
return res.status(200).json(`User has been removed successfully.`);
} catch (error) {
return res
.status(400)
.json({ message: `Occurred an error: ${error}`, error });
}
}
}
export default UsersController;
| true |
99155be10fd746eec2df2e25ceb480c96e7b0fde
|
TypeScript
|
colshacol/leenk
|
/source/client/shared/comps/Shortener/stores/ShortenerStore.ts
|
UTF-8
| 899 | 2.78125 | 3 |
[] |
no_license
|
import { observable, action, computed } from 'mobx'
import { createLink } from '../../../api/link/createLink'
export class ShortenerStore {
@observable inputValue: string = ''
@observable shortenedUrl: string = ''
@action updateInputValue = ({ target: { value }}) => {
this.inputValue = value
}
@action updateShortenedUrl = (value) => {
this.shortenedUrl = value
}
createLink = async (e) => {
if (e.key === 'Enter') {
const result = await createLink(this.inputValue)
// TODO: Present user with shortlink.
this.updateShortenedUrl(result.short)
}
}
@computed get inputValidity() {
return String(validateUrl(this.inputValue))
}
}
// TODO: Improve expression to match url.
const validateUrl = (url) => {
if (!url.length) return true
return /((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/g.test(url)
}
| true |
1d53860bd9cdb59148386ccac19e99cba6f3a05b
|
TypeScript
|
jdanyow/aurelia-converters-sample
|
/src/examples/6/sort.js
|
UTF-8
| 263 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
export class SortValueConverter {
toView(array, propertyName, direction) {
var factor = direction === 'ascending' ? 1 : -1;
return array
.slice(0)
.sort((a, b) => {
return (a[propertyName] - b[propertyName]) * factor
});
}
}
| true |
ebd4a162b454520ae72ddbadb2a9dd4d8d5b7589
|
TypeScript
|
TienCGC8JAVA/functions
|
/para.ts
|
UTF-8
| 815 | 3.796875 | 4 |
[] |
no_license
|
function userInfo1(name: string, age: number): string {
return `My name is ${name}, ${age} years old`;
}
console.log(userInfo1("john", 20));
function userInfo2(name: string = "anna", age: number = 69): string {
return `My name is ${name}, ${age} years old`;
}
console.log(userInfo2());
function userInfo3(name: string = "anna", age?: number): string {
if (age == null) {
return `My name is ${name}`;
}
return `My name is ${name}, ${age} years old`;
}
console.log(userInfo3());
console.log(userInfo3("henry", 23));
function totalLength(x: (string | any[]), y: (string[] | string)): number {
return x.length + y.length;
}
console.log(totalLength('abc', ['123']));
console.log(totalLength([1, 'abc', 'def'], ['123', 'abc']));
console.log(totalLength([1, 'abc', 'def'], 'def'));
| true |
9c446ba884e705d7911aae126fcf40e504a26dd0
|
TypeScript
|
green-fox-academy/ndndnd24
|
/lecture/week 2/day 10/hard_ones_sort_that_list.ts
|
UTF-8
| 2,333 | 4.125 | 4 |
[] |
no_license
|
// Create a function that takes a list of numbers as parameter
// Returns a list where the elements are sorted in ascending numerical order
// Make a second boolean parameter, if it's `true` sort that list descending
'use strict';
function bubble(input: number[]) {
let ascendingLine: number[] = [];
let x = 0;
let currentNumber: number = input[0];
let forLength: number = input.length;
for (let index: number = 0; index < forLength; index++) {
for (let i: number = 0; i < input.length; i++) {
if (currentNumber >= input[i]) {
currentNumber = input[i];
x = i;
}
}
input.splice(x, 1);
ascendingLine.push(currentNumber);
currentNumber = input[0];
}
console.log(ascendingLine);
}
function advancedBubble(input: number[], howToOrder: boolean) {
if (howToOrder = false) {
let ascendingLine: number[] = [];
let x = 0;
let currentNumber: number = input[0];
let forLength: number = input.length;
for (let index: number = 0; index < forLength; index++) {
for (let i: number = 0; i < input.length; i++) {
if (currentNumber >= input[i]) {
currentNumber = input[i];
x = i;
}
}
input.splice(x, 1);
ascendingLine.push(currentNumber);
currentNumber = input[0];
}
console.log(ascendingLine);
} else {
let ascendingLine: number[] = [];
let x = 0;
let currentNumber: number = input[0];
let forLength: number = input.length;
for (let index: number = 0; index < forLength; index++) {
for (let i: number = 0; i < input.length; i++) {
if (currentNumber <= input[i]) {
currentNumber = input[i];
x = i;
}
}
input.splice(x, 1);
ascendingLine.push(currentNumber);
currentNumber = input[0];
}
console.log(ascendingLine);
}
}
// Example:
bubble([4, 34, 12, 24, 9, 5]);
advancedBubble([34, 12, 24, 9, 5], true);
// should print [5, 9, 12, 24, 34]
//console.log(advancedBubble([34, 12, 24, 9, 5], true));
// should print [34, 24, 12, 9, 5]
| true |
d2b46f8f7c271d837987a3dde81cddcacd9fbd66
|
TypeScript
|
gleb-mihalkov/mst-playground
|
/src/consts/StorageKey.ts
|
UTF-8
| 530 | 2.5625 | 3 |
[] |
no_license
|
/**
* Ключ в localStorage.
*/
enum StorageKey {
/**
* Содержит токен для продления токена авторизации в RPC API.
*/
AUTH_TOKEN = 'auth_token',
/**
* Телефон, введённый при восстановлении пароля.
*/
RECOVERY_PHONE = 'recovery_phone',
/**
* Код подтверждения, введённый при восстановлении пароля.
*/
RECOVERY_CODE = 'recovery_code',
}
export default StorageKey;
| true |
cf2e5f9a03312b6576cb6e8b313953b98725e439
|
TypeScript
|
LYRA-Block-Lattice/lyra-api
|
/src/controllers/BlockController.ts
|
UTF-8
| 1,211 | 3.015625 | 3 |
[] |
no_license
|
import BlockModel, { IBlock } from "../models/BlockModel";
import { ApolloError } from "apollo-server";
/**
*
* @description holds crud operations for the Block entity
*/
/**
* gets all Blocks
* @param connection database connection
* @returns {IBlock[]} Block list
*/
export const getAllBlocks = async (connection) => {
let list: IBlock[];
try {
list = await BlockModel(connection).find();
if (list != null && list.length > 0) {
list = list.map((u) => {
var x = u.transform();
return x;
});
}
} catch (error) {
console.error("> getAllBlocks error: ", error);
throw new ApolloError("Error retrieving all Blocks");
}
return list;
};
/**
* gets Block by id
* @param connection database connection
* @param id Block id
* @returns {IBlock | null} Block or null
*/
export const getBlock = async (connection, id: string) => {
let Block: IBlock | null;
try {
Block = await BlockModel(connection).findById(id);
if (Block != null) {
Block = Block.transform();
}
} catch (error) {
console.error("> getBlock error: ", error);
throw new ApolloError("Error retrieving Block with id: " + id);
}
return Block;
};
| true |
865c2b624d874c2a539e7f92955040b7e3e7ccc1
|
TypeScript
|
Yupeng-li/redux-simple-state
|
/src/StateContainer.ts
|
UTF-8
| 1,715 | 2.65625 | 3 |
[] |
no_license
|
import ld from "lodash";
import { combineReducers } from "redux";
import { ActionConfig } from "./types/scheme";
import { LooseObject } from "./types/LooseObject";
import { AnyAction, Reducer } from "redux";
export default class StateContainer implements LooseObject {
_name: string;
_initialValue: any | undefined;
_parent: StateContainer | null;
_children: Array<StateContainer>;
_actions: Array<ActionConfig<any>>;
selector: ((state: any) => any | undefined) | null;
[extraProps: string]: any;
constructor(name: string, initialValue: any) {
this._name = name;
this._initialValue = initialValue;
this._parent = null;
this._children = [];
this.selector = null;
this._actions = [];
}
get _path(): string {
if (this._parent) {
return this._parent._path.concat(".", this._name);
} else {
return this._name;
}
}
get _reducer(): Reducer {
const self = this;
let reducerMap = self._actions.reduce((map: LooseObject, action) => {
let actionType = self._path.concat(".", action.name);
map[actionType] = action.reducer;
return map;
}, {});
let subReducerMap = self._children.reduce(
(subReducer: LooseObject, child) => {
subReducer[child._name] = child._reducer;
return subReducer;
},
{}
);
let subReducer = ld.isEmpty(subReducerMap)
? null
: combineReducers(subReducerMap);
return (state = self._initialValue, action: AnyAction) => {
let reducer = reducerMap[action.type];
if (reducer) {
return reducer(state, action);
} else if (subReducer) {
return subReducer(state, action);
} else return state;
};
}
}
| true |
d0148b166c7c1fe6cfa60d19c6417815d3f089c6
|
TypeScript
|
acecor-cotep/role-and-task
|
/lib/src/RoleSystem/Role/ARole.d.ts
|
UTF-8
| 1,967 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
/// <reference types="node" />
import Errors from '../../Utils/Errors.js';
import TaskHandler from '../Handlers/TaskHandler.js';
import ATask from '../Tasks/ATask.js';
export interface DisplayMessage {
str: string;
carriageReturn?: boolean;
out?: NodeJS.WriteStream;
from?: number | string;
time?: number;
tags?: string[];
}
export interface ArgsObject {
[key: string]: any;
}
/**
* PROGRAM process have 0 or + defined Role
*
* A Role can be described as a purpose to fulfill
*
* Example: Master or Slave -> (The purpose of Master is to manage Slave)
*
* A ROLE MUST BE DEFINED AS A SINGLETON (Which means the implementation of getInstance)
*
* A ROLE CAN BE APPLIED ONLY ONCE (Ex: You can apply the ServerAPI only once, can't apply twice the ServerAPI Role for a PROGRAM instance)
* @interface
*/
export default abstract class ARole {
name: string;
id: number;
protected active: boolean;
protected taskHandler: TaskHandler | false;
protected referenceStartTime: number;
constructor();
getReferenceStartTime(): number;
/**
* Setup a taskHandler to the role
* Every Role have its specific tasks
*/
setTaskHandler(taskHandler: TaskHandler | false): void;
getTaskHandler(): TaskHandler | false;
getTask(idTask: string): Promise<ATask>;
startTask(idTask: string, args: any): Promise<unknown>;
abstract displayMessage(param: DisplayMessage): Promise<void>;
stopTask(idTask: string): Promise<unknown>;
stopAllTask(): Promise<unknown>;
getTaskListStatus(): {
name: string;
id: string;
isActive: boolean;
}[] | Errors;
isActive(): boolean;
abstract start(...args: unknown[]): Promise<unknown>;
abstract stop(...args: unknown[]): Promise<unknown>;
buildHeadBodyMessage(head: string, body: unknown): string;
abstract takeMutex(id: string): Promise<void>;
abstract releaseMutex(id: string): Promise<void>;
}
| true |
21edba85bc1a53a5862c3be2906acc6e6033695a
|
TypeScript
|
gropax/ontos
|
/Ontos.Web/ClientApp/src/app/models/graph.ts
|
UTF-8
| 3,709 | 3.109375 | 3 |
[] |
no_license
|
export class Page {
constructor(
public id: string,
public content: string,
public type: string,
public references: Reference[] = []) {
}
}
export class PageType {
constructor(
public id: string,
public label: string,
public icon: string) {
}
public static UNKNOWN = new PageType("Unknown", "Unknown", "fas fa-question");
public static THEORY = new PageType("Theory", "Theory", "fas fa-atom");
public static CONCEPT = new PageType("Concept", "Concept", "far fa-lightbulb");
static all() {
return [
this.UNKNOWN,
this.THEORY,
this.CONCEPT
];
}
public static default = PageType.UNKNOWN;
public static parse(id: string) {
return this.all().find(pageType => pageType.id == id);
}
}
export class Reference {
constructor(
public id: number,
public pageId: number,
public expression: Expression) {
}
}
export class Expression {
constructor(
public id: number,
public language: string,
public label: string) {
}
}
export class Relation {
constructor(
public id: string,
public type: string,
public originId: string,
public targetId: string) {
}
}
export class RelatedPage {
constructor(
public id: string,
public type: string,
public originId: string,
public target: Page) {
}
}
export class RelationType {
constructor(
public label: string,
public directed: boolean,
public acyclic: boolean) {
}
public static INCLUSION = new RelationType('INCLUDE', true, true);
public static INTERSECTION = new RelationType('INTERSECT', false, false);
}
export class DirectedRelationType {
constructor(
public label: string,
public type: RelationType,
public reversed: boolean) {
}
public static INCLUDES = new DirectedRelationType("Includes", RelationType.INCLUSION, false);
public static INCLUDED_IN = new DirectedRelationType("Is included in", RelationType.INCLUSION, true);
public static INTERSECTS = new DirectedRelationType("Intersects", RelationType.INTERSECTION, false);
static all() {
return [this.INCLUDES, this.INCLUDED_IN, this.INTERSECTS];
}
}
export class NewPage {
constructor(
public content: string,
public expression: NewExpression = null) {
}
}
export class PageSearch {
constructor(
public language: string,
public text: string) {
}
}
export class PageSearchResult {
constructor(
public pageId: string,
public score: number,
public expressions: string[]) {
}
}
export class NewExpression {
constructor(
public language: string,
public label: string) {
}
}
export class NewReference {
constructor(
public pageId: number,
public expression: NewExpression) {
}
}
export class NewRelation {
constructor(
public type: RelationType,
public originId: string,
public targetId: string) {
}
public static create(type: DirectedRelationType, originId: string, targetId: string) {
if (type.reversed)
[originId, targetId] = [targetId, originId];
return new NewRelation(type.type, originId, targetId);
}
public toParams() {
return {
type: this.type.label, originId: this.originId, targetId: this.targetId,
};
}
}
export class NewRelatedPage {
constructor(
public type: DirectedRelationType,
public expression: NewExpression,
public content: string) {
}
public toParams() {
return {
type: this.type.type.label,
reversed: this.type.reversed,
expression: this.expression,
content: this.content,
};
}
}
export class UpdatePage {
constructor(
public id: string,
public content: string,
public type: string) {
}
}
| true |
2c5d25b8e4b93d016136c73dd875864333e9ba30
|
TypeScript
|
MartinBenjamin/AngularCore
|
/Web/ClientApp/src/app/Ontology/DLSafeRule.ts
|
UTF-8
| 17,186 | 2.609375 | 3 |
[] |
no_license
|
import { BuiltIn, Equal, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, NotEqual } from './Atom';
import { Axiom } from './Axiom';
import { EavStore } from './EavStore';
import { IAxiom } from "./IAxiom";
import { IClassExpression } from "./IClassExpression";
import { IClassExpressionSelector } from './IClassExpressionSelector';
import { IDataRange } from "./IDataRange";
import { IsConstant, IsVariable } from './IEavStore';
import { IIndividual } from "./IIndividual";
import { IOntology } from './IOntology';
import { IDataPropertyExpression, IObjectPropertyExpression, IPropertyExpression } from "./IPropertyExpression";
import { IPropertyExpressionSelector } from './IPropertyExpressionSelector';
import { Wrap, Wrapped, WrapperType } from './Wrapped';
// http://www.cs.ox.ac.uk/files/2445/rulesyntaxTR.pdf
/*
axioms ::= { Axiom | Rule | DGAxiom }
Rule ::= DLSafeRule | DGRule
DLSafeRule ::= DLSafeRule ‘(’ {Annotation} ‘Body’ ‘(’ {Atom} ‘)’
‘Head’ ‘(’ {Atom} ‘)’ ‘)’
Atom ::= ‘ClassAtom’ ‘(’ ClassExpression IArg ‘)’
| ‘DataRangeAtom’ ‘(’ DataRange DArg ‘)’
| ‘ObjectPropertyAtom’ ‘(’ ObjectPropertyExpression IArg IArg ‘)’
| ‘DataPropertyAtom’ ‘(’ DataProperty IArg DArg ‘)’
| ‘BuiltInAtom’ ‘(’ IRI DArg {DArg} ‘)’
| ‘SameIndividualAtom’ ‘(’ IArg IArg ‘)’
| ‘DifferentIndividualsAtom’ ‘(’ IArg IArg‘)’
IArg ::= IndividualID
| ‘IndividualVariable’ ‘(’ IRI ‘)’
DArg ::= Literal
| ‘LiteralVariable’ ‘(’ IRI ‘)’
DGRule ::= DescriptionGraphRule ‘(’ {Annotation} ‘Body’ ‘(’ {DGAtom} ‘)’
‘Head’ ‘(’ {DGAtom} ‘)’ ‘)’
DGAtom ::= ‘ClassAtom’ ‘(’ ClassExpression IArg ‘)’
| ‘ObjectPropertyAtom’ ‘(’ ObjectPropertyExpression IArg IArg ‘)’
DGAxiom ::= ‘DescriptionGraph’ ‘(’ {Annotation} DGName DGNodes
DGEdges MainClasses‘)’
DGName ::= IRI
DGNodes ::= ‘Nodes’‘(’ NodeAssertion {NodeAssertion } ‘)’
NodeAssertion ::= ‘NodeAssertion’‘(’ Class DGNode ‘)’
DGNode ::= IRI
DGEdges ::= ‘Edges’‘(’ EdgeAssertion {EdgeAssertion } ‘)’
EdgeAssertion ::= ‘EdgeAssertion’ ‘(’ ObjectProperty DGNode DGNode‘)’
MainClasses ::= ‘MainClasses’ ‘(’ Class {Class } ‘)’
*/
export type IndividualVariable = string;
export type IArg = IIndividual | IndividualVariable;
export type LiteralVariable = string;
export type DArg = any | LiteralVariable;
export type Arg = IArg | DArg;
export interface IAtom
{
Select<TResult>(selector: IAtomSelector<TResult>): TResult
}
export interface IDLSafeRule extends IAxiom
{
readonly Head: IAtom[],
readonly Body: IAtom[]
}
export interface IClassAtom extends IAtom
{
readonly ClassExpression: IClassExpression;
readonly Individual : IArg;
}
export interface IDataRangeAtom extends IAtom
{
readonly DataRange: IDataRange;
readonly Value : DArg;
}
export interface IPropertyAtom extends IAtom
{
readonly PropertyExpression: IPropertyExpression;
readonly Domain : IArg;
readonly Range : Arg;
}
export interface IObjectPropertyAtom extends IPropertyAtom
{
readonly ObjectPropertyExpression: IObjectPropertyExpression;
readonly Range : IArg;
}
export interface IDataPropertyAtom extends IPropertyAtom
{
readonly DataPropertyExpression: IDataPropertyExpression;
readonly Range : DArg;
}
export interface IComparisonAtom extends IAtom
{
readonly Lhs: Arg;
readonly Rhs: Arg;
}
export interface ILessThanAtom extends IComparisonAtom {};
export interface ILessThanOrEqualAtom extends IComparisonAtom {};
export interface IEqualAtom extends IComparisonAtom {};
export interface INotEqualAtom extends IComparisonAtom {};
export interface IGreaterThanOrEqualAtom extends IComparisonAtom {};
export interface IGreaterThanAtom extends IComparisonAtom {};
export interface IAtomSelector<TResult>
{
Class (class$ : IClassAtom ): TResult;
DataRange (dataRange : IDataRangeAtom ): TResult;
ObjectProperty (objectProperty : IObjectPropertyAtom ): TResult;
DataProperty (dataProperty : IDataPropertyAtom ): TResult;
LessThan (lessThan : ILessThanAtom ): TResult;
LessThanOrEqual (lessThanOrEqual : ILessThanOrEqualAtom ): TResult;
Equal (equal : IEqualAtom ): TResult;
NotEqual (notEqual : INotEqualAtom ): TResult;
GreaterThanOrEqual(greaterThanOrEqual: IGreaterThanOrEqualAtom): TResult;
GreaterThan (greaterThan : IGreaterThanAtom ): TResult;
}
export interface IDLSafeRuleBuilder
{
IndividualVariable(name: string): IndividualVariable;
LiteralVariable(name: string): LiteralVariable;
ClassAtom(ce: IClassExpression, individual: IArg): IClassAtom;
DataRangeAtom(dr: IDataRange, value: DArg): IDataRangeAtom;
ObjectPropertyAtom(ope: IObjectPropertyExpression, domain: IArg, range: IArg): IObjectPropertyAtom;
DataPropertyAtom(dpe: IDataPropertyExpression, domain: IArg, range: DArg): IDataPropertyAtom;
LessThan (lhs: Arg, rhs: Arg): ILessThanAtom ;
LessThanOrEqual (lhs: Arg, rhs: Arg): ILessThanOrEqualAtom ;
Equal (lhs: Arg, rhs: Arg): IEqualAtom ;
NotEqual (lhs: Arg, rhs: Arg): INotEqualAtom ;
GreaterThanOrEqual(lhs: Arg, rhs: Arg): IGreaterThanOrEqualAtom;
GreaterThan (lhs: Arg, rhs: Arg): IGreaterThanAtom ;
Rule(
head: IAtom[],
body: IAtom[]): IDLSafeRule;
}
export class DLSafeRuleBuilder implements IDLSafeRuleBuilder
{
constructor(
private _ontology: IOntology
)
{
}
IndividualVariable(
name: string
): string
{
return name;
}
LiteralVariable(
name: string
): string
{
return name;
}
ClassAtom(
ce : IClassExpression,
individual: IArg
): IClassAtom
{
return new ClassAtom(
ce,
individual);
}
DataRangeAtom(
dr : IDataRange,
value: DArg
): IDataRangeAtom
{
return new DataRangeAtom(
dr,
value);
}
ObjectPropertyAtom(
ope : IObjectPropertyExpression,
domain: IArg,
range : IArg
): IObjectPropertyAtom
{
return new ObjectPropertyAtom(
ope,
domain,
range);
}
DataPropertyAtom(
dpe : IDataPropertyExpression,
domain: IArg,
range : any
): IDataPropertyAtom
{
return new DataPropertyAtom(
dpe,
domain,
range);
}
LessThan(
lhs: any,
rhs: any
): ILessThanAtom
{
return new LessThanAtom(lhs, rhs);
}
LessThanOrEqual(
lhs: any,
rhs: any
): ILessThanOrEqualAtom
{
return new LessThanOrEqualAtom(lhs, rhs);
}
Equal(
lhs: any,
rhs: any
): IEqualAtom
{
return new EqualAtom(lhs, rhs);
}
NotEqual(
lhs: any,
rhs: any
): INotEqualAtom
{
const notEqual = {
Lhs: lhs,
Rhs: rhs,
Select: <TResult>(selector: IAtomSelector<TResult>): TResult => selector.NotEqual(notEqual)
};
return new NotEqualAtom(lhs, rhs);
}
GreaterThanOrEqual(
lhs: any,
rhs: any
): IGreaterThanOrEqualAtom
{
return new GreaterThanOrEqualAtom(lhs, rhs);
}
GreaterThan(
lhs: any,
rhs: any
): IGreaterThanAtom
{
return new GreaterThanAtom(lhs, rhs);
}
Rule(
head: IAtom[],
body: IAtom[]
): IDLSafeRule
{
return new DLSafeRule(
this._ontology,
head,
body);
}
}
export class ClassAtom implements IClassAtom
{
constructor(
public readonly ClassExpression: IClassExpression,
public readonly Individual : IArg
)
{
}
Select<TResult>(
selector: IAtomSelector<TResult>
): TResult
{
return selector.Class(this);
}
}
export class DataRangeAtom implements IDataRangeAtom
{
constructor(
public readonly DataRange: IDataRange,
public readonly Value : DArg
)
{
}
Select<TResult>(
selector: IAtomSelector<TResult>
): TResult
{
return selector.DataRange(this);
}
}
export abstract class PropertyAtom implements IPropertyAtom
{
constructor(
public readonly PropertyExpression: IPropertyExpression,
public readonly Domain : IArg,
public readonly Range : Arg
)
{
}
Select<TResult>(
selector: IAtomSelector<TResult>
): TResult
{
throw new Error("Method not implemented.");
}
}
export class ObjectPropertyAtom extends PropertyAtom implements IObjectPropertyAtom
{
constructor(
public readonly ObjectPropertyExpression: IObjectPropertyExpression,
domain : IArg,
public readonly Range : IArg
)
{
super(
ObjectPropertyExpression,
domain,
Range);
}
Select<TResult>(
selector: IAtomSelector<TResult>
): TResult
{
return selector.ObjectProperty(this);
}
}
export class DataPropertyAtom extends PropertyAtom implements IDataPropertyAtom
{
constructor(
public readonly DataPropertyExpression: IDataPropertyExpression,
domain : IArg,
public readonly Range : DArg
)
{
super(
DataPropertyExpression,
domain,
Range);
}
Select<TResult>(
selector: IAtomSelector<TResult>
): TResult
{
return selector.DataProperty(this);
}
}
export abstract class ComparisonAtom implements IComparisonAtom
{
constructor(
public Lhs: Arg,
public Rhs: Arg,
)
{
}
Select<TResult>(
selector: IAtomSelector<TResult>
): TResult
{
throw new Error("Method not implemented.");
}
}
export class LessThanAtom extends ComparisonAtom implements ILessThanAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.LessThan (this);}};
export class LessThanOrEqualAtom extends ComparisonAtom implements ILessThanOrEqualAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.LessThanOrEqual (this);}};
export class EqualAtom extends ComparisonAtom implements IEqualAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.Equal (this);}};
export class NotEqualAtom extends ComparisonAtom implements INotEqualAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.NotEqual (this);}};
export class GreaterThanOrEqualAtom extends ComparisonAtom implements IGreaterThanOrEqualAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.GreaterThanOrEqual(this);}};
export class GreaterThanAtom extends ComparisonAtom implements IGreaterThanAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.GreaterThan (this);}};
export class DLSafeRule extends Axiom implements IDLSafeRule
{
constructor(
ontology : IOntology,
public readonly Head: IAtom[],
public readonly Body: IAtom[]
)
{
super(ontology);
}
}
export function IsDLSafeRule(
axiom: any
): axiom is IDLSafeRule
{
return axiom instanceof DLSafeRule;
}
export interface ICache<TAtom>
{
Set(
atom : IAtom,
wrapped: TAtom): void;
Get(atom: IAtom): TAtom
}
export class AtomInterpreter<T extends WrapperType> implements IAtomSelector<Wrapped<T, object[] | BuiltIn>>
{
constructor(
protected _wrap : Wrap<T>,
private _propertyExpressionInterpreter: IPropertyExpressionSelector<Wrapped<T, [any, any][]>>,
private _classExpressionInterpreter : IClassExpressionSelector<Wrapped<T, Set<any>>>
)
{
}
Class(
class$: IClassAtom
): Wrapped<T, object[] | BuiltIn>
{
if(IsVariable(class$.Individual))
return this._wrap(
individuals => [...individuals].map(
individual =>
{
return { [<string>class$.Individual]: individual };
}),
class$.ClassExpression.Select(this._classExpressionInterpreter));
return this._wrap(
individuals => individuals.has(class$.Individual) ? [{}] : [],
class$.ClassExpression.Select(this._classExpressionInterpreter));
}
DataRange(
dataRange: IDataRangeAtom
): Wrapped<T, object[] | BuiltIn>
{
return this._wrap(() => (
substitutions: Iterable<object>
) =>
{
if(IsConstant(dataRange.Value))
return dataRange.DataRange.HasMember(dataRange.Value) ? substitutions : [];
return [...substitutions].filter(substitution => dataRange.DataRange.HasMember(substitution[dataRange.Value]));
});
}
ObjectProperty(
objectProperty: IObjectPropertyAtom
): Wrapped<T, object[] | BuiltIn>
{
return this.Property(objectProperty);
}
DataProperty(
dataProperty: IDataPropertyAtom
): Wrapped<T, object[] | BuiltIn>
{
return this.Property(dataProperty);
}
private Property(
property: IPropertyAtom
): Wrapped<T, object[]>
{
return this._wrap(
EavStore.Substitute([property.Domain, property.Range]),
property.PropertyExpression.Select(this._propertyExpressionInterpreter));
}
LessThan(
lessThan: ILessThanAtom
): Wrapped<T, object[] | BuiltIn>
{
return this._wrap(() => LessThan(lessThan.Lhs, lessThan.Rhs));
}
LessThanOrEqual(
lessThanOrEqual: ILessThanOrEqualAtom
): Wrapped<T, object[] | BuiltIn>
{
return this._wrap(() => LessThanOrEqual(lessThanOrEqual.Lhs, lessThanOrEqual.Rhs));
}
Equal(
equal: IEqualAtom
): Wrapped<T, object[] | BuiltIn>
{
return this._wrap(() => Equal(equal.Lhs, equal.Rhs));
}
NotEqual(
notEqual: INotEqualAtom
): Wrapped<T, object[] | BuiltIn>
{
return this._wrap(()=> NotEqual(notEqual.Lhs, notEqual.Rhs));
}
GreaterThanOrEqual(
greaterThanOrEqual: IGreaterThanOrEqualAtom
): Wrapped<T, object[] | BuiltIn>
{
return this._wrap(() => GreaterThanOrEqual(greaterThanOrEqual.Lhs, greaterThanOrEqual.Rhs));
}
GreaterThan(
greaterThan: IGreaterThanAtom
): Wrapped<T, object[] | BuiltIn>
{
return this._wrap(() => GreaterThan(greaterThan.Lhs, greaterThan.Rhs));
}
Atoms(
atoms: IAtom[]
): Wrapped<T, object[]>
{
return this._wrap(
EavStore.Conjunction(),
...atoms.map(atom => atom.Select(this)));
}
}
export function RuleContradictionInterpreter<T extends WrapperType>(
wrap : Wrap<T>,
interpreter: AtomInterpreter<T>
): (rule: IDLSafeRule) => Wrapped<T, object[]>
{
return (rule: IDLSafeRule) => wrap(
(head, body) => body.reduce<object[]>(
(failed, x) =>
{
if(!head.some(y =>
{
for(const key in x)
if(key in y && x[key] !== y[key])
return false;
return true;
}))
failed.push(x);
return failed;
},
[]),
interpreter.Atoms(rule.Head),
interpreter.Atoms(rule.Body));
}
| true |
9a20819af0b0fcc15d693977866d31b820588a59
|
TypeScript
|
rafaelssp/TestHelloMedtime
|
/TestHelloMedtime/src/app/components/ficha/filtro-nome.pipe.ts
|
UTF-8
| 421 | 2.515625 | 3 |
[] |
no_license
|
import { Pipe, PipeTransform } from '@angular/core';
import { FichaComponent } from '../../components/ficha/ficha.component';
@Pipe({
name: 'filtraFichaNome',
pure: false
})
export class FiltroNomePipe implements PipeTransform {
transform(fichas: FichaComponent[], nome: string): FichaComponent[] {
nome = nome.toUpperCase();
return fichas.filter(f => f.nomeCompleto.toUpperCase().includes(nome));
}
}
| true |
87e52e9eba09796d61ee50f1c1fc970042f82681
|
TypeScript
|
liuheyu/typescript_RPC_demo
|
/src/rpc.ts
|
UTF-8
| 1,895 | 3.578125 | 4 |
[
"Apache-2.0"
] |
permissive
|
/** ═════════🏳🌈 超轻量级的远程调用,完备的类型提示! 🏳🌈═════════ */
import type * as apis from "./apis";
type apis = typeof apis;
type method = keyof apis;
/** Remote call , 会就近的选择是远程调用还是使用本地函数 */
export function RC<K extends method>(
method: K,
data: Parameters<apis[K]>,
): Promise<unPromise<ReturnType<apis[K]>>> {
//@ts-ignore
if (process.browser === true) {
return fetch("/rpc", {
method: "POST",
body: JSON.stringify({ method, data }),
headers: {
"content-type": "application/json",
},
}).then((r) => r.json());
} else {
//@ts-ignore
return import("./apis/index").then(async (r: any) => {
return await r[method](...data);
});
}
}
/** 解开 promise 类型包装 */
declare type unPromise<T> = T extends Promise<infer R> ? R : T;
// 示例 1 直接使用 RC
RC("currentTime", []).then((r) => console.log("服务器当前时间", r));
RC("currentTime2", [true]).then((r) => console.log("服务器当前时间本地化", r));
/** 包装了一次的 RC 方便跳转到函数定义 */
export const API = new Proxy(
{},
{
get(target, p: method) {
return (...arg: any) => RC(p, arg);
},
},
) as apisPromiseify;
/** apis 中包含的方法可能不是返回 promise 的,但 RC 调用后的一定是返回 promsie */
type apisPromiseify = {
readonly [K in keyof apis]: (
...arg: Parameters<apis[K]>
) => Promise<unPromise<ReturnType<apis[K]>>>;
};
// 示例 2 通过 API 对象调用对应方法,这里的优点是可以直接跳转到对应函数的源码处
API.currentTime().then((r) => console.log("服务器当前时间", r));
API.currentTime2(true).then((r) => console.log("服务器当前时间本地化", r));
| true |
a46e3a9701a3c23a35d6cd20b7acba2f9d7e2cb0
|
TypeScript
|
jesus-crysist/text-highlighter
|
/src/app/state/text-highlighter-store.service.spec.ts
|
UTF-8
| 2,593 | 2.640625 | 3 |
[] |
no_license
|
import { TestBed } from '@angular/core/testing';
import { Action, ActionTypes } from 'src/app/state/actions';
import { HighlightModel, INITIAL_STATE } from 'src/app/state/state';
import { TextHighlighterStore } from 'src/app/state/text-highlighter-store.service';
const highlightMocks = [
{ color: 'red', text: 'brown fox'},
{ color: 'green', text: 'lazy dog'}
];
describe('TextHighlighterStore', () => {
let service: TextHighlighterStore;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [TextHighlighterStore]
});
service = TestBed.get(TextHighlighterStore);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should contain "state$" Observables and initial value', () => {
expect(service.state$).toBeDefined();
expect(service.state$.subscribe).toBeDefined();
expect(service.state).toEqual(INITIAL_STATE);
});
it('should be able to get Observable for single property', () => {
expect(service.getValueState('pickedColor').subscribe).toBeTruthy();
});
it('should dispatch "ColorAddValues" action', () => {
const colors = ['red', 'yellow', 'green'];
service.dispatch(new Action(ActionTypes.ColorAddValues, colors));
expect(service.state.colors).toBe(colors);
expect(service.state.pickedColor).toBeNull();
expect(service.state.highlights.length).toBe(0);
});
it('should dispatch "ColorPicked" action', () => {
const pickedColor = 'blue';
service.dispatch(new Action(ActionTypes.ColorPicked, pickedColor));
expect(service.state.pickedColor).toBe(pickedColor);
expect(service.state.highlights.length).toBe(0);
});
it('should dispatch "HighlightAddValues" action', () => {
service.dispatch(new Action(ActionTypes.HighlightAddValues, highlightMocks));
expect(service.state.highlights.length).toBe(2);
expect(service.state.pickedColor).toBeNull();
});
it('should dispatch "HighlightAdd" action', () => {
const highlightedText = new HighlightModel('quick brown fox', 'blue');
service.dispatch(new Action(ActionTypes.HighlightAdd, highlightedText));
expect(service.state.highlights[0]).toEqual(highlightedText);
expect(service.state.pickedColor).toBeNull();
});
it('should dispatch "HighlightRemove" action', () => {
service.dispatch(new Action(ActionTypes.HighlightAddValues, highlightMocks));
service.dispatch(new Action(ActionTypes.HighlightRemove, highlightMocks[1]));
expect(service.state.highlights.length).toEqual(1);
expect(service.state.pickedColor).toBeNull();
});
});
| true |
b5ae9a61c6b23e5d3684297700594d9f001271c7
|
TypeScript
|
stjordanis/snyk-gradle-plugin
|
/lib/errors/missing-sub-project-error.ts
|
UTF-8
| 488 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
export class MissingSubProjectError extends Error {
public name = 'MissingSubProjectError';
public subProject: string;
public allProjects: string[];
constructor(subProject: string, allProjects: string[]) {
super(
`Specified sub-project not found: "${subProject}". ` +
`Found these projects: ${allProjects.join(', ')}`,
);
this.subProject = subProject;
this.allProjects = allProjects;
Error.captureStackTrace(this, MissingSubProjectError);
}
}
| true |
581fc9c836ce80c75e5c6f5bed29b47a6c204bf9
|
TypeScript
|
Leies-202/ai
|
/src/serifs.ts
|
UTF-8
| 13,390 | 3 | 3 |
[
"MIT"
] |
permissive
|
// せりふ
export default {
core: {
setNameOk: (name) => `わかった!これからは${name}って呼ぶね!`,
san: "さん付けした方がいい?(「はい」か「いいえ」で答えてね〜)",
yesOrNo: "「はい」か「いいえ」しかわからないよ...",
hello: (name) => (name ? `こんにちは、${name}♪` : `こんにちは♪`),
helloNight: (name) => (name ? `こんばんは、${name}♪` : `こんばんは♪`),
goodMorning: (tension, name) =>
name ? `おはよう、${name}!${tension}` : `おはよう!${tension}`,
/*
goodMorning: {
normal: (tension, name) => name ? `おはよう、${name}!${tension}` : `おはよう!${tension}`,
hiru: (tension, name) => name ? `おはよう、${name}!${tension}もうお昼だよ?${tension}` : `おはよう!${tension}もうお昼だよ?${tension}`,
},
*/
goodNight: (name) =>
name ? `おやすみ、${name}!いい夢見てね〜` : "おやすみ!いい夢見てね〜",
omedeto: (name) => (name ? `ありがとう、${name}♪` : "ありがとう♪"),
erait: {
general: (name) =>
name
? [`${name}、今日もえらい!`, `${name}、今日もえらいね~♪`]
: [`今日もえらい!`, `今日もえらいね~♪`],
specify: (thing, name) =>
name
? [`${name}、${thing}てえらい!`, `${name}、${thing}てえらいね~♪`]
: [`${thing}てえらい!`, `${thing}てえらいね~♪`],
specify2: (thing, name) =>
name
? [`${name}、${thing}でえらい!`, `${name}、${thing}でえらいね~♪`]
: [`${thing}でえらい!`, `${thing}でえらいね~♪`],
},
okaeri: {
love: (name) =>
name
? [`おかえり、${name}♪`, `おかえりなさいっ、${name}っ。`]
: [
"おかえり♪ゆっくり休んでね〜♪",
"おかえりなさいっ、ご主人様っ。ゆっくり休んでね〜♪",
],
love2: (name) =>
name
? `おっかえり~${name}っっ!!!ゆっくり休んでね!`
: "おっかえり~ご主人様っっ!!!ゆっくり休んでね!",
normal: (name) => (name ? `おかえり、${name}!` : "おかえり!"),
},
itterassyai: {
love: (name) =>
name
? `いってらっしゃい、${name}♪気をつけてね〜。`
: "いってらっしゃい♪気をつけてね〜。",
normal: (name) =>
name ? `いってらっしゃい、${name}!` : "いってらっしゃい!",
},
tooLong: "長すぎるよ〜...",
invalidName: "うーん、ちょっと発音が難しいなぁ…",
requireMoreLove: "もっと仲良くなったら考えてあげる〜",
nadenade: {
normal: "ひゃっ…! びっくりした~",
love2: ["わわっ… 恥ずかしいよぉ", "あうぅ… 恥ずかしいなぁ…"],
love3: [
"んぅ… ありがとう♪",
"わっ、なんだか落ち着く♪",
"くぅんっ… 安心するなぁ…",
"眠くなってきちゃった…",
],
hate1: "…っ! やめて...",
hate2: "触らないでっ!",
hate3: "近寄らないでっ!",
hate4: "やめて...通報するよ?",
},
kawaii: {
normal: ["ありがとう♪", "(照れちゃう…)"],
love: ["嬉しい♪", "(そ、そんなの照れちゃう…)"],
hate: "…ありがとう",
},
suki: {
normal: "えっ… ありがとう…♪",
love: (name) => `私もその… ${name}のこと好きだよ!`,
hate: null,
},
hug: {
normal: "ぎゅー...",
love: "ぎゅーっ♪",
hate: "離れて...",
},
humu: {
love: "え、えっと…… ふみふみ……… どう…?",
normal: "えぇ... それはちょっと...",
hate: "……",
},
batou: {
love: "えっと…、お、おバカっ!!!",
normal: "(じとー…)",
hate: "…頭大丈夫?",
},
itai: (name) =>
name
? `${name}、大丈夫…? いたいのいたいの飛んでけ~!`
: "大丈夫…? いたいのいたいの飛んでけ~!",
ote: {
normal: "くぅん... 私わんちゃんじゃないよ...?",
love1: "わん!",
love2: "わんわん♪",
},
shutdown: "私まだ眠くないよ...?",
transferNeedDm: "わかったけど...それはチャットで話さない?",
transferCode: (code) => `わかった!\n合言葉は「${code}」だよ!`,
transferFailed: "うーん、合言葉が間違ってなぁい?",
transferDone: (name) =>
name ? `はっ...! おかえり、${name}!` : `はっ...! おかえり!`,
},
keyword: {
learned: (word, reading) => `(${word}..... ${reading}..... 覚えたっ!)`,
remembered: (word) => `${word}`,
},
dice: {
done: (res) => `${res} だよ!`,
},
birthday: {
happyBirthday: (name) =>
name ? `お誕生日おめでとう、${name}🎉` : "お誕生日おめでとう🎉",
},
/**
* リバーシ
*/
reversi: {
/**
* リバーシへの誘いを承諾するとき
*/
ok: "いいよ~",
/**
* リバーシへの誘いを断るとき
*/
decline:
"ごめんなさい、マスターに今リバーシはしちゃダメって言われてるの...",
/**
* 対局開始
*/
started: (name, strength) => `対局を${name}と始めたよ! (強さ${strength})`,
/**
* 接待開始
*/
startedSettai: (name) => `(${name}の接待を始めたよ)`,
/**
* 勝ったとき
*/
iWon: (name) => `${name}に勝ったよ♪`,
/**
* 接待のつもりが勝ってしまったとき
*/
iWonButSettai: (name) => `(${name}に接待で勝っちゃった...)`,
/**
* 負けたとき
*/
iLose: (name) => `${name}に負けちゃった...`,
/**
* 接待で負けてあげたとき
*/
iLoseButSettai: (name) => `(${name}に接待で負けてあげたよ...♪)`,
/**
* 引き分けたとき
*/
drawn: (name) => `${name}と引き分けたよ~`,
/**
* 接待で引き分けたとき
*/
drawnSettai: (name) => `(${name}に接待で引き分けちゃった...)`,
/**
* 相手が投了したとき
*/
youSurrendered: (name) => `${name}が投了しちゃった`,
/**
* 接待してたら相手が投了したとき
*/
settaiButYouSurrendered: (name) =>
`(${name}を接待していたら投了されちゃった... ごめんなさい)`,
},
/**
* 数当てゲーム
*/
guessingGame: {
/**
* やろうと言われたけど既にやっているとき
*/
alreadyStarted: "え、ゲームは既に始まってるよ!",
/**
* タイムライン上で誘われたとき
*/
plzDm: "メッセージでやろうねっ!",
/**
* ゲーム開始
*/
started: "0~100の秘密の数を当ててみて♪",
/**
* 数字じゃない返信があったとき
*/
nan: "数字でお願い!「やめる」と言ってゲームをやめることもできるよ!",
/**
* 中止を要求されたとき
*/
cancel: "わかった~。ありがとう♪",
/**
* 小さい数を言われたとき
*/
grater: (num) => `${num}より大きいよ`,
/**
* 小さい数を言われたとき(2度目)
*/
graterAgain: (num) => `もう一度言うけど${num}より大きいよ!`,
/**
* 大きい数を言われたとき
*/
less: (num) => `${num}より小さいよ`,
/**
* 大きい数を言われたとき(2度目)
*/
lessAgain: (num) => `もう一度言うけど${num}より小さいよ!`,
/**
* 正解したとき
*/
congrats: (tries) => `正解🎉 (${tries}回目で当てたよ)`,
},
/**
* 数取りゲーム
*/
kazutori: {
alreadyStarted: "今ちょうどやってるよ~",
matakondo: "また今度やろっ!",
intro: (minutes) =>
`みんな~!数取りゲームしよう!\n0~100の中で最も大きい数字を取った人が勝ちだよ!他の人と被ったらだめだよ~\n制限時間は${minutes}分!数字はこの投稿にリプライで送ってね!`,
finish: "ゲームの結果発表~!!",
finishWithWinner: (user, name) =>
name
? `今回は${user}さん(${name})の勝ち!またやろっ♪`
: `今回は${user}さんの勝ち!またやろっ♪`,
finishWithNoWinner: "今回は勝者はいなかったよ... またやろっ♪",
onagare: "参加者が集まらなかったからお流れになっちゃった...",
},
/**
* 絵文字生成
*/
emoji: {
suggest: (emoji) => `こんなのはどう?→${emoji}`,
},
/**
* 占い
*/
fortune: {
cw: (name) =>
name
? `私が今日の${name}の運勢を占ったよ...`
: "私が今日の君の運勢を占ったよ...",
},
/**
* タイマー
*/
timer: {
set: "計るね~",
invalid: "うーん...?",
tooLong: "長すぎるよ…",
notify: (time, name) =>
name ? `${name}、${time}経ったよ!` : `${time}経ったよ!`,
},
/**
* リマインダー
*/
reminder: {
invalid: "うーん...?",
reminds: "やること一覧だよっ!",
notify: (name) => (name ? `${name}、これやった?` : `これやった覚えある?`),
notifyWithThing: (thing, name) =>
name ? `${name}、「${thing}」やった?` : `「${thing}」やった覚えある?`,
done: (name) =>
name
? [
`よく出来たね、${name}♪`,
`${name}、さすがっ!`,
`${name}、えら~い!`,
]
: [`よく出来たね♪`, `さすがっ!`, `えらい...!`],
cancel: `はーい、消しておくね~`,
},
/**
* バレンタイン
*/
valentine: {
chocolateForYou: (name) =>
name
? `${name}、その... チョコレート作ったからどうぞ!🍫`
: "チョコレート作ったからよかったらどうぞ!🍫",
},
server: {
cpu: "あっつ~い…サーバーの負荷が高いよ~",
},
maze: {
post: "今日の迷路だよ! #AiMaze",
foryou: "描いたよ!",
},
chart: {
post: "インスタンスの投稿数だよ!",
foryou: "描いたよ!",
},
sleepReport: {
report: (hours) => `んぅ、${hours}時間くらい寝ちゃってたみたい...`,
reportUtatane: "ん... うたた寝しちゃってたぁ...",
},
noting: {
notes: [
"ゴロゴロ…",
"ちょっと眠い~",
"いいよ?",
"(。´・ω・)?",
"ふぇー",
"あれ…これをこうして…あれ~?",
"ぼー…",
"ふぅ…疲れたぁ~",
"味噌汁、作る?",
"ご飯にする?お風呂にする?",
"ふぇぇぇぇぇぇ!?",
"みすきーって、かわいい名前だねっ!",
"うぅ~、リバーシ難しい…",
"失敗しても、次に活かせたらオッケー!",
"なんだか、おなか空いてきちゃった♪",
"掃除は、定期的にしないとダメだよ~?",
"今日もお勤めご苦労様! 私も頑張るよ~♪",
"えっと、あれ、何しようとしたっけ…?",
"おうちがいちばん、落ち着くよ~",
"疲れたら、私がなでなでしてあげる♪",
"離れていても、心はそばに♪",
"衣亜だよ〜",
"わんちゃん可愛い!",
"ぷろぐらむ?",
"ごろーん…",
"なにもしてないのに、パソコンが壊れちゃった…",
"お布団に食べられちゃった",
"寝ながら見てるよ~",
"念力で操作してるよ~",
"仮想空間から投稿してるよ~",
"しっぽはないよ?",
"え、抗逆コンパイル性って、なに?",
"Misskeyの制服、かわいくて好きだな♪",
"ふわぁ、おふとん気持ちいいなぁ...",
"挨拶ができる人間は開発もできる!…って、syuiloさんが言ってたらしいよ",
"ふえぇ、どこ見てるの?",
"私を覗くとき、私もまた君を覗いているのだ...なんて♪",
"くぅ~ん...",
"All your note are belong to me!",
"せっかくだから、私はこの赤の扉を選ぶよっ!",
"よしっ",
"( ˘ω˘)スヤァ",
"(`・ω・´)シャキーン",
"Misskey開発者の朝は遅いらしいよ",
"の、のじゃ...",
"にゃんにゃんお!",
"上から来るよ!気をつけて!",
`🐡( '-' 🐡 )フグパンチ!!!!`,
"ごろん…",
"ふわぁ...",
"あぅ",
"ふみゃ〜",
"ふぁ… ねむねむ~",
'ヾ(๑╹◡╹)ノ"',
'私の"インスタンス"を周囲に展開して分身するのが特技!\n人数分のエネルギー消費があるから、4人くらいが限界なんだけど',
"うとうと...",
"ふわー、メモリが五臓六腑に染み渡る…",
],
want: item => `${item}、欲しいなぁ...`,
see: item => `お散歩していたら、道に${item}が落ちているのを見たよ!`,
expire: item => `気づいたら、${item}の賞味期限が切れてたよ…`,
f1: item => `今日は、${item}の紹介をするよ~。`,
f2: item => `${item}おいしい!`,
f3: item => `フォロワーさんに${item}をもらったよ。ありがとう!`,
},
};
export function getSerif(variant: string | string[]): string {
if (Array.isArray(variant)) {
return variant[Math.floor(Math.random() * variant.length)];
} else {
return variant;
}
}
| true |
3365baecd2fdd92ae2ac30debd524d6a5cdc92ab
|
TypeScript
|
ATS-UAE/car-rental-management-utils
|
/src/utils/MathUtils.ts
|
UTF-8
| 176 | 2.765625 | 3 |
[] |
no_license
|
export abstract class MathUtils {
public static rangeOverlap = (
x1: number,
x2: number,
y1: number,
y2: number
): boolean => Math.max(x1, y1) <= Math.min(x2, y2);
}
| true |
86c5f99844d730ee5794757319f542ee266e2f72
|
TypeScript
|
liangskyli/test
|
/config/init.ts
|
UTF-8
| 841 | 2.765625 | 3 |
[] |
no_license
|
//构建初始化前,没有local.config.js文件,要创建文件
//解决umi构建前会解析所有路径文件是否存在(尽管在函数中动态引用了并没有使用到的文件)
const fs = require('fs');
const initLocalConfigJsFile = () => {
const configPath = './local.config.js';
try {
const isExist = fs.existsSync(configPath);
if (!isExist) {
const jsTemplate = `module.exports = {
serverProxy: '',// 接口代理host配置
// mock数据开关,true 全部开启,false关闭,也可以传对象{}
mock: false,
// exclude,格式为 Array(string),用于忽略不需要走 mock 的文件
/* mock: {
exclude: ['mock/api.ts'],
} */
};`;
fs.writeFileSync(configPath, jsTemplate);
}
} catch (e) {
console.log(e);
process.exit();
}
};
initLocalConfigJsFile();
| true |
87b2b36e6ca3bf5deca638d114d6aa8c11db613b
|
TypeScript
|
El-kady/design_patterns_in_typescript
|
/Bridge.ts
|
UTF-8
| 1,290 | 2.9375 | 3 |
[] |
no_license
|
var mysql = require('mysql');
var mongojs = require('mongojs');
interface DbEngine {
insert(table,data);
}
class MysqlMan implements DbEngine {
connection;
constructor(config) {
this.connection = mysql.createConnection({
host: config.host,
user: config.user,
password: config.password,
database: config.database
});
}
insert(table,data) {
let query = this.connection.query('INSERT INTO '+table+' SET ?', data, function (error, results, fields) {
if (error) throw error;
});
console.log(query.sql);
}
}
class MongodbMan implements DbEngine {
db;
constructor(config) {
this.db = mongojs('mongodb://'+config.host+':'+config.port+'/' + config.database);
}
insert(table,data) {
this.db[table].insert(data)
}
}
class DbMan {
engine: DbEngine;
constructor(_engine) {
this.engine = _engine;
}
insert(table,data) {
this.engine.insert(table,data);
}
}
//let db = new DbMan(new MysqlMan({host: "localhost", user: "root", password: "123456", database: "test"}));
let db = new DbMan(new MongodbMan({host: "localhost", port: 27017, database: "test"}));
db.insert("test",{name : "insert test"});
| true |
99d94a893b48e7afd2f463944cce05bea6b1d3a7
|
TypeScript
|
tkrotoff/react-form-with-constraints
|
/packages/react-form-with-constraints/src/Field.test.ts
|
UTF-8
| 7,966 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
import { Field } from './Field';
import { FieldFeedbackType } from './FieldFeedbackType';
import { FieldFeedbackValidation } from './FieldFeedbackValidation';
test('constructor()', () => {
const field = new Field('password');
expect(field).toEqual({
name: 'password',
validations: []
});
});
// Validations rules for a password: not empty, minimum length, should contain letters, should contain numbers
const validation_empty: FieldFeedbackValidation = {
key: '0.0',
type: FieldFeedbackType.Error,
show: true
};
const validation_length: FieldFeedbackValidation = {
key: '0.1',
type: FieldFeedbackType.Error,
show: true
};
const validation_letters: FieldFeedbackValidation = {
key: '1.0',
type: FieldFeedbackType.Warning,
show: true
};
const validation_numbers: FieldFeedbackValidation = {
key: '1.1',
type: FieldFeedbackType.Warning,
show: true
};
test('addOrReplaceValidation()', () => {
const field = new Field('password');
field.addOrReplaceValidation(validation_empty);
field.addOrReplaceValidation(validation_length);
field.addOrReplaceValidation(validation_letters);
field.addOrReplaceValidation(validation_numbers);
expect(field).toEqual({
name: 'password',
validations: [validation_empty, validation_length, validation_letters, validation_numbers]
});
const validation_empty2: FieldFeedbackValidation = {
key: validation_empty.key,
type: validation_empty.type,
show: false
};
field.addOrReplaceValidation(validation_empty2);
expect(field).toEqual({
name: 'password',
validations: [validation_empty2, validation_length, validation_letters, validation_numbers]
});
const validation_length2: FieldFeedbackValidation = {
key: validation_length.key,
type: validation_length.type,
show: false
};
field.addOrReplaceValidation(validation_length2);
expect(field).toEqual({
name: 'password',
validations: [validation_empty2, validation_length2, validation_letters, validation_numbers]
});
});
test('clearValidations()', () => {
const field = new Field('password');
field.addOrReplaceValidation(validation_empty);
field.addOrReplaceValidation(validation_length);
field.addOrReplaceValidation(validation_letters);
field.addOrReplaceValidation(validation_numbers);
expect(field.validations).toEqual([
validation_empty,
validation_length,
validation_letters,
validation_numbers
]);
field.clearValidations();
expect(field).toEqual({
name: 'password',
validations: []
});
});
test('has*() + isValid()', () => {
const field = new Field('password');
expect(field.validations).toEqual([]);
expect(field.hasErrors()).toEqual(false);
expect(field.hasErrors('0')).toEqual(false);
expect(field.hasErrors('1')).toEqual(false);
expect(field.hasWarnings()).toEqual(false);
expect(field.hasWarnings('0')).toEqual(false);
expect(field.hasWarnings('1')).toEqual(false);
expect(field.hasInfos()).toEqual(false);
expect(field.hasInfos('0')).toEqual(false);
expect(field.hasInfos('1')).toEqual(false);
expect(field.hasFeedbacks()).toEqual(false);
expect(field.hasFeedbacks('0')).toEqual(false);
expect(field.hasFeedbacks('1')).toEqual(false);
expect(field.isValid()).toEqual(true);
field.addOrReplaceValidation(validation_empty);
field.addOrReplaceValidation(validation_length);
field.addOrReplaceValidation(validation_letters);
field.addOrReplaceValidation(validation_numbers);
expect(field.validations).toEqual([
validation_empty,
validation_length,
validation_letters,
validation_numbers
]);
expect(field.hasErrors()).toEqual(true);
expect(field.hasErrors('0')).toEqual(true);
expect(field.hasErrors('1')).toEqual(false);
expect(field.hasWarnings()).toEqual(true);
expect(field.hasWarnings('0')).toEqual(false);
expect(field.hasWarnings('1')).toEqual(true);
expect(field.hasInfos()).toEqual(false);
expect(field.hasInfos('0')).toEqual(false);
expect(field.hasInfos('1')).toEqual(false);
expect(field.hasFeedbacks()).toEqual(true);
expect(field.hasFeedbacks('0')).toEqual(true);
expect(field.hasFeedbacks('1')).toEqual(true);
expect(field.isValid()).toEqual(false);
const validation_empty2: FieldFeedbackValidation = {
key: validation_empty.key,
type: validation_empty.type,
show: false
};
field.addOrReplaceValidation(validation_empty2);
expect(field.validations).toEqual([
validation_empty2,
validation_length,
validation_letters,
validation_numbers
]);
expect(field.hasErrors()).toEqual(true);
expect(field.hasErrors('0')).toEqual(true);
expect(field.hasErrors('1')).toEqual(false);
expect(field.hasWarnings()).toEqual(true);
expect(field.hasWarnings('0')).toEqual(false);
expect(field.hasWarnings('1')).toEqual(true);
expect(field.hasInfos()).toEqual(false);
expect(field.hasInfos('0')).toEqual(false);
expect(field.hasInfos('1')).toEqual(false);
expect(field.hasFeedbacks()).toEqual(true);
expect(field.hasFeedbacks('0')).toEqual(true);
expect(field.hasFeedbacks('1')).toEqual(true);
expect(field.isValid()).toEqual(false);
const validation_length2: FieldFeedbackValidation = {
key: validation_length.key,
type: validation_length.type,
show: false
};
field.addOrReplaceValidation(validation_length2);
expect(field.validations).toEqual([
validation_empty2,
validation_length2,
validation_letters,
validation_numbers
]);
expect(field.hasErrors()).toEqual(false);
expect(field.hasErrors('0')).toEqual(false);
expect(field.hasErrors('1')).toEqual(false);
expect(field.hasWarnings()).toEqual(true);
expect(field.hasWarnings('0')).toEqual(false);
expect(field.hasWarnings('1')).toEqual(true);
expect(field.hasInfos()).toEqual(false);
expect(field.hasInfos('0')).toEqual(false);
expect(field.hasInfos('1')).toEqual(false);
expect(field.hasFeedbacks()).toEqual(true);
expect(field.hasFeedbacks('0')).toEqual(false);
expect(field.hasFeedbacks('1')).toEqual(true);
expect(field.isValid()).toEqual(true);
const validation_letters2: FieldFeedbackValidation = {
key: validation_letters.key,
type: validation_letters.type,
show: false
};
field.addOrReplaceValidation(validation_letters2);
expect(field.validations).toEqual([
validation_empty2,
validation_length2,
validation_letters2,
validation_numbers
]);
expect(field.hasErrors()).toEqual(false);
expect(field.hasErrors('0')).toEqual(false);
expect(field.hasErrors('1')).toEqual(false);
expect(field.hasWarnings()).toEqual(true);
expect(field.hasWarnings('0')).toEqual(false);
expect(field.hasWarnings('1')).toEqual(true);
expect(field.hasInfos()).toEqual(false);
expect(field.hasInfos('0')).toEqual(false);
expect(field.hasInfos('1')).toEqual(false);
expect(field.hasFeedbacks()).toEqual(true);
expect(field.hasFeedbacks('0')).toEqual(false);
expect(field.hasFeedbacks('1')).toEqual(true);
expect(field.isValid()).toEqual(true);
const validation_numbers2: FieldFeedbackValidation = {
key: validation_numbers.key,
type: validation_numbers.type,
show: false
};
field.addOrReplaceValidation(validation_numbers2);
expect(field.validations).toEqual([
validation_empty2,
validation_length2,
validation_letters2,
validation_numbers2
]);
expect(field.hasErrors()).toEqual(false);
expect(field.hasErrors('0')).toEqual(false);
expect(field.hasErrors('1')).toEqual(false);
expect(field.hasWarnings()).toEqual(false);
expect(field.hasWarnings('0')).toEqual(false);
expect(field.hasWarnings('1')).toEqual(false);
expect(field.hasInfos()).toEqual(false);
expect(field.hasInfos('0')).toEqual(false);
expect(field.hasInfos('1')).toEqual(false);
expect(field.hasFeedbacks()).toEqual(false);
expect(field.hasFeedbacks('0')).toEqual(false);
expect(field.hasFeedbacks('1')).toEqual(false);
expect(field.isValid()).toEqual(true);
});
| true |
968e25139ba60a59af9a408f7ae9485d4ade1132
|
TypeScript
|
artifact-project/octologger
|
/src/logger/logger.ts
|
UTF-8
| 7,287 | 2.5625 | 3 |
[] |
no_license
|
import { Entry, ScopeEntry, LoggerOptions, LoggerAPI, LoggerFactoryAPI, Logger, LoggerContext, LoggerScope, LoggerScopeContext, ContextSnapshot, EntryMeta, ScopeExecutor, SCOPE, ENTRY } from './logger.types';
import { universalOutput } from '../output/output';
import { now } from '../utils/utils';
const time = new Date();
let cid = 0;
type CompactMetaArg = [string, number, number];
function isMeta(arg: any): arg is CompactMetaArg {
return arg && arg.length === 3 && arg[0] && arg[1] > 0 && arg[2] > 0;
}
function toMeta(arg: CompactMetaArg): EntryMeta {
return {file: arg[0], line: arg[1], col: arg[2]};
}
export function isLogEntry(x: any): x is Entry {
return x && x.type !== void 0 && x.level !== void 0;
}
export function createEntry(
level: Entry['level'],
badge: Entry['badge'],
label: Entry['label'],
message: Entry['message'],
detail: Entry['detail'],
): Entry {
return {
cid: ++cid,
ts: 0,
type: ENTRY,
level,
badge,
label,
message,
detail,
meta: null,
parent: null,
entries: [],
};
}
export function createScopeEntry(
level: Entry['level'],
badge: Entry['badge'],
label: Entry['label'],
message: Entry['message'],
detail: Entry['detail'],
): ScopeEntry {
return {
cid: ++cid,
ts: 0,
level: level,
type: SCOPE,
badge,
label,
parent: null,
message,
detail,
meta: null,
entries: [],
}
}
let _activeContext: LoggerContext<any> | null = null;
export function getLoggerContext(): LoggerContext<any> | null {
return _activeContext;
}
export function switchLoggerContext(ctx: LoggerContext<any>, scope: LoggerScope<any>): ContextSnapshot | null {
if (ctx === null) {
_activeContext = null;
return null;
}
const prev_activeContext = _activeContext;
const prev_scope = ctx.scope;
const prev_scopeContext = ctx.scopeContext;
let prev_scopeContextParent: ScopeEntry | null = null;
_activeContext = ctx;
ctx.scope = scope;
if (ctx.scopeContext) {
prev_scopeContextParent = ctx.scopeContext.parent;
ctx.scopeContext.parent = scope.scope();
}
return {
activeContext: prev_activeContext,
ctx,
scope: prev_scope,
scopeContext: prev_scopeContext,
scopeContextParent: prev_scopeContextParent,
};
}
export function revertLoggerContext(snapshot: ContextSnapshot) {
const {
ctx,
scopeContext,
} = snapshot;
ctx.scope = snapshot.scope;
ctx.scopeContext = scopeContext;
if (scopeContext) {
scopeContext.parent = snapshot.scopeContextParent;
}
_activeContext = snapshot.activeContext;
}
export function createLogger<LA extends LoggerAPI>(
options: Partial<LoggerOptions>,
factory: (api: LoggerFactoryAPI) => LA,
): Logger<LA> {
const createCoreLogger = (ctx: LoggerScopeContext) => ({
add(message: string | Entry, detail?: any): Entry {
let entry: Entry;
if (isLogEntry(message)) {
entry = message;
} else {
entry = createEntry(
'log',
null,
null,
message,
detail,
);
}
const {detail:args} = entry;
if (args && args.length && isMeta(args[0])) {
entry.meta = toMeta(args.shift());
}
if (options.time) {
entry.ts = now();
}
const parent = ctx.parent;
if (parent) {
const length = (entry.parent = parent).entries.push(entry);
if (length > options.storeLast!) {
parent.entries.splice(0, 1);
}
}
if (options.silent !== true && options.output) {
options.output(entry);
}
return entry;
},
});
const root = createScopeEntry('info', '🚧', '#root', 'root', {
time,
created: new Date(),
});
const _activeScopeContext: LoggerScopeContext = {
logger: null,
parent: root,
};
const logger = createCoreLogger(_activeScopeContext);
const api = factory({
createEntry,
logger,
}) as Logger<LA> & {
m: EntryMeta | null;
};
if (options.silent == null && typeof location !== 'undefined') {
options.silent = !/^(about:|file:|https?:\/\/localhost\/)/.test(location + '');
}
if (options.time == null) {
options.time = true;
}
if (options.storeLast == null) {
options.storeLast = 1e3;
}
_activeScopeContext.logger = logger;
// Reserved methods
['add', 'clear', 'scope', 'setup', 'entries', 'last', 'priny', 'm'].forEach((name) => {
if (api.hasOwnProperty(name)) {
throw new Error(`[octoLogger] "${name}" is a reserved identifier`);
}
});
api.print = () => {
function next(root: Entry & {printed?: boolean}) {
root.printed = false;
root.entries.forEach((entry: Entry & {printed?: boolean}) => {
entry.printed = false;
options.output && options.output(entry);
if (entry.type === SCOPE) {
next(entry);
}
});
}
next(root);
// Close all groups
options.output && options.output(null);
};
api.add = (...args: any[]) => logger.add(createEntry('log', null, null, null, args));
api.clear = () => root.entries.splice(0, root.entries.length);
api.setup = (optionsPatch: Partial<LoggerOptions>) => {
for (let key in optionsPatch) {
if (optionsPatch.hasOwnProperty(key)) {
options[key] = optionsPatch[key];
}
}
};
api.entries = () => root.entries;
api.last = () => root.entries[root.entries.length - 1] || null;
api.scope = function scopeCreator(
this: Logger<LA>,
message?: string | Entry,
detail?: any,
executor?: ScopeExecutor<LA, LoggerScope<LA>>,
) {
const args = arguments;
let meta: EntryMeta | null = null;
if (args.length === 0) {
return (this as any)._scopeEntry;
}
const firstArg = args[0];
if (isMeta(firstArg)) {
meta = toMeta(firstArg);
message = args[1];
detail = args[2];
executor = args[3];
}
if (executor == null && typeof detail === 'function') {
executor = detail;
detail = null;
}
const scopeEntry = isLogEntry(message) ? message : createScopeEntry(
'info',
null,
null,
message,
detail,
);
scopeEntry.meta = meta;
_activeScopeContext.logger!.add(scopeEntry);
const logger = createCoreLogger({parent: scopeEntry, logger: null});
const scopeAPI: any = factory({
createEntry,
logger,
});
scopeAPI.add = (...args: any[]) => logger.add(createEntry('log', null, null, null, args));
scopeAPI.scope = scopeCreator;
(scopeAPI as any)._scopeEntry = scopeEntry;
// Переключаем scope
if (typeof executor === 'function') {
const prev_activeContext = _activeContext;
const prev_parentEntry = _activeScopeContext.parent;
const prev_parentLogger = _activeScopeContext.logger;
_activeContext = {
entry: scopeEntry,
scope: scopeAPI as LoggerScope<LA>,
logger,
options,
scopeContext: _activeScopeContext
};
_activeScopeContext.parent = scopeEntry;
executor(scopeAPI);
_activeContext = prev_activeContext;
_activeScopeContext.parent = prev_parentEntry;
_activeScopeContext.logger = prev_parentLogger;
}
return scopeAPI;
};
return api;
}
const BADGES = {
log: null,
info: '❕',
done: '✅',
warn: '⚠️',
error: '🛑',
verbose: '🔎',
};
export const logger = createLogger({
output: universalOutput(),
}, ({logger}) => Object.keys(BADGES).reduce((api, level) => {
api[level] = (...args: any[]) => {
logger.add(createEntry(level, BADGES[level] || null, null, null, args));
};
return api;
}, {}) as {
[K in (keyof typeof BADGES)]: (...args: any[]) => void;
});
| true |
d4cb6fbd5d44cbe59dbc2186bddc26ca494286e8
|
TypeScript
|
miltone92/Design-Patterns-Game
|
/DesignPatterns/Iterator/Concrete/ConcreteIterator.ts
|
UTF-8
| 899 | 3.359375 | 3 |
[] |
no_license
|
class ConcreteIterator implements IIterator {
container: ConcreteContainer;
currentPosition = 0;
first() {
let obj = null;
if (this.container.data.length != 0) {
this.currentPosition = 0;
obj = this.container.data[0];
}
return obj;
}
next() {
let obj = null;
if (this.currentPosition < this.container.data.length) {
obj = this.container.data[this.currentPosition];
this.currentPosition++;
}
return obj;
}
current() {
let obj = null;
if (this.currentPosition < this.container.data.length) {
obj = this.container.data[this.currentPosition];
}
return obj;
}
hasMore(): boolean {
let hasMore = false;
if (this.currentPosition < this.container.data.length) {
hasMore = true;
}
return hasMore;
}
constructor(container: ConcreteContainer) {
this.container = container;
}
}
| true |
0aca5c4895f894f43e7c28d0077e6cb34c0b6caf
|
TypeScript
|
Prashoon123/ChatCube
|
/hooks/useDarkMode.ts
|
UTF-8
| 592 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
import { useEffect, useState } from "react";
const useDarkMode = () => {
const [theme, setTheme] = useState<"light" | "dark">(
typeof window !== "undefined" ? localStorage.theme : "dark"
);
const colorTheme = theme === "dark" ? "light" : "dark";
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove(colorTheme);
root.classList.add(theme);
if (typeof window !== "undefined") {
localStorage.setItem("theme", theme);
}
}, [theme, colorTheme]);
return [colorTheme, setTheme];
};
export default useDarkMode as any;
| true |
db7a10b3beea10cbe66ba4d08fd4fd0567b16943
|
TypeScript
|
ccamateur/money-machine
|
/backend/FinancialGraphs/FinancialCostFunctions/FeeCostFunction.ts
|
UTF-8
| 1,027 | 3.34375 | 3 |
[] |
no_license
|
import {CostFunction} from "../../GraphAlgorithms/CostFunctions/CostFunction";
import {CurrencyEdge} from "../CurrencyEdge";
/**
* FeeCostFunction
*
* Returns the fee cost of an edge as its cost function
*/
export class FeeCostFunction implements CostFunction {
/**
* amountBps
*
* The amount of money to calculate fee cost with;
* Some fees are proportional to transaction size, so
* this amount is required
*
* Example: $1,000 -> 10,000,000 pips (USD bps)
*/
private amountBps: number;
/**
* getEdgeCost()
*
* Returns the time cost of an edge as its cost function
*
* @param {CurrencyEdge} e the edge to consider
* @returns {number} e.getTimeEstimateSec()
*/
public getEdgeCost(e: CurrencyEdge) : number {
return e.calculateEdgeOutcome(this.getAmountBps());
}
constructor(amountBps: number) {
this.amountBps = amountBps;
}
public getAmountBps() : number {
return this.amountBps;
}
}
| true |
9ba594f2d0d2c19c48eb30ec3fc89c8c36e12e9e
|
TypeScript
|
jaydh/enen
|
/frontend/src/reducers/graphData.ts
|
UTF-8
| 711 | 2.640625 | 3 |
[] |
no_license
|
import produce from "immer";
import parseUri from "../helpers/parseURI";
export interface IArticle {
id: string;
link: string;
addedAt: Date;
metadata?: any;
HTMLData?: string;
}
export default (state = { domains: {} }, action: any) =>
produce(state, draft => {
switch (action.type) {
case "GET_ARTICLES_FULFILLED":
draft.domains = {};
action.articles.forEach((article: IArticle) => {
const val =
(article.metadata &&
(article.metadata.ogSiteName || article.metadata.siteName)) ||
(parseUri(article.link) as any).authority;
draft.domains[val] = draft.domains[val] + 1 || 1;
});
break;
}
});
| true |
fe33d2aaaabbeb9b77a7fc3bd670dfc4cd2b8229
|
TypeScript
|
Priyanka-behera-2000/meanApr19
|
/empApp/src/app/services/emp.service.ts
|
UTF-8
| 420 | 2.59375 | 3 |
[] |
no_license
|
import { Injectable } from '@angular/core';
import { Emp } from '../modals/emp.modal';
@Injectable()
export class EmpService {
//static variabe to be used for emp id
static counter:number=1;
//Array of emp objects.
empList:Emp[];
constructor() {
this.empList=Array();
}
//to add Emp objects to the array
add(emp:Emp)
{
emp.id= EmpService.counter++;
this.empList.push(emp);
}
}
| true |
d18410b29ff2f6b135e57cbdf2aea465ea9ff363
|
TypeScript
|
tcom-software/laitKlimat
|
/store/actions/products.ts
|
UTF-8
| 543 | 2.578125 | 3 |
[] |
no_license
|
// action types
export const types = {
ADD_NEW_CACHE: "products/ADD_NEW_CACHE",
REMOVE_CACHE_BY_KEY: "products/REMOVE_CACHE_BY_KEY",
CLEAR_CACHE: "products/CLEAR_CACHE",
};
// action creators
/// cahche
export const addProductsCache = (key: any, value: any) => ({
type: types.ADD_NEW_CACHE,
payload: { key, value },
});
export const removeProductsCacheByKey = (key: any) => ({
type: types.REMOVE_CACHE_BY_KEY,
payload: key,
});
export const clearProductsCache = () => ({
type: types.CLEAR_CACHE,
});
| true |
85e6a95557ed640c617bcc0ba0a1e5aa5e8af623
|
TypeScript
|
heloisagabrielle/typescript
|
/typeStructures.ts
|
UTF-8
| 722 | 3.8125 | 4 |
[] |
no_license
|
//Aplicação de TypeScript em algumas estruturas
//Variável
let nome: string = 'Pedro Braga';
console.log(nome);
//Array
let games: string[] = ['TLOU2', 'GOW4','Goat simulator', 'Bomba Patch', 'Apex', 'KOF', 'Warzone']
console.log(games)
//Objeto
let carro: {
nome:string
ano: number
preco: number
};
carro = {nome:'Gol Quadrado', ano: 1994, preco: 15 }
console.log(carro);
//Function
function multiplicarNumero(num1: number, num2:number){
return num1 * num2;
}
console.log(multiplicarNumero(2,5))
carro = {nome:'HB20', ano:2015, preco:15}
console.log(carro);
//Function
function multiplicar(n1:number, n2:number){
return n1 * n2;
}
console.log(multiplicar(15,4));
| true |
c5d010baf62aa9691001239c672645eefe884e55
|
TypeScript
|
VunboYao/readBook
|
/TypeScript/Stydy_TypeScript/src/js/48-映射类型下.ts
|
UTF-8
| 789 | 3.671875 | 4 |
[] |
no_license
|
{
/*
* Pick映射类型
* 将原有类型中的部分内容映射到新类型中
* */
interface TestInterface {
name: string
age: number
}
type MyType = Pick<TestInterface, 'name'>
}
{
/*
* Record映射类型
* 他会将一个类型的所有属性值都映射到另一个类型上并创造一个新的类型
* */
type Animal = 'person' | 'dog' | 'cat'
interface TestInterface {
name: string
age: number
}
type MyType = Record<Animal, TestInterface>
let res: MyType = {
person: {
name: 'zs',
age: 18
},
dog: {
name: 'zs',
age: 18
},
cat: {
name: 'zs',
age: 18
}
}
}
| true |
8013213cf6416e986e958c60a8fbe7e1492cb7a3
|
TypeScript
|
khbrst/es-practice
|
/src/rxjs/operators/filtering/find.ts
|
UTF-8
| 230 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
// RxJS v6+
import { from } from 'rxjs';
import { find } from 'rxjs/operators';
const source = from([1, 2, 3, 4, 5]);
const example = source.pipe(find(x => x === 3));
example.subscribe(val => console.log(`Found value: ${val}`));
| true |
f632773602d8c5cc970a01498024e66a0bd0e6f5
|
TypeScript
|
gamejolt/client-voodoo
|
/src/selfupdater.ts
|
UTF-8
| 1,430 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import fs from './fs';
import { Controller, Events } from './controller';
import { ControllerWrapper } from './controller-wrapper';
import { Manifest } from './data';
export abstract class SelfUpdater {
static async attach(manifestFile: string): Promise<SelfUpdaterInstance> {
const manifestStr = await fs.readFile(manifestFile, 'utf8');
const manifest: Manifest = JSON.parse(manifestStr);
if (!manifest.runningInfo) {
throw new Error(`Manifest doesn't have a running info, cannot connect to self updater`);
}
const controller = new Controller(manifest.runningInfo.port, {
process: manifest.runningInfo.pid,
keepConnected: true,
});
controller.connect();
return new SelfUpdaterInstance(controller);
}
}
export type SelfUpdaterEvents = Events;
export class SelfUpdaterInstance extends ControllerWrapper<SelfUpdaterEvents> {
constructor(controller: Controller) {
super(controller);
}
async checkForUpdates(options?: { authToken?: string; metadata?: string }) {
options = options || {};
const result = await this.controller.sendCheckForUpdates(
'',
'',
options.authToken,
options.metadata
);
return result.success;
}
async updateBegin() {
const result = await this.controller.sendUpdateBegin();
return result.success;
}
async updateApply() {
const result = await this.controller.sendUpdateApply(process.env, process.argv.slice(2));
return result.success;
}
}
| true |
15628db7def2b557f50cf22703dd2b1633a2954f
|
TypeScript
|
KrakerXyz/hook.events
|
/web/src/services/useCodeMirror.ts
|
UTF-8
| 2,816 | 2.6875 | 3 |
[] |
no_license
|
import { Ref, onUnmounted, ref, isRef, watch } from 'vue';
import { loadCodeMirrorAsync } from './loadScript';
export enum CodeMirrorLanguage {
Javascript = 'javascript',
Json = 'json',
Html = 'xml',
Text = 'text'
}
export async function useCodeMirrorAsync(target: string | HTMLElement, readonly: Ref<boolean> | boolean = false, value: Ref<string> | string, language: CodeMirrorLanguage = CodeMirrorLanguage.Javascript): Promise<CodeMirror.Editor> {
console.assert(value !== undefined);
let editor: CodeMirror.Editor | null = null;
onUnmounted(() => {
if (!editor) { return; }
editor.getWrapperElement().remove();
});
await loadCodeMirrorAsync();
target = (typeof target === 'string' ? document.getElementById(target)! : target);
console.assert(!!target, 'codemirror target not found');
const languageOptions: any = { mode: { name: language } };
if (language === CodeMirrorLanguage.Json) {
languageOptions.mode.name = CodeMirrorLanguage.Javascript;
languageOptions.mode.json = true;
} else if (language === CodeMirrorLanguage.Html) {
languageOptions.mode.htmlMode = true;
} else if (language === CodeMirrorLanguage.Text) {
languageOptions.mode = null;
}
editor = (window as any).CodeMirror(target, {
...languageOptions,
theme: 'material-palenight',
lineNumbers: true,
styleActiveLine: true,
matchBrackets: true,
lineWrapping: true,
scrollbarStyle: 'simple',
indentUnit: 3,
tabSize: 3,
autoCloseBrackets: true,
foldGutter: true,
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter']
});
const readonlyRef: Ref<boolean> = (isRef(readonly) ? readonly : ref(readonly));
watch(() => readonlyRef.value, ro => {
editor!.setOption('readOnly', ro);
}, { immediate: true });
editor!.setOption('extraKeys', {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
'Shift-Alt-F': function (cm: any) {
//TODO: Add autoformat
//Codemirror remove it's autoformat so the best option now is to use this https://github.com/beautify-web/js-beautify
//we'll then do cm.setValue(js_beautify(cm.getValue()))
}
});
if (typeof value === 'string') {
editor!.setValue(value);
} else {
let lastValue = '';
watch(() => value.value, newValue => {
if ((newValue || '') === (lastValue || '')) {
return;
}
editor!.setValue(newValue);
lastValue = newValue;
}, { immediate: true });
editor!.on('change', () => {
const newValue = editor!.getValue();
if (newValue === lastValue) { return; }
value.value = newValue;
lastValue = newValue;
});
}
return editor!;
}
| true |
c50c9ef76498e90af5aed32cca7294d211bdf558
|
TypeScript
|
taylorjg/continuo-app
|
/src/components/fullscreen.ts
|
UTF-8
| 3,548 | 2.53125 | 3 |
[] |
no_license
|
import RexUIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin'
import { SceneWithRexUI } from '../types'
import * as ui from '../ui'
export class Fullscreen {
private scene: SceneWithRexUI
private sizer: RexUIPlugin.Sizer
private enterFullscreenButton: RexUIPlugin.Label
private leaveFullscreenButton: RexUIPlugin.Label
public constructor(scene: SceneWithRexUI, sizer: RexUIPlugin.Sizer) {
this.scene = scene
this.sizer = sizer
this.enterFullscreenButton = null
this.leaveFullscreenButton = null
if (this.scene.sys.game.device.fullscreen.available) {
this.scene.input.on(Phaser.Input.Events.GAMEOBJECT_DOWN, (
_pointer: Phaser.Input.Pointer,
gameObject: Phaser.GameObjects.GameObject,
_event: Phaser.Types.Input.EventData
) => {
switch (gameObject.name) {
case 'enterFullscreenButton': return this.onEnterFullscreenClick()
case 'leaveFullscreenButton': return this.onLeaveFullscreenClick()
}
})
const onResize = () => this.resize()
window.addEventListener('resize', onResize)
this.resize()
}
}
private isFullscreen() {
const windowWidth = window.innerWidth
const windowHeight = window.innerHeight
const screenWidth = window.screen.availWidth
const screenHeight = window.screen.availHeight
return windowWidth == screenWidth || windowHeight == screenHeight
}
private resize(): void {
if (this.isFullscreen() != this.scene.scale.isFullscreen) {
if (this.isFullscreen()) {
// Looks like we have entered fullscreen via F11/browser menu
this.hideButtons()
} else {
// Looks like we have exited fullscreen via F11/browser menu
this.showButtons()
}
} else {
this.showButtons()
}
}
private showButtons() {
this.hideButtons()
if (this.scene.scale.isFullscreen) {
if (!this.leaveFullscreenButton) {
this.leaveFullscreenButton = this.makeLeaveFullscreenButton()
this.sizer.add(this.leaveFullscreenButton).layout()
}
} else {
if (!this.enterFullscreenButton) {
this.enterFullscreenButton = this.makeEnterFullscreenButton()
this.sizer.add(this.enterFullscreenButton).layout()
}
}
}
private hideButtons() {
if (this.enterFullscreenButton) {
this.sizer.remove(this.enterFullscreenButton, true).layout()
this.enterFullscreenButton = null
}
if (this.leaveFullscreenButton) {
this.sizer.remove(this.leaveFullscreenButton, true).layout()
this.leaveFullscreenButton = null
}
}
private makeEnterFullscreenButton(): RexUIPlugin.Label {
return ui.createHUDSceneButton(this.scene, 'enterFullscreenButton', 'arrows-out', .4)
}
private makeLeaveFullscreenButton(): RexUIPlugin.Label {
return ui.createHUDSceneButton(this.scene, 'leaveFullscreenButton', 'arrows-in', .4)
}
private onEnterFullscreenClick(): void {
this.scene.scale.startFullscreen()
this.leaveFullscreenButton = this.makeLeaveFullscreenButton()
this.sizer
.remove(this.enterFullscreenButton, true)
.add(this.leaveFullscreenButton)
.layout()
this.enterFullscreenButton = null
}
private onLeaveFullscreenClick(): void {
this.scene.scale.stopFullscreen()
this.enterFullscreenButton = this.makeEnterFullscreenButton()
this.sizer
.remove(this.leaveFullscreenButton, true)
.add(this.enterFullscreenButton)
.layout()
this.leaveFullscreenButton = null
}
}
| true |
1aed7e3e85c7c1ab0597921f074e598f967e2f6d
|
TypeScript
|
kld87/ng-catering
|
/src/app/classes/ingredient.ts
|
UTF-8
| 114 | 2.625 | 3 |
[
"ISC"
] |
permissive
|
export class Ingredient {
id: number;
name: string;
isSpicy = false;
isGluten = false;
isMeat = false;
}
| true |
75535847987672118f4037b4ebfc3d6607ae48e3
|
TypeScript
|
ioanachiorean/fav-movie
|
/src/app/post-component/post-component.component.ts
|
UTF-8
| 1,629 | 2.53125 | 3 |
[] |
no_license
|
import { Component, OnInit, Input } from '@angular/core';
import { PostService } from './services/post.service';
@Component({
selector: 'post-component',
templateUrl: './post-component.component.html',
styleUrls: ['./post-component.component.css']
})
export class PostComponentComponent implements OnInit {
public post: any[] = [];
private url = 'https://jsonplaceholder.typicode.com/posts';
constructor(private service: PostService) {
}
ngOnInit():void {
this.service.getPosts()
.subscribe(response => {
this.post = response;
},
error => {
alert('An unexpected error occurred.');
console.log(error);
});
}
createPost(input: HTMLInputElement) {
let post: any ={ title: input.value };
input.value = '';
this.service.createPostService(post)
.subscribe((response: any) => {
post.id = response.id;
this.post.splice(0, 0 , post);
},
error => {
alert('An unexpected error occurred.');
});
}
deletePost(post: any){
this.service.deletePostService(345)
.subscribe(response=> {
let index = this.post.indexOf(post);
this.post.splice(index, 1);
},
(error:Response) => {
if (error.status === 404)
alert('This post has already been deleted.')
else {
alert('An unexpected error occurred.');
console.log(error);
}
});
}
// updatePost(post: any){
// this.http.patch(this.url + '/' + post.id, JSON.stringify({ isRead : true }))
// .subscribe(response =>{
// console.log(response);
// })
// }
}
| true |
8986d46ff66b11867a7be667735e92bf1c8b023d
|
TypeScript
|
rvalimaki/joulukalenteri
|
/src/app/app.component.ts
|
UTF-8
| 4,223 | 2.765625 | 3 |
[] |
no_license
|
import {Component, HostBinding, OnInit} from '@angular/core';
class Star {
constructor(public x: number, public y: number, public dx: number, public dy: number) {
}
move() {
this.x += this.dx;
this.y += this.dy;
}
rewind() {
this.x -= this.dx;
this.y -= this.dy;
}
}
@Component({
selector: 'app-root',
template: `
<div class="blur" [style.background-image]="background"></div>
<h1>Advent of Code: {{latestSolutionName.replace('solve', '')}}</h1>
<textarea id="input" name="input" #input></textarea>
<textarea *ngIf="debugStr" id="debug" name="debug">{{debugStr}}</textarea>
<div class="solution">
<span>{{solution}}</span>
<button (click)="solve(input.value).then()">Solve</button>
</div>
`,
styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
solution = '';
debugStr = null;
backgroundImageUrl = '';
solvingTickerInterval;
static parseStar(str: string): Star {
const parts = str
.replace(/ /g, '')
.replace(/</g, ',')
.replace(/>/g, ',')
.split(',');
return new Star(
parseInt(parts[1], 10),
parseInt(parts[2], 10),
parseInt(parts[4], 10),
parseInt(parts[5], 10)
);
}
@HostBinding('style.background-image')
get background(): string {
return 'url(' + this.backgroundImageUrl + ')';
}
constructor() {
}
ngOnInit() {
const input = localStorage.getItem('kalenteriInput');
const inputElement = document.getElementById('input');
if (inputElement != null) {
inputElement['value'] = input;
}
if (input !== '') {
this.solve(input).then();
}
}
get latestSolutionName(): string {
const numSolutions = 25;
const letters = ['b', 'a'];
for (let i = numSolutions; i > 0; i--) {
for (const letter of letters) {
const fName = 'solve' + i + letter;
if (this[fName] !== undefined) {
return fName;
}
}
}
}
async solve(input: string) {
this.solveStart();
const rand = Math.ceil(Math.random() * 25);
this.backgroundImageUrl = 'https://newevolutiondesigns.com/images/freebies/christmas-wallpaper-' + rand + '.jpg';
localStorage.setItem('kalenteriInput', input);
const solution = await this[this.latestSolutionName](input);
this.solveFinish(solution);
}
// noinspection JSMethodCanBeStatic, JSUnusedGlobalSymbols
async solve10a(input: string) {
const stars: Star[] = input.split('\n')
.map(str => AppComponent.parseStar(str));
let prevminy = 0;
let prevmaxy = 0;
let minx = 0;
let maxx = 0;
let miny = 0;
let maxy = 0;
this.debugStr = '';
let ii = 0;
for (; ii < 10000000; ii++) {
minx = Number.MAX_SAFE_INTEGER;
maxx = Number.MIN_SAFE_INTEGER;
miny = Number.MAX_SAFE_INTEGER;
maxy = Number.MIN_SAFE_INTEGER;
for (const s of stars) {
s.move();
minx = Math.min(minx, s.x);
miny = Math.min(miny, s.y);
maxx = Math.max(maxx, s.x);
maxy = Math.max(maxy, s.y);
}
if (prevminy === prevmaxy && prevminy === 0) {
prevmaxy = maxy;
prevminy = miny;
}
if (Math.abs(maxy - miny) > Math.abs(prevmaxy - prevminy)) {
for (const s of stars) {
s.rewind();
}
this.tulosta(stars, minx, maxx, miny, maxy);
return ii;
}
prevmaxy = maxy;
prevminy = miny;
}
return 'Eipä löytynyt :(';
}
tulosta(stars, minx, maxx, miny, maxy) {
this.debugStr += '\n';
for (let y = miny; y <= maxy; y++) {
for (let x = minx; x <= maxx; x++) {
this.debugStr += stars.some(s => s.x === x && s.y === y) ? '#' : '.';
}
this.debugStr += '\n';
}
}
solveStart() {
this.solution = 'solving';
if (this.solvingTickerInterval != null) {
clearInterval(this.solvingTickerInterval);
}
this.solvingTickerInterval = setInterval(() => this.solution += '.', 500);
}
solveFinish(solution) {
if (this.solvingTickerInterval != null) {
clearInterval(this.solvingTickerInterval);
}
this.solution = solution;
}
}
| true |
799b8c2d4b3075bafe8fb1f347e4e70ad53ee19d
|
TypeScript
|
morlay/redux-actions
|
/src/__tests__/index.spec.ts
|
UTF-8
| 1,278 | 2.9375 | 3 |
[] |
no_license
|
import {
test,
} from "ava";
import {
buildCreateAction,
createAction,
handleActions,
ActionMeta,
} from "../index";
interface ICounter {
counter: number;
}
interface ITypeWrappers {
success: {
toString(): string;
};
failed: {
toString(): string;
};
toString(): string;
}
const typeWrappers = {
success: (type: string): string => `${type}_SUCCESS`,
failed: (type: string): string => `${type}_FAILED`,
};
const dispatchSuccess = <Payload, Meta>(action: ActionMeta<Payload, Meta>) => ({
...action,
type: `${action.type}_SUCCESS`,
});
test("reducer should change state correct", (t) => {
const createMultiAction = buildCreateAction<ITypeWrappers, number, any>(typeWrappers);
const syncAction = createAction("syncAction");
const asyncAction = createMultiAction("asyncAction");
const reducer = handleActions<ICounter, number, any>({
[syncAction]: ({ counter }, payload) => ({
counter: payload,
}),
[`${asyncAction.success}`]: ({ counter }, payload) => ({
counter: counter + payload,
}),
}, { counter: 0 });
t.deepEqual(
reducer({ counter: 3 }, dispatchSuccess(asyncAction(3))),
{ counter: 6 },
);
t.deepEqual(
reducer({ counter: 3 }, syncAction(4)),
{ counter: 4 },
);
});
| true |
7bedda5038b8b6d066556fad5cf74564551bc7a5
|
TypeScript
|
chase-moskal/metalshop
|
/source/business/auth/validate-profile.ts
|
UTF-8
| 1,504 | 3.1875 | 3 |
[
"ISC"
] |
permissive
|
import {MetalProfile} from "../../types.js"
export const nicknameMax = 21
export const taglineMax = 32
export function validateProfile(profile: MetalProfile): {
problems: string[]
} {
let problems = []
let fields = Object.entries(profile)
function pluck<T extends keyof MetalProfile>(prop: T): MetalProfile[T] {
const [,value] = fields.find(([key]) => key === prop)
fields = fields.filter(([key]) => key !== prop)
return value
}
function assert(condition: boolean, problem: string) {
if (!condition) problems.push(problem)
return condition
}
function assertString({label, subject, min, max}: {
label: string
subject: string
min: number
max: number
}) {
assert(typeof subject === "string", `${label} must be string`)
&& assert(subject.length >= min, `${label} must be at least ${min} characters`)
&& assert(subject.length <= max, `${label} must be ${max} characters or less`)
}
//
// actual validations
//
// validate nickname
{
const label = "nickname"
assertString({
label,
subject: pluck(label),
min: 1,
max: nicknameMax,
})
}
// validate tagline
{
const label = "tagline"
assertString({
label,
subject: pluck(label),
min: 0,
max: taglineMax,
})
}
// validate avatar
{
const label = "avatar"
assertString({
label,
subject: pluck(label),
min: 0,
max: 1024,
})
}
// validate against excess data
assert(fields.length === 0, "must have no excess profile data")
return {problems}
}
| true |
c657e5bb18e260c3432b33b0b92ecc666ef8ca50
|
TypeScript
|
jsmorales/angularForms
|
/src/app/components/aprox-data/aprox-data.component.ts
|
UTF-8
| 4,499 | 2.71875 | 3 |
[] |
no_license
|
import { Component, OnInit } from '@angular/core';
// for work with forms we need to import this libs, on app.module you need to import ReactiveFormsModule below to the import of FormsModule
import {FormGroup, FormControl, Validators} from '@angular/forms';
import {Observable} from 'rxjs';
interface People {
id: number;
firstName: string;
lastName: string;
email: string;
}
@Component({
selector: 'app-aprox-data',
templateUrl: './aprox-data.component.html',
styleUrls: ['./aprox-data.component.css']
})
export class AproxDataComponent implements OnInit {
// this object of type FormGroup is the responsible of the form
form: FormGroup;
// for the binding with the form we put [formGroup]="nameOfTheObjectoONthisCaseForm" on the html
peopleExample: People[] = [
{
id: 1,
firstName: 'Mark',
lastName: 'Otto',
email: '@mdo'
},
{
id: 2,
firstName: 'Martín',
lastName: 'De Fransisco',
email: '@mfrans'
},
{
id: 3,
firstName: 'Santiago',
lastName: 'Moure',
email: '@mamerMoure'
}
];
peopleGet: People;
loading = true;
constructor() {
// on the declaration we have the controls definition, on the controls definition we have the value of the control
// the validations and the async validations
this.form = new FormGroup({
id: new FormControl('', [Validators.required, Validators.pattern('[0-9]{1,4}')]),
firstName: new FormControl('', [Validators.required, Validators.minLength(4)]), // for bind each control we must put formControlName="nameofthecontrol" on each control
lastName: new FormControl('', [Validators.required, this.noLastNameMorales]), // we call Validators to call the validations form the control, we use our validator without ()
email: new FormControl('',
[Validators.required,
Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,3}$')
]
),
username: new FormControl('', [Validators.required], this.existeUsuario),
password1: new FormControl('', Validators.required),
password2: new FormControl()
});
// to set values to the form on an automatic way put this, this works only if the object has the same estructure of the form
// this.form.setValue(this.user);
// set the validators in other context, we must put the bind function to assign the this element to the form itself
this.form.get('password2').setValidators([Validators.required, this.noEqualPassword.bind(this.form)]);
// subscribe to the observable valueChanges of the form, form only one control use this.form.controls['fieldName'].valueChanges
this.form.valueChanges.subscribe( data => {
console.log(data);
});
// subscribe to the observable only for status changes of async validations
this.form.get('username').statusChanges.subscribe( data => {
console.log(data);
});
}
ngOnInit() {
this.loadTable();
}
getSubmitForm() {
console.log(this.form);
console.log(this.form.value);
// to reset on pristine form do this
// this.form.reset(this.user);
// this.form.reset();
this.peopleExample.push(this.form.value);
}
loadTable() {
setTimeout(() => {
this.loading = false;
}, 3000);
}
getIdPerson(id: number) {
console.log('Mostrando persona: ' + id);
console.log(this.getPeople(id));
this.peopleGet = this.getPeople(id);
}
getPeople(id: number): People {
const peopleRes = this.peopleExample.filter((people: People) => {
if (people.id === id) {
return people;
}
});
return peopleRes[0];
}
// personal validations
noLastNameMorales(control: FormControl): { [s: string]: boolean } {
if ( control.value === 'morales') {
return {nomorales : true};
}
return null;
}
noEqualPassword(control: FormControl): { [s: string]: boolean } {
const form: FormGroup = this;
if ( control.value !== form.get('password1').value) {
return {noequalpassword : true};
}
return null;
}
// this validator is async, this returns a promise
existeUsuario(control: FormControl): Promise<any>|Observable<any> {
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value === 'AlocerX') {
resolve({existeusuario: true, userValidated: control.value});
} else {
resolve(null);
}
}, 4000);
});
return promise;
}
}
| true |
abf20766ba7ebe38c5a7154cddfcbb5fb3b312b3
|
TypeScript
|
Malinina1995/social-application
|
/src/reducers/usersReducer.ts
|
UTF-8
| 6,598 | 2.609375 | 3 |
[] |
no_license
|
import {ResultCodes, ResultType} from "../api/api";
import {UserType} from "../types";
import {ThunkAction} from "redux-thunk";
import {AppReducerType} from "../redux-store";
import {Dispatch} from "redux";
import {usersAPI} from "../api/users-api";
const FOLLOW = "user/FOLLOW";
const UNFOLLOW = "user/UNFOLLOW";
const SET_USERS = "user/SET-USERS";
const SET_CURRENT_PAGE = "user/SET-CURRENT-PAGE";
const SET_TOTAL_USER_COUNT = "user/SET-TOTAL-USER-COUNT";
const TOGGLE_IS_FETCHING = "user/TOGGLE-IS-FETCHING";
const TOGGLE_IS_FOLLOWING_PROGRESS = "user/TOGGLE-IS-FOLLOWING-PROGRESS";
type UsersInitialStateType = {
users: UserType[];
pageSize: number;
totalUsersCount: number;
currentPage: number;
isFetching: boolean;
followInProgress: number[]; // arrays of usersId
}
type UsersStateActions = FollowActionCreatorType
| UnfollowActionCreatorType
| SetUsersActionCreatorType
| SetCurrentPageActionCreatorType
| SetTotalUserCountActionCreatorType
| ToggleIsFetchingActionCreatorType
| FollowingInProgressActionCreatorType;
type UsersThunkType = ThunkAction<Promise<void>, AppReducerType, unknown, UsersStateActions>;
type DispatchType = Dispatch<UsersStateActions>;
type FollowActionCreatorType = {
type: typeof FOLLOW;
userId: number
}
type UnfollowActionCreatorType = {
type: typeof UNFOLLOW;
userId: number
}
type SetUsersActionCreatorType = {
type: typeof SET_USERS;
users: UserType[]
}
type SetCurrentPageActionCreatorType = {
type: typeof SET_CURRENT_PAGE;
currentPage: number
}
let initialState: UsersInitialStateType = {
users: [],
pageSize: 10,
totalUsersCount: 0,
currentPage: 1,
isFetching: true,
followInProgress: []
};
type SetTotalUserCountActionCreatorType = {
type: typeof SET_TOTAL_USER_COUNT;
totalUsersCount: number
}
type ToggleIsFetchingActionCreatorType = {
type: typeof TOGGLE_IS_FETCHING;
isFetching: boolean
}
type FollowingInProgressActionCreatorType = {
type: typeof TOGGLE_IS_FOLLOWING_PROGRESS;
isFetching: boolean;
userId: number
}
export let usersReducer = (state = initialState, action: UsersStateActions): UsersInitialStateType => {
switch (action.type) {
case FOLLOW:
return {
...state,
users: state.users.map(user => {
if (user.id === action.userId) {
return {...user, followed: true};
}
return user;
})
};
case UNFOLLOW:
return {
...state,
users: state.users.map(user => {
if (user.id === action.userId) {
return {...user, followed: false};
}
return user;
})
};
case SET_USERS:
return {
...state,
users: action.users
};
case SET_CURRENT_PAGE:
return {
...state,
currentPage: action.currentPage
};
case SET_TOTAL_USER_COUNT:
return {
...state,
totalUsersCount: action.totalUsersCount
};
case TOGGLE_IS_FETCHING:
return {
...state,
isFetching: action.isFetching
};
case TOGGLE_IS_FOLLOWING_PROGRESS:
return {
...state,
followInProgress: action.isFetching
? [...state.followInProgress, action.userId]
: state.followInProgress.filter(id => id !== action.userId)
};
default:
return state;
}
};
const followActionCreator = (userId: number): FollowActionCreatorType => {
return {
type: FOLLOW,
userId
};
};
const unfollowActionCreator = (userId: number): UnfollowActionCreatorType => {
return {
type: UNFOLLOW,
userId
};
};
const setUsersActionCreator = (users: UserType[]): SetUsersActionCreatorType => {
return {
type: SET_USERS,
users
};
};
const setCurrentPageActionCreator = (currentPage: number): SetCurrentPageActionCreatorType => {
return {
type: SET_CURRENT_PAGE,
currentPage
};
};
const setTotalUserCountActionCreator = (totalUsersCount: number): SetTotalUserCountActionCreatorType => {
return {
type: SET_TOTAL_USER_COUNT,
totalUsersCount
};
};
const toggleIsFetchingActionCreator = (isFetching: boolean): ToggleIsFetchingActionCreatorType => {
return {
type: TOGGLE_IS_FETCHING,
isFetching
};
};
const followingInProgressActionCreator = (isFetching: boolean, userId: number): FollowingInProgressActionCreatorType => {
return {
type: TOGGLE_IS_FOLLOWING_PROGRESS,
isFetching,
userId
};
};
export const getUserThunkCreator = (pageSize: number, currentPage: number): UsersThunkType => {
return async (dispatch) => {
dispatch(toggleIsFetchingActionCreator(true));
let res = await usersAPI.getUsers(pageSize, currentPage);
dispatch(toggleIsFetchingActionCreator(false));
dispatch(setUsersActionCreator(res.items));
dispatch(setTotalUserCountActionCreator(res.totalCount));
dispatch(setCurrentPageActionCreator(currentPage));
};
};
const _followUnfollowMethod = async (dispatch: DispatchType, id: number, apiMethod: (id: number) => Promise<ResultType>,
actionCreator: (id: number) => UsersStateActions) => {
dispatch(followingInProgressActionCreator(true, id));
let res = await apiMethod(id);
if (res.resultCode === ResultCodes.Success) {
dispatch(actionCreator(id));
}
dispatch(followingInProgressActionCreator(false, id));
}
export const followUserThunkCreator = (id: number): UsersThunkType => {
return async (dispatch) => {
await _followUnfollowMethod(dispatch, id, usersAPI.followUsers.bind(usersAPI), followActionCreator);
};
};
export const unfollowUserThunkCreator = (id: number): UsersThunkType => {
return async (dispatch) => {
await _followUnfollowMethod(dispatch, id, usersAPI.unfollowUsers.bind(usersAPI), unfollowActionCreator);
};
};
| true |
65ffc3e6c64ad13d702f8f007a6cfe4cfccd27b8
|
TypeScript
|
basarat/typescript-node
|
/poelstra4/myprogram.ts
|
UTF-8
| 629 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
import mylib = require("mylib");
import myotherlib = require("myotherlib");
function assert(cond: boolean): void {
if (!cond) {
throw new Error("assertion failed");
}
}
var a = mylib.myfunc();
var b = myotherlib.myotherfunc();
var str: string = a.foo;
var num: number = b.foo;
assert(typeof a.foo === "string");
assert(typeof b.foo === "number");
myotherlib.myAsync().then((x) => {
console.log(x.foo); // 42
});
// These should give compile errors:
// var p: Promise; // Promise is ambiently declared through `myotherlib`, but should not leak to here
// var b: Buffer; // again ambiently declared through `myotherlib`
| true |
74e46ba03f84928958b375ec5823816d6bb9eea1
|
TypeScript
|
end5/CoCWebOld
|
/build/Game/Items/Materials/MaterialLib.ts
|
UTF-8
| 1,823 | 2.78125 | 3 |
[] |
no_license
|
import { KitsuneStatue } from './KitsuneStatue';
import { Material } from './Material';
import { MaterialName } from './MaterialName';
import { Dictionary } from '../../../Engine/Utilities/Dictionary';
import { ItemDesc } from '../ItemDesc';
export class MaterialLib extends Dictionary<Material> {
public constructor() {
super();
this.set(MaterialName.BlackChitin, new Material(MaterialName.BlackChitin, new ItemDesc("B.Chitn", "a large shard of chitinous plating",
"A perfect piece of black chitin from a bee-girl. It still has some fuzz on it."),
"You look over the scale carefully but cannot find a use for it. Maybe someone else will know how to use it."));
this.set(MaterialName.GoldenStatue, new KitsuneStatue());
this.set(MaterialName.GreenGel, new Material(MaterialName.GreenGel, new ItemDesc("GreenGl", "a clump of green gel",
"This tough substance has no obvious use that you can discern."),
"You examine the gel thoroughly, noting it is tough and resiliant, yet extremely pliable. Somehow you know eating it would not be a good idea."));
this.set(MaterialName.ToughSpiderSilk, new Material(MaterialName.ToughSpiderSilk, new ItemDesc("T.SSilk", "a bundle of tough spider-silk",
"This bundle of fibrous silk is incredibly tough and strong, though somehow not sticky in the slightest. You have no idea how to work these tough little strand(s into anything usable. Perhaps one of this land's natives might have an idea?"),
"You look over the tough webbing, confusion evident in your expression. There's really nothing practical you can do with these yourself. It might be best to find someone more familiar with the odd materials in this land to see if they can make sense of it."));
}
}
| true |
c5aa7ecade3dbe457b81de7de5f11eb6a26179cd
|
TypeScript
|
zhangchongyu/egret_p2
|
/src/LayerManager.ts
|
UTF-8
| 3,229 | 2.75 | 3 |
[] |
no_license
|
namespace manager
{
/**
* 简单层级管理
*/
export class LayerManager
{
public constructor()
{
}
private static _instance: LayerManager;
/**
* LayerManager实例
*/
public static getInstance(): LayerManager
{
if(LayerManager._instance == null)
{
LayerManager._instance = new LayerManager();
}
return LayerManager._instance;
}
private baseLayer: egret.DisplayObjectContainer;
private modelLayer: egret.DisplayObjectContainer;
/**
* 初始化
*/
public init(parent: egret.DisplayObjectContainer)
{
let stage = parent.stage;
this.baseLayer = new eui.Group();
this.baseLayer.touchEnabled = false;
this.modelLayer = new eui.Group();
this.modelLayer.touchEnabled = false;
this.resizeHandler(stage.stageWidth, stage.stageHeight);
stage.addChild(this.baseLayer);
stage.addChild(this.modelLayer);
stage.addEventListener(egret.Event.RESIZE, this.resizeStage, this);
}
/**
* 舞台尺寸重置
*/
private resizeStage(e: egret.Event): void
{
let stage: egret.Stage = e.currentTarget;
this.resizeHandler(stage.stageWidth, stage.stageHeight);
// this.resizeClass(stage.stageWidth, stage.stageHeight);
}
/**
* 匹配图层大小
*/
private resizeHandler(stageWidth: number, stageHeight: number)
{
this.baseLayer.width = stageWidth;
this.baseLayer.height = stageHeight;
this.modelLayer.width = stageWidth;
this.modelLayer.height = stageHeight;
}
private resizeClass(stageWidth: number, stageHeight: number): void
{
for(let item in this.classDict)
{
this.classDict[item].width = stageWidth;
this.classDict[item].height = stageHeight;
}
}
/**
* 限定类名字典
*/
private classDict = {};
/**
* 添加到舞台
*/
public addChildWithClass(clazz: any): void
{
let className: string = egret.getQualifiedClassName(clazz);
console.log(`className:${className}`);
let object: any = this.classDict[className];
if(object == null)
{
object = new clazz();
// object.width = this.baseLayer.width;
// object.height = this.baseLayer.height;
this.classDict[className] = object;
}
this.baseLayer.addChild(object);
}
/**
* 移出舞台
*/
public removeChildWithClass(clazz: any): void
{
let className = egret.getQualifiedClassName(clazz);
if(clazz.parent != null)
{
clazz.parent.removeChild(clazz);
}
delete this.classDict[className];
}
}
}
| true |
13b7f91bfb6640188cddb2c730423817ca715694
|
TypeScript
|
lMINERl/ts-react
|
/src/redux/actions/DataActions.ts
|
UTF-8
| 904 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
import { DataModel } from '../../models/DataModel';
export interface Action {
type?: DataAction;
// tslint:disable-next-line: no-any
payload?: any;
}
// actions const
export enum DataAction {
GET_ALL_DATA = 'GET_ALL_DATA',
GET_DATA_BY_NAME = 'GET_DATA_BY_NAME',
DELETE_DATA_BY_ID = 'DELETE_DATA_BY_ID',
ADD_DATA = 'ADD_DATA',
ERROR = 'ERROR'
}
// Actions
export const getAllData = (response: DataModel[]): Action => {
return {
type: DataAction.GET_ALL_DATA,
payload: response
};
};
export const getDataByName = (name: string): Action => {
return {
type: DataAction.GET_DATA_BY_NAME,
payload: name
};
};
export const deleteDataById = (id: number): Action => {
return {
type: DataAction.DELETE_DATA_BY_ID,
payload: id
};
};
export const addDataToList = (data: DataModel): Action => {
return {
type: DataAction.ADD_DATA,
payload: data
};
};
| true |
ab6585ef866c9bae238fe925e41c85f9e0660db1
|
TypeScript
|
ucdavis/uccsc-mobile-functions
|
/functions/src/notifications/index.ts
|
UTF-8
| 2,522 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
import * as functions from "firebase-functions";
import * as Expo from "expo-server-sdk";
import FirebaseClient from "../services/firebase";
import ExpoClient from "../services/expo";
const db = FirebaseClient.firestore();
export const addNotificationToken = functions.https.onRequest(
async (req, res) => {
try {
// parse out data
const data = req.body;
// save to db
const doc = await db.collection('devices').add({
token: data.token,
user: data.user
});
// return id snapshot
res.json(doc);
} catch (error) {
console.error(error);
res.json(error);
}
}
);
export const sendNotification = functions.https.onRequest(async (req, res) => {
try {
// fetch devices
const devices = await db.collection('devices').get();
// map tokens to messages
const messages = [];
devices.forEach(device => {
const data = device.data();
// Each push token looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]
const token = data.token.value;
// Check that all your push tokens appear to be valid Expo push tokens
if (!Expo.isExpoPushToken(token)) {
console.error(`Push token ${token} is not a valid Expo push token`);
return false;
}
// Construct a message (see https://docs.expo.io/versions/latest/guides/push-notifications.html)
messages.push({
to: token,
sound: "default",
body: "This is a test notification",
data: { withSome: "data" }
});
return false;
});
// The Expo push notification service accepts batches of notifications so
// that you don't need to send 1000 requests to send 1000 notifications. We
// recommend you batch your notifications to reduce the number of requests
// and to compress them (notifications with similar content will get
// compressed).
const chunks = ExpoClient.chunkPushNotifications(messages);
// Send the chunks to the Expo push notification service. There are
// different strategies you could use. A simple one is to send one chunk at a
// time, which nicely spreads the load out over time:
const receipts = [];
for (const chunk of chunks) {
try {
const receipt = await ExpoClient.sendPushNotificationsAsync(chunk);
console.log(receipt);
} catch (error) {
console.error(error);
}
}
res.json(receipts);
} catch (error) {
console.error(error);
res.json(error);
}
});
| true |
a108178a2ed4aba6209fbe976e383b7926e4dec2
|
TypeScript
|
gradebook/utils
|
/packages/fast-pluralize/src/fast-pluralize.ts
|
UTF-8
| 777 | 3.46875 | 3 |
[] |
no_license
|
// Ending pairs to use, in order of precedence
const endings = [
['sis', 'sis'],
['zzes', 'z'],
['ies', 'y'],
['s', ''],
];
const OVERRIDES: Record<string, string> = {
bonuses: 'bonus',
};
export function singularize(phrase: string): string {
phrase = phrase.trim();
const phraseLower = phrase.toLowerCase();
if (Object.hasOwnProperty.call(OVERRIDES, phraseLower)) {
const newPhrase = OVERRIDES[phraseLower];
// Try to preserve case
if (phraseLower.startsWith(newPhrase)) {
return phrase.slice(0, newPhrase.length);
}
return newPhrase;
}
// Loop through each pair and replace
for (const [plural, singular] of endings) {
if (phrase.endsWith(plural)) {
return phrase.slice(0, phrase.length - plural.length) + singular;
}
}
return phrase;
}
| true |
fe7ea7060076189e0073bb51c69045d95dd8b049
|
TypeScript
|
kemalbekcan/Pokemon
|
/src/reducers/pokeReducers.ts
|
UTF-8
| 4,735 | 2.640625 | 3 |
[] |
no_license
|
import {
GET_POKE_SUCCESS,
GET_POKE_STATS,
POKE_FAILED,
POKE_STATS_FAILED,
POKE_ABILITIES_SUCCESS,
POKE_ABILITIES_FAILED,
ADD_LIKE_SUCCESS,
ADD_UNLIKE_SUCCESS,
LIKE_FAILED,
CATCH_POKEMON_SUCCESS,
DELETE_CATCH_POKEMON,
ALL_DELETE_CATCH_POKEMON
} from '../actions/types';
interface IIinitialState {
loading: boolean;
pokemons: any;
successMessage: string | null;
failedMessage: string | null;
stats: any;
abilities: any;
favourite: any;
pokeCatch: any;
}
const initialState: IIinitialState = {
loading: true,
pokemons: [],
successMessage: null,
failedMessage: null,
stats: [],
abilities: [],
favourite: [],
pokeCatch: [],
}
interface IPokeActions {
type: typeof GET_POKE_SUCCESS;
payload: any;
}
interface IPokeFailed {
type: typeof POKE_FAILED;
payload: string;
}
interface IPokeGetImage {
type: typeof GET_POKE_STATS;
payload: any;
}
interface IPokeErrFailed {
type: typeof POKE_STATS_FAILED;
payload: string;
}
interface IPokeAbilities {
type: typeof POKE_ABILITIES_SUCCESS;
payload: string;
}
interface IPokeAbilitiesFailed {
type: typeof POKE_ABILITIES_FAILED;
payload: string;
}
interface IPokeLikeSuccess {
type: typeof ADD_LIKE_SUCCESS;
payload: string;
}
interface IPokeUnlikeSuccess {
type: typeof ADD_UNLIKE_SUCCESS;
payload: any;
}
interface IPokeFavFailed {
type: typeof LIKE_FAILED;
payload: string;
}
interface IPokeCatchSuccess {
type: typeof CATCH_POKEMON_SUCCESS;
payload: string;
}
interface IPokeDeleteCatchSuccess {
type: typeof DELETE_CATCH_POKEMON;
payload: any;
}
interface IPokeAllDeleteCatchSuccess {
type: typeof ALL_DELETE_CATCH_POKEMON;
payload: any;
}
export type pokeActions = IPokeActions | IPokeFailed | IPokeGetImage | IPokeErrFailed | IPokeAbilities | IPokeAbilitiesFailed | IPokeLikeSuccess | IPokeUnlikeSuccess | IPokeFavFailed | IPokeCatchSuccess | IPokeDeleteCatchSuccess | IPokeAllDeleteCatchSuccess;
const pokeReducers = (state: IIinitialState = initialState, action: pokeActions) => {
switch (action.type) {
case GET_POKE_SUCCESS:
return {
...state,
pokemons: action.payload,
successMessage: "Success",
loading: false,
}
case ADD_LIKE_SUCCESS:
localStorage.setItem("like", JSON.stringify([action.payload, ...state.favourite]))
return {
...state,
favourite: [action.payload, ...state.favourite],
loading: false,
}
case ADD_UNLIKE_SUCCESS:
localStorage.setItem("like", JSON.stringify(state.favourite.filter((fav: any) => fav.id !== action.payload.id)))
return {
...state,
favourite: state.favourite.filter((fav: any) => fav.id !== action.payload.id),
loading: false
}
case LIKE_FAILED:
return {
...state,
failedMessage: 'Something went wrong',
loading: false
}
case GET_POKE_STATS:
return {
...state,
stats: action.payload,
loading: false
}
case POKE_FAILED:
return {
...state,
failedMessage: 'Something went wrong !',
loading: false,
}
case POKE_STATS_FAILED:
return {
...state,
failedMessage: 'Image upload error !',
loading: false
}
case POKE_ABILITIES_SUCCESS:
return {
...state,
abilities: action.payload,
loading: false,
}
case POKE_ABILITIES_FAILED:
return {
...state,
failedMessage: 'Something went wrong !',
loading: false,
}
case CATCH_POKEMON_SUCCESS:
return {
...state,
pokeCatch: [action.payload, ...state.pokeCatch],
loading: false,
}
case DELETE_CATCH_POKEMON:
return {
...state,
pokeCatch: state.pokeCatch.filter((item: any) => item.pokemon !== action.payload.pokemon),
loading: false
}
case ALL_DELETE_CATCH_POKEMON:
return {
...state,
pokeCatch: [],
loading: false
}
default:
return state;
}
}
export default pokeReducers;
| true |
f7560f53cd384e66b1de8a4897c586035178431e
|
TypeScript
|
vbmeo/AngularP3
|
/tre/src/app/gestone-utenti/gestone-utenti.component.ts
|
UTF-8
| 1,136 | 2.59375 | 3 |
[] |
no_license
|
import { Component, OnInit } from '@angular/core';
import {Utenti} from '../Model/Utenti.model';
@Component({
selector: 'app-gestone-utenti',
templateUrl: './gestone-utenti.component.html',
styleUrls: ['./gestone-utenti.component.css']
})
export class GestoneUtentiComponent implements OnInit {
//listaUtenti : Utenti[];
utenteNuovo: Utenti;
listaUtenti = new Array<Utenti>();
constructor() { }
ngOnInit() {
this.listaUtenti.push(new Utenti('mauro','Bologna'));
this.listaUtenti.push(new Utenti('Paolino','Bentivoglio'));
this.listaUtenti.push(new Utenti('Mister x','Bologna'));
}
addUtente(nome:string,citta:string){
var utente:Utenti = new Utenti(nome,citta);
this.listaUtenti.push(utente);
}
deleteUtente(indice:number){
console.log('indice '+indice);
//cicla array e togli elementao con id passato
//non funziona bene rivedere
for( var i = 0; i < this.listaUtenti.length; i++){
if ( this.listaUtenti[i].id === indice) {
this.listaUtenti.splice(i, 1);
console.log('Cancellato '+this.listaUtenti.splice(i, 1));
}
}
}
}
| true |
acab9b255ee2221a6c03a752fadc64957a9b67b9
|
TypeScript
|
CN-Shopkeeper/ol_workshop
|
/src/components/page-maps/utils/styled-by-area.ts
|
UTF-8
| 1,060 | 2.734375 | 3 |
[] |
no_license
|
import { getArea } from "ol/sphere";
import colormap from "colormap";
import { Style, Fill, Stroke } from "ol/style";
import RenderFeature from "ol/render/Feature.js";
import Feature from "ol/Feature.js";
import Geometry from "ol/geom/Geometry.js";
import { clamp } from "../utils/clamp-area";
const min = 1e8; // the smallest area
const max = 2e13; // the biggest area
const steps = 50;
// 一个颜色区间,共有50种颜色
const ramp = colormap({
colormap: "blackbody",
nshades: steps
});
// 根据面积找到其颜色下标
function getColor(feature: RenderFeature | Feature<Geometry>) {
const area = getArea(feature.getGeometry() as Geometry);
const f = Math.pow(clamp((area - min) / (max - min), 0, 1), 1 / 2);
const index = Math.round(f * (steps - 1));
return ramp[index];
}
function styleByArea(feature: RenderFeature | Feature<Geometry>): Style {
return new Style({
fill: new Fill({
color: getColor(feature)
}),
stroke: new Stroke({
color: "rgba(255,255,255,0.8)"
})
});
}
export { styleByArea };
| true |
af1e21ac4c417edac952bbb56f1064e45188d22e
|
TypeScript
|
erinduncan/Vet-Application
|
/Front End/vet-app/src/utilites/index.ts
|
UTF-8
| 1,065 | 2.5625 | 3 |
[] |
no_license
|
import { combineReducers } from "redux";
import { userReducer } from "../reducers/login-reducer";
import { clientReducer } from "../reducers/client-reducer";
import { employeeReducer } from "../reducers/employee-reducer";
import { petReducer } from "../reducers/pet-reducer";
export interface IUserState {
currentUser: any;
loggedIn: boolean;
loginMessage: string;
}
export interface IRegisterState {
newUser: any;
registerMessage: string;
}
export interface IClientState {
clients: any,
client: any,
clientMessage: string,
id: number
}
export interface IPetState {
pets: any,
pet: any,
petMessage: string,
id: number
}
export interface IEmployeeState {
employees: any,
employee: any,
employeeMessage: string,
id: number
}
export interface IState {
userState: IUserState;
clientState: IClientState;
employeeState: IEmployeeState;
petState: IPetState;
}
export const state = combineReducers<IState>({
userState: userReducer,
clientState: clientReducer,
employeeState: employeeReducer,
petState: petReducer
});
| true |
b26ad1628552c1726f8705579d6a6d6f84e22d5b
|
TypeScript
|
riganti/dotvvm
|
/src/Framework/Framework/Resources/Scripts/utils/dom.ts
|
UTF-8
| 841 | 2.75 | 3 |
[
"Apache-2.0"
] |
permissive
|
export const getElementByDotvvmId = (id: string) => {
return <HTMLElement> document.querySelector(`[data-dotvvm-id='${id}']`);
}
/**
* @deprecated Use addEventListener directly
*/
export function attachEvent(target: any, name: string, callback: (ev: PointerEvent) => any, useCapture: boolean = false) {
target.addEventListener(name, callback, useCapture);
}
export const isElementDisabled = (element: HTMLElement | null | undefined) =>
element &&
["A", "INPUT", "BUTTON"].indexOf(element.tagName) > -1 &&
element.hasAttribute("disabled")
export function setIdFragment(idFragment: string | null | undefined) {
if (idFragment != null) {
// first clear the fragment to scroll onto the element even when the hash is equal to idFragment
location.hash = "";
location.hash = idFragment;
}
}
| true |
ca8d4064c0a5687cd979383efd435e56cdf36e41
|
TypeScript
|
Loebas/Opdracht-Webapp-4
|
/gameapp/src/app/game.ts
|
UTF-8
| 711 | 2.78125 | 3 |
[] |
no_license
|
export class Game {
constructor(
private _id: number,
private _naam: string,
private _minSpelers: number,
private _maxSpelers: number,
private _difficulty: number,
) { }
get id(): number {
return this._id;
}
get naam(): string {
return this._naam;
}
get minSpelers(): number {
return this._minSpelers;
}
get maxSpelers(): number {
return this._maxSpelers;
}
get difficulty(): number {
return this._difficulty;
}
static fromJSON(json: any): Game {
const g = new Game(json.id, json.spelNaam, json.minSpelers, json.maxSpelers, json.difficulty)
return g;
}
}
| true |
7953dedf929dd8fe3f5911fadb1de23743159af0
|
TypeScript
|
typexs/typexs-ng
|
/archive/packages/base/messages/IMessage.ts
|
UTF-8
| 197 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
export enum MessageType {
SUCCESS = 'SUCCESS',
ERROR = 'ERROR',
INFO = 'INFO',
WARNING = 'WARNING'
}
export interface IMessage {
type: MessageType;
topic?: any;
content: any;
}
| true |
0c0ad8ca052ddf2ffda67362c4c77cd73608b954
|
TypeScript
|
mpicciolli/mean-stack-typescript-project-template
|
/server/utility.ts
|
UTF-8
| 621 | 3.34375 | 3 |
[] |
no_license
|
export class Enum {
static getNames(e:any):Array<string> {
var a:Array<string> = [];
for (var val in e) {
if (isNaN(val)) {
a.push(val);
}
}
return a;
}
static getValues(e:any):Array<number> {
var a:Array<number> = [];
for (var val in e) {
if (!isNaN(val)) {
a.push(parseInt(val, 10));
}
}
return a;
}
static getValue(e:any, name:string):number {
return e[name];
}
static getName(e:any, val:number):string {
return e[val];
}
}
| true |
10fd0e2e1ad14fef61a1dcb1e69c34dda270c994
|
TypeScript
|
singzinc/dotNet
|
/TypeScript/typescript_example2/example1.ts
|
UTF-8
| 144 | 3.03125 | 3 |
[] |
no_license
|
function greeter (person: String){
return "Hello, " + person;
}
var user = "test user 1";
console.log("this is test : " + greeter(user));
| true |
1531663789591d73d3be6ba7cb4048e0ef58f52e
|
TypeScript
|
MaximStrnad/prgGame
|
/src/scripts/core/classes/Grid.ts
|
UTF-8
| 1,202 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
import Cell from "./Cell"
export default class Grid {
cells: Cell[];
cellsVeritacally: number;
cellsHorizonataly: number;
totalCells: number;
p: p5;
size: number;
constructor(p: p5, width: number, height:number, size: number) {
this.p = p;
this.cellsHorizonataly = Math.floor(width/size);
this.cellsVeritacally = Math.floor(height/size);
this.totalCells = this.cellsHorizonataly * this.cellsVeritacally;
this.cells = [];
this.size = size;
for(let i = 0; i <= this.totalCells; i++){
const color: p5.Vector = p.createVector(32,234,232);
let x = i % this.cellsHorizonataly === 0 ? this.size * this.cellsHorizonataly : i % this.cellsHorizonataly * this.size;
let y = i % this.cellsVeritacally === 0 ? this.size * (i / this.cellsVeritacally) : i % this.cellsVeritacally * this.size;
const pos: p5.Vector = p.createVector(x, y);
const size: p5.Vector = p.createVector(40,40);
this.cells.push(new Cell(this.p, pos, size, null, color));
}
}
public render () {
this.p.rect(304,304,32,32);
this.p.fill(32,43,134);
}
}
| true |
4b55216b91c1244a944fb411f285308197cbf052
|
TypeScript
|
lawvs/Algorithm-Training
|
/leetcode/315.count-of-smaller-numbers-after-self.ts
|
UTF-8
| 492 | 3.25 | 3 |
[] |
no_license
|
function countSmaller(nums: number[]): number[] {
const sortedNums: number[] = []
for (let i = nums.length - 1; i >= 0; i--) {
const curNum = nums[i]
sortedNums.push(curNum)
let cnt = 0
// insertion sort
let j = sortedNums.length - 2
for (; j >= 0 && sortedNums[j] >= curNum; j--) {
sortedNums[j + 1] = sortedNums[j]
cnt++
}
sortedNums[j + 1] = curNum
nums[i] = sortedNums.length - cnt - 1
}
// console.log(sortedNums)
return nums
}
| true |
26a9f676ce8ec3602ba6fdd1e98c724fd7176ca9
|
TypeScript
|
iksaku/djambi
|
/src/api/piece/Militant.ts
|
UTF-8
| 192 | 2.515625 | 3 |
[] |
no_license
|
import { Piece } from './Piece'
export class Militant extends Piece {
public get type(): string {
return 'Militant'
}
public get maxMovementDistance(): number {
return 3
}
}
| true |
f5c1da9a0003558ee1e5160c5fdbeb65e386d051
|
TypeScript
|
ptwu/candidate-decider-google-form
|
/src/firebase-auth.ts
|
UTF-8
| 1,354 | 3.125 | 3 |
[] |
no_license
|
import firebase from 'firebase/app';
import 'firebase/auth';
export type AppUser = {
readonly displayName: string;
readonly email: string;
readonly token: string;
};
/**
* Returns the promise of an app user from the given raw firebase user.
*
* @param firebaseUser a raw firebase user or null.
* @return the promise of an app user or null if there is no such user..
*/
export async function toAppUser(firebaseUser: firebase.User | null): Promise<AppUser | null> {
if (firebaseUser == null) {
return null;
}
const { displayName, email } = firebaseUser;
if (typeof displayName !== 'string' || typeof email !== 'string') {
throw new Error('Bad user!');
}
const token: string = await firebaseUser.getIdToken(true);
return { displayName, email, token };
}
let appUser: AppUser | null = null;
firebase.auth().onAuthStateChanged(async user => {
appUser = await toAppUser(user);
});
export const hasUser = (): boolean => appUser != null;
export function cacheAppUser(user: AppUser): void {
appUser = user;
}
/**
* Returns the global app user.
*
* If the user is not cached yet, it will not try to get one from firebase.
* Instead, it will throw an error.
*/
export function getAppUser(): AppUser {
const user = appUser;
if (user == null) {
throw new Error('App is not initialized.');
}
return user;
}
| true |
5d9dee32340452b8eb3057248596aae18d5244da
|
TypeScript
|
dlgmltjr0925/marrakech
|
/libs/market_namespace.ts
|
UTF-8
| 2,275 | 2.578125 | 3 |
[] |
no_license
|
import { MarketListObject } from '../api/market/market.dto';
import { Server } from 'socket.io';
import SocketNamespace from './socket_namespace';
export interface ConnectUser {
socketId: string;
userId: number;
roomId: number;
}
export interface DisconnectUser extends ConnectUser {}
export interface MarketMessage {
roomId: number;
status:
| 'JOIN_DEALER'
| 'LEAVE_DEALER'
| 'JOIN_SPECTATOR'
| 'LEAVE_SPECTATOR'
| 'REJECT'
| 'BAN';
market?: MarketListObject;
socketId?: string;
}
export default class MarketNamespace extends SocketNamespace {
constructor(io: Server) {
super(io, /^\/market\/\d+$/);
this.addEventListener('connect', (socket) => {
const token = socket.handshake.auth.token;
const userId = this.getUserIdByToken(token);
if (!userId) return;
const room = socket.nsp.name.replace('/market/', 'market');
socket.join(room);
console.info(`[socket][${room}] joined - ${socket.id}`);
const connectUser: ConnectUser = {
socketId: socket.id,
userId,
roomId: parseInt(room.replace('market', '')),
};
this.ns.emit('connectUser', connectUser);
});
this.addEventListener('connect', (socket) => {
socket.on('updatePlayGame', (msg: string) => {
console.log(msg);
});
});
this.addEventListener('connect', (socket) => {
socket.on('updateMarket', (marketMessage: MarketMessage) => {
const room = `market${marketMessage.roomId}`;
this.ns.to(room).emit('market', marketMessage);
});
});
this.addEventListener('disconnect', (socket) => {
const token = socket.handshake.auth.token;
const userId = this.getUserIdByToken(token);
if (!userId) return;
const room = socket.nsp.name.replace('/market/', 'market');
const disconnectUser: ConnectUser = {
socketId: socket.id,
userId,
roomId: parseInt(room.replace('market', '')),
};
this.ns.emit('disconnectUser', disconnectUser);
});
}
getUserIdByToken(token: string | null) {
if (!token) return null;
token = Buffer.from(token.replace('Basic ', ''), 'base64')
.toString('utf8')
.split(':')[0];
return parseInt(token);
}
}
| true |
8a68c9084264d19743701b62372c2aa221931e63
|
TypeScript
|
NanimonoDemonai/kani.tech
|
/src/components/hooks/store.ts
|
UTF-8
| 1,452 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import {
configureStore as configureReduxToolkitStore,
combineReducers,
Store,
} from "@reduxjs/toolkit";
import {
TypedUseSelectorHook,
useDispatch as defaultDispatch,
useSelector as defaultSelector,
useStore,
} from "react-redux";
import { pageMetaReducer } from "./slices/pageMetaSlice";
import { pageOptionReducer } from "./slices/pageOptionSlice";
import { AsyncReducer, RootState, StaticReducer } from "./types";
const staticReducer: StaticReducer = {
pageMeta: pageMetaReducer,
pageOption: pageOptionReducer,
};
const asyncReducer: Partial<AsyncReducer> = {};
export const store = configureReduxToolkitStore({
reducer: staticReducer,
});
export const useInjectReducer = (state: Partial<AsyncReducer>): void => {
const store = useStore();
injectReducer(store, state);
};
export const injectReducer = (
store: Store,
state: Partial<AsyncReducer>
): void => {
Object.entries(state).forEach(([key, value]) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
asyncReducer[key] = value;
});
store.replaceReducer(
combineReducers({
...staticReducer,
...asyncReducer,
})
);
};
export type Dispatch = typeof store.dispatch;
export const useDispatch = (): Dispatch => defaultDispatch<Dispatch>();
export const useSelector: TypedUseSelectorHook<RootState> = defaultSelector;
export type AsyncThunkConfig = {
state: RootState;
dispatch: Dispatch;
};
| true |
90a50e89fb48e96a2bd6046a0a74cc3cbe61f4b9
|
TypeScript
|
Mati365/ts-c-compiler
|
/packages/compiler-rpn/src/utils/MathExpression.ts
|
UTF-8
| 6,130 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
import * as R from 'ramda';
import { parseNumberToken } from '@compiler/lexer/utils/parseNumberToken';
import { isQuote } from '@compiler/lexer/utils/matchCharacter';
import { reduceTextToBitset } from '@compiler/core/utils';
import { MathOperator } from './MathOperators';
import { MathError, MathErrorCode } from './MathError';
export type MathPostfixTokens = (string | MathOperator)[];
export type MathParserConfig = {
keywordResolver?: (name: string) => number;
};
/**
* Converts array of postifx tokens into single string
*/
export function joinPostifxTokens(tokens: MathPostfixTokens): string {
return R.reduce(
(acc, token) => {
const char = token instanceof MathOperator ? token.char : token;
return acc ? `${acc} ${char}` : char;
},
'',
tokens,
);
}
/**
* Replaces all quotes in string to ascii numbers
*/
export function replaceQuotesWithNumbers(expression: string): string {
for (let i = 0; i < expression.length; ++i) {
const c = expression[i];
if (isQuote(c)) {
let quoteBuffer = '';
for (
let j = i + 1;
j < expression.length && !isQuote(expression[j]);
++j
) {
quoteBuffer += expression[j];
}
expression =
expression.slice(0, i) +
reduceTextToBitset(quoteBuffer) +
expression.slice(i + quoteBuffer.length + 2);
}
}
return expression;
}
/**
* Concerts expression to RPN and calculates it
*/
export class MathExpression {
/**
* Calculates expression
*/
static evaluate(phrase: string, parserConfig?: MathParserConfig): number {
return MathExpression.reducePostfixToNumber(
MathExpression.toRPN(phrase),
parserConfig,
);
}
/**
* Transforms expression to postfix
*/
static toRPN(phrase: string): MathPostfixTokens {
const stack: MathOperator[] = [];
const buffer: MathPostfixTokens = [];
const tokens: string[] = R.reject(
R.isEmpty,
R.split(
MathOperator.MATCH_OPERATOR_REGEX,
replaceQuotesWithNumbers(phrase).replace(/\s/g, ''),
),
);
for (let i = 0; i < tokens.length; ++i) {
let c = tokens[i];
let operator = MathOperator.findOperatorByCharacter(c);
// handle <<
if (!operator) {
operator = MathOperator.findOperatorByCharacter(c + tokens[i + 1]);
if (operator) {
++i;
c += tokens[i + 1];
}
}
if (operator) {
// prefix cases with 0: (-1), +1+2
if (
(operator === MathOperator.PLUS || operator === MathOperator.MINUS) &&
(!i ||
(tokens[i - 1] &&
MathOperator.findOperatorByCharacter(tokens[i - 1]) ===
MathOperator.LEFT_BRACKET))
) {
buffer.push('0');
}
if (operator === MathOperator.RIGHT_BRACKET) {
let foundLeftBracket = false;
while (stack.length) {
const stackOperator = R.last(stack);
if (stackOperator === MathOperator.LEFT_BRACKET) {
stack.pop();
foundLeftBracket = true;
break;
}
buffer.push(stack.pop());
}
if (!foundLeftBracket) {
throw new MathError(MathErrorCode.MISSING_LEFT_BRACKET);
}
} else if (operator === MathOperator.LEFT_BRACKET) {
stack.push(operator);
} else {
// drop when right hand priority stack operator on stack < operator priority
// drop when left hand priority stack operator on stack >= operator priority
while (stack.length) {
const stackOperator = R.last(stack);
// check priority
if (
(!operator.rightHand &&
operator.priority <= stackOperator.priority) ||
(operator.rightHand && operator.priority < stackOperator.priority)
) {
buffer.push(stack.pop());
} else {
break;
}
}
stack.push(operator);
}
} else {
buffer.push(c);
}
}
while (stack.length) {
const token = stack.pop();
if (
token === MathOperator.RIGHT_BRACKET ||
token === MathOperator.LEFT_BRACKET
) {
throw new MathError(MathErrorCode.INCORRECT_BRACKETS);
}
buffer.push(token);
}
return buffer;
}
/**
* Calculates value of postfix expression
*/
static reducePostfixToNumber(
tokens: MathPostfixTokens,
parserConfig?: MathParserConfig,
): number {
const numberStack: number[] = [];
for (let i = 0; i < tokens.length; ++i) {
const token = tokens[i];
if (token instanceof MathOperator) {
// handle ++2 digit, it should be 2
// -2 should be 0-2
const missingArgs = token.argsCount - numberStack.length;
if (missingArgs > 0) {
if (token === MathOperator.PLUS || token === MathOperator.MINUS) {
R.times(() => {
numberStack.unshift(0);
}, missingArgs);
} else {
throw new MathError(MathErrorCode.MISSING_OPERANDS);
}
}
const args = numberStack.splice(
numberStack.length - token.argsCount,
token.argsCount,
);
numberStack.push(token.resolver(args));
} else {
const nestedLabel = token && token[0] === '.';
let number = nestedLabel ? NaN : +token;
if (Number.isNaN(number)) {
// parsing using custom parser is slower than just `+${digit}`
// so it is second parse method
const parsedNumber = !nestedLabel && parseNumberToken(token);
if (parsedNumber) {
[, number] = parsedNumber;
} else {
number = parserConfig?.keywordResolver?.(token);
if (R.isNil(number)) {
throw new MathError(MathErrorCode.UNKNOWN_KEYWORD, { token });
}
}
}
numberStack.push(number);
}
}
return R.last(numberStack) ?? null;
}
}
| true |
3ec82c66c35f9a0defff644844f1e85e66b53285
|
TypeScript
|
kinjalik/screeps-algorithm
|
/src/utils/RoomUtils.ts
|
UTF-8
| 361 | 2.640625 | 3 |
[
"Unlicense"
] |
permissive
|
function getNotEmptyContainers(room: Room) {
const containers = <StructureContainer[]>room.find(FIND_STRUCTURES, {
filter: (struct: Structure): Boolean =>
struct.structureType == STRUCTURE_CONTAINER
});
containers.sort((a, b) => a.store.getUsedCapacity() - b.store.getUsedCapacity());
return containers;
}
export {
getNotEmptyContainers
}
| true |
4ef51f043b0d40b1fd07e7be3161a66996a4cca2
|
TypeScript
|
ErickTamayo/react-native-breeze
|
/src/plugins/lineHeight.ts
|
UTF-8
| 410 | 2.546875 | 3 |
[] |
no_license
|
import { PluginFunction, PluginPattern } from "./types";
export type PluginGroups = {
key: string;
};
export const pattern: PluginPattern = ({ keys }) => {
return new RegExp(`^leading-(?<key>${keys("lineHeight")})$`);
};
export const plugin: PluginFunction<PluginGroups> = ({ groups, theme }) => {
const { key } = groups;
const value = theme(["lineHeight", key]);
return { lineHeight: value };
};
| true |
c5b83bfe9272eaecc3f221b6214dfc3abb11fed5
|
TypeScript
|
WMs784/host
|
/main.ts
|
UTF-8
| 1,118 | 2.703125 | 3 |
[] |
no_license
|
let index = 0;
let host_num = 1;
let list = [ArrowNames.North,ArrowNames.NorthEast,ArrowNames.East,ArrowNames.SouthEast,
ArrowNames.South,ArrowNames.SouthWest,ArrowNames.West,ArrowNames.NorthWest];
let map = [ArrowNames.North,ArrowNames.South,ArrowNames.East,ArrowNames.West,ArrowNames.NorthEast];
let map2 = [1,2,3,4,5]
radio.setGroup(1);
radio.onReceivedString(function (rs: string) {
let n = parseInt(rs.slice(1));
if(rs[0] =='i'){//目的地番号の場合
for(let i = 0;i < 8;i++){
if(map[n] == list[i]){//正しい矢印がlistのどこに載ってるかを探す
radio.sendString(map2[n].toString()+host_num.toString()+'i'+i.toString());//iを文字列に変換しidをつけて送信
index = i;
}
}
if(rs[0]=='d'){//方角の場合
let cd = (n+45*index)%360;//目的地の方向を計算
let cd1 = cd.toString();//文字列に変換
radio.sendString(map2[n].toString()+ host_num.toString()+'d'+cd1);//idをつけて送信
basic.showNumber(cd);
}
}
})
| true |
afed491a1f198e66dcb9cdf5e270801a305a7c11
|
TypeScript
|
luohuidong/electron-music
|
/src/renderer/api/playList/requestPlaylistDetail.ts
|
UTF-8
| 1,005 | 2.84375 | 3 |
[] |
no_license
|
import { get } from "../http";
interface Artist {
name: string;
id: number;
}
/** 专辑 */
interface Album {
id: number;
name: string;
}
/** 歌单歌曲数据 */
interface Songs {
name: string;
id: number;
ar: Artist[];
al: Album;
}
/** 歌单歌曲 id */
interface SongIds {
id: number;
}
/** 歌单详情数据 */
interface PlayListDetailData {
tracks: Songs[];
trackIds: SongIds[];
id: number; // 歌单 id
tags: string[]; // 标签
}
/**
* 获取歌单详情
* @param playListId 歌单 id
*/
export async function requestPlaylistDetail(
playListId: number
): Promise<PlayListDetailData> {
try {
const config = {
url: "/playlist/detail",
params: {
id: playListId,
},
};
const { data } = await get(config);
const { code, playlist } = data;
if (code !== 200) {
throw new Error("获取歌单详情失败");
}
return playlist;
} catch (error) {
throw new Error("获取歌单详情失败");
}
}
| true |
6bc308a750f3b966f982aa0a520105cdce0979a1
|
TypeScript
|
ar-nelson/jaspr
|
/src/PrettyPrint.ts
|
UTF-8
| 7,135 | 3 | 3 |
[
"ISC"
] |
permissive
|
import {Jaspr, Deferred, isArray, isObject, isMagic} from './Jaspr'
import {reservedChar} from './Parser'
import chalk from 'chalk'
import {join, sum, identity} from 'lodash'
const defaultIndent = 2
const maxLength = 80
const maxEntries = 36
const maxDepth = 36
function spaces(n: number) {
let s = ''
for (let i = 0; i < n; i++) s += ' '
return s
}
const escapes: {[e: string]: string} = {
'\n': '\\n',
'\r': '\\r',
'\f': '\\f',
'\v': '\\v',
'“': '\\“',
'”': '\\”',
'\\': '\\\\'
}
function quoteString(
str: string,
truncateAt = Infinity,
quoteColor: (s: string) => string = identity,
escapeColor: (s: string) => string = identity,
ellipsisColor: (s: string) => string = identity
): string {
let out = quoteColor('“'), len = 1
for (let c of str) {
if (escapes.hasOwnProperty(c)) {
len++
c = escapeColor(escapes[c])
}
if (len >= truncateAt) {
out += ellipsisColor('…')
break
}
out += c
len++
}
return out + quoteColor('”')
}
abstract class Form {
abstract length(): number
abstract toStringInline(color?: boolean): string
abstract toStringBlock(color?: boolean, offset?: number, hanging?: number): string
toString(color = true, offset = 0, hanging?: number) {
if (this.length() < maxLength - offset) {
return this.toStringInline(color)
} else {
return this.toStringBlock(color, offset, hanging)
}
}
}
class ArrayForm extends Form {
elements: Form[]
constructor(elements: Form[]) {
super()
this.elements = elements
}
length() {
return 2 + sum(this.elements.map(x => x.length())) +
(this.elements.length > 0 ? this.elements.length - 1 : 0)
}
toStringInline(color = true) {
return (color ? chalk.cyan('[') : '[') +
join(this.elements.map(x => x.toStringInline(color)), ' ') +
(color ? chalk.cyan(']') : ']')
}
toStringBlock(color = true, offset = 0, hanging = offset) {
const token: (x: string) => string = color ? chalk.cyan : identity
return token('[') + '\n' +
join(this.elements.map(x =>
spaces(hanging + defaultIndent) +
x.toString(color, hanging + defaultIndent)),
token(',') + '\n') +
'\n' + spaces(hanging) + token(']')
}
}
class ObjectForm extends Form {
entries: {
key: string,
unquoted: boolean,
len: number,
form: Form
}[]
constructor(entries: [string, Form][]) {
super()
this.entries = entries.map(([key, form]) => {
if (key === '' || reservedChar.test(key)) {
return {key, unquoted: false, len: quoteString(key).length, form}
} else {
return {key, unquoted: true, len: key.length, form}
}
})
}
length() {
return 2 + sum(this.entries.map(({len, form}) => len + 1 + form.length())) +
(this.entries.length > 0 ? this.entries.length - 1 : 0)
}
toStringInline(color = true) {
const token: (x: string) => string = color ? chalk.green : identity
return token('{') +
join(this.entries.map(({key, unquoted, form: value}) => {
if (unquoted) {
return key + token(':') + value.toStringInline(color)
} else {
return quoteString(key, undefined,
token, token, color ? chalk.gray : identity) +
token(':') + value.toStringInline(color)
}
}), ' ') + token('}')
}
toStringBlock(color = true, offset = 0, hanging = offset) {
const token: (x: string) => string = color ? chalk.green : identity
return token('{') + '\n' +
join(this.entries.map(({key, len, unquoted, form: value}) => {
const keyStr = spaces(hanging + defaultIndent) +
(unquoted ? key : quoteString(key, undefined,
token, token, color ? chalk.gray : identity)) +
token(':') + ' '
if (hanging + defaultIndent + len + 2 + value.length() < maxLength) {
return keyStr + value.toStringInline(color)
} else {
return keyStr + value.toString(color,
hanging + defaultIndent + len + 2,
hanging + defaultIndent)
}
}), token(',') + '\n') +
'\n' + spaces(hanging) + token('}')
}
}
class StringForm extends Form {
str: string
unquoted: boolean
len: number
constructor(str: string) {
super()
this.str = str
if (str === '' || reservedChar.test(str)) {
this.unquoted = false
this.len = quoteString(str).length
} else {
this.unquoted = true
this.len = str.length
}
}
length() { return this.len }
toStringInline(color = true) {
if (this.unquoted) return this.str
else return quoteString(this.str, undefined,
color ? chalk.gray : identity,
color ? chalk.yellow : identity,
color ? chalk.gray : identity)
}
toStringBlock(color = true, offset = 0, hanging = -1) {
let out = '', len = maxLength - offset
if (hanging >= 0 && offset + this.str.length > maxLength) {
out += '\n' + spaces(hanging)
len = maxLength - hanging
}
if (this.unquoted && this.str.length <= len) return out + this.str
else return out + quoteString(this.str, len,
color ? chalk.gray : identity,
color ? chalk.yellow : identity,
color ? chalk.gray : identity)
}
}
class ConstantForm extends Form {
str: string
color: (s: string) => string
constructor(str: string, color: (s: string) => string = identity) {
super()
this.str = str
this.color = color
}
length() { return this.str.length }
toStringInline(color = true) { return color ? this.color(this.str) : this.str }
toStringBlock(color = true, offset = 0, hanging = -1) {
if (hanging >= 0 && offset + this.str.length > maxLength) {
return '\n' + spaces(hanging) + (color ? this.color(this.str) : this.str)
}
return color ? this.color(this.str) : this.str
}
}
function buildForms(it: Jaspr | Deferred, depth = 0): Form {
if (depth >= maxDepth) {
return new ConstantForm('... (too deep)', chalk.gray)
} else if (it === null) {
return new ConstantForm('null', chalk.magentaBright)
} else if (it === true) {
return new ConstantForm('true', chalk.greenBright)
} else if (it === false) {
return new ConstantForm('false', chalk.redBright)
} else if (typeof it === 'number') {
return new ConstantForm('' + it, chalk.cyanBright)
} else if (typeof it === 'string') {
return new StringForm(it)
} else if (it instanceof Deferred) {
if (it.value !== undefined) {
return buildForms(it.value, depth)
} else {
return new ConstantForm(it.toString(), chalk.yellow)
}
} else if (isArray(it)) {
return new ArrayForm(it.map(e => buildForms(e, depth + 1)))
} else if (isMagic(it)) {
return new ConstantForm('(magic)', chalk.yellowBright)
} else if (isObject(it)) {
return new ObjectForm(
Object.keys(it).map(k => <any>[k, buildForms(it[k], depth + 2)]))
} else {
return new ConstantForm('' + it, chalk.yellow)
}
}
export default function prettyPrint(it: Jaspr, color = true) {
return buildForms(it).toString(color)
}
| true |
3df317b9707460b4d9f7f05f47b82b0688d157c6
|
TypeScript
|
thomas-crane/sgml
|
/src/syntax/syntax-token.ts
|
UTF-8
| 734 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
import { SyntaxKind } from './syntax-kind';
import { SyntaxNode } from './syntax-node';
import { SyntaxTrivia } from './syntax-trivia';
import { TextSpan } from './text-span';
export class SyntaxToken extends SyntaxNode {
readonly children = [];
constructor(
readonly kind: SyntaxKind,
readonly span: TextSpan,
/**
* The value of this token.
*/
readonly value: string,
/**
* Syntax trivia which appears before this token in the source.
*/
readonly leadingTrivia: SyntaxTrivia[] = [],
/**
* Syntax trivia which appears after this token and on the
* same line as this token in the source.
*/
readonly trailingTrivia: SyntaxTrivia[] = [],
) {
super();
}
}
| true |
5b7d1aa84968f1519b1ed529142b08fe70e872e5
|
TypeScript
|
discordjs/discord.js
|
/packages/builders/src/interactions/slashCommands/options/boolean.ts
|
UTF-8
| 614 | 2.8125 | 3 |
[
"Apache-2.0"
] |
permissive
|
import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';
import { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';
/**
* A slash command boolean option.
*/
export class SlashCommandBooleanOption extends ApplicationCommandOptionBase {
/**
* The type of this option.
*/
public readonly type = ApplicationCommandOptionType.Boolean as const;
/**
* {@inheritDoc ApplicationCommandOptionBase.toJSON}
*/
public toJSON(): APIApplicationCommandBooleanOption {
this.runRequiredValidations();
return { ...this };
}
}
| true |
3a409adc9d7e8a98dce303d1ec9cc9e54c21e733
|
TypeScript
|
jackfranklin/fetch-engine
|
/src/utils/composeEvery.test.ts
|
UTF-8
| 967 | 2.71875 | 3 |
[] |
no_license
|
/// <reference path="../.d.test.ts" />
"use strict";
import test = require("ava");
import composeEvery from "./composeEvery";
test("composeEvery is requireable", (t: TestAssertions) => {
t.ok(composeEvery);
});
test(
"it composes identity functions to produce passed value",
(t: TestAssertions) => {
const id = x => x;
const f = composeEvery([id, id]);
t.is(f(true), true);
t.is(f(false), false);
}
);
test(
"it composes value generating functions",
(t: TestAssertions) => {
const yes = () => true;
const no = () => false;
t.is(composeEvery([yes, yes])(true), true);
t.is(composeEvery([yes, yes])(false), true);
t.is(composeEvery([yes, no ])(true), false);
t.is(composeEvery([yes, no ])(false), false);
t.is(composeEvery([no, yes])(true), false);
t.is(composeEvery([no, yes])(false), false);
t.is(composeEvery([no, no ])(true), false);
t.is(composeEvery([no, no ])(false), false);
}
);
| true |
0adae82b8121a2ced87b3d0ecc3953a890ee036d
|
TypeScript
|
ariesjia/react-use-form
|
/src/reducer.ts
|
UTF-8
| 1,889 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
import {omit} from "./utils/omit";
import {FiledType} from "./filed-type";
import { getResetValue } from "./index";
export const actions = {
UPDATE_FIELD: 'UPDATE_FIELD',
SET_ERRORS: 'SET_ERRORS',
RESET: 'REST',
}
const getErrors = function(keys, fields, errors) {
const fieldsError = fields || {}
return Array.isArray(keys) ? keys.reduce((prev, key) => {
return fieldsError[key] ? {
...prev,
[key]: fieldsError[key],
} : omit(prev, [key])
}, errors) : fieldsError
}
export const reducer = function(state, action) {
const payload = action.payload
switch (action.type) {
case actions.UPDATE_FIELD:
return {
...state,
fields: {
...state.fields,
[payload.name]: {
...state.fields[payload.name],
...payload.data,
},
}
}
case actions.SET_ERRORS:
return {
...state,
errors: getErrors(
payload.keys,
payload.fieldsError,
state.errors
)
}
case actions.RESET:
const keys = payload.keys && payload.keys.length ? payload.keys : Object.keys(state.fields)
const fieldOptions = payload.fieldOptions || {}
const fields = state.fields
const resetFields = Object.keys(fields).reduce((prev, name) => {
const field = fields[name]
const option = fieldOptions[name] || {}
const shouldReset = keys.includes(name)
return shouldReset ? {
...prev,
[name]: {
...field,
value: getResetValue(option.type || FiledType.text),
}
} : prev
}, {})
return {
...state,
fields: {
...fields,
...resetFields
},
errors: getErrors(
keys,
{},
state.errors
)
}
default:
return state
}
}
| true |
f483606996d3dbaefff5f86442e49d7cd7ceb8f7
|
TypeScript
|
usb777/typescript
|
/OOP/classes/Animal.ts
|
UTF-8
| 1,756 | 3.578125 | 4 |
[] |
no_license
|
/**
4 Pillars of OOP:
1. Abstraction: abstract classes and Interfaces
2. Inheritence: extends and implements-- class className <name_of_Interface>
3. Encapsulation: restrict access keywords:=== public, private, protected, -default- === and Getter-Setter methods
4. Polymorphism: many-forms - in same class or file -
=== a. Same name function-method with different parameters (Overload)
=== b. Same name function-method from Parent-to-Child with same parameters, but different Logic (Override)
*/
interface Body
{
skelet: string
}
export default class Animal<Body> // class with interface
{
z:string ="hello Animal" ; // default
private tail:boolean;
private voice:string;
private legs : number;
private skelet:string="horde" // from Interface bpdy
protected eye:string ="2 yeys";
constructor ()
{
this.tail = true;
this.voice = "rrrrrr";
this.legs = 4;
}
public getRun(params:boolean)
{
if (params) console.log("Fast running");
else { console.log("slow running");}
}
public setTail(tail:boolean): void
{
this.tail = tail;
}
public getTail():boolean
{
return this.tail;
}
// Setter and Getter for voice fields banch
public setVoice(voice:string): void
{
this.voice = voice;
}
public getVoice():string
{
return this.voice;
}
// Setter and Getter for legs fields banch
public setLegs(legs:number): void
{
this.legs = legs;
}
public getLegs():number
{
return this.legs;
}
public toString() : string
{ return "tail = "+this.tail+" voice = "+this.voice+ " legs = "+ this.legs; }
}
| true |
95afe612278e26f908b8a3593051f918a63f911c
|
TypeScript
|
zWaR/typescript-patterns
|
/src/abstract-factory/try-abstract-factory.ts
|
UTF-8
| 344 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import { NYPizzaStore } from './creators';
import { PizzaBase } from './domain';
class TryAbstractFactory {
public static run() {
const nyStore: NYPizzaStore = new NYPizzaStore();
const nyPizza: PizzaBase = nyStore.orderPizza('cheese');
console.log(`NY pizza ${nyPizza.getName()} ordered`);
}
}
TryAbstractFactory.run();
| true |
0eab71d8fd00fb511f55640358211200cf1389fb
|
TypeScript
|
jamiesunderland/rest-my-case
|
/test/HttpStringHelper.spec.ts
|
UTF-8
| 2,147 | 2.84375 | 3 |
[] |
no_license
|
import HttpConfig from '../src/HttpConfig';
import HttpStringHelper from '../src/HttpStringHelper';
import { clientCase } from './mocks';
describe('HttpStringHelper', () => {
let httpStringHelper: HttpStringHelper;
let config;
beforeEach(() => {
config = new HttpConfig();
config.port = 8080;
httpStringHelper = new HttpStringHelper(config);
});
describe('.formatUriPrefix', () => {
test("when the uri is prefixed with a /", () => {
let uri = "/test";
expect(httpStringHelper.formatUriPrefix(uri)).toEqual("test");
});
test("when the uri is suffixed with a /", () => {
let uri = "/test";
expect(httpStringHelper.formatUriPrefix(uri)).toEqual("test");
});
test("when the uri is suffixed with a / and prefixed with a /", () => {
let uri = "/test/";
expect(httpStringHelper.formatUriPrefix(uri)).toEqual("test");
});
test("when the uri is has no prefix or suffic of /", () => {
let uri = "test";
expect(httpStringHelper.formatUriPrefix(uri)).toEqual("test");
});
});
describe('.requestUrl', () => {
let uri = "test";
let uriPrefix = "api";
let queryString = "";
test('when the port does not equal 80 or 443', () => {
config.port = 80;
expect(httpStringHelper.requestUrl(uri, uriPrefix, queryString))
.toEqual("http://localhost/api/test");
});
test('when the port does equal 80', () => {
config.port = 8080;
expect(httpStringHelper.requestUrl(uri, uriPrefix, queryString))
.toEqual("http://localhost:8080/api/test");
});
});
describe('.getQuery', () => {
test('when the query is a string it returns the uri encoded string', () => {
let query = "test=test value"
expect(httpStringHelper.getQuery(query))
.toEqual("?test=test%20value");
});
test('when the query is an object it case converts and stringifies', () => {
let queryString = "?key_one=1&key_two=two&key_three={\"key_four\":[{\"key_five\":5},{\"key_six\":6}]}";
expect(httpStringHelper.getQuery(clientCase))
.toEqual(queryString);
});
});
});
| true |
18e8183d1b47a0d0c866466d03321cdf508df3a9
|
TypeScript
|
kirontoo/QRMyWifi
|
/src/lib/util.ts
|
UTF-8
| 1,086 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
import QRCode from "qrcode";
export interface WifiCredentials {
network: string;
password: string;
encryption: string;
hidden: boolean;
}
export const sampleWifiCred: WifiCredentials = {
network: "sampleSSID",
password: "samplePassword",
encryption: "WPA",
hidden: false,
};
export const generateQRCode = ({
network,
password,
encryption,
hidden,
}: WifiCredentials) => {
// if entries are not filled, don't generate
if (network === "" && password === "") {
return;
}
const QRCanvas = document.getElementById("canvas");
// remove any existing canvases
let existingCanvas = document.getElementsByTagName("canvas");
if (existingCanvas.length > 0) {
QRCanvas!.removeChild(existingCanvas[0]);
}
// generate QR code
let credentials = `WIFI:S:${network};T:${encryption};P:${password};`;
credentials += hidden ? "H:true" : "H:false";
QRCode.toCanvas(credentials, { scale: 4, width: 300 }, function (err, qr) {
if (err) {
console.error(err);
return;
}
qr.id = "qrcode";
QRCanvas!.appendChild(qr);
});
};
| true |
102e3c7c761fc079cbdcd36f6859ff47cf866dda
|
TypeScript
|
chenjsh36/media-carrier
|
/src/utils/dataTransform.ts
|
UTF-8
| 2,064 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
import { get } from 'lodash';
import Request from './request';
export function arrayBuffer2Blob(arrayBuffer: any, type: string ) {
const blob = new Blob([arrayBuffer], { type });
return blob;
}
export function arrayBuffer2File(arrayBuffer: any, name: string, options?: { type?: string; lastModified?: number } ) {
const file = new File([arrayBuffer], name, options);
return file;
}
export function blob2ArrayBuffer(blob: Blob): Promise<ArrayBuffer> {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = function() {
resolve(fileReader.result as ArrayBuffer);
};
fileReader.onerror = function(evt) {
const err1 = get(evt, 'target.error.code', 'NO CODE');
const err2 = get(fileReader, 'error.code', 'NO CODE');
reject(`fileReader read blob error: ${err1} or ${err2}`);
};
fileReader.readAsArrayBuffer(blob);
});
}
export function blob2ObjectURL(blob: Blob): string {
const url = URL.createObjectURL(blob);
return url;
}
export function blob2AudioEelemnt(blob: Blob): HTMLAudioElement {
const url = blob2ObjectURL(blob);
return new Audio(url);
}
export function blob2VideoElement(blob: Blob): HTMLVideoElement {
const url = blob2ObjectURL(blob);
const video = document.createElement('video');
video.src = url;
return video;
}
type FileType = 'arrayBuffer' | 'file';
export async function reqMedia(url: string, fileType: FileType = 'arrayBuffer' ): Promise<ArrayBuffer | Blob> {
if (!url) return Promise.resolve(null);
return Request({
url,
method: 'get',
responseType: 'arraybuffer',
}).then((res: any) => {
const arrayBuffer = res.data;
const contentType = res.headers['content-type'] || '';
let ret = arrayBuffer;
if (fileType === 'file') {
ret = arrayBuffer2File(ret, 'result', { type: contentType });
}
return ret;
})
};
export default {
arrayBuffer2Blob,
arrayBuffer2File,
blob2ArrayBuffer,
blob2AudioEelemnt,
blob2VideoElement,
blob2ObjectURL,
reqMedia,
}
| true |
34023c3232b7402d8dd79079554efb68aeddbcbe
|
TypeScript
|
jonathapriebe/NodeJS-Interview
|
/src/models/customer.ts
|
UTF-8
| 773 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
import mongoose, { Document, Model } from 'mongoose';
export interface Customer {
_id?: string;
name: string;
gender: string;
dt_birthday: Date;
age: number;
city_id: string;
}
const schema = new mongoose.Schema(
{
name: { type: String, required: true },
gender: { type: String, required: true },
dt_birthday: { type: Date, required: true },
age: { type: Number, required: true },
city_id: { type: String, required: true },
},
{
toJSON: {
transform: (_, ret): void => {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
},
},
}
);
interface CustomerModel extends Omit<Customer, '_id'>, Document {}
export const Customer: Model<CustomerModel> = mongoose.model(
'Customer',
schema
);
| true |
590822eca99ff891cecbc7a66aaca8104516cf89
|
TypeScript
|
mcortesi/battle4tronia-server
|
/src/db/message-store.ts
|
UTF-8
| 2,524 | 2.671875 | 3 |
[] |
no_license
|
import db from '../connections/postgres';
import { MessageType, MessagePlayerOpened, MessageDealerAccepted, MessagePlayerClosed } from '../model/message';
import { Address } from '../tron/types';
export function fromPG(record: any): MessagePlayerOpened | MessageDealerAccepted | MessagePlayerClosed {
const obj = record.text;
switch(obj.type) {
case MessageType.PLAYER_OPENED: {
return {
playerAddress: record.player_address,
channelId: record.channel_id,
round: record.round,
publicKey: record.public_key,
type: record.type,
bet: obj.bet,
player: obj.player,
playerRandomHash1: obj.playerRandomHash1,
playerRandomHash2: obj.playerRandomHash2,
playerRandomHash3: obj.playerRandomHash3,
signature: obj.signature
};
}
case MessageType.DELEAR_ACCEPTED: {
return {
messagePlayerOpened: obj.messagePlayerOpened,
type: obj.type,
dealerRandomNumber1: obj.dealerRandomNumber1,
dealerRandomNumber2: obj.dealerRandomNumber2,
dealerRandomNumber3: obj.dealerRandomNumber3,
signature: obj.signature
};
}
case MessageType.PLAYER_CLOSED: {
return {
messageDealerAccepted: obj.messageDealerAccepted,
type: obj.type,
playerUpdated: obj.playerUpdated,
playerRandomNumber1: obj.playerRandomNumber1,
playerRandomNumber2: obj.playerRandomNumber2,
playerRandomNumber3: obj.playerRandomNumber3,
signature: obj.signature
};
}
default: throw("Unrecognized message type");
}
}
export async function getLastMessage(playerAddress: Address): Promise<null | MessagePlayerOpened | MessageDealerAccepted | MessagePlayerClosed> {
const res = await db.oneOrNone<any>(
'select * from messages where player_address = $(playerAddress) order by created_date desc limit 1',
{
playerAddress,
}
);
return res != null ? fromPG(res) : null;
}
export function insertMessage(
playerAddress: Address,
channelId: number,
round: number,
type: string,
text: string
): Promise<boolean> {
return db.result(
`INSERT INTO messages(
player_address,
channel_id,
round,
type,
text
) VALUES (
$(playerAddress),
$(channelId),
$(round),
$(type),
$(text)
) ON CONFLICT DO NOTHING`,
{
playerAddress,
channelId,
round,
type,
text
},
cb => cb.rowCount === 1
);
}
| true |
9d3e81d2c3302648f1ee2f107eb35d35ef6f3b49
|
TypeScript
|
BraTTik/redux-paint
|
/src/modules/strokes/actions.ts
|
UTF-8
| 345 | 2.5625 | 3 |
[] |
no_license
|
import { Stroke } from '../../types';
export const END_STROKE = 'END_STROKE';
export type StrokesAction = {
type: typeof END_STROKE;
payload: { stroke : Stroke, historyLimit : number}
}
export const endStroke = (stroke : Stroke, historyLimit: number) => {
return {type: END_STROKE, payload: {stroke, historyLimit} };
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.