blob_id
large_stringlengths 40
40
| language
large_stringclasses 1
value | repo_name
large_stringlengths 5
119
| path
large_stringlengths 4
271
| score
float64 2.52
4.84
| int_score
int64 3
5
| text
stringlengths 26
4.09M
|
|---|---|---|---|---|---|---|
33f00bd561a7ac8823e646575c99365d1f6ce3ee
|
TypeScript
|
BlockCat/DogmaJS
|
/src/core/effects/DogmaEffect.ts
| 2.71875
| 3
|
import DogmaExpressionTree from './DogmExpressionTree';
import Modifier, {DogmaAssociation} from '../modifier/Modifier';
import CacheHandler from '../CacheHandler';
import {DogmaEnvironmentType} from '../modifier/DogmaEnvironment';
import {GroupFilter, TypeFilter} from '../modifier/Filter';
export default class DogmaEffect {
effectId: number;
preExpressionId: number;
name: string;
description: string;
printFormat: string;
private modifiers: Modifier[] = null;
constructor(effectId: number, description: string, name: string, preExpressionId: number) {
this.effectId = effectId;
this.preExpressionId = preExpressionId;
this.name = name;
this.description = description;
this.printFormat = null;
}
getExpressionTree(): DogmaExpressionTree {
return DogmaExpressionTree.BuildTree(this.preExpressionId);
}
getModifiers(): Modifier[] {
if (this.modifiers === null) {
console.log('Loading effect modifiers');
this.modifiers = [];
this.Parse(this.getExpressionTree());
}
return this.modifiers;
}
Parse(tree: DogmaExpressionTree ) {
if (tree.operand.operandKey === 'COMBINE') {
this.Parse(tree.arg1);
this.Parse(tree.arg2);
return;
}
if (!['AGGM', 'AGIM', 'AGORSM', 'AGRSM', 'AIM', 'ALGM', 'ALM', 'ALRSM', 'AORSM', ].some(x => x === tree.operand.operandKey)) {
console.log('Invalid expression tree: ' + tree.operand.operandKey);
return;
}
// Get the attribute from an expression
const changeAttribute = CacheHandler.GetCacheHandler().GetAttribute(tree.arg2.expression.expressionAttributeID);
const association = tree.arg1.arg1.expression.expressionName as DogmaAssociation;
const targetAttribute = CacheHandler.GetCacheHandler().GetAttribute(tree.arg1.arg2.arg2.expression.expressionAttributeID);
const newModifier = new Modifier(association, targetAttribute, changeAttribute);
let dogmaEnvironmentType;
// Type filter (skill)
if (tree.arg1.arg2.arg1.operand.operandKey === 'LS') {
const filterType = tree.arg1.arg2.arg1.arg2.expression.expressionTypeID;
dogmaEnvironmentType = tree.arg1.arg2.arg1.arg1.expression.expressionName as DogmaEnvironmentType;
newModifier.setFilter(new TypeFilter(filterType));
} else if (tree.arg1.arg2.arg1.operand.operandKey === 'LG') {
// Group filter
const filterGroup = tree.arg1.arg2.arg1.arg2.expression.expressionGroupID;
dogmaEnvironmentType = tree.arg1.arg2.arg1.arg1.expression.expressionName as DogmaEnvironmentType;
newModifier.setFilter(new GroupFilter(filterGroup));
} else {
dogmaEnvironmentType = tree.arg1.arg2.arg1.expression.expressionName as DogmaEnvironmentType;
}
newModifier.setEnvironmentType(dogmaEnvironmentType);
console.log('Modifier loaded:', newModifier);
this.modifiers.push(newModifier);
}
}
|
353520e5941be5777403bf8f9b090fe6c00399a0
|
TypeScript
|
leemit/typescript-demo
|
/app/src/Line.ts
| 3.1875
| 3
|
/// <reference path='includes.ts' />
module sample {
'use strict'
export class Line implements Shape, Equality<Line> {
constructor(public start: Point, public end: Point) {
}
draw(context: CanvasRenderingContext2D) {
context.beginPath();
context.moveTo(this.start.x, this.start.y);
context.lineTo(this.end.x, this.end.y);
context.stroke();
}
public equals(other: Line) : boolean {
return this.start.equals(other.start) && this.end.equals(other.end);
}
}
}
|
4cb9eac913e445bb6aa696d44ce321ca714b59ee
|
TypeScript
|
phamhuuan/LibraryClient
|
/src/reducers/genresReducer.ts
| 2.78125
| 3
|
import {GenresReducerActionType} from './../@types/action/index';
import {GET_ALL_GENRES_FAIL, GET_ALL_GENRES_RESET_MESSAGE, GET_ALL_GENRES_SUCCESS} from './../actions/ActionType';
import {GenresReducerStateType} from "../@types/reducer";
const initialState: GenresReducerStateType = {
data: [],
getGenresMessage: '',
getGenreErrorCode: undefined,
};
const genresReducer = (state = initialState, action: GenresReducerActionType): GenresReducerStateType => {
switch (action.type) {
case GET_ALL_GENRES_RESET_MESSAGE:
return {...state, getGenresMessage: ''};
case GET_ALL_GENRES_SUCCESS:
state.data = action.genres;
state.getGenresMessage = GET_ALL_GENRES_SUCCESS;
return {...state};
case GET_ALL_GENRES_FAIL:
state.getGenreErrorCode = action.errorCode;
state.getGenresMessage = GET_ALL_GENRES_FAIL;
return {...state};
default:
return state;
}
}
export default genresReducer;
|
054a0e279bf52a61f56038a917a91a6ce00a782a
|
TypeScript
|
felipejsborges/proffy-api
|
/src/infra/http/validators/users/loginValidator.ts
| 2.609375
| 3
|
import { Request, Response, NextFunction } from 'express';
import Joi from 'joi';
const loginSchema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(6).required(),
});
export default async function loginValidator(
request: Request,
response: Response,
next: NextFunction,
): Promise<void> {
const { email, password } = request.body;
await loginSchema.validateAsync({
email,
password,
});
return next();
}
|
9f1c4c42c43b3c28ed1c086cc21be554e7f7d305
|
TypeScript
|
rolesvillesoftware/RolesvilleTools
|
/dist/src/Exception.d.ts
| 2.515625
| 3
|
export declare class Exception {
private _message;
private _stackTrace;
private _innerException;
readonly message: string;
readonly stackTrace: string;
readonly innerException: Exception;
readonly error: Error;
constructor(error: Error | Exception | string, innerException?: Error | string | Exception);
buildError(error: Error): void;
buildException(exception: Exception): void;
buildString(error: string): void;
}
|
6b1f7a1259a5c613894d8eab0cfc9c74fae4ec2e
|
TypeScript
|
JulesCubs/IntroTypeScript
|
/src/typeVoid.ts
| 3.8125
| 4
|
//Void
//Explicito
function showInfo(user: any): any {
console.log("User Info", user.id, user.userName, user.firstName);
}
//Inferido
function showFormattedInfo(user: any) {
console.log(
"User Info",
`
id: ${user.id}
username: ${user.userName}
firstname: ${user.firstName}
`
);
}
showInfo({ id: 1, userName: "Jules", firstName: "Julian" });
showFormattedInfo({ id: 1, userName: "Jules", firstName: "Julian" });
//tipo Void como tipo de dato en una variable
let unusable: void;
//void puede tomar el valor de null o undefined
//unusable = null;
//unusable = undefined;
//Never
//Inferido
function handleError(code: number, message: string): never {
//Process you code here
//Generate a message
throw new Error(`${message}. Code: ${code}`);
}
try {
handleError(404, "Not Found");
} catch (error) {}
// function sumNumbers(limit: number): never {
// let sum = 0;
// while (true) {
// sum++;
// }
// }
// sumNumbers(10);
//ciclo infinito
|
39ce5c046e4d7f6d4f0fcb28b5cd03d3ee93834d
|
TypeScript
|
puneetgupta4java/EmployeeManagementUI
|
/src/app/state/actions/ems.action.ts
| 2.734375
| 3
|
import { Action } from '@ngrx/store';
import { Employee } from 'src/app/model/employee.model';
/**
* Enum for EmsUiAction
*/
export enum EmsUiAction {
AddEmployee = '[ems-ui] Add new employee',
AddEmployeeSuccess = '[ems-ui] Add new employee success',
AddEmployeeFailure = '[ems-ui] Add new employee failure',
UpdateEmployeeCount = '[ems-ui] update employees count',
SaveEmployees = '[ems-ui] Save employees'
}
export class AddEmployeeAction implements Action {
readonly type = EmsUiAction.AddEmployee;
constructor(public payload: Employee) { }
}
export class AddEmployeeSuccessAction implements Action {
readonly type = EmsUiAction.AddEmployeeSuccess;
}
export class AddEmployeeFailureAction implements Action {
readonly type = EmsUiAction.AddEmployeeFailure;
}
export class UpdateEmployeeCountAction implements Action {
readonly type = EmsUiAction.UpdateEmployeeCount;
}
export class SaveEmployeesAction implements Action{
readonly type = EmsUiAction.SaveEmployees;
constructor(public payload: Employee[]) { }
}
export type EmsUiActions =
| AddEmployeeAction
| AddEmployeeSuccessAction
| AddEmployeeFailureAction
| UpdateEmployeeCountAction
| SaveEmployeesAction;
|
ba833846dc26b0b9dd95faa2e5a6e011ba242817
|
TypeScript
|
jconnor0078/lotery-app-rest
|
/src/mongo/models/users.ts
| 2.71875
| 3
|
import { Schema, model, Document } from "mongoose";
export interface IUser extends Document {
name: string;
lastName: string;
documentType: string;
documentNumber: string;
email: string;
address: string;
birthday: Date;
phone1: string;
phone2?: string;
phone3?: string;
image: string;
imageDocument: string;
userName: string;
password: string;
roles: string[];
creatorUser: IUser | string;
modifierUser?: IUser | string;
}
const userSchema: Schema = new Schema(
{
name: { type: String, require: true },
lastName: { type: String, require: true },
documentType: {
type: String,
require: true,
enum: ["cedula", "pasaporte"],
default: "cedula",
},
documentNumber: { type: String, require: true },
birthday: { type: Date, require: true },
email: { type: String, require: true },
address: { type: String, require: true },
phone1: { type: String, require: true },
phone2: { type: String, require: true },
phone3: { type: String, require: true },
image: { type: String, require: true },
imageDocument: { type: String, require: true },
userName: { type: String, require: true },
password: { type: String, require: true },
roles: [{ type: String, enum: ["admin", "seller"], default: "seller" }],
creatorUser: { type: Schema.Types.ObjectId, ref: "User" },
modifierUser: { type: Schema.Types.ObjectId, ref: "User" },
},
{
timestamps: true,
}
);
const userModel = model<IUser>("User", userSchema);
export default userModel;
|
1a0a2da1bf062a0d67e57b3087428335827fbebb
|
TypeScript
|
uwblueprint/BEP
|
/server/src/api/users/picklists/UserPicklistRouter.ts
| 2.609375
| 3
|
/**
* Required External Modules and Interfaces
*/
import * as UserPicklistService from './UserPicklistService';
import * as Express from 'express';
/**
* Router Definition
*/
export const userPicklistRouter = Express.Router();
/**
* Controller Definitions
*/
// GET users/:name
userPicklistRouter.get('/:name', async (req: Express.Request, res: Express.Response) => {
const picklistName: string = req.params.name;
try {
const picklist: string[] = await UserPicklistService.getUserPicklist(picklistName);
res.status(200).send(picklist);
} catch (e) {
res.status(500).send({ msg: e.message });
}
});
// // GET users/:name
userPicklistRouter.get('/opportunity/:name', async (req: Express.Request, res: Express.Response) => {
const picklistName: string = req.params.name;
try {
const picklist: string[] = await UserPicklistService.getOpportunityPicklist(picklistName + '__c');
res.status(200).send(picklist);
} catch (e) {
res.status(500).send({ msg: e.message });
}
});
|
ba687c0d53c03b7e7f15fab892ef8f8cd17a2e2e
|
TypeScript
|
hanzo2001/gi-json
|
/sources/Nodes/Member.ts
| 2.640625
| 3
|
/// <reference path="../typings/index.d.ts" />
import {ValueContainer} from "./ValueContainer";
import {ElementParser} from "./Utils";
import {MemberName} from "./MemberName";
export class Member extends ValueContainer implements iMember {
n: iMemberName;
constructor(h: iNodeHash, name: string, input: HTMLElement|ValueType, f: iNodeFactory) {
super();
this.f = f;
let e: HTMLElement = this._init(h,input);
if (input instanceof HTMLElement) {
this.n = new MemberName(h,<HTMLElement>e.firstChild);
} else {
this.n = new MemberName(h,name);
this._append(this.n,this.v);
}
}
getName(): string {
return this.n.name;
}
setName(name: string) {
this.n.setName(name);
}
toString() {
return '"'+ElementParser.str2json(this.n+'')+'":'+this.v;
}
protected _init(h: iNodeHash, input: HTMLElement|ValueType): HTMLElement {
let e: HTMLElement;
if (input instanceof HTMLElement) {
e = super._init(h,input);
this.v = this.f.create(this._h,<HTMLElement>e.lastChild);
} else {
e = super._init(h,'member');
this.v = this.f.create(this._h,input);
this._append(this.v);
}
return e;
}
}
|
39356f2750b0cb6b804cd7ea8c804b34ce35f4c6
|
TypeScript
|
NDSU-CSA/hack-b0t
|
/src/commands/fun/zimzam.ts
| 2.8125
| 3
|
import { Command } from "../command";
import { ICommandParams } from "../../misc/globals";
import fs from "fs";
/**
* Anime
*
* Sends a picture of anime
*
* Category : fun
* Admin : no
* Chat params : none
*/
async function execute(params: ICommandParams) : Promise<void> {
// ignore messages without a channel
if(!params.message.channel) return;
const filename : string = "./res/img/beepboop.gif";
// upload file to channel of original request
params.slack.files.upload({
filename: filename,
file: fs.createReadStream(filename),
channels: params.message.channel
});
}
export const command : Command = new Command({
name: "zimzam",
description: "Oh I love Cowboy ZimZam!",
category: "fun",
usage: "zimzam",
admin: false,
execute : execute
});
|
7e763848ff836cfa1ff37b36d3413d6e6c134024
|
TypeScript
|
filipagh/loopback4-test
|
/src/models/shop-note.model.ts
| 2.609375
| 3
|
import {Entity, model, property, hasMany} from '@loopback/repository';
import {Item, ItemWithRelations} from './item.model';
@model()
export class ShopNote extends Entity {
@property({
type: 'number',
id: true,
generated: true,
})
id?: number;
@property({
type: 'string',
required: true,
})
name: string;
@hasMany(() => Item)
items: Item[];
constructor(data?: Partial<ShopNote>) {
super(data);
}
}
export interface ShopNoteRelations {
// describe navigational properties here
items?: ItemWithRelations[];
}
export type ShopNoteWithRelations = ShopNote & ShopNoteRelations;
|
9de27ca01662273809128b0b2703b722addbd05a
|
TypeScript
|
maasencioh/cheminfo-types
|
/src/core/DoubleArray.d.ts
| 2.71875
| 3
|
/**
* In order to store an array of numbers we prefer to either use native javascript
* arrays or to use Float64Array
*/
export type DoubleArray = number[] | Float64Array;
|
1a96ca94a6693580d5342878ec3a39b19fa4ee43
|
TypeScript
|
lcmpembroke/TypeScriptCrashCourseUdemy
|
/01_types.ts
| 4.21875
| 4
|
let aName: any; // type of any allows different types to be assigned later
aName = 12;
aName = "Tomato";
let aName2 = "Apple";
//aName2 = 12; cannot do this as initial assignment was to a string so it has to remain as a string
let anArray: any[] = ["tea", "coffee", "milk"];
console.log(`anArray initially: ${anArray[0]}, ${anArray[1]}, ${anArray[2]}`);
anArray = [2, 3]; // can do this because array initially was created of any[]
console.log(`anArray second: ${anArray[0]}, ${anArray[1]}`);
anArray = ["tea", 55];
console.log(`anArray third: ${anArray[0]}, ${anArray[1]}`);
let numbersArray: number[] = [2, 3, 4, 5, 6];
numbersArray = [1, 2,99];
console.log(`NumberArray length: ${numbersArray.length}`);
for (var i in numbersArray) {
console.log(`Number: ${numbersArray[i]}`);
}
// -------------------------------------------------------
// writing functions strictly - assigning types to all variables - could be writeen without ANY types defined but then errors only detected in runtime rather than compile time
function testFunction(val1: number, val2: number): number {
let total: number = val1 + val2;
return total;
}
console.log(`testFunction(2,4): ${testFunction(2, 4)}`);
|
8e570fcc540a0b4aba55db7dc6280c737751263d
|
TypeScript
|
Sxip/express-typescript-boilerplate
|
/app/Logger.ts
| 2.59375
| 3
|
import { createLogger, format, transports } from 'winston'
import chalk from 'chalk'
import path from 'path'
/**
* Logger formatter.
*
* @param colorize
*/
const formatter = (colorize: boolean) =>
format.printf(info => {
const content = colorize ? chalk.yellow(JSON.stringify(info)) : JSON.stringify(info)
return `[${info.timestamp}] ${info.level}: ${info.message} ${content}`
})
/**
* Logger.
*/
export default createLogger({
transports: [
new transports.File({
filename: path.join('./logs/error.log'),
level: 'error',
format: format.combine(format.timestamp(), formatter(false)),
}),
new transports.File({
filename: path.join('./logs/combined.log'),
format: format.combine(format.timestamp(), formatter(false)),
}),
new transports.Console({
level: 'info',
format: format.combine(format.timestamp(), format.colorize(), formatter(true)),
}),
],
})
|
3eee4b39f386235c6b5a51318461b25d1f9e4881
|
TypeScript
|
kakisoft/PracticeJavaScript
|
/TypeScript/practice_typescript04.ts
| 2.84375
| 3
|
/*
★AMD方式でコンパイル
-------------------------------------------------------
tsc practice_typescript04.ts -t ES5 -m amd
※nodeで実行できない
-------------------------------------------------------
'--module' option : 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'esnext'.
*/
//==================================
// 外部モジュール
//==================================
//外部モジュールは内部モジュールと違い、1 ファイルに 1 モジュール入れることになる。
//(module の外枠は不要)
//=====< 宣言方法 >=====
// Node - CommonJS
// RequireJS - AMD方式
import User = require("./modules/player"); //※拡張子は不要。呼び出し元のファイル名の拡張子は「.ts」
console.log(User.name);
|
a0095106a309a8751119f4935cf7317c525df968
|
TypeScript
|
RomaSRS/My-blog
|
/src/helpers/uniqueId.ts
| 2.859375
| 3
|
const idCounter: { [prefix: string]: number } = {};
export default function uniqueId(prefix = 'id'): string {
if (!idCounter[prefix]) {
idCounter[prefix] = 0;
}
// eslint-disable-next-line no-plusplus
const id = ++idCounter[prefix];
if (prefix === 'id') {
return `${id}`;
}
return `${prefix}${id}`;
}
|
1a7ef9f65c205f5d65479c851d723744e7a691e7
|
TypeScript
|
dslming/learningComputerGraphics
|
/ThreejsLearning/011-webpack-ff91/src/shader/stop_bar_vert.glsl.ts
| 2.609375
| 3
|
export default
`
varying float brightness;
varying vec2 vUV;
// Normalizes a value between 0 - 1
float normFloat(float n, float minVal, float maxVal){
return max(0.0, min(1.0, (n-minVal) / (maxVal-minVal)));
}
void main() {
vUV = uv;
vec4 realPos = modelMatrix * vec4(position, 1.0);
vec3 realNorm = normalize(vec3(modelMatrix * vec4(normal, 0.0)));
vec3 lightVector = normalize(cameraPosition - realPos.xyz);
float diffuse = dot(realNorm, lightVector);
brightness = normFloat(diffuse, 0.0, 0.5);
vec4 mvPosition = viewMatrix * realPos;
gl_Position = projectionMatrix * mvPosition;
}
`
|
7c4e23587c69e13e0b75922766e8f67d33cea2e9
|
TypeScript
|
IronOnet/codebases
|
/codebases/coursera.org/static/bundles/goal-setting/utils/computeGoalProgressLevel.ts
| 2.65625
| 3
|
import { LearnerGoal } from 'bundles/goal-setting/types/LearnerGoal';
import {
GoalNDaysAWeek,
StreakLevels,
FirstAssignmentLevels,
FinishNVideosLevels,
GoalProgressLevels,
} from 'bundles/goal-setting/types/GoalProgressLevels';
import {
GOAL_TYPE_COMPLETE_N_ASSIGNMENTS,
GOAL_TYPE_N_DAY_STREAK,
GOAL_TYPE_N_DAYS_A_WEEK,
GOAL_TYPE_COMPLETE_N_VIDEOS,
} from './constants';
type ComputationConfig = {
learnerGoal: LearnerGoal;
isPullBased?: boolean;
};
export const computeFinishNVideosProgressLevel = ({
learnerGoal,
isPullBased,
}: ComputationConfig): FinishNVideosLevels => {
const {
goalType: {
definition: { n },
},
} = learnerGoal;
const progress = learnerGoal.progress || {};
const history = progress.history || [];
const progressPercentage = (progress || {}).percentage;
if (history.length >= n) {
return 'goalComplete';
}
if (isPullBased) {
if (progressPercentage <= 0.05) {
return 'lowProgress';
} else {
return 'significantProgress';
}
}
if (history.length === n - 1) {
return 'oneVideoLeft';
} else if (history.length >= n / 2) {
return 'halfOfNVideos';
} else if (history.length >= 2) {
return 'afterTwoVideos';
}
return 'lowProgress';
};
export const computeFirstAssignmentProgressLevel = ({
learnerGoal,
isPullBased,
}: ComputationConfig): FirstAssignmentLevels => {
const {
goalType: {
definition: { n },
},
} = learnerGoal;
const progress = learnerGoal.progress || {};
const history = progress.history || [];
if (history.length >= n) {
return 'goalComplete';
}
if (isPullBased) {
return 'lowProgress';
}
if (history.length === 0) {
return 'openAssignment';
}
return 'lowProgress';
};
export const computeStreakProgressLevel = ({ learnerGoal }: ComputationConfig): StreakLevels => {
const {
goalType: {
definition: { n },
},
} = learnerGoal;
const progress = learnerGoal.progress || {};
const history = progress.history || [];
if (history.length >= n) {
return 'goalComplete';
}
if (history.length === 2) {
return 'secondDay';
} else if (history.length === 1) {
return 'firstDay';
}
return 'streakBroken';
};
export const computeGoalNDaysAWeekProgressLevel = ({ learnerGoal }: ComputationConfig): GoalNDaysAWeek => {
const {
goalType: {
definition: { n },
},
} = learnerGoal;
const progress = learnerGoal.progress || {};
const history = progress.history || [];
if (history.length > n) {
switch (history.length) {
case 7:
return 'goalExceeded7DayStreak';
case 6:
return n === 5 ? 'goalExceededByOneDay' : 'goalExceededNice';
case 5:
return 'goalExceededAwesome';
case 4:
return n === 3 ? 'goalExceededByOneDay' : 'goalExceededGreat';
case 3:
return 'goalExceededByOneDay';
default:
return 'oneDayComplete';
}
}
if (history.length === n) {
return 'goalComplete';
}
switch (history.length) {
case 4:
return 'goalAlmostComplete';
case 3:
return 'threeDaysComplete';
case 2:
return n === 3 ? 'goalAlmostComplete' : 'twoDaysComplete';
case 1:
return 'oneDayComplete';
default:
return 'oneDayComplete';
}
};
export default ({ learnerGoal, isPullBased }: ComputationConfig): GoalProgressLevels | null => {
const { typeName } = (learnerGoal || {}).goalType || {};
switch (typeName) {
case GOAL_TYPE_COMPLETE_N_VIDEOS:
return computeFinishNVideosProgressLevel({ learnerGoal, isPullBased });
case GOAL_TYPE_COMPLETE_N_ASSIGNMENTS:
return computeFirstAssignmentProgressLevel({ learnerGoal, isPullBased });
case GOAL_TYPE_N_DAY_STREAK:
return computeStreakProgressLevel({ learnerGoal, isPullBased });
case GOAL_TYPE_N_DAYS_A_WEEK:
return computeGoalNDaysAWeekProgressLevel({ learnerGoal });
default:
return null;
}
};
|
b572d43e97794c507bf0065e45dae4f366b8d3c9
|
TypeScript
|
my9527/strategies-blockchain
|
/src/lib/utils.ts
| 2.671875
| 3
|
import CryptoJS from 'crypto';
import path from 'path';
import fs, { ReadStream, WriteStream } from 'fs';
import uuid from 'uuid';
// import { ApiKey } from '../config';
export function sign(text: string, secret: string, outputType:any = 'base64') {
return CryptoJS
.createHmac('sha256', secret)
.update(text)
.digest(outputType);
}
// kucoin auth
export function auth(ApiKey: any, method: string, url: string, data: any) {
const timestamp = Date.now();
const signature = sign(timestamp + method.toUpperCase() + url + data, ApiKey.secret);
return {
'KC-API-KEY': ApiKey.key,
'KC-API-SIGN': signature,
'KC-API-TIMESTAMP': timestamp.toString(),
'KC-API-PASSPHRASE': ApiKey.passphrase || '',
'Content-Type': 'application/json',
};
}
export async function readFile(filePath: string): Promise<string> {
const fileAbsolutePath: string = path.join(__dirname, filePath);
console.log(fileAbsolutePath);
const readStream: ReadStream = fs.createReadStream(fileAbsolutePath);
let chunk: string = "";
return new Promise((resolve) => {
readStream.on('data', data => {
chunk += data;
});
readStream.on('end', () => {
resolve(chunk);
});
readStream.on('error', (err: Error) => {
resolve(err.message);
})
})
}
export async function writeFile(filePath: string, content: string): Promise<string> {
const fileAbsolutePath: string = path.join(__dirname, filePath);
const writeStream: WriteStream = fs.createWriteStream(fileAbsolutePath);
return new Promise(resolve => {
writeStream.write(content);
writeStream.on('end', () => {
resolve("");
});
writeStream.on('error', (err: Error) => {
resolve(err.message);
});
})
}
export function genClientOid() {
return uuid.v4();
}
export function strTo2String(str: string): string {
var result = [];
var list = str.split("");
for (var i = 0; i < list.length; i++) {
var item = list[i];
var binaryStr: string = item.charCodeAt(0).toString(8);
result.push(binaryStr);
}
return result.join("");
}
export const getPrecision = (num: number) => {
return (num.toString().split('.')[1] || '').length
}
|
1270feb47eb69c0a4053195fd410ca82f754da41
|
TypeScript
|
ChonyiLama/flashcardApp
|
/src/app/vocablist-data.service.ts
| 2.671875
| 3
|
import { Injectable } from '@angular/core';
import { VOCABLIST } from './vocablist-data';
@Injectable({
providedIn: 'root'
})
export class VocablistDataService {
constructor() { }
addWord(name, alt_names, meaning): void {
const word = new Map();
word.set('name', name);
word.set('alt_names', alt_names);
word.set('meaning', meaning);
VOCABLIST.push(word);
}
removeWord(name): void {
VOCABLIST.forEach((element, index) => {
if (element.get('name') === name) {
delete VOCABLIST[index];
console.log('removing word ', element);
}
});
}
getRandomWord(): Map<any, any> {
return VOCABLIST[Math.floor(Math.random() * VOCABLIST.length)];
}
// If easy, lower the chance that it will show up.
// Click 'EASY'-> store index of word->
getVocabList(): any {
return VOCABLIST;
}
}
|
6a086c115c636cf1943b8c42a2f1f0af56e43551
|
TypeScript
|
Titaye/slate-yjs
|
/src/apply/node/moveNode.ts
| 2.734375
| 3
|
import { MoveNodeOperation } from 'slate';
import { SyncDoc, SyncNode } from '../../model';
import { getParent } from '../../path';
import { cloneSyncElement } from '../../utils';
/**
* Applies a move node operation to a SyncDoc.
*
* @param doc
* @param op
*/
export default function moveNode(doc: SyncDoc, op: MoveNodeOperation): SyncDoc {
const [from, fromIndex] = getParent(doc, op.path);
const [to, toIndex] = getParent(doc, op.newPath);
if (
SyncNode.getText(from) !== undefined ||
SyncNode.getText(to) !== undefined
) {
throw new TypeError("Can't move node as child of a text node");
}
const fromChildren = SyncNode.getChildren(from);
const toChildren = SyncNode.getChildren(to);
const toMove = fromChildren!.get(fromIndex);
const toInsert = cloneSyncElement(toMove);
fromChildren!.delete(fromIndex);
toChildren!.insert(Math.min(toIndex, toChildren!.length), [toInsert]);
return doc;
}
|
44e1a0cbee6b5af3b36af96991aed6629ee7737c
|
TypeScript
|
Dhumez-Sebastien/trap.js
|
/src/protocols/Core.ts
| 2.953125
| 3
|
///<reference path="./../defLoader.d.ts" />
/**
* Core
*
* @module :: Core
* @description :: The Core class of all Protocols.
*/
class Core {
/**
* The name of protocol
* @type {string}
* @protected
*/
protected _protocolName : string = '';
/**
* Time during which the connection attempt stay in memory (in seconds) (3600 by default)
*
* @property _accountFindTime
* @type {number}
* @protected
*/
protected _accountFindTime : number;
/**
* Enable or disable account locking protection (true by default)
*
* @property _accountLockEnable
* @type {boolean}
* @protected
*/
protected _accountLockEnable : boolean = true;
/**
* Time during account is locked
*
* @property _accountLockTime
* @type {number}
* @protected
*/
protected _accountLockTime : number;
/**
* Number of attempt before lock account (15 by default)
*
* @property _accountMaxRetry
* @type {number}
* @protected
*/
protected _accountMaxRetry : number;
/**
* Time during which the connection attempt stay in memory (in seconds) (3600 by default)
*
* @property _userFindTime
* @type {number}
* @protected
*/
protected _userFindTime : number;
/**
* Time during user IP is locked
*
* @property _userBanTime
* @type {number}
* @protected
*/
protected _userBanTime : number;
/**
* Number of attempt before ban user (10 by default)
*
* @property _userMaxRetry
* @type {number}
* @protected
*/
protected _userMaxRetry : number;
/**
* Basic constructor
*
* @param jailConfig {IJailConfig} Jail configuration
*/
public constructor(jailConfig : IJailConfig) {
if (jailConfig) {
// Account
this._accountFindTime = (jailConfig.accountFindTime) ? jailConfig.accountFindTime : 3600 * 1000;
this._accountLockEnable = (jailConfig.accountLockEnable === true);
this._accountLockTime = (jailConfig.accountLockTime) ? jailConfig.accountLockTime : 600 * 1000;
this._accountMaxRetry = (jailConfig.accountMaxRetry) ? jailConfig.accountMaxRetry : 15;
// User
this._userFindTime = (jailConfig.userFindTime) ? jailConfig.userFindTime : 3600 * 1000;
this._userBanTime = (jailConfig.userBanTime) ? jailConfig.userBanTime : 7200 * 1000;
this._userMaxRetry = (jailConfig.userMaxRetry) ? jailConfig.userMaxRetry : 10;
}
}
/**
* Init protocol
*
* @method boot
*/
public boot(protocolConfig : IRedisProtocolConfig, cb : Function) : void {
cb();
}
/**
* Update jails configuration
*
* @method configJail
* @param jailConfig {IJailConfig} Jail configuration
*/
public configJail(jailConfig : IJailConfig) : void {
if (jailConfig) {
// Account
if (jailConfig.accountFindTime) {
this._accountFindTime = jailConfig.accountFindTime * 1000;
}
if (jailConfig.accountLockEnable !== void 0) {
this._accountLockEnable = !!jailConfig.accountLockEnable;
}
if (jailConfig.accountLockTime) {
this._accountLockTime = jailConfig.accountLockTime * 1000;
}
if (jailConfig.accountMaxRetry) {
this._accountMaxRetry = jailConfig.accountMaxRetry;
}
// User
if (jailConfig.userFindTime) {
this._userFindTime = jailConfig.userFindTime * 1000;
}
if (jailConfig.userBanTime) {
this._userBanTime = jailConfig.userBanTime * 1000;
}
if (jailConfig.userMaxRetry) {
this._userMaxRetry = jailConfig.userMaxRetry;
}
}
}
/**
* Get the name of protocol
*
* @method getName
* @return {string} Name of protocol
*/
public getName() : string {
return this._protocolName;
}
/**
* Unban user manually
* @method unbanUser
*
* @param ip {string} IP of user who must be unbanned
*/
public unbanUser(ip : string) : void {
}
/**
* Unlock account manually
* @method unlockAccount
*
* @param accountID {string} Account ID for unlock
*/
public unlockAccount(accountID : string) : void {
}
}
// Export Local protocol
export = Core;
|
f2df25be43d90fcb31e07e18c466a7ce074389d4
|
TypeScript
|
deguilardi/uqac-8INF871-pong
|
/3-ECS/src/main.ts
| 2.953125
| 3
|
import { DisplaySystem } from "./displaySystem";
import { LogicSystem } from "./logicSystem";
import { Resources } from "./resources";
import { ISceneDesc, Scene } from "./scene";
import { ISystem } from "./system";
import * as Utils from "./utils";
// ## Variable *systems*
// Représente la liste des systèmes utilisés par notre moteur
let systems: ISystem[];
// ## Méthode *run*
// Cette méthode initialise les différents systèmes nécessaires
// et démarre l'exécution complète du jeu.
export function run(canvasId: string) {
setupSystem(canvasId);
return launchGame();
}
// ## Méthode *launchGame*
// Cette méthode initialise la scène du jeu et lance la
// boucle de jeu.
function launchGame() {
const content = Resources.load<string>("3-ECS/scenes/scene.json")!;
const sceneDescription = JSON.parse(content) as ISceneDesc;
Scene.create(sceneDescription);
let lastTime: number | undefined;
function iterate(time: number) {
if (lastTime === undefined) {
lastTime = time;
}
// Le temps est compté en millisecondes, on désire
// l'avoir en secondes, sans avoir de valeurs trop énorme.
const delta = Utils.clamp((time - lastTime) / 1000, 0, 0.1);
lastTime = time;
for (const s of systems) {
s.iterate(delta);
}
window.requestAnimationFrame(iterate);
}
window.requestAnimationFrame(iterate);
}
// ## Méthode *setupSystem*
// Cette méthode initialise les différents systèmes nécessaires.
function setupSystem(canvasId: string) {
const display = new DisplaySystem(canvasId);
const logic = new LogicSystem();
systems = [display, logic];
}
|
990de5f7e5856a68364fbb7eb855a6dcd7ef6527
|
TypeScript
|
sphere-group/pegasus
|
/api/core/keyboard.ts
| 3.03125
| 3
|
/*
* Copyright (c) 2014 The Sphere Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module keyboard
* @author Bruce Pascoe (Fat Cerberus)
*/
export default class KeyboardModule
{
/**
* Keyboard key constants.
*/
public enum Key
{
None,
Escape,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
Tilde,
Key0,
Key1,
Key2,
Key3,
Key4,
Key5,
Key6,
Key7,
Key8,
Key9,
Minus,
Equals,
Backspace,
Tab,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LShift,
RShift,
CapsLock,
NumLock,
ScrollLock,
LCtrl,
RCtrl,
Alt,
AltGr,
Space,
OpenBrace,
CloseBrace,
Semicolon,
Apostrophe,
Comma,
FullStop,
Slash,
Backslash,
Enter,
Insert,
Delete,
Home,
End,
PageUp,
PageDown,
Up,
Right,
Down,
Left,
NumPad0,
NumPad1,
NumPad2,
NumPad3,
NumPad4,
NumPad5,
NumPad6,
NumPad7,
NumPad8,
NumPad9
}
/**
* Clear the keyboard key queue.
*
* @static
*/
public static clearQueue(): void
{
}
/**
* Find whether a keyboard key is currently pressed.
*
* @static
* @param {Key} key - The keyboard key to check.
* @return {boolean} - Whether the key is pressed.
*/
public static isPressed(key: Key): boolean
{
}
/**
* Get the Unicode character associated with a keyboard key.
* For example, keyToChar(Key.A) is "A".
*
* Non-character keys such as PageUp or Shift will give an empty string.
*
* @param {Key} key- A keyboard key.
*/
public static keyToChar(key: Key): string
{
}
/**
* Read the next key from the key queue.
*
* @static
*/
public static readKey(): Key
{
}
}
|
4dcea0fa311e5de113cb0651ca5cdb35edefb055
|
TypeScript
|
OntimeLengo/ontime-pm
|
/src/Task.ts
| 2.6875
| 3
|
import { EventEmitter } from './EventEmitter';
import { DB } from './db';
interface ITask {
run(): Promise<any>;
destroy(): void;
pause(): Promise<void>;
resume(): Promise<void>;
cancel(): Promise<void>;
}
abstract class Task extends EventEmitter implements ITask {
constructor(private _db: DB) {
super();
}
async run(): Promise<any> {
throw new Error('Method "run" is not implemented');
}
destroy(): void {
delete this._db;
this.stopListening();
}
async pause(): Promise<void> {
throw new Error('Method "pause" is not implemented');
}
async resume(): Promise<void> {
throw new Error('Method "resume" is not implemented');
}
async cancel(): Promise<void> {
throw new Error('Method "cancel" is not implemented');
}
}
export {
Task,
ITask
};
|
5eca4dcaf8a4e3d155ca8aeed47cdcba126afcd6
|
TypeScript
|
Ecodev/natural
|
/projects/natural/src/lib/modules/common/pipes/swiss-date.pipe.ts
| 2.75
| 3
|
import {Pipe, PipeTransform} from '@angular/core';
import {DatePipe} from '@angular/common';
/**
* A normal DatePipe but with default formatting to be '12.24.2020 23:30' to match the most common use-cases
*/
@Pipe({
name: 'swissDate',
standalone: true,
})
export class NaturalSwissDatePipe extends DatePipe implements PipeTransform {
public override transform(value: null | undefined, format?: string, timezone?: string, locale?: string): null;
public override transform(
value: Date | string | number | null | undefined,
format?: string,
timezone?: string,
locale?: string,
): string | null;
public override transform(
value: Date | string | number | null | undefined,
format = 'dd.MM.y HH:mm',
timezone?: string,
locale?: string,
): string | null {
return super.transform(value, format, timezone, locale);
}
}
|
9abbcb25a6068b5ebf45f54987f3d2cc29050ddd
|
TypeScript
|
yszk0123/dali
|
/src/shared/utils/formatDaliDate.ts
| 2.640625
| 3
|
function pad(n: number): string {
return n < 10 ? `0${n}` : `${n}`;
}
export default function formatDaliDate(dirtyDate: Date): string {
const year = dirtyDate.getUTCFullYear();
const month = dirtyDate.getUTCMonth();
const date = dirtyDate.getUTCDate();
return `${year}-${pad(month)}-${pad(date)}`;
}
|
95f6b971e941c0674b78d311b09f6386f6d7f32c
|
TypeScript
|
AdeThorMiwa/quidax
|
/api/src/modules/book/dto.ts
| 2.734375
| 3
|
import { Field, InputType } from '@nestjs/graphql';
import { ApiProperty } from '@nestjs/swagger';
import {
IsArray,
IsDate,
IsInt,
IsNotEmpty,
IsNumber,
IsOptional,
IsString,
Max,
Min,
} from 'class-validator';
@InputType()
class CreateBookDto {
@ApiProperty({
description: 'Book cover name',
default: 'book-url.jpg',
required: true,
})
@Field()
@IsString({ message: 'Please provide a valid book cover image' })
@IsNotEmpty({ message: 'Cover field cannot be empty' })
cover_image: string;
@ApiProperty({
description: 'Book title',
default: "Hitchhiker's guide to the galaxy",
required: true,
})
@Field()
@IsString({ message: 'Please provide a valid book title' })
@IsNotEmpty({ message: 'Title field cannot be empty' })
title: string;
@ApiProperty({
description: 'Number of available copies',
default: 100,
required: true,
})
@Field()
@IsInt({ message: 'Please provide a number of available book copies' })
@IsNotEmpty()
availability: number;
@ApiProperty({
description: 'Book release date',
default: new Date(),
required: false,
})
@Field({ nullable: true })
@IsString({ message: 'Please provide a valid release date' })
@IsOptional()
release_date: string;
@ApiProperty({
description: 'Book genre',
default: ['sci-fi', 'horror'],
required: true,
})
@Field(() => [String], { nullable: true })
@IsString({ message: 'Please provide a valid genre', each: true })
@IsArray()
genre: string[];
@ApiProperty({
description: 'Additional tags',
default: ['sci-fi', 'adapted'],
required: false,
})
@Field(() => [String], { nullable: true })
@IsString({ message: 'Please provide a valid tag', each: true })
@IsArray()
@IsOptional()
tags: string[];
@ApiProperty({
description: 'Book synopsis',
default:
'The hitchhikers guide to the galaxy is not a book for the faint of heart... Arthur dent is a... blah blah',
required: true,
})
@Field()
@IsString({ message: 'Please provide a valid synopsis' })
@IsNotEmpty()
synopsis: string;
@ApiProperty({
description: 'Book price',
default: 1000.9,
required: true,
})
@Field()
@IsNumber(
{ maxDecimalPlaces: 2 },
{ message: 'Please provide a valid price' },
)
@IsNotEmpty()
price: number;
}
@InputType()
class UpdateBookDto {
@ApiProperty({
description: 'Book cover name',
default: 'book-url.jpg',
required: false,
})
@Field({ nullable: true })
@IsString()
@IsOptional({ message: 'Cover field cannot be empty' })
cover_image: string;
@ApiProperty({
description: 'Book title',
default: "Hitchhiker's guide to the galaxy",
required: false,
})
@Field({ nullable: true })
@IsString({ message: 'Please provide a valid book title' })
@IsOptional()
title: string;
@ApiProperty({
description: 'Number of available copies',
default: 100,
required: false,
})
@Field({ nullable: true })
@IsInt({ message: 'Please provide a number of available book copies' })
@IsOptional()
availability: number;
@ApiProperty({
description: 'Book release date',
default: new Date(),
required: false,
})
@Field({ nullable: true })
@IsDate({ message: 'Please provide a valid release date' })
@IsOptional()
release_date: Date;
@ApiProperty({
description: 'Book genre',
default: ['sci-fi', 'horror'],
required: false,
})
@Field(() => [String], { nullable: true })
@IsString({ message: 'Please provide a valid genre', each: true })
@IsArray()
@IsOptional()
genre: string[];
@ApiProperty({
description: 'Additional tags',
default: ['sci-fi', 'adapted'],
required: false,
})
@Field(() => [String], { nullable: true })
@IsString({ message: 'Please provide a valid tag', each: true })
@IsArray()
@IsOptional()
tags: string[];
@ApiProperty({
description: 'Book synopsis',
default:
'The hitchhikers guide to the galaxy is not a book for the faint of heart... Arthur dent is a... blah blah',
required: false,
})
@Field({ nullable: true })
@IsString({ message: 'Please provide a valid synopsis' })
@IsOptional()
synopsis: string;
@ApiProperty({
description: 'Book price',
default: 1000.9,
required: false,
})
@Field({ nullable: true })
@IsNumber(
{ maxDecimalPlaces: 2 },
{ message: 'Please provide a valid price' },
)
@IsOptional()
price: number;
}
@InputType()
class BookRatingDto {
@ApiProperty({
description: 'Rating value',
default: 4.5,
required: true,
})
@Field({ nullable: false })
@IsNumber(
{ maxDecimalPlaces: 1 },
{ message: 'Please provide a valid rating' },
)
@IsNotEmpty()
@Max(5)
@Min(0.5)
rating: number;
}
@InputType()
class UpdateAvaialabilityDto {
@ApiProperty({
description: 'Total number of available copies',
default: 100,
required: true,
})
@Field({ nullable: false })
@IsInt({
message: 'Please provide a valid number of total available copies',
})
@IsNotEmpty({ message: 'total field cannot be empty' })
total: number;
@ApiProperty({
description: 'Total number of sold copies',
default: 60,
required: true,
})
@Field({ nullable: false })
@IsInt({
message: 'Please provide a valid number of sold available copies',
})
@IsNotEmpty({ message: 'sold field cannot be empty' })
sold: number;
}
export { CreateBookDto, UpdateBookDto, BookRatingDto, UpdateAvaialabilityDto };
|
3e321ed104cbe8270e003ea05f8bca82f264bae2
|
TypeScript
|
FullScreenShenanigans/LevelEditr
|
/typings/ObjectMakr.d.ts
| 3.296875
| 3
|
declare namespace ObjectMakr {
/**
* A tree representing class inheritances, where each key represents
* a class, and its children inherit from that class.
*/
interface IClassInheritance {
[i: string]: IClassInheritance;
}
/**
* Properties for a class prototype, which may be of any type.
*/
interface IClassProperties {
[i: string]: any;
}
/**
* Listing of class Functions, keyed by name.
*/
interface IClassFunctions {
[i: string]: IClassFunction;
}
/**
* Root abstract definition for class Functions.
*/
interface IClassFunction {
new (): any;
}
/**
* Member callback for when an output onMake is a Function.
*/
interface IOnMakeFunction {
(output: any, name: string, settings: any, defaults: any): any;
}
/**
* Settings to initialize a new IObjectMakr.
*/
interface IObjectMakrSettings {
/**
* A sketch of class inheritance.
*/
inheritance: IClassInheritance;
/**
* Properties for each class.
*/
properties?: IClassProperties;
/**
* Whether a full property mapping should be made for each type.
*/
doPropertiesFull?: boolean;
/**
* How propperties can be mapped from an Array to indices.
*/
indexMap?: any[];
/**
* Optionally, a String index for each generated Object's Function to
* be run when made.
*/
onMake?: string;
/**
* Optionally, existing classes that can be passed in instead of using auto-generated ones.
*/
functions?: IClassFunctions;
/**
* A scope to call onMake functions in, if not this IObjectMakr.
*/
scope?: any;
}
/**
* A abstract factory for dynamic attribute-based JavaScript classes.
*/
interface IObjectMakr {
/**
* @returns The complete inheritance mapping.
*/
getInheritance(): any;
/**
* @returns The complete properties mapping.
*/
getProperties(): any;
/**
* @returns The properties for a particular class.
*/
getPropertiesOf(title: string): any;
/**
* @returns Full properties, if doPropertiesFull is true.
*/
getFullProperties(): any;
/**
* @returns Full properties for a particular class, if
* doPropertiesFull is true.
*/
getFullPropertiesOf(title: string): any;
/**
* @returns The full mapping of class constructors.
*/
getFunctions(): IClassFunctions;
/**
* @param name The name of a class to retrieve.
* @returns The constructor for the given class.
*/
getFunction(name: string): IClassFunction;
/**
* @param type The name of a class to check for.
* @returns Whether that class exists.
*/
hasFunction(name: string): boolean;
/**
* @returns The scope onMake functions are called in, if not this.
*/
getScope(): any;
/**
* @returns The optional mapping of indices.
*/
getIndexMap(): any[];
/**
* Creates a new instance of the specified type and returns it.
* If desired, any settings are applied to it (deep copy using proliferate).
*
* @param name The name of the type to initialize a new instance of.
* @param [settings] Additional attributes to add to the new instance.
* @returns A newly created instance of the specified type.
*/
make(name: string, settings?: any): any;
}
/**
* A abstract factory for dynamic attribute-based JavaScript classes.
*/
class ObjectMakr implements IObjectMakr {
/**
* The sketch of class inheritance.
*/
private inheritance;
/**
* Properties for each class.
*/
private properties;
/**
* The actual Functions for the classes to be made.
*/
private functions;
/**
* A scope to call onMake functions in, if not this.
*/
private scope;
/**
* Whether a full property mapping should be made for each type.
*/
private doPropertiesFull;
/**
* If doPropertiesFull is true, a version of properties that contains the
* sum properties for each type (rather than missing inherited ones).
*/
private propertiesFull;
/**
* How properties can be mapped from an Array to indices.
*/
private indexMap;
/**
* Optionally, a String index for each generated Object's Function to
* be run when made.
*/
private onMake;
/**
* Initializes a new instance of the ObjectMakr class.
*
* @param settings Settings to be used for initialization.
*/
constructor(settings: IObjectMakrSettings);
/**
* @returns The complete inheritance mapping.
*/
getInheritance(): any;
/**
* @returns The complete properties mapping.
*/
getProperties(): any;
/**
* @returns The properties for a particular class.
*/
getPropertiesOf(title: string): any;
/**
* @returns Full properties, if doPropertiesFull is true.
*/
getFullProperties(): any;
/**
* @returns Full properties for a particular class, if
* doPropertiesFull is true.
*/
getFullPropertiesOf(title: string): any;
/**
* @returns The full mapping of class constructors.
*/
getFunctions(): IClassFunctions;
/**
* @param name The name of a class to retrieve.
* @returns The constructor for the given class.
*/
getFunction(name: string): IClassFunction;
/**
* @returns The scope onMake functions are called in, if not this.
*/
getScope(): any;
/**
* @param type The name of a class to check for.
* @returns Whether that class exists.
*/
hasFunction(name: string): boolean;
/**
* @returns The optional mapping of indices.
*/
getIndexMap(): string[];
/**
* Creates a new instance of the specified type and returns it.
* If desired, any settings are applied to it (deep copy using proliferate).
*
* @param name The name of the type to initialize a new instance of.
* @param settings Additional attributes to add to the new instance.
* @returns A newly created instance of the specified type.
*/
make(name: string, settings?: any): any;
/**
* Parser that calls processPropertyArray on all properties given as arrays
*
* @param properties Type properties for classes to create.
*/
private processProperties(properties);
/**
* Creates an output properties object with the mapping shown in indexMap
*
* @param properties An Array with indiced versions of properties
*/
private processPropertyArray(indexMap);
/**
* Recursive parser to generate each Function, starting from the base.
*
* @param base An object whose keys are the names of Functions to
* made, and whose values are objects whose keys are
* for children that inherit from these Functions
* @param parent The parent class Function of the classes about to be made.
* @param parentName The name of the parent class to be inherited from,
* if it is a generated one (and not Object itself).
*/
private processFunctions(base, parent, parentName?);
/**
* Proliferates all members of the donor to the recipient recursively, as
* a deep copy.
*
* @param recipient An object receiving the donor's members.
* @param donor An object whose members are copied to recipient.
* @param noOverride If recipient properties may be overriden (by default, false).
*/
private proliferate(recipient, donor, noOverride?);
}
}
declare var module: any;
|
73b19e73add5feb1d5c3a8b17008f779aad6320f
|
TypeScript
|
coderofsalvation/react-admin
|
/packages/ra-core/src/controller/field/useReferenceArrayFieldController.ts
| 2.953125
| 3
|
import { useMemo } from 'react';
import get from 'lodash/get';
import { Record, RecordMap, Identifier } from '../../types';
import { useGetMany } from '../../dataProvider';
/**
* @typedef ReferenceArrayProps
* @type {Object}
* @property {Array} ids the list of ids.
* @property {Object} data Object holding the reference data by their ids
* @property {Object} error the error returned by the dataProvider
* @property {boolean} loading is the reference currently loading
* @property {boolean} loaded has the reference already been loaded
* @property {string} referenceBasePath basePath of the reference
*/
interface ReferenceArrayProps {
ids: Identifier[];
data: RecordMap;
error?: any;
loading: boolean;
loaded: boolean;
referenceBasePath: string;
}
interface Option {
basePath: string;
record?: Record;
reference: string;
resource: string;
source: string;
}
/**
* Hook that fetches records from another resource specified
* by an array of *ids* in current record.
*
* @example
*
* const { ids, data, error, loaded, loading, referenceBasePath } = useReferenceArrayFieldController({
* basePath: 'resource';
* record: { referenceIds: ['id1', 'id2']};
* reference: 'reference';
* resource: 'resource';
* source: 'referenceIds';
* });
*
* @param {Object} option
* @param {string} option.basePath basepath to current resource
* @param {Object} option.record The The current resource record
* @param {string} option.reference The linked resource name
* @param {string} option.resource The current resource name
* @param {string} option.source The key of the linked resource identifier
*
* @returns {ReferenceArrayProps} The reference props
*/
const useReferenceArrayFieldController = ({
resource,
reference,
basePath,
record,
source,
}: Option): ReferenceArrayProps => {
const ids = get(record, source) || [];
const { data, error, loading, loaded } = useGetMany(reference, ids);
const referenceBasePath = basePath.replace(resource, reference); // FIXME obviously very weak
return {
ids,
data: useMemo(() => indexById(data), [data]),
error,
loaded,
loading,
referenceBasePath,
};
};
const indexById = (records: Record[] = []) =>
records
.filter(r => typeof r !== 'undefined')
.reduce((prev, current) => {
prev[current.id] = current;
return prev;
}, {});
export default useReferenceArrayFieldController;
|
e6b5f1b281c5b981a9a7825825c82c23c57f4908
|
TypeScript
|
taktik/typescript-http-client
|
/src/index.ts
| 2.96875
| 3
|
import type { Logger } from 'generic-logger-typings'
import FilterChainImpl from './filterChainImpl'
/**
* In order to be an HttpClient, the class should:
* Make a call to the server and returning a response
* Make a simpler call to the server that only returns a part of the response
* Add a filter to its filter list
*/
export interface HttpClient {
executeForResponse<T> (request: Request): Promise<Response<T>>
callForResponse<T> (request: Request): Promise<Response<T>>
execute<T> (request: Request): Promise<T>
call<T> (request: Request): Promise<T>
addFilter (filter: Filter<unknown, unknown>, name: string, config?: FilterConfig): FilterRegistration
}
// Main class to make calls to the API
// method call will call method doFilter and it will call method execute
class HttpClientImpl implements HttpClient {
private readonly _filters: InstalledFilter[]
constructor() {
this._filters = []
}
// Takes parameters and creates an InstalledFilter with them
// Add the InstalledFilter to the filter array
// The InstalledFilter is made of two parts: The Filter and the FilterConfig
addFilter(filter: Filter<unknown, unknown>, name: string, config?: FilterConfig): FilterRegistration {
const installedFilter = new InstalledFilter(filter, name, config)
const filters = this._filters
// Returns an object with a method to remove the added filter
filters.push(installedFilter)
return {
remove(): void {
remove(installedFilter, filters)
}
}
}
// Takes a Request and returns the body of the promise returned by the method callForResponse
async execute<T>(call: Request): Promise<T> {
return (await this.callForResponse<T>(call)).body as T
// body can be null but in such cases, an error will be thrown
}
// Takes a Request, creates the main chain of filters with the current filters of httpclient
// and then calls the method doFilter with the received Request
async executeForResponse<T> (call: Request): Promise<Response<T>> {
return new FilterChainImpl(this._filters).doFilter(call) as Promise<Response<T>>
}
// Same as execute
async call<T> (call: Request): Promise<T> {
return this.execute<T>(call)
}
// Same as executeForResponse
async callForResponse<T> (call: Request): Promise<Response<T>> {
return this.executeForResponse<T>(call)
}
}
// Interfaces can hold properties
// This interface only contains a map of string-string
export interface Headers {
[name: string]: string
}
// Contains every parameter needed for a request as properties
export class Request {
private _xhr: XMLHttpRequest | undefined
private aborted = false
set xhr(xhr: XMLHttpRequest | undefined) {
if (this.aborted) {
throw Error('request aborted')
}
this._xhr = xhr
}
get xhr (): XMLHttpRequest | undefined {
return this._xhr
}
get isAborted(): boolean {
return this.aborted
}
abort() {
if (this.xhr) {
this.xhr.abort()
}
this.aborted = true
}
upload: {
onprogress: { (event: Event): void }
onloadstart: { (event: Event): void }
}
url: string
contentType = 'application/json; charset=UTF-8'
// A way to declare an enumeration (can be anything because of the string but the IDE will suggest the 4 first verbs)
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | string = 'GET'
responseType: XMLHttpRequestResponseType = 'json'
withCredentials = false
body?: object | Document | BodyInit | null
headers: Headers = {}
timeout = 30000
readyState = 0
properties: {[key: string]: unknown} = {}
// constructor that can take a lot of parameters but only the URL is mandatory
constructor(url: string, {
contentType, method, responseType,
withCredentials, body, headers, timeout
}: {
contentType?: string, method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | string, responseType?: XMLHttpRequestResponseType,
withCredentials?: boolean, body?: object | Document | BodyInit | null, headers?: Headers, timeout?: number
} = {}) {
this.url = url
if (contentType) {
this.contentType = contentType
}
if (method) {
this.method = method
}
if (responseType) {
this.responseType = responseType
}
if (withCredentials) {
this.withCredentials = withCredentials
}
if (body) {
this.body = body
}
if (headers) {
this.headers = headers
}
if (timeout) {
this.timeout = timeout
}
this.upload = {
onprogress: () => void 0,
onloadstart: () => void 0
}
}
// sets the properties (like a constructor for changes)
set({
contentType, method, responseType,
withCredentials, body, headers, timeout
}: {
contentType?: string, method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | string, responseType?: XMLHttpRequestResponseType,
withCredentials?: boolean, body?: object | Document | BodyInit | null, headers?: Headers, timeout?: number
}): Request {
if (contentType) {
this.contentType = contentType
}
if (method) {
this.method = method
}
if (responseType) {
this.responseType = responseType
}
if (withCredentials) {
this.withCredentials = withCredentials
}
if (body) {
this.body = body
}
if (headers) {
this.headers = headers
}
if (timeout) {
this.timeout = timeout
}
return this
}
setContentType(contentType: string): Request {
this.contentType = contentType
return this
}
setMethod(method: 'GET' | 'POST' | 'PUT' | 'DELETE' | string = 'GET'): Request {
this.method = method
return this
}
setResponseType(responseType: XMLHttpRequestResponseType) {
this.responseType = responseType
return this
}
setWithCredentials(withCredentials: boolean) {
this.withCredentials = withCredentials
return this
}
setBody(body?: object | Document | BodyInit | null) {
this.body = body
return this
}
setHeaders(headers: Headers) {
this.headers = headers
return this
}
addHeader(headerName: string, value: string) {
this.headers[headerName] = value
}
setTimeout(timeout: number) {
this.timeout = timeout
return this
}
setProperty (key: string, value: unknown) {
this.properties[key] = value
return this
}
getProperty (key: string): unknown {
return this.properties[key]
}
}
// The class that our calls return
export class Response<T> {
readonly properties: {[key: string]: unknown} = {}
constructor(readonly request: Request,
readonly status: number,
readonly statusText: string,
readonly headers: Headers,
readonly body: T | null
) {
}
setProperty(key: string, value: unknown) {
this.properties[key] = value
return this
}
getProperty(key: string): unknown {
return this.properties[key]
}
}
/**
* Interface useful to remove a Filter after it has been added to the httpClient array
*/
export interface FilterRegistration {
// Remove the filter
remove(): void
}
/**
* A FilterChain should have a method to apply all its filters
* on a Request and send it to the server
*/
export interface FilterChain<T> {
doFilter(call: Request): Promise<Response<T>>
}
// Third parameter is a function that will call the execute method with a given request
// Only the first parameter of the constructor is obligatory
// Has all the filters that could be applied to a request
// Goes throught them and applies them to the request if the config is matching
export class FilterCollection implements Filter<unknown, unknown> {
constructor(readonly filters: InstalledFilter[]) {
}
/**
* @param call Is the request we want to modify
* @param filterChain is an Interface that is a Filter, but its goal is to simulate
* nested filters. So it contains an array of filter and its doFilter loops through all its filters
* before continuing with the main chain of filters
*/
doFilter (call: Request, filterChain: FilterChain<unknown>): Promise<Response<unknown>> {
return new FilterChainImpl(this.filters, 0, request => filterChain.doFilter(request)).doFilter(call)
}
}
/**
* Is composed of a FilterConfig that checks the request to know if the Filter should be applied
* and of a Filter that does something to the request/response
*/
export class InstalledFilter {
constructor(readonly filter: Filter<unknown, unknown>, readonly name: string, readonly config?: FilterConfig) {
}
}
/*
A filter configuration
*/
export interface FilterConfig {
/*
Return "true" if this filter should be applied to the given call
*/
enabled(call: Request): boolean
}
export interface Filter<T, U> {
doFilter(call: Request, filterChain: FilterChain<T>): Promise<Response<U>>
}
/*
Factory method
*/
export function newHttpClient(): HttpClient {
return new HttpClientImpl()
}
let log: Logger
export function getLogger(): Logger | undefined {
return log
}
export function setLogger(logger: Logger) {
log = logger
}
// Utility methods
function remove(item: unknown, array: unknown[]) {
const index = array.indexOf(item, 0)
if (index > -1) {
array.splice(index, 1)
}
}
|
e1eb419187c81a4e3592b21f5964da04f3cf6873
|
TypeScript
|
keshav121992/My_First_Todo_Application_with_Java_SpringBoot_Angular
|
/src/app/list-todo/list-todo.component.ts
| 2.609375
| 3
|
import { Component, OnInit } from '@angular/core';
import { TododataService } from '../service/data/tododata.service';
import { Router } from '@angular/router';
export class Todo{
constructor(
public id: Number,
public username: string,
public discription: string,
public targateDate: Date,
public done: boolean
){
}
}
@Component({
selector: 'app-list-todo',
templateUrl: './list-todo.component.html',
styleUrls: ['./list-todo.component.css']
})
export class ListTodoComponent implements OnInit {
todos : Todo[]
message: string
// new Todo(1,'Learn to Dance', false, new Date()),
// new Todo(2,'Learn to Java', false, new Date()),
// new Todo(3,'Learn to SpringBoot', false, new Date()),
// new Todo(4,'Learn to Angular', false, new Date()),
// new Todo(5,'Visit USA & UK', false, new Date())
// // {id:1, description: 'Learn to Dance'},
// // {id:2, description: 'Learn to Java'},
// // {id:3, description: 'Learn to SpringBoot'},
// // {id:4, description: 'Learn to Angular'},
// // {id:5, description: 'Visit USA & UK'}
// ]
// todo={
// id: 1,
// description: 'Learn to java'
// }
constructor(
private todoService: TododataService,
private router: Router
) { }
ngOnInit() {
this.todoService.retriveAllTodos('in28Minutes').subscribe(
response=>{
console.log(response);
this.todos = response;
}
)
}
deleteTodo(id){
this.todoService.deleteTodo('in28Minutes', id).subscribe(
response=>{
console.log(response);
this.message = `Deleted todo ${id} successfully!`
}
)
console.log(`delete todo ${id}` );
}
updateTodo(id){
console.log(`update todo ${id}` );
this.router.navigate([`todo`, id])
}
}
|
b64e57ca0a6b07342f7b74c77bb345479ca0ef88
|
TypeScript
|
zcong1993/sequelize-v5-ts-example
|
/src/index.ts
| 2.5625
| 3
|
import { syncForce, dump } from './common'
import { User, Post, Tag } from './model'
const run = async () => {
await syncForce()
const user = await User.create(
{
name: 'zcong',
detail: {
gender: 'male'
}
},
{
include: [
{
association: User.associations.detail
}
]
}
)
const post = await user.createPost({
title: 'test',
description: 'desc',
content: 'lorem'
})
dump(user)
dump(post)
const u = await Post.findByPk(1, {
include: [
{
association: Post.associations.author
}
]
})
dump(u)
const p2 = await user.createPost(
{
title: 'test2',
description: 'desc',
content: 'lorem',
tags: [
{
name: 'tag1'
}
]
},
{
include: [
{
association: Post.associations.tags
}
]
}
)
dump(p2)
const tag = await Tag.findByPk(1)
const p3 = await user.createPost({
title: 'test2',
description: 'desc',
content: 'lorem'
})
await p3.addTag(tag)
dump(p3)
const p4 = await Post.findAll({
include: [
{
association: Post.associations.author
},
{
association: Post.associations.tags
}
]
})
dump(p4)
}
run().catch(console.log)
|
1ac30b2d8e6909a9253c6c8f2d584e49d7083c76
|
TypeScript
|
chistogo/ScalarJS
|
/src/matrix.ts
| 3.421875
| 3
|
class Matrix{
protected columnsCount:number;
protected rowsCount:number;
protected data:number[];
// The idea behind this variable is that you can set it to false and get better performance.
// Feature might be removed or expanded in future.
static safe = true;
constructor(matrixData:number[], rowCount:number=1 , columnCount?:number ){
if (!matrixData){
throw new Error("There is no spoon. (MatrixData is falsely)");
}
if(!columnCount){
columnCount = matrixData.length;
}
if(columnCount <= 0 || rowCount <= 0){
throw new Error("Invalid Length of a matrix");
}
if(rowCount*columnCount != matrixData.length ){
throw new Error("Invalid Matrix Size");
}
this.columnsCount = columnCount;
this.rowsCount = rowCount;
if(Matrix.safe){
this.data = Matrix.cloneData(matrixData);
}else{
this.data = matrixData;
}
}
isSquare():boolean{
return this.rowsCount == this.columnsCount;
}
isIdentity():boolean{
if(!this.isSquare()){
return false;
}
for (let i = 0; i<this.data.length;i++) {
let value = (i%(this.rowsCount+1)==0) ? 1 : 0;
if(this.data[i] != value){
return false;
}
}
return true;
}
transpose():Matrix{
let data = Array(this.data.length);
let index = 0;
for (let i = 0; i < this.columnsCount; i++) {
for (let j = 0; j < this.data.length; j+= this.columnsCount) {
data[index] = this.data[i+j];
index++;
}
}
return new Matrix(data,this.columnsCount,this.rowsCount);
}
add(matrix:Matrix):Matrix{
if(!this.isSameDimension(matrix)){
throw new Error("Matrices need to be the same size to add.");
}
let newData = new Array(this.data.length);
for(let i = 0 ; i<this.data.length;i++){
newData[i] = this.data[i] + matrix.data[i];
}
return new Matrix(newData,this.rowsCount,this.columnsCount);
}
subtract(matrix:Matrix):Matrix{
if(!this.isSameDimension(matrix)){
throw new Error("Matrices need to be the same size to subtract.");
}
let newData = new Array(this.data.length);
for(let i = 0 ; i<this.data.length;i++){
newData[i] = this.data[i] - matrix.data[i];
}
return new Matrix(newData,this.rowsCount,this.columnsCount);
}
equal(matrix:Matrix):boolean{
if(!this.isSameDimension(matrix)){
return false;
}
for(let i = 0;i<this.data.length;i++){
if(matrix.data[i] != this.data[i]){
return false;
}
}
return true;
}
scalarMultiply(num:number):Matrix{
if (typeof num != "number"){
throw new Error("Cannot Scalar multiply by a non number");
}
let newData = new Array(this.data.length);
for (let i=0 ; i<this.data.length; i++){
newData[i] = this.data[i]*num;
}
return new Matrix(newData,this.rowsCount,this.columnsCount);
}
multiply(matrix:Matrix):Matrix{
if(this.columnsCount != matrix.rowsCount){
throw new Error("Invalid Matrix Dimensions for a Multiplication");
}
let newMatrixData = new Array(this.rowsCount*matrix.columnsCount);
let newMatrixIndex = 0 ;
for(let i = 0; i < this.data.length; i = i + this.columnsCount) {
for (let j = 0; j < matrix.columnsCount; j++) {
let sum = 0;
let x = i;
let y = j;
while (x < this.columnsCount+i) {
sum = sum + this.data[x] * matrix.data[y];
x = x + 1;
y = y + matrix.columnsCount;
}
newMatrixData[newMatrixIndex] = sum;
newMatrixIndex++;
}
}
return new Matrix(newMatrixData,this.rowsCount,matrix.columnsCount);
}
isSameDimension(matrix:Matrix):boolean{
return (this.columnsCount == matrix.columnsCount && this.rowsCount == matrix.rowsCount);
}
getValue(row:number, column:number):number{
return this.getValueA(row-1,column-1)
}
getValueA(row:number, column:number):number{
if(row>=this.rowsCount || column>=this.columnsCount || row<0 || column<0){
throw new Error('Matrix out of bound');
}
return this.data[(row)*(this.columnsCount)+column];
}
getData():number[]{
return Matrix.safe ? Matrix.cloneData(this.data) : this.data;
}
toString():string{
let rtnString = '\n[\n\t\t\ '+this.data[0];
for (let i = 1; i < this.data.length; i++) {
if(i%this.columnsCount==0){
rtnString+= '\n\t';
}
rtnString+= '\t'+','+this.data[i];
}
return rtnString + '\n]\n';
}
private static cloneData(data:number[]){
let newData = new Array(data.length);
for (let i = 0; i < data.length; i++){
newData[i] = data[i]
}
return newData;
}
static generateIdentityMatrix(size:number):Matrix{
if(!size || size <= 0){
throw new Error("Invalid Matrix Size");
}
let data = new Array(size*size);
for (let i = 0; i<size*size;i++){
data[i] = (i%(size+1)==0) ? 1 : 0;
}
return new Matrix(data,size,size);
}
public static isMatrix(obj){
return !(!obj || !obj.columnsCount || !obj.rowsCount || !obj.rowsCount);
}
// Aliasing
sub = this.subtract;
T = this.transpose;
t = this.transpose;
eq = this.equal;
sm = this.scalarMultiply;
m = this.multiply;
}
// Export Module if only you are in a node like environment.
// This way this class can be used in vanilla JavaScript
try{
// This is done so that TypeScript doesn't complain about module not existing.
eval('module.exports = Matrix');
}catch (e){}
|
337ed6500b38a46f113cf38fd1ed00ce1dd06c25
|
TypeScript
|
cbrandolino/webvtt.ts
|
/src/demo/vtt/useCues.ts
| 2.671875
| 3
|
import { Reducer, useReducer, useEffect, useRef } from 'react'
import { createCuesDiv } from './renderer';
import { parseVtt } from './parser';
import { JsonCue } from '../../lib/types';
interface ICueState {
time:number,
currentCues:Array<JsonCue>,
parsedCues:Array<JsonCue>;
parsedRegions:Array<VTTRegion>;
}
const initialState = {
time: 0,
currentCues: [],
parsedCues: [],
parsedRegions: [],
};
const getCurrentCues = (time:number, parsedCues:Array<JsonCue>):Array<JsonCue> =>
parsedCues.filter(({ startTime, endTime }) => time >= startTime && time < endTime);
const cueReducer:Reducer<ICueState, {type: string, payload: any}> = (state, action) => {
switch (action.type) {
case 'updateTime':
return {
...state,
time: action.payload,
currentCues: getCurrentCues(action.payload, state.parsedCues),
};
case 'loadData':
return {
...state,
...action.payload
};
default:
return state;
}
}
const useCues = (source:string) => {
const cueBoxRef = useRef<HTMLDivElement>(null);
const [state, dispatch] = useReducer(cueReducer, initialState);
const updateTime = (time:number) => dispatch({ type: 'updateTime', payload: time });
const parserCallback = (data:{ parsedCues:Array<JsonCue> }) =>
dispatch({ type: 'loadData', payload: data });
useEffect(() => {
console.log({ source })
source && parseVtt(source, parserCallback);
}, [source]);
useEffect(() => {
if (cueBoxRef.current) {
createCuesDiv(state.currentCues, cueBoxRef.current);
}
}, [state.currentCues, source]);
return { updateTime, state, cueBoxRef };
}
export default useCues;
|
9ae1fe1d0acf17b882a610f794d31b4a75d4c249
|
TypeScript
|
willwsharp/Mallard-Manager
|
/src/app/core/models/projects/ProjectTask.model.ts
| 2.65625
| 3
|
import { Validatable } from '../validation/Validatable.interface';
export class ProjectTask implements Validatable {
constructor(public name: string) {}
public isValid(): boolean {
return this.name !== '';
}
}
|
40f950720ef90665784f7848556436925fc595cf
|
TypeScript
|
nicolaskr/NotreProjetAngular
|
/src/app/model/session.ts
| 2.734375
| 3
|
import { SessionKey } from './session-key';
import { Partie } from './partie';
import { SessionRessource } from './session-ressource';
import { SessionBatiment } from './session-batiment';
import { Compte } from './compte';
export class Session {
constructor(
private _id: SessionKey,
private _def: number,
private _att: number,
private _sessionBatiment: SessionBatiment[],
private _sessionRessource: SessionRessource[],
private _tourEnCours: boolean
) {}
/**
* Getter compte
* @return {Compte}
*/
public get id(): SessionKey {
return this._id;
}
public get tourEnCours(): boolean {
return this._tourEnCours;
}
/**
* Getter def
* @return {number}
*/
public get def(): number {
return this._def;
}
/**
* Getter listBatiments
* @return {SessionBatiment[]}
*/
public get sessionBatiment(): SessionBatiment[] {
return this._sessionBatiment;
}
/**
* Getter att
* @return {number}
*/
public get att(): number {
return this._att;
}
/**
* Getter listRessources
* @return {SessionRessource []}
*/
public get sessionRessource(): SessionRessource[] {
return this._sessionRessource;
}
/**
* Setter compte
* @param {Compte} value
*/
public set id(value: SessionKey) {
this._id = value;
}
public set tourEnCours(value: boolean) {
this._tourEnCours = value;
}
/**
* Setter def
* @param {number} value
*/
public set def(value: number) {
this._def = value;
}
/**
* Setter listBatiments
* @param {SessionBatiment[]} value
*/
public set sessionBatiment(value: SessionBatiment[]) {
this._sessionBatiment = value;
}
/**
* Setter att
* @param {number} value
*/
public set att(value: number) {
this._att = value;
}
/**
* Setter listRessources
* @param {SessionRessource []} value
*/
public set sessionRessource(value: SessionRessource[]) {
this._sessionRessource = value;
}
}
|
46d1075f583b9e3fb76633fd02e0d5db0525312a
|
TypeScript
|
netochaves/grommet
|
/src/js/utils/index.d.ts
| 2.890625
| 3
|
// colors.js
declare const normalizeColor: (
color: string | { dark?: string; light?: string },
theme: object,
required?: boolean
) => string;
export {normalizeColor}
// object.js
export type DeepReadonly<T extends object> = {
readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
}
export type NonUndefined<T> = T extends undefined ? never: T;
export type NonUndefinedProps<T extends object> = {
[K in keyof T]?: NonUndefined<T[K]>;
}
export type DeepFreeze = <T extends object>(obj: T) => DeepReadonly<T>;
// overload because generic variadic solution has messy result and all/most mergings are binary
export interface DeepMerge {
<T extends object, S extends object>(target: T, source: S): T & S;
<T extends object, S extends object[]>(target: T, ...sources: S): T & S[number];
}
export type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
export type PolymorphicType = keyof JSX.IntrinsicElements | React.ComponentType<any>
declare const isObject: (item:any) => boolean;
declare const deepFreeze: DeepFreeze;
declare const deepMerge: DeepMerge;
declare const removeUndefined: <T extends object>(obj: T) => NonUndefinedProps<T>;
export {isObject, deepFreeze, deepMerge, removeUndefined};
// Extracting types for common properties among components
type BoxSideType = "top" | "left" | "bottom" | "right" | "start" | "end" | "horizontal" | "vertical" | "all" | "between";
type BoxSizeType = "xsmall" | "small" | "medium" | "large" | "xlarge" | string;
type BoxStyleType = "solid" | "dashed" | "dotted" | "double" | "groove" | "ridge" | "inset" | "outset" | "hidden";
export type EdgeSizeType = "xxsmall" | "xsmall" | "small" | "medium" | "large" | "xlarge";
type EdgeType = "none" | EdgeSizeType | {bottom?: EdgeSizeType | string,end?: EdgeSizeType | string,horizontal?: EdgeSizeType | string,left?: EdgeSizeType | string,right?: EdgeSizeType | string,start?: EdgeSizeType | string,top?: EdgeSizeType | string,vertical?: EdgeSizeType | string} | string
export type A11yTitleType = string;
export type AlignContentType = "start" | "center" | "end" | "between" | "around" | "stretch";
export type AlignSelfType = "start" | "center" | "end" | "stretch";
export type AnimateType = boolean;
export type BackgroundType = string | {color?: ColorType,dark?: boolean | string,image?: string,position?: string,opacity?: "weak" | "medium" | "strong" | number | boolean,repeat?: "no-repeat" | "repeat" | string,size?: "cover" | "contain" | string,light?: string};
export type BasisType = "xxsmall" | "xsmall" | "small" | "medium" | "large" | "xlarge" | "xxlarge" | "full" | "1/2" | "1/3" | "2/3" | "1/4" | "2/4" | "3/4" | "auto" | string;
export type BorderType = boolean | BoxSideType | {color?: ColorType, side?: BoxSideType, size?: BoxSizeType, style?: BoxStyleType} | ({color?: ColorType, side?: BoxSideType, size?: BoxSizeType, style?: BoxStyleType})[];
export type ColorType = string | {dark?: string,light?: string} | undefined;
export type ElevationType = "none" | "xsmall" | "small" | "medium" | "large" | "xlarge" | string;
export type FillType = "horizontal" | "vertical" | boolean;
export type GapType = "none" | EdgeSizeType | string;
export type GraphColorsType = string[] | {dark?: string[],light?: string[]};
export type GridAreaType = string;
export type JustifyContentType = "start" | "center" | "end" | "between" | "around" | "stretch";
export type KeyboardType = ((event: React.KeyboardEvent<HTMLElement>) => void);
export type MarginType = EdgeType;
export type OpacityType = "weak" | "medium" | "strong" | string | true | false | number;
export type PadType = EdgeType;
export type PlaceHolderType = string | JSX.Element | React.ReactNode;
export type RoundType = boolean | "xsmall" | "small" | "medium" | "large" | "xlarge" | "full" | string | {corner?: "top" | "left" | "bottom" | "right" | "top-left" | "top-right" | "bottom-left" | "bottom-right",size?: "xsmall" | "small" | "medium" | "large" | "xlarge" | string};
export type TextAlignType = "start" | "center" | "end";
declare const breakpointEdgeSize: {
none?: string;
hair?: string;
xxsmall?: string;
xsmall?: string;
small?: string;
medium?: string;
large?: string;
xlarge?: string;
};
export type BreakpointEdgeSize = typeof breakpointEdgeSize;
declare const breakpointBorderSize: {
xsmall?: string;
small?: string;
medium?: string;
large?: string;
xlarge?: string;
}
export type BreakpointBorderSize = typeof breakpointBorderSize;
declare const breakpointSize: {
xxsmall?: string;
xsmall?: string;
small?: string;
medium?: string;
large?: string;
xlarge?: string;
full?: string;
};
export type BreakpointSize = typeof breakpointSize;
|
619870d2f6b6ada0380c9c36f5f7643dabb018d0
|
TypeScript
|
Hebilicious/FloomDeliveryTracker
|
/generated/prisma-client/prisma-schema.ts
| 2.625
| 3
|
export const typeDefs = /* GraphQL */ `type AggregateCoordinate {
count: Int!
}
type AggregateOrder {
count: Int!
}
type AggregateOrderUpdate {
count: Int!
}
type AggregateUser {
count: Int!
}
type BatchPayload {
count: Long!
}
type Coordinate {
latitute: Float!
longitude: Float!
}
type CoordinateConnection {
pageInfo: PageInfo!
edges: [CoordinateEdge]!
aggregate: AggregateCoordinate!
}
input CoordinateCreateInput {
latitute: Float!
longitude: Float!
}
input CoordinateCreateOneInput {
create: CoordinateCreateInput
}
type CoordinateEdge {
node: Coordinate!
cursor: String!
}
enum CoordinateOrderByInput {
latitute_ASC
latitute_DESC
longitude_ASC
longitude_DESC
id_ASC
id_DESC
createdAt_ASC
createdAt_DESC
updatedAt_ASC
updatedAt_DESC
}
type CoordinatePreviousValues {
latitute: Float!
longitude: Float!
}
type CoordinateSubscriptionPayload {
mutation: MutationType!
node: Coordinate
updatedFields: [String!]
previousValues: CoordinatePreviousValues
}
input CoordinateSubscriptionWhereInput {
mutation_in: [MutationType!]
updatedFields_contains: String
updatedFields_contains_every: [String!]
updatedFields_contains_some: [String!]
node: CoordinateWhereInput
AND: [CoordinateSubscriptionWhereInput!]
OR: [CoordinateSubscriptionWhereInput!]
NOT: [CoordinateSubscriptionWhereInput!]
}
input CoordinateUpdateDataInput {
latitute: Float
longitude: Float
}
input CoordinateUpdateManyMutationInput {
latitute: Float
longitude: Float
}
input CoordinateUpdateOneRequiredInput {
create: CoordinateCreateInput
update: CoordinateUpdateDataInput
upsert: CoordinateUpsertNestedInput
}
input CoordinateUpsertNestedInput {
update: CoordinateUpdateDataInput!
create: CoordinateCreateInput!
}
input CoordinateWhereInput {
latitute: Float
latitute_not: Float
latitute_in: [Float!]
latitute_not_in: [Float!]
latitute_lt: Float
latitute_lte: Float
latitute_gt: Float
latitute_gte: Float
longitude: Float
longitude_not: Float
longitude_in: [Float!]
longitude_not_in: [Float!]
longitude_lt: Float
longitude_lte: Float
longitude_gt: Float
longitude_gte: Float
AND: [CoordinateWhereInput!]
OR: [CoordinateWhereInput!]
NOT: [CoordinateWhereInput!]
}
scalar Long
type Mutation {
createCoordinate(data: CoordinateCreateInput!): Coordinate!
updateManyCoordinates(data: CoordinateUpdateManyMutationInput!, where: CoordinateWhereInput): BatchPayload!
deleteManyCoordinates(where: CoordinateWhereInput): BatchPayload!
createOrder(data: OrderCreateInput!): Order!
updateOrder(data: OrderUpdateInput!, where: OrderWhereUniqueInput!): Order
updateManyOrders(data: OrderUpdateManyMutationInput!, where: OrderWhereInput): BatchPayload!
upsertOrder(where: OrderWhereUniqueInput!, create: OrderCreateInput!, update: OrderUpdateInput!): Order!
deleteOrder(where: OrderWhereUniqueInput!): Order
deleteManyOrders(where: OrderWhereInput): BatchPayload!
createOrderUpdate(data: OrderUpdateCreateInput!): OrderUpdate!
updateOrderUpdate(data: OrderUpdateUpdateInput!, where: OrderUpdateWhereUniqueInput!): OrderUpdate
updateManyOrderUpdates(data: OrderUpdateUpdateManyMutationInput!, where: OrderUpdateWhereInput): BatchPayload!
upsertOrderUpdate(where: OrderUpdateWhereUniqueInput!, create: OrderUpdateCreateInput!, update: OrderUpdateUpdateInput!): OrderUpdate!
deleteOrderUpdate(where: OrderUpdateWhereUniqueInput!): OrderUpdate
deleteManyOrderUpdates(where: OrderUpdateWhereInput): BatchPayload!
createUser(data: UserCreateInput!): User!
updateUser(data: UserUpdateInput!, where: UserWhereUniqueInput!): User
updateManyUsers(data: UserUpdateManyMutationInput!, where: UserWhereInput): BatchPayload!
upsertUser(where: UserWhereUniqueInput!, create: UserCreateInput!, update: UserUpdateInput!): User!
deleteUser(where: UserWhereUniqueInput!): User
deleteManyUsers(where: UserWhereInput): BatchPayload!
}
enum MutationType {
CREATED
UPDATED
DELETED
}
interface Node {
id: ID!
}
type Order {
id: ID!
user: User!
consignmentId: Int!
deliveryLocation: Coordinate!
senderLocation: Coordinate!
updates(where: OrderUpdateWhereInput, orderBy: OrderUpdateOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [OrderUpdate!]
active: Boolean
currentStatus: OrderStatus!
}
type OrderConnection {
pageInfo: PageInfo!
edges: [OrderEdge]!
aggregate: AggregateOrder!
}
input OrderCreateInput {
user: UserCreateOneInput!
consignmentId: Int!
deliveryLocation: CoordinateCreateOneInput!
senderLocation: CoordinateCreateOneInput!
updates: OrderUpdateCreateManyInput
active: Boolean
currentStatus: OrderStatus!
}
type OrderEdge {
node: Order!
cursor: String!
}
enum OrderOrderByInput {
id_ASC
id_DESC
consignmentId_ASC
consignmentId_DESC
active_ASC
active_DESC
currentStatus_ASC
currentStatus_DESC
createdAt_ASC
createdAt_DESC
updatedAt_ASC
updatedAt_DESC
}
type OrderPreviousValues {
id: ID!
consignmentId: Int!
active: Boolean
currentStatus: OrderStatus!
}
enum OrderStatus {
BEING_PREPARED
EN_ROUTE_TO_SENDER
WAITING_AT_SENDER
EN_ROUTE_TO_RECIPIENT
DELIVERED
UNSUCESSFUL
}
type OrderSubscriptionPayload {
mutation: MutationType!
node: Order
updatedFields: [String!]
previousValues: OrderPreviousValues
}
input OrderSubscriptionWhereInput {
mutation_in: [MutationType!]
updatedFields_contains: String
updatedFields_contains_every: [String!]
updatedFields_contains_some: [String!]
node: OrderWhereInput
AND: [OrderSubscriptionWhereInput!]
OR: [OrderSubscriptionWhereInput!]
NOT: [OrderSubscriptionWhereInput!]
}
type OrderUpdate {
id: ID!
consignmentId: Int!
coordinate: Coordinate!
status: OrderStatus!
}
type OrderUpdateConnection {
pageInfo: PageInfo!
edges: [OrderUpdateEdge]!
aggregate: AggregateOrderUpdate!
}
input OrderUpdateCreateInput {
consignmentId: Int!
coordinate: CoordinateCreateOneInput!
status: OrderStatus!
}
input OrderUpdateCreateManyInput {
create: [OrderUpdateCreateInput!]
connect: [OrderUpdateWhereUniqueInput!]
}
type OrderUpdateEdge {
node: OrderUpdate!
cursor: String!
}
input OrderUpdateInput {
user: UserUpdateOneRequiredInput
consignmentId: Int
deliveryLocation: CoordinateUpdateOneRequiredInput
senderLocation: CoordinateUpdateOneRequiredInput
updates: OrderUpdateUpdateManyInput
active: Boolean
currentStatus: OrderStatus
}
input OrderUpdateManyMutationInput {
consignmentId: Int
active: Boolean
currentStatus: OrderStatus
}
enum OrderUpdateOrderByInput {
id_ASC
id_DESC
consignmentId_ASC
consignmentId_DESC
status_ASC
status_DESC
createdAt_ASC
createdAt_DESC
updatedAt_ASC
updatedAt_DESC
}
type OrderUpdatePreviousValues {
id: ID!
consignmentId: Int!
status: OrderStatus!
}
input OrderUpdateScalarWhereInput {
id: ID
id_not: ID
id_in: [ID!]
id_not_in: [ID!]
id_lt: ID
id_lte: ID
id_gt: ID
id_gte: ID
id_contains: ID
id_not_contains: ID
id_starts_with: ID
id_not_starts_with: ID
id_ends_with: ID
id_not_ends_with: ID
consignmentId: Int
consignmentId_not: Int
consignmentId_in: [Int!]
consignmentId_not_in: [Int!]
consignmentId_lt: Int
consignmentId_lte: Int
consignmentId_gt: Int
consignmentId_gte: Int
status: OrderStatus
status_not: OrderStatus
status_in: [OrderStatus!]
status_not_in: [OrderStatus!]
AND: [OrderUpdateScalarWhereInput!]
OR: [OrderUpdateScalarWhereInput!]
NOT: [OrderUpdateScalarWhereInput!]
}
type OrderUpdateSubscriptionPayload {
mutation: MutationType!
node: OrderUpdate
updatedFields: [String!]
previousValues: OrderUpdatePreviousValues
}
input OrderUpdateSubscriptionWhereInput {
mutation_in: [MutationType!]
updatedFields_contains: String
updatedFields_contains_every: [String!]
updatedFields_contains_some: [String!]
node: OrderUpdateWhereInput
AND: [OrderUpdateSubscriptionWhereInput!]
OR: [OrderUpdateSubscriptionWhereInput!]
NOT: [OrderUpdateSubscriptionWhereInput!]
}
input OrderUpdateUpdateDataInput {
consignmentId: Int
coordinate: CoordinateUpdateOneRequiredInput
status: OrderStatus
}
input OrderUpdateUpdateInput {
consignmentId: Int
coordinate: CoordinateUpdateOneRequiredInput
status: OrderStatus
}
input OrderUpdateUpdateManyDataInput {
consignmentId: Int
status: OrderStatus
}
input OrderUpdateUpdateManyInput {
create: [OrderUpdateCreateInput!]
update: [OrderUpdateUpdateWithWhereUniqueNestedInput!]
upsert: [OrderUpdateUpsertWithWhereUniqueNestedInput!]
delete: [OrderUpdateWhereUniqueInput!]
connect: [OrderUpdateWhereUniqueInput!]
disconnect: [OrderUpdateWhereUniqueInput!]
deleteMany: [OrderUpdateScalarWhereInput!]
updateMany: [OrderUpdateUpdateManyWithWhereNestedInput!]
}
input OrderUpdateUpdateManyMutationInput {
consignmentId: Int
status: OrderStatus
}
input OrderUpdateUpdateManyWithWhereNestedInput {
where: OrderUpdateScalarWhereInput!
data: OrderUpdateUpdateManyDataInput!
}
input OrderUpdateUpdateWithWhereUniqueNestedInput {
where: OrderUpdateWhereUniqueInput!
data: OrderUpdateUpdateDataInput!
}
input OrderUpdateUpsertWithWhereUniqueNestedInput {
where: OrderUpdateWhereUniqueInput!
update: OrderUpdateUpdateDataInput!
create: OrderUpdateCreateInput!
}
input OrderUpdateWhereInput {
id: ID
id_not: ID
id_in: [ID!]
id_not_in: [ID!]
id_lt: ID
id_lte: ID
id_gt: ID
id_gte: ID
id_contains: ID
id_not_contains: ID
id_starts_with: ID
id_not_starts_with: ID
id_ends_with: ID
id_not_ends_with: ID
consignmentId: Int
consignmentId_not: Int
consignmentId_in: [Int!]
consignmentId_not_in: [Int!]
consignmentId_lt: Int
consignmentId_lte: Int
consignmentId_gt: Int
consignmentId_gte: Int
coordinate: CoordinateWhereInput
status: OrderStatus
status_not: OrderStatus
status_in: [OrderStatus!]
status_not_in: [OrderStatus!]
AND: [OrderUpdateWhereInput!]
OR: [OrderUpdateWhereInput!]
NOT: [OrderUpdateWhereInput!]
}
input OrderUpdateWhereUniqueInput {
id: ID
}
input OrderWhereInput {
id: ID
id_not: ID
id_in: [ID!]
id_not_in: [ID!]
id_lt: ID
id_lte: ID
id_gt: ID
id_gte: ID
id_contains: ID
id_not_contains: ID
id_starts_with: ID
id_not_starts_with: ID
id_ends_with: ID
id_not_ends_with: ID
user: UserWhereInput
consignmentId: Int
consignmentId_not: Int
consignmentId_in: [Int!]
consignmentId_not_in: [Int!]
consignmentId_lt: Int
consignmentId_lte: Int
consignmentId_gt: Int
consignmentId_gte: Int
deliveryLocation: CoordinateWhereInput
senderLocation: CoordinateWhereInput
updates_every: OrderUpdateWhereInput
updates_some: OrderUpdateWhereInput
updates_none: OrderUpdateWhereInput
active: Boolean
active_not: Boolean
currentStatus: OrderStatus
currentStatus_not: OrderStatus
currentStatus_in: [OrderStatus!]
currentStatus_not_in: [OrderStatus!]
AND: [OrderWhereInput!]
OR: [OrderWhereInput!]
NOT: [OrderWhereInput!]
}
input OrderWhereUniqueInput {
id: ID
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
type Query {
coordinates(where: CoordinateWhereInput, orderBy: CoordinateOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Coordinate]!
coordinatesConnection(where: CoordinateWhereInput, orderBy: CoordinateOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): CoordinateConnection!
order(where: OrderWhereUniqueInput!): Order
orders(where: OrderWhereInput, orderBy: OrderOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Order]!
ordersConnection(where: OrderWhereInput, orderBy: OrderOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): OrderConnection!
orderUpdate(where: OrderUpdateWhereUniqueInput!): OrderUpdate
orderUpdates(where: OrderUpdateWhereInput, orderBy: OrderUpdateOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [OrderUpdate]!
orderUpdatesConnection(where: OrderUpdateWhereInput, orderBy: OrderUpdateOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): OrderUpdateConnection!
user(where: UserWhereUniqueInput!): User
users(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [User]!
usersConnection(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): UserConnection!
node(id: ID!): Node
}
type Subscription {
coordinate(where: CoordinateSubscriptionWhereInput): CoordinateSubscriptionPayload
order(where: OrderSubscriptionWhereInput): OrderSubscriptionPayload
orderUpdate(where: OrderUpdateSubscriptionWhereInput): OrderUpdateSubscriptionPayload
user(where: UserSubscriptionWhereInput): UserSubscriptionPayload
}
type User {
id: ID!
name: String!
}
type UserConnection {
pageInfo: PageInfo!
edges: [UserEdge]!
aggregate: AggregateUser!
}
input UserCreateInput {
name: String!
}
input UserCreateOneInput {
create: UserCreateInput
connect: UserWhereUniqueInput
}
type UserEdge {
node: User!
cursor: String!
}
enum UserOrderByInput {
id_ASC
id_DESC
name_ASC
name_DESC
createdAt_ASC
createdAt_DESC
updatedAt_ASC
updatedAt_DESC
}
type UserPreviousValues {
id: ID!
name: String!
}
type UserSubscriptionPayload {
mutation: MutationType!
node: User
updatedFields: [String!]
previousValues: UserPreviousValues
}
input UserSubscriptionWhereInput {
mutation_in: [MutationType!]
updatedFields_contains: String
updatedFields_contains_every: [String!]
updatedFields_contains_some: [String!]
node: UserWhereInput
AND: [UserSubscriptionWhereInput!]
OR: [UserSubscriptionWhereInput!]
NOT: [UserSubscriptionWhereInput!]
}
input UserUpdateDataInput {
name: String
}
input UserUpdateInput {
name: String
}
input UserUpdateManyMutationInput {
name: String
}
input UserUpdateOneRequiredInput {
create: UserCreateInput
update: UserUpdateDataInput
upsert: UserUpsertNestedInput
connect: UserWhereUniqueInput
}
input UserUpsertNestedInput {
update: UserUpdateDataInput!
create: UserCreateInput!
}
input UserWhereInput {
id: ID
id_not: ID
id_in: [ID!]
id_not_in: [ID!]
id_lt: ID
id_lte: ID
id_gt: ID
id_gte: ID
id_contains: ID
id_not_contains: ID
id_starts_with: ID
id_not_starts_with: ID
id_ends_with: ID
id_not_ends_with: ID
name: String
name_not: String
name_in: [String!]
name_not_in: [String!]
name_lt: String
name_lte: String
name_gt: String
name_gte: String
name_contains: String
name_not_contains: String
name_starts_with: String
name_not_starts_with: String
name_ends_with: String
name_not_ends_with: String
AND: [UserWhereInput!]
OR: [UserWhereInput!]
NOT: [UserWhereInput!]
}
input UserWhereUniqueInput {
id: ID
}
`
|
f430a995324edd5ae8bc07a25d78829c20d7c583
|
TypeScript
|
xhackax47/JavaScript-TypeScript
|
/exos/ex1.ts
| 3.171875
| 3
|
import { Promise } from 'es6-promise';
console.log('--------------------------- TP TYPESCRIPT ----------------------------');
let noteTab20: Array<number> = [8, 5, 7];
let noteTab10: Array<number> = noteTab20.map((elmt) => elmt / 2);
let intTab1 = [0, 1, 2, 3, 4];
let intTab2 = [5, 6, 7, 8, 9];
let intTab3 = [1, true, 'Three'];
let stringTab1: Array<string> = Array(10);
let myUnion: number | Array<number>;
let myUnion2: number | Array<string>;
let myUnion3 = [];
let total10 = noteTab10.reduce((acc, elmt) => { return acc += elmt });
let total20 = noteTab20.reduce((acc, elmt) => { return acc += elmt });
let dix: string = '/10';
let vingt: string = '/20';
let stringLg: string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tempus lorem ut ipsum placerat, sit amet mattis enim rhoncus. Duis eu dictum ante';
let noteA: number = 15;
let noteB: number = 10;
let noteC: number = 12;
let noteD: number = 19;
noteTab20.push(noteA);
noteTab20.push(noteB);
noteTab20.push(noteC);
noteTab20.push(noteD);
// ENUMERATION
enum enumColor {
Rouge,
Vert,
Bleu,
}
let enumR = enumColor.Rouge;
let enumV = enumColor.Vert;
let enumBl = enumColor.Bleu;
let nbIndice = 1;
// INTERFACES
interface Surface2D {
aire(): number;
perimeter(): number;
}
interface DataStructure {
x: number;
y: number;
rayon?: number;
}
interface Pet {
nom: string;
age: number;
poids: number;
}
// CLASSES ET OBJETS A LA VOLEE
let mJackson = {
nom: 'Jackson',
prenom: 'Michael',
dateNaissance: '29/08/1958',
nomComplet(): string {
return 'Nom complet : ' + this.prenom + ' ' + this.nom;
}
}
class Personne {
nom: string;
prenom: string;
dateNaissance: string;
constructor(nom: string, prenom: string, dateNaissance: string) {
this.nom = nom;
this.prenom = prenom;
this.dateNaissance = dateNaissance;
}
nomComplet(): string {
return 'Nom complet : ' + this.prenom + ' ' + this.nom;
}
}
class Rectangl implements Surface2D {
longueur: number;
largeur: number;
constructor(longueur: number, largeur: number) {
this.longueur = longueur;
this.largeur = largeur;
}
aire = () => { return this.largeur * this.longueur };
perimeter = () => { return 2 * this.largeur + 2 * this.longueur }
}
class Carré extends Rectangl {
constructor(cote: number) {
super(cote, cote);
}
}
class Employee {
userId: string;
constructor(userId: string) {
this.userId = userId;
}
displayUserId() {
setTimeout(() => {
console.log(`UserId de l'employée = ${this.userId}`);
}, 1000)
}
}
// FONCTIONS
function moy10(total10: number): number {
return (total10) / noteTab10.length;
}
function max10(noteTab10: Array<number>): number {
return Math.max(...noteTab10);
}
function min10(noteTab10: Array<number>): number {
return Math.min(...noteTab10);
}
function moy20(total20: number): number {
return (total20) / noteTab20.length;
}
function max20(noteTab20: Array<number>): number {
return Math.max(...noteTab20);
}
function min20(noteTab20: Array<number>): number {
return Math.min(...noteTab20);
}
function filter10(noteTab10: Array<number>) {
return noteTab10.filter(elmt => {
return (elmt > min10(noteTab10) && (elmt < max10(noteTab10)));
});
}
function filter20(noteTab20: Array<number>) {
return noteTab20.filter(elmt => {
return (elmt > min20(noteTab20) && (elmt < max20(noteTab20)));
});
}
function add2nb(a: number, b: number) {
var sum = a + b;
return sum;
}
let y: number = (function (a: number, b: number) { return a + b; })(20, 25);
let x: number = ((a, b) => a + b)(20, 25);
function userIdEmployee() {
console.log("Let's get started!");
var myEmployee = new Employee('47');
myEmployee.displayUserId();
}
function callCallBack(name: string) {
console.log(name);
}
function helloCallback(callback) {
let name = 'TestCallBack';
callback(name);
}
function orderByName() {
let orderByName = listPersonsWorking.sort((p1, p2) => {
if (p1.nom < p2.nom) {
return -1;
} else if (p1.nom > p2.nom) {
return 1;
} else if (p1.nom === p2.nom) {
return 0;
} else {
if (p1.prenom < p2.prenom) {
return -1;
} else if (p1.prenom > p2.prenom) {
return 1;
} else { return 0; }
}
});
return orderByName;
}
console.log('-------------------------------------------------------');
console.log(total10 + '' + total20);
console.log('Moyenne des notes : ' + moy20(total20) + vingt);
console.log('Note maximale : ' + max20(noteTab20) + vingt);
console.log('Note minimale : ' + min20(noteTab20) + vingt);
console.log('Notes du minimum au maximum : ' + filter20(noteTab20));
console.log('-------------------------------------------------------');
console.log('Moyenne des notes : ' + moy10(total10) + dix);
console.log('Note maximale : ' + max10(noteTab10) + dix);
console.log('Note minimale : ' + min10(noteTab10) + dix);
console.log('Notes du minimum au maximum : ' + filter10(noteTab10));
console.log('-------------------------------------------------------');
console.log('Slice de stringLg de 1 à 22 : ' + stringLg.slice(1, 22));
console.log('Affichage enumColor via nbIndice (' + nbIndice + ') : ' + enumColor[nbIndice]);
console.log('-------------------------------------------------------');
console.log('Affichage Tableau Entiers intTab1 : ' + intTab1);
console.log('Affichage Tableau Entiers intTab2 : ' + intTab2);
console.log('Affichage Tableau Entiers intTab3 : ' + intTab3);
console.log('Affichage Tableau Strings stringTab1 : ' + stringTab1);
console.log('-------------------------------------------------------');
console.log('Affichage valeur myUnion avant init : ' + (myUnion));
console.log('Affichage valeur myUnion après init : ' + (myUnion = 5));
if (typeof (myUnion) === typeof ('number[]')) {
console.log('Le type de myUnion est un Array<number>');
} else if (typeof (myUnion) === 'number') {
console.log('Le type de myUnion est un number');
} else {
console.log('Le type de myUnion est inconnu');
}
console.log('Affichage valeur myUnion après init : ' + (myUnion3 = [1, 2, 3]));
if (typeof (myUnion) === typeof ('number[]')) {
console.log('Le type de myUnion est un Array<number>');
} else if (typeof (myUnion) === 'number') {
console.log('Le type de myUnion est un number');
} else {
console.log('Le type de myUnion est inconnu');
}
console.log('-------------------------------------------------------');
console.log('Affichage valeur myUnion2 : ' + (myUnion2 = ['Test', 'Test2']));
switch (typeof (myUnion2)) {
case typeof ('string[]'): {
console.log('Le type de myUnion2 est un Array<string>');
break;
}
case 'number': {
console.log('Le type de myUnion2 est un number');
break;
}
default: {
console.log('Le type de myUnion2 est inconnu');
break;
}
}
console.log('-------------------------------------------------------');
let n1 = 20;
let n2 = 25;
console.log('Fonction add2nb sur n1 et n2 : ' + add2nb(n1, n2));
console.log('Fonction y : ' + y);
console.log('Fonction x : ' + x);
console.log('-------------------------------------------------------');
console.log('OBJETS');
console.log('-------------------------------------------------------');
console.log(mJackson.nomComplet());
let gHellscream: Personne = mJackson;
gHellscream.nom = 'Hellscream'; gHellscream.prenom = 'Grommash'; gHellscream.dateNaissance = '01/01/1900';
console.log(gHellscream.nomComplet());
let figure1: DataStructure = { x: 5, y: 10, rayon: 10, };
let figure2: DataStructure = { x: 10, y: 20 };
console.log('Figure 1 interface DataStructure : X= ' + figure1.x + ' Y= ' + figure1.y + ' et Rayon = ' + figure1.rayon);
console.log('Figure 1 interface DataStructure : X= ' + figure2.x + ' et Y= ' + figure2.y);
let Cat: Pet = { nom: 'Cat', age: 10, poids: 20 };
let Dog: Pet = { nom: 'Dog', age: 1, poids: 10 };
let Horse: Pet = { nom: 'Horse', age: 15, poids: 500 };
let Crocodile: Pet = { nom: 'Crocodile', age: 50, poids: 20 };
let tabPet: Array<Pet> = [Cat, Dog, Horse, Crocodile];
console.log('Tableau Animaux NON-TRIES : ')
console.log(tabPet);
let triPet = tabPet.sort(
(a1, a2) => {
if (a1.age < a2.age) {
return -1;
} else if (a1.age > a2.age) {
return 1;
} else if (a1.age === a2.age) {
return 0;
} else { }
});
console.log('Tableau Animaux TRIES : ')
console.log(triPet);
helloCallback(callCallBack);
userIdEmployee();
console.log('-------------------------------------------------------');
let listInt: Array<number> = [1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
let sommeListInt = listInt.reduce((acc, curr) => { return acc + curr; });
let filterListInt = listInt.filter((elmt => { return (elmt > 6) }));
let nbElmtListInt = listInt.reduce((acc) => { return acc += 1 }, 0);
console.log("Somme de listInt : ")
console.log(sommeListInt);
console.log("Moyenne de listInt : ")
console.log(sommeListInt / listInt.length)
console.log("Nombres de listInt supérieurs à 6 : ")
console.log(filterListInt);
console.log("Nombres d'éléments : ")
console.log(nbElmtListInt);
console.log('-------------------------------------------------------');
let p1: Personne = new Personne('Pe1', 'Pe1', '01-01-2001');
let p2: Personne = new Personne('Pe2', 'Pe2', '01-01-2002');
let p3: Personne = new Personne('Pe3', 'Pe3', '01-01-2003');
let p4: Personne = new Personne('Pe4', 'Pe4', '01-01-2004');
let p5: Personne = new Personne('Pe5', 'Pe5', '01-01-2005');
let pD: Personne = new Personne('Dp6', 'Pe6', '01-01-2006');
let p7: Personne = new Personne('Pe7', 'Pe7', '01-01-2007');
let p8: Personne = new Personne('Pe8', 'Pe8', '01-01-2008');
let p9: Personne = new Personne('Pe9', 'Pe9', '01-01-2009');
let dupont: Personne = new Personne('Dupont', 'Henry', '01-01-2010');
let listPersonsOriginal: Array<Personne> = [p1, p2, p3, p4, p5, pD, p7, p8, p9, dupont];
let listPersonsWorking: Array<Personne> = listPersonsOriginal.slice();
console.log("Lister listPersons par nom : ")
console.log(orderByName());
let listPersonsD = listPersonsWorking.filter((elmt: Personne) => { return ((elmt.nom.slice(0, 1))) === 'D' });
console.log("Filtrer par nom commencant par D sur listPersons : ")
console.log(listPersonsD);
console.log("Afficher Nom seulement sur listPersons : ")
let listPersonsName: Array<Personne> = [];
listPersonsWorking.map((elmt: Personne) => {
elmt.nom = elmt.nom.toUpperCase();
listPersonsName.push(elmt);
});
let listPersonsFirstNameDsc = listPersonsName.sort((p1, p2) => {
if (p1.prenom < p2.prenom) {
return 1;
} else if (p1.prenom > p2.prenom) {
return -1;
} else {
return 0;
}
});
console.log("Afficher Liste DSC sur prénom : ");
console.log(listPersonsFirstNameDsc);
console.log("Afficher list2personsSlice : ");
let list2personsSlice = listPersonsWorking.slice(0, 2);
console.log(list2personsSlice);
console.log("Afficher list2personsFilter : ");
let list2personsFilter = listPersonsWorking.filter((elmt: Personne, index: number) => { return index < 2 });
console.log(list2personsFilter);
console.log("Afficher index 7,8 et 9 de listPersonsWorking : ");
let listPersons789 = listPersonsWorking.filter((elmt: Personne, index: number) => { return index >= 7 && index < 10 });
console.log(listPersons789);
console.log("Afficher seulement Dupont dans listPersonsWorking : ");
let listDupont = listPersonsWorking.filter((elmt: Personne) => { return elmt.nom === 'DUPONT' });
console.log(listDupont);
console.log("Afficher personnes commencant par D dans listPersonsWorking : ");
let listPersonsStartsWithD = listPersonsWorking.some((elmt: Personne) => { return elmt.nom.slice(0, 1) === 'D' });
console.log("Présence de personnes avec un nom commencant par D : " + listPersonsStartsWithD);
console.log('-------------------------------------------------------');
console.log("Affichage testNum avec Promise : ")
let testNum = (n: number) => {
return new Promise(function (resolve, reject) {
if (n > 10) {
resolve("CHIFFRE AU DESSUS DE 10");
} else {
reject("ERREUR")
}
});
}
testNum(11).then(value => console.log(value)).catch(err => console.log("Error"));
let listString: Array<string> = ['Test1', 'Test2', 'Test3'];
let triStringArray = (listString: Array<string>) => {
return new Promise(function (resolve, reject) {
if (listString.some((val: string) => {
return !isNaN(Number(val));
}))
reject('Il y a un nombre');
else {
listString.sort().forEach((listString) => console.log(listString.toUpperCase()));
}
resolve('OK');
});
}
triStringArray(listString).
then((value: string) => { console.log(value); }).
catch((value: string) => { console.log(value); });
|
88bb6a4837cf227ac3153ec1ee7023b10f70aed9
|
TypeScript
|
JonDotsoy/envuse
|
/packages/envuse/data-source/statements/components/statement-object/statement-number-object.ts
| 2.890625
| 3
|
import { BufferCursor } from "../../lib/buffer-cursor";
import { BCharType } from "../../tdo/b-char-type";
import { CharactersKey as k } from "../../tdo/characters-key";
import { b } from "../../lib/to-buffer";
import { StatementObjectTypes } from "../../tdo/statement-object-types";
import { StatementObjectDefinition } from "../statement-object-definition";
export class StatementNumberObject extends StatementObjectDefinition {
assert(
bufferCursor: BufferCursor<BCharType>
): bufferCursor is BufferCursor<number> {
return bufferCursor.has() && k.numbers.includes(bufferCursor.current());
}
prepare(bufferCursor: BufferCursor<number>): void {
const raw: number[] = [];
const appendRaw = (...chars: number[]) => {
raw.push(...chars);
};
this.type = StatementObjectTypes.Number;
while (bufferCursor.hasOrEnd()) {
if (
bufferCursor.isClosed() ||
k.space === bufferCursor.current() ||
bufferCursor.current() === k.newLineLF ||
bufferCursor.current() === k.equalsSign
) {
this.value = Number(b(raw));
return;
}
if (
bufferCursor.has() &&
(k.numbers.includes(bufferCursor.current()) ||
bufferCursor.current() === k.dot)
) {
appendRaw(bufferCursor.current());
bufferCursor.forward();
continue;
}
if (bufferCursor.current() === k.underscore) {
bufferCursor.forward();
continue;
}
this.rejectUnexpectedTokenError();
}
}
}
|
75249a2219776c16ffd9fe5a75f1c648076a0142
|
TypeScript
|
udecode/plate
|
/packages/media/src/image/withImageEmbed.ts
| 2.578125
| 3
|
import { PlateEditor, Value, WithPlatePlugin } from '@udecode/plate-common';
import { insertImage } from './transforms/insertImage';
import { ImagePlugin } from './types';
import { isImageUrl } from './utils/isImageUrl';
/**
* If inserted text is image url, insert image instead.
*/
export const withImageEmbed = <
V extends Value = Value,
E extends PlateEditor<V> = PlateEditor<V>,
>(
editor: E,
// eslint-disable-next-line unused-imports/no-unused-vars
plugin: WithPlatePlugin<ImagePlugin, V, E>
) => {
const { insertData } = editor;
editor.insertData = (dataTransfer: DataTransfer) => {
const text = dataTransfer.getData('text/plain');
if (isImageUrl(text)) {
insertImage(editor, text);
return;
}
insertData(dataTransfer);
};
return editor;
};
|
bdc97cf275520dacec978e475749421996152672
|
TypeScript
|
guilhermeSousa1/get-a-car
|
/apps/get-a-car/src/app/core/services/notification/notification.service.ts
| 2.546875
| 3
|
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
/**
* Service used to create notifications.
*/
@Injectable({
providedIn: 'root'
})
export class NotificationService {
/**
* Class constructor.
*
* @param snackBar Injection of the MatSnackBar service
*/
constructor(private snackBar: MatSnackBar) {
}
/**
* Shows the error notification.
*
* @public
* @param message The error message
*/
public showError(message: string): void {
this.snackBar.open(message, 'X',
{ panelClass: ['error-notification'], duration: 5000, horizontalPosition: 'end', verticalPosition: 'top' });
}
}
|
0d7335cf8f40e3866727c65254c07c06232bd76e
|
TypeScript
|
water102/fx-common
|
/src/format/slugify.ts
| 2.8125
| 3
|
import { isEmpty } from "ramda";
export const slugify = (text: string): string => {
if (isEmpty(text)) return ''
text = text
.toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/[^\p{L}\p{N}-]/gu, '') // Remove non-alphanumeric characters except hyphens
.normalize('NFD') // Normalize Unicode characters
.replace(/[\u0300-\u036f]/g, '') // Remove diacritical marks
.replace(/--+/g, '-')
.replace(/^-+|-+$/g, '')
// for Vietnamese characters
const from = "àáạảãâầấậẩẫăằắặẳẵèéẹẻẽêềếệểễìíịỉĩòóọỏõôồốộổỗơờớợởỡùúụủũưừứựửữỳýỵỷỹđ·/_,:;";
const to = "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyd------";
for (let i = 0, l = from.length; i < l; i++) {
text = text.replace(new RegExp(from.charAt(i), "g"), to.charAt(i));
}
return text
}
|
85b00ff6015833abbdd0877f1a128df33841f7cc
|
TypeScript
|
radman0x/rl-lib
|
/rl-ecs/src/lib/components/bang.model.ts
| 2.625
| 3
|
import { Component } from 'rad-ecs';
export interface BangData {
strength: number;
}
export class Bang extends Component implements BangData {
public readonly strength: number;
constructor(data: BangData) {
super();
Object.assign(this, data);
}
}
|
a80ca7b052010179ff3561fc236e85e44ebdacfe
|
TypeScript
|
dvallin/lazy-ecs
|
/src/spatial/space.ts
| 3.40625
| 3
|
import { Vector } from "./vector"
import { Option } from "lazy-space"
export interface Space<A> {
get(pos: Vector): Option<A>
set(pos: Vector, objects: A): void
remove(pos: Vector): Option<A>
}
export class DiscreteSpace<A> implements Space<A> {
private readonly objects: Map<string, A> = new Map()
public get(pos: Vector): Option<A> {
const key = pos.key()
return Option.of(this.objects.get(key))
}
public set(pos: Vector, objects: A): void {
const key = pos.key()
this.objects.set(key, objects)
}
public remove(pos: Vector): Option<A> {
const key = pos.key()
const value = Option.of(this.objects.get(key))
this.objects.delete(key)
return value
}
}
export class SubSpace<A> implements Space<A> {
public constructor(
public readonly space: Space<A>,
public readonly transform: (pos: Vector) => Vector
) { }
public get(pos: Vector): Option<A> {
return this.space.get(this.transform(pos))
}
public set(pos: Vector, objects: A): void {
return this.space.set(this.transform(pos), objects)
}
public remove(pos: Vector): Option<A> {
return this.space.remove(this.transform(pos))
}
}
|
776752e6cf5bbf36f56c7157f1359e0cbfef7ca8
|
TypeScript
|
ljuvtliv/switchdrive
|
/src/api/routers/switchRouter.ts
| 2.5625
| 3
|
import { U_TYPE } from "@base/work";
const Router = require('koa-router')
export class SwitchRouter {
router;
constructor(){
this.router = new Router();
//Router defs here, tying into functions on this class
this.router.get('/', function (ctx, next) {
ctx.send('Hello World!')
});
this.router.get('/test', function (ctx, next) {
});
this.router.get('/orphans', async function (ctx, next) {
ctx.body = await ctx.core.loader.update_orphans();
});
this.router.get('/update/:type', async function (ctx,next) {
let type = ctx.params['type'];
//Type is ALL,TitleDB,GameDB or Drive
/*
gamedb = games you own
titledb = the titleid database
drive = import_drive
*/
let gamedirs = ctx.core.gamedirs;
let drive_folders = ctx.core.drivedirs;
if(type == "all" || type == "titledb"){
await ctx.core.titledb.work(U_TYPE.ALL);
}
if(type == "all" || type == "gamedb"){
let ret;
for(var i in gamedirs){
ret = await ctx.core.loader.refresh(gamedirs[i]);
ret.toFile(ctx.core.basedir+'log/refresh_'+i+'.log');
}
}
if(type == "all" || type == "drive"){
for(var i in drive_folders){
let ret = await ctx.core.loader.import_drive(drive_folders[i]);
ret.toFile(ctx.core.basedir+'logs/driveImport_'+drive_folders[i].input+'.log');
}
}
console.log(type);
ctx.body = 'worked';
});
}
getRouter(){
return this.router;
}
}
|
4a684baaf162e4d6703600ae9b98b2d067a5cd66
|
TypeScript
|
skyskyskyha/hearthstone-battlegrounds-tools
|
/src/renderer/core/hooks/useSurprise.ts
| 2.515625
| 3
|
import React from 'react'
// @ts-ignore
import Emoji233333 from 'emoji-233333'
const list = [
{
label: 'hbt',
url: 'https://hs.chenyueban.com/hearthstone/images/surprise/logo.png',
},
{
label: 'HBT',
url: 'https://hs.chenyueban.com/hearthstone/images/surprise/logo.png',
},
{
label: '雪之下雪乃',
url:
'https://hs.chenyueban.com/hearthstone/images/surprise/surprise-01.jpg',
},
]
const options = {
// DOM / 选择器
base: 'emoji', // string | HTMLElement
// 表情缩放程度
scale: 0.3, // number
// 动画速度
speed: 3, // number
// 递增速度
increaseSpeed: 0.3, // number
// 表情密度
density: 3, // number
// 是否启用内置缓存机制
cache: true, // boolean
// 是否启用交错效果
staggered: Math.random() > 0.5, // boolean
// 自定义表情图片地址 url || base64
emoji: 'https://hs.chenyueban.com/hearthstone/images/surprise/logo.png', // string
}
function useSurprise(): { run: (value: string) => void } {
const handleLaunch = React.useCallback((value: string) => {
list.forEach((item) => {
if (value?.includes(item.label)) {
const canvas =
document.querySelector('#emoji') ?? document.createElement('canvas')
canvas.id = 'emoji'
canvas.setAttribute(
'style',
`position: fixed;top: 0;left: 0;z-index: -1;`
)
canvas.setAttribute('width', window.innerWidth.toString())
canvas.setAttribute('height', window.innerHeight.toString())
const root = document.querySelector('#root')
root?.appendChild(canvas)
// @ts-ignore
options.base = canvas
options.emoji = item.url
const emoji233333 = new Emoji233333(options)
emoji233333.launch()
}
})
}, [])
return {
run: handleLaunch,
}
}
export default useSurprise
|
2266db3e682798b1d7580e78e9b74ad49e4d2838
|
TypeScript
|
mohitv789/reading-app-api
|
/src/app/profile/store/profile.actions.ts
| 2.53125
| 3
|
import { Action } from '@ngrx/store';
import { Image } from '../image.model';
export const SET_IMAGES = '[Function] Set Images';
export const FETCH_IMAGES = '[Functions] Fetch Images';
export const ADD_IMAGE = '[Function] Add Image';
export const UPDATE_IMAGE = '[Function] Update Image';
export const DELETE_IMAGE = '[Function] Delete Image';
export const STORE_IMAGES = '[Function] Store Images';
export class SetImages implements Action {
readonly type = SET_IMAGES;
constructor(public payload: Image[]) {}
}
export class FetchImages implements Action {
readonly type = FETCH_IMAGES;
}
export class AddImage implements Action {
readonly type = ADD_IMAGE;
constructor(public payload: Image) {}
}
export class UpdateImage implements Action {
readonly type = UPDATE_IMAGE;
constructor(public payload: { index: number; newImage: Image }) {}
}
export class DeleteImage implements Action {
readonly type = DELETE_IMAGE;
constructor(public payload: number) {}
}
export class StoreImages implements Action {
readonly type = STORE_IMAGES;
}
export type ImageActions =
| SetImages
| FetchImages
| AddImage
| UpdateImage
| DeleteImage
| StoreImages;
|
8b90576849612b5185153df92d9e6de5fbe4032c
|
TypeScript
|
RGFTheCoder/noted
|
/src/types/Note.ts
| 2.53125
| 3
|
export type Note = { name: string; tags: string[]; content: string };
type TagDef = { color: string };
export type NoteData = {
tags: Record<string, TagDef>;
notes: Note[];
};
|
56c19705e4e7cdf4f186c2d444079178a965c61e
|
TypeScript
|
edumentab/talks-redux-patterns
|
/src/v06/redux/lib/types/thunk.ts
| 3.140625
| 3
|
type ThunkCreatorWithoutOptions<A, S> = () => Thunk<A, S>
type ThunkCreatorWithOptions<A, S, O> = (opts: O) => Thunk<A, S>
export type ThunkCreator<A, S, O = undefined> = O extends undefined
? ThunkCreatorWithoutOptions<A, S>
: ThunkCreatorWithOptions<A, S, O>
export type Thunk<A, S> = (
dispatch: (action: A) => void,
getState: () => S
) => void
|
bb71d927e196b6bdccf023e130f2800e6dc6f191
|
TypeScript
|
tomzhang/swim
|
/swim-system-js/swim-ux-js/@swim/mapbox/main/MapboxProjection.ts
| 2.53125
| 3
|
// Copyright 2015-2020 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as mapboxgl from "mapbox-gl";
import {AnyPointR2, PointR2} from "@swim/math";
import {AnyLngLat, LngLat, MapProjection} from "@swim/map";
export class MapboxProjection implements MapProjection {
/** @hidden */
readonly _map: mapboxgl.Map;
constructor(map: mapboxgl.Map) {
this._map = map;
}
get map(): mapboxgl.Map {
return this._map;
}
get bounds(): Readonly<[LngLat, LngLat]> {
const mapBounds = this._map.getBounds();
return [new LngLat(mapBounds.getWest(), mapBounds.getSouth()),
new LngLat(mapBounds.getEast(), mapBounds.getNorth())];
}
project(lnglat: AnyLngLat): PointR2;
project(lng: number, lat: number): PointR2;
project(lng: AnyLngLat | number, lat?: number): PointR2 {
let coord: mapboxgl.LngLatLike;
if (typeof lng === "number") {
coord = new mapboxgl.LngLat(lng, lat!);
} else {
coord = lng;
}
const {x, y} = this._map.project(coord);
return new PointR2(x, y);
}
unproject(point: AnyPointR2): LngLat;
unproject(x: number, y: number): LngLat;
unproject(x: AnyPointR2 | number, y?: number): LngLat {
let point: mapboxgl.PointLike;
if (typeof x === "number") {
point = new mapboxgl.Point(x, y!);
} else if (Array.isArray(x)) {
point = x;
} else {
point = new mapboxgl.Point(x.x, x.y);
}
const {lng, lat} = this._map.unproject(point);
return new LngLat(lng, lat);
}
}
|
f61aabca8cc9c81ac82a1ed75f7619a713a707fa
|
TypeScript
|
markmccoid/rn-movietracker
|
/src/hooks/useWatchProviderData.ts
| 2.796875
| 3
|
import { useEffect, useState } from "react";
import { movieGetWatchProviders } from "@markmccoid/tmdb_api";
import _ from "lodash";
type ProviderInfo = {
provider: string;
logoURL: string;
providerId: number;
displayPriority: number;
};
export type WatchProvidersType = {
justWatchLink: string;
stream: ProviderInfo[];
rent: ProviderInfo[];
buy: ProviderInfo[];
};
const initWatchProviders: WatchProvidersType = {
justWatchLink: "",
stream: [],
rent: [],
buy: [],
};
export function useWatchProviderData(movieId: string): [WatchProvidersType, boolean] {
let [watchProviders, setWatchProviders] = useState<WatchProvidersType>(initWatchProviders);
let [isLoading, setIsLoading] = useState<boolean>(true);
// looks for data first in local storage
// if not there, then reads from API and saves to local storage
const loadWatchProviderData = async () => {
setIsLoading(true);
if (!movieId) {
setWatchProviders(initWatchProviders);
setIsLoading(false);
return;
}
// not passing country codes, which means we will only get back 'US'
const tempData = await movieGetWatchProviders(movieId);
const tempDataUS: WatchProvidersType = tempData.data.results.US;
// Sort each array "rent, buy, stream" by their displayPriority
const finalData = {
...tempDataUS,
rent: _.sortBy(tempDataUS.rent, ["displayPriority"]),
buy: _.sortBy(tempDataUS.buy, ["displayPriority"]),
stream: _.sortBy(tempDataUS.stream, ["displayPriority"]),
};
setIsLoading(false);
// { justWatchLink, stream: { provider, logoURL, providerId, displayPriority}, rent, buy}
setWatchProviders(finalData);
};
useEffect(() => {
loadWatchProviderData();
}, [movieId]);
return [watchProviders, isLoading];
}
|
0a482e1e9f70c08a0177bc51edd82a687eb39621
|
TypeScript
|
dbspt/nodejs-app-example-docker
|
/src/app/services/example.ts
| 2.609375
| 3
|
import ExampleModel from "../models/example";
import IExample from '../interfaces/example';
class ExampleService {
public async getInformation(): Promise<IExample[]> {
return await ExampleModel.find({});
}
public async setInformation(data: IExample): Promise<IExample>{
const example = new ExampleModel(data)
return await example.save()
}
}
export default new ExampleService();
|
1e91cfb92704e87a21628a080b3c024f56bb6b3f
|
TypeScript
|
rjvalencia/au-eva
|
/src/models/acct-list.ts
| 2.6875
| 3
|
import { Acct, Annotation } from '../models/acct';
//
export class AcctList extends Array<Acct | Annotation> {
equationSide: string;
listTotal: number;
idToFind;
private constructor() {
super()
}
static create(equationSide: string): AcctList {
return Object.assign(Object.create(AcctList.prototype), { equationSide });
}
refresh(): void {
this.sort((a, b) => a.compareTo(b));
let listTotal = 0.00;
for (let listItem of this) {
if (listItem instanceof Acct) {
listItem.bchgList.refresh();
listTotal += listItem.bchgList.endingBalance;
}
}
this.listTotal = listTotal;
}
}
|
59f9fc29830585a76b38043820159db4bdcb98d3
|
TypeScript
|
postor/quick-buf
|
/src/decode.ts
| 2.734375
| 3
|
import { BitReader } from "./bits"
// import { EncodeUints } from "./encode"
import { ParseConfig, Structure, StructureMeta, StructureMetaItem } from "./Structure"
import { TypeClasses, TypeSizes, TypeValues, ValueTypes } from "./util"
import { VUintReader } from "./VUint"
const UTF8 = new TextDecoder()
// let DecodeUints: number[] = []
// let _fixedArrayCount=0
// export const fixedArrayCount=()=>_fixedArrayCount
export function decode(buf: ArrayBuffer, structure?: Structure | ParseConfig): any {
// bitmask, type counts, string total bytes
let cur = 0, stringArr: string[] = []
let ui32 = () => {
let rtn = buffReader<number>(buf, Uint32Array, cur, 1)()
cur += 4
return rtn
}
let bitmask = ui32(), arrsCounts = new Array(10).fill(0)
// console.log({ bitmask })
for (let i = 0; i < arrsCounts.length; i++) {
if (bitmask & (1 << i)) {
arrsCounts[i] = ui32()
}
}
let booleanSize = (bitmask & (1 << 11)) && ui32(), stringTotalSize = (bitmask & (1 << 12)) && ui32()
// console.log(arrsCounts.concat([booleanSize, stringTotalSize]), bitmask.toString(2))
// console.log(arrsCounts)
// init readers
let arrs = arrsCounts.map((x, i) => {
if (!x) return () => 0
let size = TypeSizes[i] * x
// console.log(`${TypeClasses[i]}`, { x, i, size, cur })
let reader = buffReader(buf.slice(cur, cur + size), TypeClasses[i])
cur += size
return reader
})
arrs[TypeValues.boolean] = getBooleanReader()
arrs[TypeValues.string] = getStringReader()
arrs[TypeValues.uint] = getUintReader()
//
const struct = structure
? structure instanceof Structure
? structure
: Structure.parse(structure)
: readStructure() as Structure
// console.log({ struct, structure })
return readData(struct)
function readStructure(): Structure {
let data = readData(StructureMeta) as StructureMetaItem[]
// console.log({ structure: data })
return Structure.restruct(data)
}
function readData(struct: Structure) {
switch (struct.type) {
case 'array': return readArray(struct.contents as Structure, struct.arrLength)
case 'object': return readObj(struct.contents as Structure[])
case 'bigint':
case 'string': return arrs[TypeValues.string]()
case 'number':
case 'Double': return arrs[TypeValues.Float64]()
case 'Float':
case 'float':
return arrs[TypeValues.Float32]()
default: return arrs[TypeValues[struct.type]]()
}
function readObj(structs: Structure[]): any {
let obj: { [key: string]: any } = {}
for (let s of structs) {
obj[s.name] = readData(s)
}
// console.log(structs, obj)
return obj
}
function readArray(struct: Structure, length = 0): any {
// if(length) _fixedArrayCount++
let arr = [], leng = length == 0 ? arrs[TypeValues.uint]() as number : length
// console.log(`arr.lenght=${length}`)
for (let i = 0; i < leng; i++) {
arr.push(readData(struct))
}
return arr
}
}
function getUintReader() {
// console.log({ uintStartDecode: cur }, buf.slice(cur))
let reader = new VUintReader(new Uint8Array(buf, cur))
return () => {
let tmp = reader.read()
// DecodeUints.push(tmp)
// if (DecodeUints[DecodeUints.length - 1] != EncodeUints[DecodeUints.length - 1]) {
// console.log(EncodeUints, DecodeUints, tmp, reader)
// throw 'mismatch!'
// }
return tmp
}
}
function getStringReader() {
let strOffset = cur
cur += stringTotalSize
return () => {
let exists = arrs[TypeValues.boolean]()
if (exists) {
return stringArr[arrs[TypeValues.uint]() as number]
}
let length = arrs[TypeValues.uint]() as number
if (!length) return ''
let rtn = UTF8.decode(new Uint8Array(buf, strOffset, length))
stringArr.push(rtn)
strOffset += length
return rtn
}
}
function getBooleanReader() {
let size = Math.ceil(booleanSize / 8),
reader = new BitReader(new Uint8Array(buf, cur, size))
cur += size
return () => reader.read()
}
}
function buffReader<T>(buf: ArrayBuffer, TypeClass: any, offset?: number, length?: number) {
let i = 0, arr = new TypeClass(buf, offset, length)
return () => arr[i++] as T
}
|
e7316f05e93a3b2b66f352a5b38ea93b68a67fb5
|
TypeScript
|
Nieks1911/PRG04-homework
|
/CMTTHE04-Week2-oefening1-master/dev/bubble.ts
| 3
| 3
|
class Bubble {
div: HTMLElement
bubble: HTMLElement
constructor() {
console.log("Blub... blub...")
this.bubble = document.createElement("bubble")
this.bubble.addEventListener("click", () => this.popBubble())
let game = document.getElementsByTagName("game")[0]
game.appendChild(this.bubble)
}
popBubble() {
console.log("Plop!")
this.bubble.remove()
}
// Random Position
randomPos() {
let rndX = Math.random() * (window.innerWidth - this.bubble.clientWidth)
let rndY = Math.random() * (window.innerHeight - this.bubble.clientHeight)
this.bubble.style.transform = `translate(${rndX}px, ${rndY}px)`
}
}
|
b50e740c202cc9af6db0d653829483338bbd7005
|
TypeScript
|
wsz7777/kh-tool
|
/src/base/FileToBase64.ts
| 3.21875
| 3
|
/**
* 把文件读取成 base64 格式
* @param file 文件对象
*/
export function FileToBase64(file: File): Promise<string | ArrayBuffer | null> {
const reading = new FileReader();
return new Promise((resolve, reject) => {
reading.onload = (event: ProgressEvent<FileReader>) =>
resolve(event?.target?.result || null);
reading.onerror = () => reject(new Error("文件读取失败"));
reading.readAsDataURL(file);
});
}
|
2bf520b23af09e0240945db2530382d27ef7289a
|
TypeScript
|
gabliam/gabliam
|
/packages/web/graphql-core/__tests__/fixtures/resolvers/hero-resolver.ts
| 2.671875
| 3
|
import { GabResolver } from '@gabliam/graphql-core';
import {
Arg,
Mutation,
Publisher,
PubSub,
Query,
Root,
Subscription,
} from 'type-graphql';
import { Hero } from '../entities/hero';
import { Paginate } from './array-util';
import { HeroInput } from './types/hero-input';
import { PaginatedHero } from './types/paginated-hero';
@GabResolver((of) => Hero)
export class HeroResolver {
public heroRepository: Hero[] = [
{ id: 1, name: 'spiderman', power: 'spider', amountPeopleSaved: 10 },
{
id: 2,
name: 'Wolverine',
power: 'Superhuman senses',
amountPeopleSaved: 100,
},
];
private nextId = this.heroRepository.length + 2;
@Mutation((returns) => Hero)
async submitHero(
@PubSub('heroAdded') publish: Publisher<Hero>,
@Arg('heroInput') heroInput: HeroInput,
) {
const hero: Hero = {
// eslint-disable-next-line no-plusplus
id: this.nextId++,
...heroInput,
};
this.heroRepository.push(hero);
await publish(hero);
return hero;
}
@Query((returns) => [Hero])
async heroes() {
const heroes = this.heroRepository;
if (heroes.length > 0) {
return heroes;
}
return [];
}
@Subscription({ topics: 'heroAdded' })
heroAdded(@Root() hero: Hero): Hero {
return hero;
}
@Query((returns) => PaginatedHero)
async getPageOfHeroes(
@Arg('sortField', (type) => String, { nullable: true })
sortField: keyof Hero | undefined,
@Arg('sortOrder', (type) => String, { nullable: true })
sortOrder: 'ASC' | 'DESC' | undefined,
@Arg('page', { defaultValue: 0 }) page: number,
@Arg('perPage', { defaultValue: 10 }) perPage: number,
): Promise<PaginatedHero> {
if (page < 0) {
page = 0;
}
if (perPage < 1) {
perPage = 1;
}
const start = (page + 1) * perPage;
const end = start + perPage - 1;
const items = new Paginate(this.heroRepository)
.setOffset(start)
.setLimit(end - start)
.get();
return {
items,
totalCount: items.length,
};
}
}
|
c17735ff57ed7dacdce76dbffdc226b439ae8145
|
TypeScript
|
kscarrot/planting
|
/src/util/randomArray.test.ts
| 2.65625
| 3
|
import randomArray from './randomArray'
test('should be empty', () => {
expect(randomArray(-1)).toStrictEqual([])
})
test('should be interger', () => {
expect(randomArray(3.5).length).toBe(3)
})
test('normal case', () => {
expect(randomArray(10).length).toBe(10)
})
|
268ff33fefc6f427ac1afceb930130274b34f10a
|
TypeScript
|
KokoDoko/level-editor
|
/dev/domobject.ts
| 2.953125
| 3
|
class DOMObject {
public x : number;
public y : number;
public width : number;
public height : number;
public scale : number;
public tag : string;
protected div: HTMLElement;
constructor(x: number, y: number, tag: string) {
this.x = x;
this.y = y;
this.scale = 1;
this.tag = tag;
this.div = document.createElement(tag);
document.body.appendChild(this.div);
this.width = this.div.offsetWidth;
this.height = this.div.offsetHeight;
this.draw();
}
public update() : void {
}
public draw(): void {
this.div.style.transform = `translate(${this.x}px, ${this.y}px) scale(${this.scale})`;
}
}
|
82ec33f777e0dfd27617347fea99e45f954428bb
|
TypeScript
|
zelderus/budget.ts
|
/src/scripts/models/Accounts.ts
| 2.71875
| 3
|
import FormValidator from './FormValidator';
import IconData from './../datas/IconData';
namespace Accounts {
/**
* Счет.
*/
export class AccountEntity implements IClientObjectResponse {
id: string;
title: string;
order: number;
sum: number;
currencyId: string;
isCredit: boolean;
creditLimit: number;
iconId: string;
isDefault: boolean;
constructor () {
this.id = null;
this.isCredit = false;
this.creditLimit = 0;
this.currencyId = null;
this.iconId = null;
this.isDefault = false;
}
fromJson (j: any): void {
this.id = j.id;
this.title = j.title;
this.order = j.order;
this.sum = j.sum;
this.currencyId = j.currencyId;
this.isCredit = j.isCredit;
this.creditLimit = j.creditLimit;
this.iconId = j.iconId;
this.isDefault = j.isDefault;
}
toJson(): any {
let json = {
id: this.id,
title: this.title,
order: this.order,
sum: this.sum,
currencyId: this.currencyId,
isCredit: this.isCredit,
creditLimit: this.creditLimit,
iconId: this.iconId,
isDefault: this.isDefault
};
return json;
}
private _clonig(toNew: boolean = true, from: AccountEntity = null):AccountEntity {
let objTo = toNew ? new AccountEntity() : this;
let objFrom = from == null ? this : from;
//objTo = Object.create(objFrom);
objTo.id = objFrom.id;
objTo.title = objFrom.title;
objTo.order = objFrom.order;
objTo.sum = objFrom.sum;
objTo.currencyId = objFrom.currencyId;
objTo.isCredit = objFrom.isCredit;
objTo.creditLimit = objFrom.creditLimit;
objTo.iconId = objFrom.iconId;
objTo.isDefault = objFrom.isDefault;
return objTo;
}
clone(): AccountEntity {
return this._clonig(true, null);
}
fill(from: AccountEntity): void {
this._clonig(false, from);
}
}
/**
* Ключи ошибок валидации.
*/
export enum AccountFormValidationKeys {
Title = 1,
Currency = 2,
Sum = 3,
CreditLimit = 4
}
/**
* Валидация формы счета.
*/
export class AccountFormValidation extends FormValidator.Validator<AccountEntity> {
constructor() {
super();
}
public validate(entity: AccountEntity): void {
this.clearErrors();
this.validateTitle(entity);
this.validateCurrency(entity);
// TODO:
}
public validateTitle(entity: AccountEntity, withDeleteError: boolean = false): void {
if (withDeleteError) this.deleteError(AccountFormValidationKeys.Title);
this.errStringIsNullOrEmpty(entity.title, AccountFormValidationKeys.Title, "введите название");
}
public validateCurrency(entity: AccountEntity, withDeleteError: boolean = false): void {
if (withDeleteError) this.deleteError(AccountFormValidationKeys.Currency);
this.errIsNull(entity.currencyId, AccountFormValidationKeys.Currency, "укажите валюту");
}
}
}
export default Accounts;
|
544ac138b366db359bcc045adb0f90ecbde6b908
|
TypeScript
|
GuoBinyong/json-tls
|
/src/tools.ts
| 3.875
| 4
|
/**
* 安全地解析字符串,不会抛出错误,返回一个表示解析结果的信息对象
* @param text : string 必需, 一个有效的 JSON 字符串。
* @param reviver ?: function 可选,一个转换结果的函数, 将为对象的每个成员调用此函数。
* @returns {
* parsed: boolean, 表示是否成功解析
* result: string | JSONObject 最终解析的结果,如果成功解析,则该值为解析后的JSON对象,如果未成功解析,则该值为原字符串 text
* } 解析的结果;
*/
export function safelyParse(text: string, reviver?: (this: any, key: string, value: any) => any): { parsed: boolean, result: string | any } {
const parseInfo = {
parsed: true,
result: text
};
try {
parseInfo.result = JSON.parse(text, reviver);
} catch (e) {
parseInfo.parsed = false;
}
return parseInfo;
}
/**
* 将目标深度序列化成JSON字符串;即将 target 及 target 的中的所有对象属性单独序列化成 JSON 字符串;
* 我称这样的 JSON 字符串为 深度 JSON 字符串,英文为 DeepJSON;
* @param target : any 将要序列化成 一个JSON 字符串的值。
* @param replacer ? : (key,vlaue)=>vlaue | Array 如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中;如果该参数为null或者未提供,则对象所有的属性都会被序列化;关于该参数更详细的解释和示例,请参考使用原生的 JSON 对象一文。
* @param space ? 指定缩进用的空白字符串,用于美化输出(pretty-print);如果参数是个数字,它代表有多少的空格;上限为10。该值若小于1,则意味着没有空格;如果该参数为字符串(字符串的前十个字母),该字符串将被作为空格;如果该参数没有提供(或者为null)将没有空格。
* @returns string 一个表示给定值的经过深度序化化后的JSON字符串,即 深度 JSON 字符串。
*
* 注意:
* 深度 JSON 字符串 只能通过 `deepParse()` 才还完全解析,如果用 `JSON.parse()` 来解析,则只能解析出顶层对象,顶层对象的那些值是对象类型的成员还是 深度 JSON 字符串
*/
type ReplacerFun = (this: any, key: string, value: any) => any;
type ReplacerArr = (number | string)[];
export function deepStringify(target: any, replacer?: ReplacerArr | ReplacerFun | null , space?: string | number): string{
const newTarget = Object.keys(target).reduce((total:any,key)=>{
let prop = target[key];
if (typeof prop == "object"){
prop = deepStringify(prop,replacer , space);
}
total[key] = prop;
return total;
},{});
// @ts-ignore
return JSON.stringify(newTarget,replacer , space)
}
/**
* 深度解析,专门用于解析 深度 JSON 字符串 DeepJSON,即: deepStringify() 的逆运算
* @param text 深度 JSON 字符串
* @param reviver 同 JSON.parse() 的 reviver
* @returns any
*/
export function deepParse(text: string, reviver?: (this: any, key: string, value: any) => any): any{
const result = correctParse(text, reviver);
if (typeof result == "object"){
Object.keys(result).forEach((key)=> {
let prop = result[key];
prop = deepParse(prop,reviver);
result[key] = prop;
});
}
return result;
}
/**
* 判断 text 是否是有效的JSON字符串
* @returns boolean
*/
export function isJSONString(text: string): boolean {
try {
var parsed = JSON.parse(text);
var isJSON = parsed !== text;
} catch (e) {
isJSON = false;
}
return isJSON;
}
/**
* correctParse(text,reviver)
* 正确地解析,即:如果 text 是有效的 JSON 字符串,则解析它并返回解析后的结果,否则,返回原来的text
* @param text ?: string 被解析的字符串
* @returns any
*/
export function correctParse(text?: string, reviver?: (this: any, key: string, value: any) => any): any {
try {
var parsed = JSON.parse(text as string, reviver);
var isJSON = parsed !== text;
} catch (e) {
isJSON = false;
}
if (!isJSON){
parsed = text;
}
return parsed;
}
|
445ceaa9886722c3b62cca6433912acb5b08f8be
|
TypeScript
|
pardhuphanikumar/Typescript
|
/TypeScript-example1/unions.ts
| 3.328125
| 3
|
interface IPizza {
foodType: 'pizza',
toppings: string[],
crust: string
}
interface Isandwich {
foodType: 'sandwich',
toppings: string[],
bread: string,
}
type Food = Isandwich | IPizza
const myFood: Isandwich = {
bread: 'oeu',
foodType: 'sandwich',
toppings: ['qee', 'a']
}
const myFood2: IPizza = {
crust: 'foo',
foodType: 'pizza',
toppings: ['qee', 'a']
}
function eatFood(food: Food) {
if (food.foodType === 'pizza') {
console.log(food);
} else {
console.log(food);
food.bread//auto suggest their model instareface
}
}
eatFood(myFood)
|
3cea66e544735bff7fbc121239cab45de089a1cf
|
TypeScript
|
banaanihillo/lut_fullstack
|
/oeypoedalxr.angular/src/app/product-information/product-information.component.ts
| 2.5625
| 3
|
import {
Component,
OnInit
} from '@angular/core'
import {ActivatedRoute} from "@angular/router"
import {products} from "../products"
import {ShoppingCartService} from "../shopping-cart.service"
@Component({
selector: 'app-product-information',
templateUrl: './product-information.component.html',
styleUrls: ['./product-information.component.css']
})
export class ProductInformationComponent implements OnInit {
product
//nothing else? what a weird syntax
constructor(
private route: ActivatedRoute,
private shoppingCartService: ShoppingCartService
//capitalized? or not? is that the same thing or
) {
//and this is empty too? alright
}
//and this intentionally has the same name as the service method?
addToCart(product) {
this.shoppingCartService.addToCart(product)
console.log(`Added ${product.name} into the cart.`)
}
ngOnInit() {
const productRouteIdentificator = this.route.snapshot.paramMap
.get("productid")
this.product = products.find(product => {
return (product.id === productRouteIdentificator)
})
}
}
|
ab754314e5535ceae1063bfceb96c5c51cbee96e
|
TypeScript
|
c2cn/san-devtools
|
/packages/shared/src/Bridge.ts
| 2.953125
| 3
|
import EventEmitter from './EventEmitter';
import {Message} from '../types';
const BATCH_DURATION = 100;
interface Wall {
listen: (fn: Function) => void;
send: (data: any) => void;
}
export default class Bridge extends EventEmitter {
wall: Wall;
_batchingQueue: any[] = [];
_sendingQueue: any[] = [];
_receivingQueue: any[] = [];
_sending = false;
_time: number = 0;
_timer!: any;
constructor(wall: Wall) {
super();
this.wall = wall;
wall.listen((messages: Message | Message[]) => {
if (Array.isArray(messages)) {
messages.forEach(message => this._emit(message));
}
else {
this._emit(messages);
}
});
}
/**
* Send an event.
*
* @param {String} event
* @param {*} payload
*/
send(event: string, payload: any) {
if (Array.isArray(payload)) {
const lastIndex = payload.length - 1;
payload.forEach((chunk, index) => {
this._send({
event,
chunk: chunk,
isLast: index === lastIndex
});
});
this._flush();
}
else if (this._time === 0) {
this._send([{event, payload}]);
this._time = Date.now();
}
else {
this._batchingQueue.push({
event,
payload
});
const now = Date.now();
if (now - this._time > BATCH_DURATION) {
this._flush();
}
else {
this._timer = setTimeout(() => this._flush(), BATCH_DURATION);
}
}
}
/**
* Log a message to the devtools background page.
*
* @param {String} message
*/
log(message: string) {
this.send('log', message);
}
_flush() {
if (this._batchingQueue.length) {
this._send(this._batchingQueue);
}
clearTimeout(this._timer);
this._batchingQueue.length = 0;
this._time = 0;
}
_emit(message: Message) {
if (typeof message === 'string') {
this.emit(message);
}
else if (message.chunk) {
this._receivingQueue.push(message.chunk);
if (message.isLast) {
this.emit(message.event, this._receivingQueue);
this._receivingQueue.length = 0;
}
}
else {
this.emit(message.event, message.payload);
}
}
_send(messages: Message | Message[]) {
this._sendingQueue.push(messages);
this._nextSend();
}
_nextSend() {
if (!this._sendingQueue.length || this._sending) {
return;
}
this._sending = true;
const messages = this._sendingQueue.shift();
try {
this.wall.send(messages);
}
catch (err) {
if (err.message === 'Message length exceeded maximum allowed length.') {
this._sendingQueue.splice(
0,
0,
messages.map((message: any) => [message])
);
}
}
this._sending = false;
requestAnimationFrame(() => this._nextSend());
}
}
|
622dddad6df0410b9d8e860471e007c62cf3d84f
|
TypeScript
|
ClemWiz/Error-pattern-NodeJS
|
/ctrl.ts
| 2.96875
| 3
|
import { Request, Response } from "express";
import { getUser} from "./logic";
import ApiError, { ErrorLevel } from "./CustomError";
export async function doSomethingWithUser(req: Request, res: Response): Promise<void> {
const userId = checkUserId(req.params.id);
const user = await getUser(userId);
res.status(200).json(user);
}
export async function userDoSomething(req: Request, res: Response): Promise<void> {
const userId = checkUserId(req.params.id);
const user = await getUser(userId);
const doable = req.params.doable;
switch (doable) {
case "illegal":
throw new ApiError(403, "Illegal action", "ILLEGAL_ACTION", ErrorLevel.Warning, { user, type: "userAction", context: { do: doable }});
case "error":
throw new ApiError(500, "Normal error", "INTERNAL_ERROR", ErrorLevel.Error, { type: "errorLevel", context: { userId: req.params.id }});
case "fatal":
throw new ApiError(500, "Fatal error", "INTERNAL_ERROR", ErrorLevel.Fatal, { type: "errorLevel", context: { userId: req.params.id }});
default:
break;
}
res.status(200).json({ ...user, do: doable });
}
function checkUserId(userId: string): number {
const parsedId = parseInt(userId, 10);
if (isNaN(parsedId)) {
throw new ApiError(400, "Invalid user ID", "INVALID_USER_ID", ErrorLevel.Warning, { type: "User", context: { userId }});
}
else return parsedId;
}
|
944f5101bc0afe828e86d1f5dd457a4ca74d42d3
|
TypeScript
|
wavevision/class-name
|
/src/types.ts
| 2.859375
| 3
|
import { USE_VALUE } from './constants';
export type Props = Record<string, unknown>;
export type State = Props;
export type Parameters<P = Props, S = State> = { props: P; state: S };
export type Modifiers = Array<boolean | string | null | undefined>;
export type ModifierFunction<P = Props, S = State> = (
parameters: Parameters<P, S>,
) => unknown;
export type ModifiersCallbackResult<P = Props, S = State> = Record<
keyof P | keyof S | string,
boolean | typeof USE_VALUE | ModifierFunction<P, S>
>;
export type ModifiersCallback<P, S> = (
parameters: Parameters<P, S>,
) => ModifiersCallbackResult<P, S> | void;
export interface ClassNameFormatter<P = Props, S = State> {
readonly baseClass: string;
readonly block: (...modifiers: Modifiers) => string;
readonly compose: (...classNames: string[]) => string;
readonly create: (
newClass: string,
block?: boolean,
excludeModifiers?: boolean,
) => ClassNameFormatter<P, S>;
readonly element: (className: string, ...modifiers: Modifiers) => string;
readonly extra: (className: string, prefix?: string) => string;
}
|
a9dcf8ef76c7ba4889a7c12bae8f1e407b1f4bde
|
TypeScript
|
andymikulski/ai-starter
|
/src/ai/utils/WaitMillisecondsAction.ts
| 2.890625
| 3
|
import { Action, BehaviorStatus } from "../base/BehaviorTree";
export class WaitMillisecondsAction extends Action {
constructor(private waitForMS: number | (() => number)) {
super();
}
private waitThreshold: number;
private startTime: number;
onInitialize() {
this.startTime = Date.now();
this.waitThreshold =
typeof this.waitForMS === "function" ? this.waitForMS() : this.waitForMS;
}
update() {
const now = Date.now();
if (now - this.startTime < this.waitThreshold) {
return BehaviorStatus.RUNNING;
}
return BehaviorStatus.SUCCESS;
}
}
|
efbb7a4f1c70cecf69083ecb5eef374cab092c54
|
TypeScript
|
Renanmacedo/dojo-dotz
|
/src/app/literal/index.ts
| 3.171875
| 3
|
// qualquer string
export function printAnySize(size: string) {}
// aceita somente os tipos informados
//type LiteralTypes = "xs" | "md" | "lg" | "xl";
export function printLiteralSize(size: "xs" | "md" | "lg" | "xl") {}
|
0c0899f121e0c034528275673550c5acfa178af2
|
TypeScript
|
jurajtrappl/Desmond
|
/data_api/src/core/services/DateTime/IDateTimeService.ts
| 3.125
| 3
|
import { MilitaryTime } from 'src/core/values/MilitaryTime'
export interface IDateTimeService {
/**
* Returns the given date time as a date string in the format .
* @param dateTime date time to format.
*/
formatDate(dateTime: string): string
/**
* Returns the given date time as a date time string in the format .
* @param dateTime date time to format.
*/
formatDateTime(dateTime: string): string
/**
* Returns the given date time as a time string in the format .
* @param dateTime date time to format.
*/
formatTime(dateTime: string): string
/**
* Adds the given hours and minutes to the given date time.
* @param dateTime date time to add hours and minutes to.
* @param time hours and minutes to add.
*/
update(dateTime: string, time: MilitaryTime): string
}
|
1bc2d13d439eb34111e221ba64412453f716347b
|
TypeScript
|
pedropaiva1/canopus-backend
|
/src/carousels/carousels.service.ts
| 2.59375
| 3
|
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UserEntity } from 'src/users/entities/user.entity';
import { Repository } from 'typeorm';
import { CreateCarouselDto } from './dto/create-carousel.dto';
import { UpdateCarouselDto } from './dto/update-carousel.dto';
import { CarouselEntity } from './entities/carousel.entity';
@Injectable()
export class CarouselsService {
constructor(
@InjectRepository(CarouselEntity)
private readonly carouselRepository: Repository<CarouselEntity>,
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
) {}
async create(userId: string, createCarouselDto: CreateCarouselDto) {
const { title } = createCarouselDto;
const carouselExists = await this.carouselRepository.findOne({ title: title });
if (carouselExists) {
throw new BadRequestException(
`Carousel with title ${title} already exists`,
);
}
const user = await this.userRepository.findOne({ where: { id: userId } });
if (!user) {
throw new NotFoundException(`User with id ${userId} not found`);
}
const carousel = await this.carouselRepository.create({
title,
author: user,
});
await this.carouselRepository.save(carousel);
return carousel
}
async findAll() {
const carousels = this.carouselRepository.find();
if (!carousels) {
return { error: 'Users not found' };
}
return carousels;
}
async findOneOrFail(id: number) {
try {
return await this.carouselRepository.findOneOrFail(id);
} catch (error) {
throw new NotFoundException(error.message);
}
}
async update(id: number, updateCarouselDto: UpdateCarouselDto, userId: string) {
const carousel = await this.findOneOrFail(id);
if (!carousel) {
throw new NotFoundException(`Carousel with ${id} not found`);
}
if(carousel.author.id !== userId){
throw new BadRequestException(`Operation not allowed for User with id ${userId}`)
}
this.carouselRepository.merge(carousel, updateCarouselDto);
return await this.carouselRepository.save(carousel);
}
async remove(id: number, userId: string) {
console.log(id);
const carouselExists = await this.carouselRepository.findOne(id);
if (!carouselExists) {
throw new NotFoundException(`carousel with ${id} not found`);
}
if(carouselExists.author.id !== userId){
throw new BadRequestException(`Operation not allowed for User with id ${userId}`)
}
await this.carouselRepository.softDelete(id);
}
}
|
59f331f740ea0049234f2403321561ffe594b170
|
TypeScript
|
ilanddev/javascript-sdk
|
/src/sdk/model/vm/__json__/vm-power-operation-type.ts
| 2.765625
| 3
|
/**
* Enumeration of the available power operations for a VM.
*/
export type VmPowerOperation = 'poweron' | 'poweroff' | 'suspend' | 'shutdown' | 'reset' | 'reboot';
|
07e15e875468b48975dfee957e55ac2ea63b5fd1
|
TypeScript
|
andyinthemachine/real-eyes
|
/src/constants.ts
| 2.5625
| 3
|
interface iInfo {
name: string,
version: string,
routes: Array<{
controller: string;
description: string;
method: string;
uri: string;
version: string;
body?: any,
}>,
}
const INFO: iInfo = {
name: 'REAL EYES API',
version: '0.0.1',
routes: [
{
uri: 'api/info',
controller: 'getInfo',
description: 'This is a simple Api endpoint for fetching data about this project',
method: 'GET',
version: '1'
},
{
uri: 'api/encode',
controller: 'encodeAsset',
description: 'Downloads an asset and encodes it to a specified format',
method: 'POST',
version: '1',
body: {
url: 'Downloadbale asset url',
videoBitrate: 'Output asset bitrate value',
videoCodec: 'Output asset codec value or default=aac'
}
},
{
uri: 'api/metadata?asset=<downlodable-asset-url>',
controller: 'getMetadata',
description: 'Fetch metadata for a downloadable asset',
method: 'GET',
version: '1'
},
{
uri: 'api/outputhls',
controller: 'outputHls',
description: 'Output hls assets for a downloadable file ',
method: 'GET',
version: '1'
},
]
};
export {
INFO,
}
|
81ec65fa08b9f344db469d6bb8f7919e448ac0e8
|
TypeScript
|
smartshare-labs/react-boilerplate
|
/src/utils/Greeting.ts
| 3.046875
| 3
|
import moment from "moment-timezone";
export const getGreetingTime = () => {
const currentTime = moment();
if (!currentTime || !currentTime.isValid()) {
return "Hello";
}
const splitAfternoon = 12; // 24hr time to split the afternoon
const splitEvening = 17; // 24hr time to split the evening
const currentHour = parseFloat(currentTime.format("HH"));
if (currentHour >= splitAfternoon && currentHour <= splitEvening) {
// Between 12 PM and 5PM
return "Good Afternoon";
} else if (currentHour >= splitEvening) {
// Between 5PM and Midnight
return "Good Evening";
}
// Between dawn and noon
return "Good Morning";
};
|
ebb65745917fec7413016400eb4c46bd9012f8aa
|
TypeScript
|
lol-matchmaker/riot-hackathon
|
/src/renderer/ws_messages.ts
| 2.890625
| 3
|
/** Server -> Client: Not authenticated. */
export interface ChallengeMessage {
type: 'challenge';
/** Challenge token to be set as the summoner's verification string. */
token: string;
}
/** Client -> Server: Ready to be authenticated. */
export interface AuthMessage {
type: 'auth';
accountId: string;
summonerId: string;
}
/** Server -> Client: Authenticated. Make requests. */
export interface WelcomeMessage {
type: 'ready';
}
/** Client -> Server: Player is ready to get matched. Do magic. */
export interface RequestQueueMessage {
type: 'plsqueue';
data: JSON;
}
/** Server -> Client: Player is in queue. Ask player to wait. */
export interface QueuedMessage {
type: 'queued';
}
/** Client -> Server: Player is ready to get matched. Do magic. */
export interface CancelQueueMessage {
type: 'noqueue';
}
/** Server -> Client: Player is no longer in the queue for some reason. */
export interface DequeuedMessage {
type: 'dequeued';
}
/** A role in the Server -> Client matchmaking packet. */
export type MatchedMessagePlayerRole =
'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
/** Per-player information in the Server -> Client matchmaking packet. */
export interface MatchedMessagePlayerInfo {
account_id: string;
summoner_id: string;
summoner_name: string;
role: MatchedMessagePlayerRole;
}
/** Server -> Client: Player is in match. */
export interface MatchedMessage {
type: 'matched';
players: MatchedMessagePlayerInfo[];
}
/** All messages. */
export type WsMessage =
ChallengeMessage | AuthMessage | WelcomeMessage | RequestQueueMessage |
QueuedMessage | CancelQueueMessage | DequeuedMessage | MatchedMessage;
|
8589bd63ba757e6a1f9ade4e19b9d4fbb8bd5c14
|
TypeScript
|
camelCaseDave/xrm-mock
|
/test/page/step/step.mock.test.ts
| 2.640625
| 3
|
import { StepMock } from "../../../src/xrm-mock/processflow/step/step.mock";
describe("Xrm.ProcessFlow.Step Mock", () => {
let step: StepMock;
beforeEach(() => {
step = new StepMock("First Name", "firstname", true);
});
it("should instantiate", () => {
expect(step).toBeDefined();
});
it("should be called First Name", () => {
expect(step.getName()).toBe("First Name");
});
it("should have an attribute of firstname", () => {
expect(step.getAttribute()).toBe("firstname");
});
it("should be required", () => {
expect(step.isRequired()).toBe(true);
});
});
|
6e26b83c7ef76ff496454e0ba7b3cb8d2794fd94
|
TypeScript
|
greghart/climbing-app
|
/src/typescript/redux/ducks/util/scopeObject.ts
| 3.28125
| 3
|
import * as ReduxActions from 'redux-actions';
/**
* Compose an action object to be scoped
*
* @param {object} - An action object to add scope to
* @param {array} - Array of scopes to add
* @returns {function} a new thunk which wraps dispatch in given scope
*/
export default <Payload>(
action: ReduxActions.Action<Payload>,
scope: string,
): ReduxActions.Action<Payload> & { scope: string } => {
return {
...action,
// Concat existing scope if any
scope: ((action as any).scope || '') + scope,
};
};
|
d7bd2fbfcfbe654d9d89a454bbecee25f9e7b9d0
|
TypeScript
|
Zilborg/payload
|
/src/admin/api.ts
| 2.671875
| 3
|
import qs from 'qs';
type GetOptions = RequestInit & {
params?: Record<string, unknown>
}
export const requests = {
get: (url: string, options: GetOptions = { headers: {} }): Promise<Response> => {
let query = '';
if (options.params) {
query = qs.stringify(options.params, { addQueryPrefix: true });
}
return fetch(`${url}${query}`, {
credentials: 'include',
...options,
});
},
post: (url: string, options: RequestInit = { headers: {} }): Promise<Response> => {
const headers = options && options.headers ? { ...options.headers } : {};
const formattedOptions: RequestInit = {
...options,
method: 'post',
credentials: 'include',
headers: {
...headers,
},
};
return fetch(`${url}`, formattedOptions);
},
put: (url: string, options: RequestInit = { headers: {} }): Promise<Response> => {
const headers = options && options.headers ? { ...options.headers } : {};
const formattedOptions: RequestInit = {
...options,
method: 'put',
credentials: 'include',
headers: {
...headers,
},
};
return fetch(url, formattedOptions);
},
patch: (url: string, options: RequestInit = { headers: {} }): Promise<Response> => {
const headers = options && options.headers ? { ...options.headers } : {};
const formattedOptions: RequestInit = {
...options,
method: 'PATCH',
credentials: 'include',
headers: {
...headers,
},
};
return fetch(url, formattedOptions);
},
delete: (url: string, options: RequestInit = { headers: {} }): Promise<Response> => {
const headers = options && options.headers ? { ...options.headers } : {};
const formattedOptions: RequestInit = {
...options,
method: 'delete',
credentials: 'include',
headers: {
...headers,
},
};
return fetch(url, formattedOptions);
},
};
|
1d0f1b6688d4d4d21be59ed5e5b0138c5d188958
|
TypeScript
|
NikaBuligini/react-nb-hooks
|
/src/utils/useFocus.ts
| 2.796875
| 3
|
import { useState } from 'react';
type Handlers = {
onFocus: () => void;
onBlur: () => void;
};
export function useFocus(): [boolean, Handlers] {
const [isFocused, setFocus] = useState(false);
const bind = {
onFocus: () => setFocus(true),
onBlur: () => setFocus(false),
};
return [isFocused, bind];
}
|
aeb53539a1d3d79dafd3eead7d7efd1752e9c24e
|
TypeScript
|
niuniu384665340/bxjs-base
|
/framework/plugins/database/index.ts
| 2.671875
| 3
|
import {Entity, BaseEntity, PrimaryColumn, BeforeInsert, CreateDateColumn, Index, UpdateDateColumn} from '@bxjs/typeorm'
const shortid = require('shortid')
export * from '@bxjs/typeorm'
@Entity()
export abstract class XBaseEntity extends BaseEntity {
// 数据库自增主键存在分布式扩容以及安全隐患在阿里内部不适合使用,改进方案如下:
// 阿里内部安全规范要求id不可预测不可枚举,不能使用int或bigint自增主键定义id。
// 本项目适合将id使用shortid满足要求并且无需修改业务逻辑(并支持分布式id生成算法适合以后分库分表算法实现)
@PrimaryColumn({type: 'char', length: '16'}) // 优化为char[16]固定长度便于主键索引查询性能优化(存储空间一点浪费不是问题)
id: string
@BeforeInsert()
protected generateID() {
this.id = shortid.generate()
// 严格验证shortid的生成策略是否正确,如果出错第一时间报警排查问题。
if (!(this.id && shortid.isValid(this.id) &&
this.id.length >= 7 && this.id.length <= 14)) {
xwarn({id: this.id})
xassert(false, ERR$UNKNOWN)
}
}
// 增加索引解决id随机后无法排序问题
@Index()
@CreateDateColumn()
created_at: Date
@UpdateDateColumn()
updated_at: Date
}
|
727b1ec6ca96444409a82cbb9249e944e8e53f4e
|
TypeScript
|
soinanataliya/some-components
|
/src/components/interval/_types.ts
| 2.546875
| 3
|
export type IntervalsType = {
title: string;
value: number;
isSeen: boolean;
};
|
a854a4b942f9a1f23681e224374daf1b1cd2e8cc
|
TypeScript
|
alvarorahul/TypeDocs
|
/samples/sample.d.ts
| 3.546875
| 4
|
declare module "E" {
export = Main;
module Main {
/**
* Defines an item.
*/
const item: string;
}
}
declare module "A/B/C" {
/**
* Test module documentation.
*/
module D {
}
/**
* Second test module documentation.
* More information about the module.
*/
module E {
}
}
declare module "A/B" {
export = Main;
module Main {
/**
* Defines an item.
*/
interface Item {
}
/**
* Defines some value.
*/
const SomeValue: string;
/**
* Defines some class.
*/
class SomeClass {
/**
* Creates an instance of some class.
*
* @param data Data for some class.
*/
constructor(data: any);
}
}
}
declare module TestModule {
/**
* Class that does this.
*/
class TestClass {
/**
* Creates a new instance of TestClass.
*
* @param paramA Parameter A.
* @param paramB Parameter B.
*/
constructor(paramA: string, paramB?: string);
/**
* Docs for sample method.
*
* @param a test.
* @returns The return value.
*/
public testMethod(a: number): number;
}
enum TestEnum {
None = 0,
First = 1,
}
interface TestInterface {
"interface-property": number;
}
export module Inner {
export const test: string;
export type foo = string;
}
}
declare module "OtherModule" {
import Impl = TestModule.Inner;
export = Impl;
}
declare module "OtherModule/InnerModule" {
class Foo {
public bar: string;
}
}
declare abstract class Animal {
}
declare class Class1 {
prop1: null;
prop2: undefined;
}
/**
* Documentation for test interface.
*/
declare interface AnInterface {
(): string;
(input: string): string;
count: number;
}
|
80873d6e355b7735667355a28b60a61bc5b1f6ab
|
TypeScript
|
iangregsondev/ts-proto
|
/integration/simple-long/simple-test.ts
| 2.71875
| 3
|
import { SimpleWithMap } from './simple';
describe('simple', () => {
it('can fromPartial maps', () => {
const s1 = SimpleWithMap.fromPartial({
intLookup: { 1: 2, 2: 1 },
longLookup: { '1': 2, '2': 1 },
});
expect(s1).toMatchInlineSnapshot(`
Object {
"intLookup": Object {
"1": 2,
"2": 1,
},
"longLookup": Object {
"1": Long {
"high": 0,
"low": 2,
"unsigned": false,
},
"2": Long {
"high": 0,
"low": 1,
"unsigned": false,
},
},
"nameLookup": Object {},
}
`);
});
it('can toJSON/fromJSON maps', () => {
const s1 = SimpleWithMap.fromPartial({
intLookup: { 1: 2, 2: 1 },
longLookup: { '1': 2, '2': 1 },
});
const json = SimpleWithMap.toJSON(s1);
expect(json).toMatchInlineSnapshot(`
Object {
"intLookup": Object {
"1": 2,
"2": 1,
},
"longLookup": Object {
"1": "2",
"2": "1",
},
"nameLookup": Object {},
}
`);
const s2 = SimpleWithMap.fromJSON(JSON.parse(JSON.stringify(json)));
expect(s2).toMatchInlineSnapshot(`
Object {
"intLookup": Object {
"1": 2,
"2": 1,
},
"longLookup": Object {
"1": Long {
"high": 0,
"low": 2,
"unsigned": false,
},
"2": Long {
"high": 0,
"low": 1,
"unsigned": false,
},
},
"nameLookup": Object {},
}
`);
});
});
|
93e3d45300e77384b38c609b51a366c2447f1972
|
TypeScript
|
simple5960/cache
|
/index.ts
| 2.5625
| 3
|
export function serviceWorker(swPath:string)
{
if ('serviceWorker' in navigator) {
window.addEventListener('load', function (event) {
navigator.serviceWorker.register(swPath, {
scope: '/'
})
.then(function (registeration) {
console.log('Service worker register success with scope ' + registeration.scope);
});
});
navigator.serviceWorker.oncontrollerchange = function (event) {
};
// 如果用户处于断网状态进入页面,用户可能无法感知内容是过期,需要提示用户断网了,并在重新连接后告诉用户
if (!window.navigator.onLine) {
window.addEventListener('online', function () {
});
}
}
}
export function cacheToLocalStorage(key:string,data:object)
{
localStorage.setItem(key,JSON.stringify(data))
}
export function getDataFromLocalStorage(key:string):JSON | Array<null>{
var data=localStorage.getItem(key);
if(data!==null){
//本地存储里面的数据字符串格式
return JSON.parse(data);
}
else{
return [];
}
}
export function cacheToSessionStorage(key:string,data:object)
{
sessionStorage.setItem(key,JSON.stringify(data))
}
export function getDataFromSessionStorage(key:string):JSON | Array<null>{
var data=sessionStorage.getItem(key);
if(data!==null){
//本地存储里面的数据字符串格式
return JSON.parse(data);
}
else{
return [];
}
}
|
d9814719fee813950fb8230ea4102e05dc0c29eb
|
TypeScript
|
naoki-sawada/github-release-watcher
|
/src/updateChecker.ts
| 2.8125
| 3
|
import axios from "axios";
interface UpdateCheckerOptions {
method?: string;
url: string;
headers?: any;
version: (data: any) => string | Promise<string>;
checker: (version: string) => boolean | Promise<boolean>;
notification: (version: string, subscribed: boolean) => void;
}
const updateChecker = async ({
method,
url,
headers,
version,
checker,
notification,
}: UpdateCheckerOptions): Promise<boolean> => {
if (!url || !checker || !version) {
throw new Error("`url`, `checker` or `version` param required."); // TODO: Fix
}
try {
const { data } = await axios({
method: method || "get",
url,
headers: headers || {
Accept: "application/vnd.github.v3+json",
},
});
const latest = await version(data);
const isUpdate = await checker(latest);
const subscribed = isUpdate === null;
if (subscribed || isUpdate) {
notification(latest, subscribed);
}
return isUpdate;
} catch (e) {
throw e;
}
};
export default updateChecker;
|
21a0cf6041ff9eec18964e4510092d88484987f7
|
TypeScript
|
julien-c/coreml-protobuf-parser
|
/lib/Log.ts
| 2.875
| 3
|
import * as colors from 'colors';
import * as util from 'util';
export const c = {
__log: (args: any[], opts: {
color?: colors.Color,
colors?: boolean,
} = {}) => {
const inspectOpts = (opts.colors !== undefined)
? { depth: 20, colors: opts.colors }
: { depth: 20, colors: true }
;
if (process.env.NO_COLOR) {
inspectOpts.colors = false;
}
const s = args.map(o => {
if (typeof o === 'string') {
return o;
} else {
return util.inspect(o, inspectOpts);
}
}).join(' ');
console.log(opts.color ? opts.color(s) : s);
},
log: (...args) => {
c.__log(args);
},
debug: (...args) => {
c.__log(args, { color: colors.gray, colors: false });
},
success: (...args) => {
c.__log(args, { color: colors.green });
},
error: (...args) => {
c.__log(args, { color: colors.red });
},
info: (...args) => {
c.__log(args, { color: colors.cyan });
},
introspect: (...args) => {
c.__log(args.map(a => [
a,
typeof a,
a.constructor.name,
]));
},
}
|
f0a47e907c25f225ff7171ad4acbcf8f2f52e3ce
|
TypeScript
|
AdinoWayne/VuMucDiThu
|
/code/999-available-captures-for-rook.ts
| 2.828125
| 3
|
function numRookCaptures(board: string[][]): number {
var r, c;
var row, col;
rook_search:
for (r = 0; r < 8; r++) {
for (c = 0; c < 8; c++) {
if (board[r][c] == 'R') {
row = r;
col = c;
break rook_search;
}
}
}
var captures = 0;
function oneCapture(rStart, cStart, rStep, cStep) {
for (r = rStart, c = cStart; ; r += rStep, c += cStep) {
if (!board[r] || !board[r][c]) {
return 0;
} else if (board[r][c] == 'p') {
return 1;
} else if (board[r][c] != '.') {
return 0;
}
}
}
captures += oneCapture(row-1, col, -1, 0);
captures += oneCapture(row+1, col, 1, 0);
captures += oneCapture(row, col-1, 0, -1);
captures += oneCapture(row, col+1, 0, 1);
return captures;
};
|
fa2494297b8695813f37a72ecadc2ab94039df68
|
TypeScript
|
isaquielfernandes/node-rest-api
|
/src/controllers/ForecastController.ts
| 2.53125
| 3
|
import { Request, Response } from "express";
import { getRepository } from "typeorm";
import { Forecast } from "../entity/Forecast";
import { ForecastService } from "../services/ForecastService";
export default class ForecastController {
public findAll = async (req: Request, res: Response): Promise<Response> => {
const results = await getRepository(Forecast).find({
relations: ["temp", "feels_like", "weather"],
});
return res.json(results);
};
public findById = async ( req: Request, res: Response): Promise<Response> => {
const results = await getRepository(Forecast).findOne(req.params.id, {
relations: ["temp", "feels_like", "weather"],
});
return res.json(results);
};
public create = async (req: Request, res: Response): Promise<Response> => {
const { dt, sunrise, sunset, temp, feels_like, pressure, humidity, weather, speed, deg, clouds, pop } = req.body;
const forecastService = new ForecastService();
const newForecast = await forecastService.insert({ dt, sunrise, sunset, temp, feels_like, pressure, humidity, weather, speed, deg, clouds, pop });
return res.status(201).json(newForecast);
};
}
|
24d1070f4631f9db27d701b71efd93a322e55f2d
|
TypeScript
|
DPiyumantha/Fast-track-training-with-Krish
|
/words/src/app/user-input/user-input.component.ts
| 2.609375
| 3
|
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-user-input',
templateUrl: './user-input.component.html',
styleUrls: ['./user-input.component.scss']
})
export class UserInputComponent implements OnInit {
regex=/[a-z]*[aeiou][a-z]*/gi
inputText: string = '';
result: {
words: string[],
error: boolean,
errorMessage: string
} = { words: [], error: false, errorMessage: '' }
@Output() clickEvent: EventEmitter<any> = new EventEmitter();
constructor() { }
ngOnInit(): void {
}
sortWordsWithVowels(): void {
this.result.words = [];
if (this.inputText.length < 1) {
this.result.errorMessage = "Please type some text";
this.result.error = true
}
else {
this.result.errorMessage = '';
this.result.error = false;
this.result.words = Array.from(new Set(this.inputText
.trim()
.toLowerCase()
.replace(/[^a-zA-Z\s\d]/g, '')
.split(" ")
.filter(word => word.match(this.regex))
.sort())
)
}
}
onClick() {
this.sortWordsWithVowels();
this.result.words.length<1?
this.clickEvent.emit({...this.result, error:true,errorMessage:"No words with vowels"}):
this.clickEvent.emit(this.result)
}
}
|
d22d56bcf5972fb163af5502fd0551e28cb1469c
|
TypeScript
|
dannius/rows-code
|
/src/app/pipes/closest-products.pipe.ts
| 2.640625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { IMileage } from '@lib/mileage';
@Pipe({
name: 'closestProducts',
pure: true,
})
export class ClosestProductsPipe implements PipeTransform {
public transform(products: IMileage[], estimate: number, count: number): any {
return [
...this.getLeftArray(products, estimate, count),
...this.getRightArray(products, estimate, count),
];
}
private getLeftArray(products: IMileage[], estimate: number, count: number) {
const leftProducts = products.filter(p => p.mileage < estimate);
if (count / 2 > leftProducts.length) {
return leftProducts;
}
return leftProducts.splice(leftProducts.length - count / 2, count / 2);
}
private getRightArray(products: IMileage[], estimate: number, count: number) {
const rightProducts = products.filter(p => p.mileage >= estimate);
if (count / 2 > rightProducts.length) {
return rightProducts;
}
return rightProducts.splice(0, count / 2);
}
}
|
ee5b8e3feda0fcaa8d3daf805a57f31027793fe5
|
TypeScript
|
ps-aux/deployers
|
/src/fs/dir/unused/listDir.test.ts
| 2.8125
| 3
|
import { listDir } from 'src/fs/dir/unused/listDir'
import { DirFileItem } from 'src/fs/types'
import { testDataDir } from 'src/_test'
const expectPath = (f: DirFileItem, end: string) => {
if (!f.absPath.startsWith('/')) {
throw new Error(`Path ${f.absPath} is not absolute`)
}
if (f.localPath.startsWith('/')) {
throw new Error(`Path ${f.localPath} is absolute`)
}
expect(f.localPath).toBe(end)
if (!f.absPath.endsWith(end))
throw new Error(`'${f.absPath}' does not end with '${end}'`)
}
it('works', () => {
const dir = testDataDir('listDir')
const r = listDir(dir)
expectPath(r[0], 'a.txt')
expectPath(r[1], 'd1/b.txt')
expectPath(r[2], 'd1/d2/c.txt')
})
|
d53191127f45105e2dd1e8072d36e46460aed113
|
TypeScript
|
CamielJalink/Advent-of-Code-2020
|
/day23/part2/src/game.ts
| 3.421875
| 3
|
import { Cup } from "./cup";
export class Game {
gameState: Map<number, Cup> = new Map();
pickedUpCups: Cup[] = [];
currentCup: Cup;
constructor(gameState: number[]){
const tempGameState: Cup[] = [];
this.currentCup = new Cup(gameState[0]);
tempGameState.push(this.currentCup);
for(let i = 1; i < gameState.length; i++){
const cup = new Cup(gameState[i]);
cup.prevCup = tempGameState[i - 1];
cup.prevCup.nextCup = cup;
tempGameState.push(cup);
}
tempGameState[0].prevCup = tempGameState[tempGameState.length-1];
tempGameState[tempGameState.length - 1].nextCup = tempGameState[0];
tempGameState.forEach((cup: Cup) => {
this.gameState.set(cup.name, cup);
})
}
playMove(): void{
// Pick up three cups and close the circle behind them
this.pickUpCups();
// Find the target cup
const target: Cup = this.findTarget();
// Insert picked up cups behind the target and fix their references
this.insertIntoGamestate(target);
// When the move is done, update the gameState.
this.currentCup = this.currentCup.nextCup;
}
pickUpCups(): void{
const cup1: Cup = this.currentCup.nextCup;
const cup2: Cup = cup1.nextCup;
const cup3: Cup = cup2.nextCup;
const cup4: Cup = cup3.nextCup;
this.pickedUpCups = [cup1, cup2, cup3];
this.currentCup.nextCup = cup4;
cup4.prevCup = this.currentCup;
}
findTarget(): Cup{
let targetName: number = this.currentCup.name - 1;
let stillSearching: boolean = true;
while (stillSearching) {
if (targetName === 0) {
targetName = 1000000;
}
let targetInPickedUp: boolean = false;
for(let i = 0; i < this.pickedUpCups.length; i++){
if(this.pickedUpCups[i].name === targetName){
targetInPickedUp = true;
}
}
if (targetInPickedUp) {
targetName = targetName - 1;
} else {
stillSearching = false;
}
}
let targetCup: Cup = new Cup(-1);
const target = this.gameState.get(targetName);
if(target !== undefined){
targetCup = target;
}
return targetCup;
}
insertIntoGamestate(targetCup: Cup): void{
const cup1: Cup = this.pickedUpCups[0];
const cup3: Cup = this.pickedUpCups[2];
cup3.nextCup = targetCup.nextCup;
targetCup.nextCup = cup1;
cup1.prevCup = targetCup;
targetCup.nextCup.prevCup = cup3;
}
findTwoCupsAfter1(): void{
const cup1 = this.gameState.get(1);
if(cup1 !== undefined){
const cup2: Cup = cup1.nextCup;
const cup3: Cup = cup2.nextCup;
console.log(cup2.name * cup3.name);
}
}
}
|
0aab10b8b15729f01fe5a11b3e47108f71659b69
|
TypeScript
|
taoqili/comlib-pc-normal
|
/src/datatable/editors/blocks/logic/logic_includes.ts
| 2.515625
| 3
|
const DataTpt = {
type: 'Array'
}
export default {
name: 'xg.logic_includes',
title: '包含',
data: DataTpt,
render(renderer, data) {
renderer.setStyle('logic_blocks')
renderer.setOutput(true, 'Boolean')
renderer.setInputsInline(true)
renderer.appendValueInput('judged').setCheck(['Array', 'String']).appendField('列表或文字')
renderer.appendValueInput('val').appendField('中包含')
},
to(type, block) {
if (type === 'js') {
const judged = Blockly.JavaScript.valueToCode(block, 'judged', Blockly.JavaScript.ORDER_NONE) || '[]'
const val = Blockly.JavaScript.valueToCode(block, 'val', Blockly.JavaScript.ORDER_NONE) || '[]'
return [`${judged}.includes(${val})`, Blockly.JavaScript.ORDER_ATOMIC]
}
}
}
|
80abea03c7b02566f3e0045df1f3b95e5bf91e7b
|
TypeScript
|
maranite/Keylab-Viper
|
/ts-stubs/ParameterBank.d.ts
| 3.265625
| 3
|
/** Defines a bank of parameters. */
interface ParameterBank {
/** Gets the number of slots that these remote controls have. */
getParameterCount(): number;
/** Returns the parameter at the given index within the bank.
* @param indexInBank
the parameter index within this bank. Must be in the range [0..getParameterCount()-1].
* @returns The requested parameter */
getParameter(indexInBank: number): Parameter;
/** Informs the application how to display the controls during the on screen notification.
@param type which kind of hardware control is used for this bank (knobs/encoders/sliders)
@param columns How wide this section is in terms of layout (4/8/9) */
setHardwareLayout(type: any|HardwareControlType, columns: 4 | 8 | 9): void;
}
|
523a998fb09615fccc33bdf6f131889ab19745cc
|
TypeScript
|
ChrystianSchutz/Omdb-Api-Search-TypeScript-Redux-Challange
|
/src/store/actions/itemActions.ts
| 2.734375
| 3
|
import { MovieListArray } from "../../types/";
export function fetchHasErrored(bool: boolean) {
return {
type: "ITEMS_HAS_ERRORED",
hasErrored: bool,
};
}
export function fetchLoading(bool: boolean) {
return {
type: "ITEMS_IS_LOADING",
isLoading: bool,
};
}
export function fetchSuccess(items: MovieListArray) {
return {
type: "ITEMS_FETCH_DATA_SUCCESS",
items,
};
}
export function fetchData(url: string) {
return (dispatch: Function) => {
dispatch(fetchLoading(true));
fetch(url)
.then((a) => a)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(fetchLoading(false));
return response.json();
})
.then((dara) => dara)
.then((items) => dispatch(fetchSuccess(items)))
.catch((error) => dispatch(fetchHasErrored(true)));
};
}
|
bb8012a565bf2e8274d867fd001c76dcef4ac179
|
TypeScript
|
VugarAhmadov/island.is
|
/libs/application/templates/family-matters/core/src/utils/index.ts
| 2.796875
| 3
|
import parse from 'date-fns/parse'
import format from 'date-fns/format'
import is from 'date-fns/locale/is'
import enGB from 'date-fns/locale/en-GB'
import sortBy from 'lodash/sortBy'
import { parsePhoneNumberFromString } from 'libphonenumber-js'
import kennitala from 'kennitala'
import { Address, Child, NationalRegistry, Person } from '../types'
export const formatSsn = (ssn: string) => {
return ssn.replace(/(\d{6})(\d+)/, '$1-$2')
}
export const formatAddress = (address: Address) => {
if (!address) {
return null
}
return `${address.streetName}, ${address.postalCode} ${address.city}`
}
export const getSelectedChildrenFromExternalData = (
children: Child[],
selectedChildren: string[],
): Child[] => {
return children.filter((child) => selectedChildren.includes(child.nationalId))
}
interface ChildrenResidenceInfo {
parentName: string
address: Address
nationalId: string
}
const extractParentInfo = ({
address,
fullName,
nationalId,
}: NationalRegistry | Person): ChildrenResidenceInfo => {
return {
nationalId,
address,
parentName: fullName,
}
}
export const childrenResidenceInfo = (
applicant: NationalRegistry,
selectedChildren: string[],
): {
current: ChildrenResidenceInfo
future: ChildrenResidenceInfo
} => {
const children = getSelectedChildrenFromExternalData(
applicant.children,
selectedChildren,
)
const parentB = children[0].otherParent
const childrenLiveWithApplicant = children.some(
(child) => child.livesWithApplicant,
)
return {
current: childrenLiveWithApplicant
? extractParentInfo(applicant)
: extractParentInfo(parentB),
future: childrenLiveWithApplicant
? extractParentInfo(parentB)
: extractParentInfo(applicant),
}
}
export const formatDate = ({
date,
formatter = 'PPP',
localeKey = 'is',
}: {
date: string
formatter?: string
localeKey?: string
}) => {
try {
const locale = localeKey === 'is' ? is : enGB
const parsedDate = parse(date, 'yyyy-MM-dd', new Date())
return format(parsedDate, formatter, { locale })
} catch {
return date
}
}
export const getOtherParentInformation = (
children: Child[],
selectedChildren: string[],
): Person => {
const selected = getSelectedChildrenFromExternalData(
children,
selectedChildren,
)
return selected?.[0]?.otherParent
}
export const formatPhoneNumber = (phoneNumber: string): string => {
const phone = parsePhoneNumberFromString(phoneNumber, 'IS')
return phone?.formatNational() || phoneNumber
}
export const sortChildrenByAge = (children: Child[]): Child[] => {
return sortBy(children, (child) => {
return kennitala.info(child.nationalId)?.birthday
})
}
|
66a32b8614feeb0450e43834270525585f5360bb
|
TypeScript
|
dsharma-learn/workspaces
|
/angular/Udemy_CompleteGuidetoAngular2/Learning-Angular-2.0-CodeFromClass/class-8_BasicRouting/dev/contacts/contact-list.component.ts
| 2.640625
| 3
|
import {Component} from "angular2/core";
import {OnInit} from "angular2/core";
import {ContactComponent} from "./contact.component";
import {ContactService} from "./contact.service";
import {Contact} from "./contact";
@Component({
selector: "contact-list",
templateUrl: "../dev/contacts/contact-list.component.html",
directives: [ContactComponent],
providers:[ContactService],
styleUrls:["../src/css/app.css"]
})
// Without Lifecycle hooks - call thru constructor
/*
export class ContactListComponent{
public contacts : Contact[];
public selectedContact = {};
public onNameClick(contact){
this.selectedContact = contact;
}
//info: if you want to pre-select first element from contact list then
// you can define constructor on this class and initialize defaults.
//this is same as
// private contactService : ContactService
// this.contactService = contactService;
constructor(private _contactService: ContactService){
this.getContacts();
}
// Call service now
getContacts(){
this._contactService.getContacts().then((contacts:Contact[])=>this.contacts = contacts);
}
}
*/
// With Lifecycle hooks
export class ContactListComponent implements OnInit{
public contacts : Contact[];
public selectedContact = {};
public onNameClick(contact){
this.selectedContact = contact;
}
//info: if you want to pre-select first element from contact list then
// you can define constructor on this class and initialize defaults.
//this is same as
// private contactService : ContactService
// this.contactService = contactService;
constructor(private _contactService: ContactService){
this.getContacts();
}
// Call service now
getContacts(){
this._contactService.getContacts().then((contacts:Contact[])=>this.contacts = contacts);
}
ngOnInit () :any {
this.getContacts();
}
}
|
89cc20ca04161c28e9173428edc64f76d8177c6c
|
TypeScript
|
mcorrigan89/mpls-openmic
|
/src/entity/artist.ts
| 2.5625
| 3
|
import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';
import { Timeslot } from './timeslot';
import { Template } from './template';
@Entity()
export class Artist extends Template {
@PrimaryGeneratedColumn('uuid')
public id: string;
@Column('text', { nullable: true })
public name: string;
@Column('text', { nullable: true })
public description: string;
@OneToMany(type => Timeslot, timeslot => timeslot.artist)
public timeslots: Array<Timeslot>;
}
|