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
|
|---|---|---|---|---|---|---|
27e57a8513af85e3996ec7cdcee71928fd58b009
|
TypeScript
|
bcgov/embc-ess
|
/pdf-service/src/api/middleware.ts
| 2.546875
| 3
|
import { Request, Response, NextFunction, Express } from 'express';
import bodyParser from 'body-parser';
import { MAX_PAYLOAD_SIZE, ENABLE_CORS } from '../config';
import { sysdebug } from '../lib/utils';
export const applyMiddleware = (app: Express) => {
if (ENABLE_CORS) {
sysdebug('Applying CORS middleware.')
app.use(function handleCors(req: Request, res: Response, next: NextFunction) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Authorization,responseType');
res.setHeader('Access-Control-Allow-Credentials', 'true');
next();
});
}
// Limit to 10mb if HTML has e.g. inline images
app.use(bodyParser.text({ limit: MAX_PAYLOAD_SIZE, type: 'text/html' }));
}
|
df10e1c740362128273c844528ac209bac3e19ae
|
TypeScript
|
TarVK/model-react
|
/src/model/dataSources/ExecutionState.ts
| 3.125
| 3
|
import {handleHookError} from "../../tools/hookErrorHandler";
import {IDataHook} from "../_types/IDataHook";
import {isDataLoadRequest} from "../_types/IDataLoadRequest";
import {IDataSource} from "../_types/IDataSource";
import {AbstractDataSource} from "./AbstractDataSource";
/**
* A class to keep track of executing promises
*/
export class ExecutionState
extends AbstractDataSource<boolean>
implements IDataSource<boolean> {
protected executing: Promise<any>[] = [];
/**
* Retrieves whether any promises are executing
* @param hook The hook to subscribe to changes, and store the meta loading state
* @returns Whether any promises are still executing
*/
public get(hook?: IDataHook): boolean {
super.addListener(hook);
if (this.executing.length > 0) {
if (isDataLoadRequest(hook)) {
try {
hook.markIsLoading?.();
} catch (e) {
handleHookError(e, this, hook, "markIsLoading");
}
}
return true;
}
return false;
}
/**
* Retrieves the same result as the `get` method,
* except it doesn't pass the loading as meta state to the hook
* @param hook The hook to subscribe to changes
* @returns Whether any promises are executing
*/
public isLoading(hook?: IDataHook): boolean {
super.addListener(hook);
return this.executing.length > 0;
}
/**
* Adds a promise for which to keep track of its execution state.
* If an asynchronous function is added, it will automatically be invoked.
* @param promise The promise to be added
* @returns The promise itself, for chaining
*/
public add<T>(promise: Promise<T> | (() => Promise<T>)): Promise<T> {
const normalized = promise instanceof Function ? (promise = promise()) : promise;
this.executing.push(normalized);
promise.then(() => this.remove(normalized));
if (this.executing.length == 1) this.callListeners();
return normalized;
}
/**
* Removes a promise which may have been aded before
* @param promise The promise to be removed
* @returns Whether the promise was present, and not already resolved
*/
public remove(promise: Promise<any>): boolean {
const index = this.executing.indexOf(promise);
if (index != -1) {
this.executing.splice(index, 1);
if (this.executing.length == 0) this.callListeners();
return true;
}
return false;
}
}
|
c7374ce9e1cca0aacebabeea60a671a3e71dd9b4
|
TypeScript
|
team-gu/service
|
/FE/store/stickySlice.ts
| 2.8125
| 3
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
interface SectionOffset {
top: number;
height: number;
offset: number;
endOffset: number;
}
interface StickyState {
isFixed: boolean;
translateY: number;
offsets: SectionOffset[];
}
const initialState: StickyState = {
isFixed: false,
translateY: 0,
offsets: [
{ top: 0, height: 0, offset: 0, endOffset: 0 },
{ top: 0, height: 0, offset: 0, endOffset: 0 },
],
};
export const stickyReducer = createSlice({
name: 'sticky',
initialState,
reducers: {
setFixed(state, action: PayloadAction<boolean>) {
state.isFixed = action.payload;
},
setOffset(state, action: PayloadAction<[number, SectionOffset]>) {
const [order, offset] = action.payload;
const offsets = state.offsets;
offsets[order] = offset;
state.offsets = [...offsets];
},
},
});
export const { setFixed, setOffset } = stickyReducer.actions;
export default stickyReducer.reducer;
|
70a5a77d1804ed080606d4e19e0f6cad3aac3495
|
TypeScript
|
Enhmunh-E/tsparticles
|
/engine/src/Updaters/Roll/RollUpdater.ts
| 2.953125
| 3
|
import type { IDelta, IParticleUpdater } from "../../Core/Interfaces";
import type { Particle } from "../../Core/Particle";
import { colorToHsl, getRangeValue } from "../../Utils";
import { AlterType } from "../../Enums";
function updateRoll(particle: Particle, delta: IDelta): void {
const roll = particle.options.roll;
if (!particle.roll || !roll.enable) {
return;
}
const speed = particle.roll.speed * delta.factor;
const max = 2 * Math.PI;
particle.roll.angle += speed;
if (particle.roll.angle > max) {
particle.roll.angle -= max;
}
}
export class RollUpdater implements IParticleUpdater {
init(particle: Particle): void {
const rollOpt = particle.options.roll;
if (rollOpt.enable) {
particle.roll = {
angle: Math.random() * Math.PI * 2,
speed: getRangeValue(rollOpt.speed) / 360,
};
if (rollOpt.backColor) {
particle.backColor = colorToHsl(rollOpt.backColor);
} else if (rollOpt.darken.enable && rollOpt.enlighten.enable) {
const alterType = Math.random() >= 0.5 ? AlterType.darken : AlterType.enlighten;
particle.roll.alter = {
type: alterType,
value: alterType === AlterType.darken ? rollOpt.darken.value : rollOpt.enlighten.value,
};
} else if (rollOpt.darken.enable) {
particle.roll.alter = {
type: AlterType.darken,
value: rollOpt.darken.value,
};
} else if (rollOpt.enlighten.enable) {
particle.roll.alter = {
type: AlterType.enlighten,
value: rollOpt.enlighten.value,
};
}
} else {
particle.roll = { angle: 0, speed: 0 };
}
}
isEnabled(particle: Particle): boolean {
const roll = particle.options.roll;
return !particle.destroyed && !particle.spawning && roll.enable;
}
update(particle: Particle, delta: IDelta): void {
if (!this.isEnabled(particle)) {
return;
}
updateRoll(particle, delta);
}
}
|
460c292e8304fbd69e8ddd8823b0d9581b6b746b
|
TypeScript
|
gabrielDevlog/uml-online
|
/src/plantuml-proxy/shared/dtos/diagram.ts
| 3.015625
| 3
|
import { IsString, IsNotEmpty } from "class-validator";
/**
* A diagram
*/
export interface DiagramDTO {
id: string;
title: string;
data: string;
}
/**
* Data needed to create a diagram
*/
export class DiagramCreateDTO {
@IsString()
@IsNotEmpty()
title: string;
@IsString()
@IsNotEmpty()
data: string;
}
/**
* An error that occured when parsing text
*/
export interface RenderDiagramErrorDTO {
/**
* Line where the error occured
*/
line: number;
/**
* Message describing the error
*/
message: string;
}
|
2d256d354ce7465df3f80b1bf5d13f3a96018927
|
TypeScript
|
supabase/supabase
|
/supabase/functions/common/tokenizer.ts
| 2.71875
| 3
|
import { init, Tiktoken } from 'https://esm.sh/@dqbd/tiktoken@1.0.2/lite/init'
import { ChatCompletionRequestMessage } from 'https://esm.sh/v113/openai@3.2.1'
const encoderResponse = await fetch('https://esm.sh/@dqbd/tiktoken@1.0.2/encoders/cl100k_base.json')
const cl100kBase = await encoderResponse.json()
await init(async (imports) => {
const req = await fetch('https://esm.sh/@dqbd/tiktoken/lite/tiktoken_bg.wasm')
return WebAssembly.instantiate(await req.arrayBuffer(), imports)
})
export const tokenizer = new Tiktoken(
cl100kBase.bpe_ranks,
cl100kBase.special_tokens,
cl100kBase.pat_str
)
/**
* Count the tokens for multi-message chat completion requests
*/
export function getChatRequestTokenCount(
messages: ChatCompletionRequestMessage[],
model = 'gpt-3.5-turbo-0301'
): number {
const tokensPerRequest = 3 // every reply is primed with <|im_start|>assistant<|im_sep|>
const numTokens = messages.reduce((acc, message) => acc + getMessageTokenCount(message, model), 0)
return numTokens + tokensPerRequest
}
/**
* Count the tokens for a single message within a chat completion request
*
* See "Counting tokens for chat API calls"
* from https://github.com/openai/openai-cookbook/blob/834181d5739740eb8380096dac7056c925578d9a/examples/How_to_count_tokens_with_tiktoken.ipynb
*/
export function getMessageTokenCount(
message: ChatCompletionRequestMessage,
model = 'gpt-3.5-turbo-0301'
): number {
let tokensPerMessage: number
let tokensPerName: number
switch (model) {
case 'gpt-3.5-turbo':
console.warn(
'Warning: gpt-3.5-turbo may change over time. Returning num tokens assuming gpt-3.5-turbo-0301.'
)
return getMessageTokenCount(message, 'gpt-3.5-turbo-0301')
case 'gpt-4':
console.warn('Warning: gpt-4 may change over time. Returning num tokens assuming gpt-4-0314.')
return getMessageTokenCount(message, 'gpt-4-0314')
case 'gpt-3.5-turbo-0301':
tokensPerMessage = 4 // every message follows <|start|>{role/name}\n{content}<|end|>\n
tokensPerName = -1 // if there's a name, the role is omitted
break
case 'gpt-4-0314':
tokensPerMessage = 3
tokensPerName = 1
break
default:
throw new Error(
`Unknown model '${model}'. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.`
)
}
return Object.entries(message).reduce((acc, [key, value]) => {
acc += tokenizer.encode(value).length
if (key === 'name') {
acc += tokensPerName
}
return acc
}, tokensPerMessage)
}
/**
* Get the maximum number of tokens for a model's context.
*
* Includes tokens in both message and completion.
*/
export function getMaxTokenCount(model: string): number {
switch (model) {
case 'gpt-3.5-turbo':
console.warn(
'Warning: gpt-3.5-turbo may change over time. Returning max num tokens assuming gpt-3.5-turbo-0301.'
)
return getMaxTokenCount('gpt-3.5-turbo-0301')
case 'gpt-4':
console.warn(
'Warning: gpt-4 may change over time. Returning max num tokens assuming gpt-4-0314.'
)
return getMaxTokenCount('gpt-4-0314')
case 'gpt-3.5-turbo-0301':
return 4097
case 'gpt-4-0314':
return 4097
default:
throw new Error(`Unknown model '${model}'`)
}
}
|
c1c49f404eb01c0d833ec6fad83fd8996952c9ee
|
TypeScript
|
stephensmitchell-forks/minimatrix
|
/test/compare.spec.ts
| 2.796875
| 3
|
import { expect } from 'chai';
import { Compare } from '../src/index';
const EPS = 1e-14;
describe('Compare Functions', () => {
it('should test if number is close to zero', () => {
expect(Compare.isZero(2e-14, EPS)).to.be.false;
expect(Compare.isZero(0.7e-14, EPS)).to.be.true;
});
it('should test if number is greater than zero', () => {
expect(Compare.isGTZero(1.1e-14, EPS)).to.be.true;
expect(Compare.isGTZero(0.7e-14, EPS)).to.be.false;
});
it('should test if number is less than zero', () => {
expect(Compare.isLTZero(-1.1e-14, EPS)).to.be.true;
expect(Compare.isLTZero(-0.7e-14, EPS)).to.be.false;
});
it('should test if 2 numbers are approximately equal', () => {
expect(Compare.isEqual(-1.1e-14, -1.19e-14, EPS)).to.be.true;
expect(Compare.isEqual(-7e-14, -8.1e-14, EPS)).to.be.false;
});
});
|
a1c28458d892f94459889b9d0f06c8058e43223d
|
TypeScript
|
lksmangai/PMOAngular-development
|
/src/app/models/viewTimesheet.model.ts
| 2.59375
| 3
|
export interface IViewTimesheet {
id?: number;
projectId?: number;
employeeId?: number;
projectName?: string;
loghours?: number;
notes?: string;
}
export class ViewTimesheet implements IViewTimesheet {
constructor(public id?: number, public projectId?: number, public employeeId?: number, public projectName?: string, public loghours?: number, public notes?: string) { }
}
|
65a102fd5f0f5e48195803e61bbc0bebe362061b
|
TypeScript
|
abas619/react-recontext
|
/src/utils.ts
| 2.65625
| 3
|
const loggerStyle = "font-weight: bold";
const actionNameToTypes = (actionName: string) => {
return actionName
.replace(/([A-Z])/g, "_$1")
.trim()
.toUpperCase();
};
const printDebugInfo = (
currentAction: string,
state: object,
params: object,
nextState: object
) => {
console.log(
`---> ACTION: %c${actionNameToTypes(currentAction)}`,
`color: #000000; ${loggerStyle}`
);
console.log(" %cprev state ", `color: #708090; ${loggerStyle}`, state);
console.log(" %cparams ", `color: #0000FF; ${loggerStyle}`, params);
console.log(" %cnext state ", `color: #008000; ${loggerStyle}`, nextState);
};
const printWarning = (message: string) => {
console.log(`%c${message}`, `color: #FFA500; ${loggerStyle}`);
};
export { actionNameToTypes, printDebugInfo, printWarning };
|
1bdb2cd9027498c1df23ff0b68342f1439871d93
|
TypeScript
|
chriscastaneda/blog-restfulAPI
|
/server/src/daos/author-dao.ts
| 3.109375
| 3
|
/* istanbul ignore file */
import { dbConnection} from '../daos/db';
import { Author, AuthorRow } from '../models/Author';
/**Database query logic */
//Retrieve all
export function getAllAuthors(): Promise<Author[]> { //Promise<Author[]> returning promise
const sql = 'SELECT * FROM authors'; //Query database
return dbConnection.query<AuthorRow>(sql, []).then(result => { //return promise type as QueryResult<AuthorRow>
const queryrows: AuthorRow[] = result.rows; //extract rows from query response
const authors: Author[] = queryrows.map(row => Author.from(row)); //convert sql row data format into author.ts(static method) JS objects
return authors; //return promise<Author[]>
});
};
//Retrieve by Id
export function getAuthorById(id: number): Promise<Author> {
const sql = 'SELECT * FROM authors WHERE id = $1'; //Parameterize queries
return dbConnection.query<AuthorRow>(sql, [id]) //Filter response for only [id]
.then(result => result.rows.map(row => Author.from(row))[0]); //Limit result to 1 object by index[0]
};
//Validation interface
interface Exists {
exists: boolean;
};
//Valid author by id in database
export async function authorExists(authorId: number): Promise<boolean> {
const sql = `SELECT EXISTS(SELECT id FROM authors WHERE id = $1)`; //Validate user via database by boolean
const result = await dbConnection.query<Exists>(sql, [authorId]);
return result.rows[0].exists; //if boolean: 0, user exists
};
//Create
export function saveAuthor(author: Author): Promise<Author> {
const sql = `INSERT INTO authors (first_name, last_name, email) \
VALUES ($1, $2, $3) RETURNING *`; //Returning Data after insertion
return dbConnection.query<AuthorRow>(sql, [ //Filter placeholder response with [firstName, lastName, email]
author.firstName,
author.lastName,
author.email
]).then(result => result.rows.map(row => Author.from(row))[0]);
};
//Update by sql coalesce
export function patchAuthor(author: Author): Promise<Author> {
const sql = `UPDATE authors SET \
first_name = COALESCE($2, first_name), \
last_name = COALESCE($3, last_name), \
email = COALESCE($4, email) \
WHERE id = $1 RETURNING *`;
return dbConnection.query<AuthorRow>(sql, [
author.id,
author.firstName,
author.lastName,
author.email
]).then(result => result.rows.map(row => Author.from(row))[0]);
};
//Delete by Id
export function deleteAuthorById(id: number): Promise<Author> {
const sql = `DELETE FROM authors WHERE id = $1 RETURNING *`;
return dbConnection.query<AuthorRow>(sql, [id])
.then(result => result.rows.map(row => Author.from(row))[0]);
};
|
9ed330bead364658603be24c8518a1c118de31c0
|
TypeScript
|
wpflying/05_utils
|
/src/utils/judgers/inArray.ts
| 3.890625
| 4
|
/**
* 判定目标值是否包含在目标数组中
* @param val 需要判定的值
* @param arr 数组(可能包含目标值)
* @example
* inArray(2, [1, 2, 3]) // true
* inArray('hello', ['hello', 'world']) // true
*/
export default function inArray<T extends unknown>(val: T, arr: T[]) {
return arr.includes(val)
}
|
83766910f720d588f69ce514fa520a79465c4a53
|
TypeScript
|
aches/component-dm
|
/src/renderer/store/BaseStore.ts
| 3.140625
| 3
|
import {Log} from "../util/Log";
/**
*数据存储类
*@since 2.0
*@author zhiguo
*@Date 2018/6/28 9:37
*/
export class BaseStore {
private getData(key: string) {
return localStorage.getItem(key);
}
/**
* 查询数据并转换为对象
* @param {string} key
* @returns {any}
*/
public getDataObj(key: string): any{
const data = this.getData(key);
let result;
try {
result = JSON.parse(data);
}catch (e) {
Log.e('数据转换异常');
result = data;
}finally {
return result;
}
}
public getDataStr(key: string): string {
return this.getData(key);
}
public getDataNumber(key: string): number {
return Number.parseInt(this.getData(key));
}
/**
*保存数据
* @param {string} key
* @param val
*/
public saveData(key: string, val: any) {
if(typeof val != "string" && typeof val != "number" ){
localStorage.setItem(key,JSON.stringify(val)) ;
}else{
localStorage.setItem(key, val.toString()) ;
}
}
}
|
aca6fc912f262baf1e1405c5ee286cd9d3c1b891
|
TypeScript
|
leelhn2345/chatbot-engine
|
/src/messenger/axios-client.ts
| 2.609375
| 3
|
import axios, { AxiosInstance } from "axios";
import { HTTPClient } from "../type/client";
/** Create a default HTTP client using axios */
export function createAxiosClient(axiosInstance: AxiosInstance = axios) {
const client: HTTPClient = {
communicate: async (request) => {
const { url, headers, maxContentLength, query: params } = request;
const config = { headers, maxContentLength };
const { data } = await (function () {
switch (request.method) {
case "GET":
return axiosInstance.get(url, { params, ...config });
case "POST":
return axiosInstance.post(url, request.body, { params, ...config });
}
})();
return data;
},
};
return client;
}
export default createAxiosClient();
|
7a81bbf77f0086fbe49df81d014bb500a4fa7adc
|
TypeScript
|
kobishiamka/server
|
/actionControllers.ts
| 2.671875
| 3
|
import "reflect-metadata";
import { Controller, Body, Post, Res } from "routing-controllers";
import { Response } from 'express'
import { protfolio } from "./model/protfolio";
import { history } from "./model/history";
@Controller()
export class actionControllers {
//Realization of the buy function
@Post("/buy")
async buy(@Body() body: any, @Res() res: Response) {
let notInProtfolio: boolean = true;
const tempTotalBuyPrice: number = parseInt(body.currentPrice) * parseInt(body.quantity)
const tempHoldingValue: number = parseInt(body.quantity) * parseInt(body.currentPrice)
const tempProfit: number = 0
//handel strengthening stock scenario
let result = await protfolio.find({ where: { sName: body.sName } })
if (result != null) {
notInProtfolio = false
let newQuantity: number = (parseInt(body.quantity) + result.quantity)
let newTotalBuyPrice: number = (result.totalBuyPrice + (parseInt(body.quantity) * parseInt(body.currentPrice)))
let newHoldinigValue: number = newQuantity * parseInt(body.currentPrice)
let newProfit: number = (newHoldinigValue) - (newTotalBuyPrice)
protfolio.update({ currentPrice: body.currentPrice, quantity: newQuantity, totalBuyPrice: newTotalBuyPrice, holdingValue: newHoldinigValue, profit: newProfit }, { where: { sName: body.sName } })
}
//handel scenario of new stock in protfolio
if (notInProtfolio) {
const newStockinProtfolio = new protfolio({ sName: body.sName, currentPrice: parseInt(body.currentPrice), quantity: parseInt(body.quantity), totalBuyPrice: tempTotalBuyPrice, holdingValue: tempHoldingValue, profit: tempProfit })
newStockinProtfolio.save();
}
//update history table BUY mode
const newStockinHistoryUpdate = new history({ action: 'BUY', sName: body.sName, totalBuyPrice: tempTotalBuyPrice, quantity: body.quantity, log: body.log })
await newStockinHistoryUpdate.save();
return res.send(body)
}
@Post("/sell")
async sell(@Body() body: any, @Res() res: Response) {
let crossLimit: boolean = false
const tempTotalBuyPrice: number = parseInt(body.currentPrice) * parseInt(body.quantity)
let result = await protfolio.find({ where: { sName: body.sName } })
let profitPerIter: number = body.quantity * (body.currentPrice - (result.totalBuyPrice / result.quantity))
if (result != null) {
if (result.quantity === parseInt(body.quantity)) {
protfolio.destroy({ where: { sName: body.sName } })
const newStockinHistoryUpdate = new history({ action: 'SELL', sName: body.sName, totalBuyPrice: tempTotalBuyPrice, quantity: body.quantity, log: body.log ,ppi: profitPerIter})
await newStockinHistoryUpdate.save();
}
if (result.quantity > parseInt(body.quantity)) {
let newCurrentPrice: number = parseInt(body.currentPrice)
let newQuantity: number = (result.quantity - parseInt(body.quantity))
let newTotalBuyPrice = ( result.totalBuyPrice / result.quantity ) * newQuantity
let newHoldinigValue: number = (newQuantity * newCurrentPrice)
let newProfit: number = newHoldinigValue - newTotalBuyPrice
protfolio.update({ currentPrice: newCurrentPrice, quantity: newQuantity, totalBuyPrice: newTotalBuyPrice, holdingValue: newHoldinigValue, profit: newProfit }, { where: { sName: body.sName } })
const newStockinHistoryUpdate = new history({ action: 'SELL', sName: body.sName, totalBuyPrice: tempTotalBuyPrice, quantity: body.quantity, log: body.log , ppi: profitPerIter})
await newStockinHistoryUpdate.save();
}
if (result.quantity < parseInt(body.quantity)) {
console.log("ERROR : You do not have enough shares in the portfolio ")
const newStockinHistoryUpdate = new history({ action: 'SELL FAILURE', sName: body.sName, totalBuyPrice: 0, quantity: 0, log: 'ERROR : You do not have enough shares in the portfolio' })
await newStockinHistoryUpdate.save();
}
}
return res.send(body)
}
}
|
55e8268cc67eb416a0093e4555e651d1ec7f60b8
|
TypeScript
|
adiostone/one-table-api
|
/src/modules/database/RedisConnector.ts
| 2.578125
| 3
|
import Redis, { Redis as IORedis } from 'ioredis'
export default class RedisConnector {
private static _instance: RedisConnector
private _conn: IORedis
/**
* Get singleton instance
*
* @constructor
*/
public static get I(): RedisConnector {
if (this._instance === undefined) {
this._instance = new this()
}
return this._instance
}
/**
* Private constructor for singleton pattern
*/
// eslint-disable-next-line no-useless-constructor,@typescript-eslint/no-empty-function
private constructor() {}
public get conn(): IORedis {
return this._conn
}
public connect(): void {
this._conn = new Redis({
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT, 10),
db: parseInt(process.env.REDIS_DATABASE, 10),
password: process.env.REDIS_PASSWORD
})
}
public close(): void {
this._conn.disconnect()
this._conn = undefined
}
}
|
3b7b91c2d4a68929d4fdeb74cff6855312727efb
|
TypeScript
|
logoss233/LayaPandaRun
|
/src/object/item/eatItem/Coin.ts
| 2.671875
| 3
|
class Coin extends EatItem{
speed=15 //被磁铁吸引的速度
magnent_distance=800 //吸引的范围
constructor(){
super()
this.poolTag="Coin"
var ani=new Animation()
this.addChild(ani)
ani.loadAnimation("CoinAnimation.ani")
ani.play(0,true,"ani1")
this.setBounds(new Rectangle(2,2,60,60))
}
eat(){
//播放声音
var index=Math.floor(Math.random()*3)+1
var path="res/sound/coin"+String(index)+".mp3"
SoundManager.playSound(path)
//生成特效
var effect=Pool.getItemByClass("EatEffect",EatEffect)
$game.itemPlace.addChild(effect)
effect.pos(this.x+32,this.y+32)
effect.start()
//效果
//加分
$game.coin++
//删除自己
this.delete()
}
update(){
var player=$game.player
if (player.isMagnent){
var dx=player.x-this.x
var dy=player.y-this.y
var adx=Math.abs(dx)
var ady=Math.abs(dy)
var distance=Math.sqrt(dx*dx+dy*dy)
if (distance<=this.magnent_distance){
this.x+=dx/(adx+ady)*this.speed
this.y+=dy/(adx+ady)*this.speed
}
}
}
}
|
5c65a76d10f388a1bff4cda24ec946b39e908da4
|
TypeScript
|
DJAPavlik/ionicAuth
|
/src/app/user.service.ts
| 2.65625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from '../models/user';
// 3. Create a JSON header to be attached to outbound post requests
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class UserService {
private url:string
private getUsersUrl:string
private delUserUrl:string
constructor(private http: HttpClient) {
let l = window.location;
let host:string;
if(l.port == '8100'){
host = 'localhost:3000';
}else{
host = l.hostname + ((l.port.length>0)?':' + l.port:'');
}
// console.log(' - host in UserService');
// console.log(host);
this.url = `${l.protocol}//${host}/api/auth/`;
this.getUsersUrl=`${l.protocol}//${host}/api/users`
this.delUserUrl = `${l.protocol}//${host}/api/users`
// console.log(' - this.url in UserService');
// console.log(this.url);
// console.log('');
// alert('hold in constructor');
}
registerUser(user: User): Observable<User>{
return this.http.post<User>(this.getUsersUrl , user, httpOptions);
}
deleteUser (_id: string): Observable<User> {
console.log('check this check this')
console.log(`${this.delUserUrl}${_id}`)
return this.http.delete<User>(`${this.delUserUrl}/${_id}` );
}
updateUser(user: User): Observable<User>{
return this.http.put<User>(this.getUsersUrl , user, httpOptions);
}
logIn(user: User): Observable<User>{
return this.http.post<User>(this.url + 'login', user, httpOptions);
}
getUsersArray(): Observable<User[]> {
return this.http.get<User[]>(this.getUsersUrl)
}
getUserById(id: string): Observable<User> {
return this.http.get<User>(`${this.getUsersUrl}/${id}` )
}
} // end class UserService
|
6f2b90008550de4be380c69c51e025f26693a1b5
|
TypeScript
|
bmancini55/algorithms
|
/src/BinarySearchTree/Recursive/PeekMin.ts
| 3.71875
| 4
|
export class Node<T> {
public key: T;
public left: Node<T>;
public right: Node<T>;
public parent: Node<T>;
constructor(key: T) {
this.key = key;
this.parent = null;
this.left = null;
this.right = null;
}
}
/**
* Finds the min value in the tree staring at the root.
* Executes in θ(height) which has average complexity of O(log n) and
* a worst case runtime of O(n).
*/
export function peekMin<T>(root: Node<T>): Node<T> {
if (!root) return root;
while (root.left) {
root = root.left;
}
return root;
}
|
738f3125aef4fd78c2b7970cbbf2a110077dd208
|
TypeScript
|
ygortavela/TabelaBrasileirao
|
/frontend/src/store/teams/types.ts
| 2.71875
| 3
|
export interface TeamState {
pending: boolean;
error: any;
teams: Team[];
selectedTeam: Team;
formType: 'CREATE' | 'EDIT' | null;
}
export const FETCH_TEAMS_PENDING = 'FETCH_TEAMS_PENDING';
export const FETCH_TEAMS_SUCCESS = 'FETCH_TEAMS_SUCCESS';
export const FETCH_TEAMS_ERROR = 'FETCH_TEAMS_ERROR';
export const ADD_TEAM = 'ADD_TEAM';
export const REMOVE_TEAM = 'DELETE_TEAM';
export const SELECT_TEAM = 'SELECT_TEAM';
export const TOGGLE_FORM_TYPE = 'TOGGLE_FORM_TYPE';
export interface FetchTeamsPendingAction {
type: typeof FETCH_TEAMS_PENDING;
}
export interface FetchTeamsSucessAction {
type: typeof FETCH_TEAMS_SUCCESS;
payload: Team[];
}
export interface FetchTeamsErrorAction {
type: typeof FETCH_TEAMS_ERROR;
payload: any;
}
export interface AddTeamAction {
type: typeof ADD_TEAM;
payload: Team;
}
export interface DeleteTeamAction {
type: typeof REMOVE_TEAM;
meta: {
teamId: number;
};
}
export interface SelectTeamAction {
type: typeof SELECT_TEAM;
payload: Team;
}
export interface ToggleFormTypeAction {
type: typeof TOGGLE_FORM_TYPE;
payload: 'CREATE' | 'EDIT' | null;
}
export type TeamActionTypes =
| FetchTeamsPendingAction
| FetchTeamsSucessAction
| FetchTeamsErrorAction
| AddTeamAction
| DeleteTeamAction
| SelectTeamAction
| ToggleFormTypeAction;
|
b4bb86aebd08bf2f6fd98e0f1ee27a47367bf83a
|
TypeScript
|
paraslov/irx-test1-soc-net
|
/src/n7-helpers/cookie.ts
| 2.703125
| 3
|
export function set_cookie(name: string, value: string) {
const cookie_string = name + '=' + escape(value)
document.cookie = cookie_string
}
export function delete_cookie(cookie_name: string) {
const cookie_date = new Date()
cookie_date.setTime(cookie_date.getTime() - 1)
document.cookie = cookie_name += '=; expires=' + cookie_date.toUTCString()
}
export function get_cookie(cookie_name: string) {
const results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)')
if (results)
return (unescape(results[2]))
else
return null
}
|
44cd61bfd8187a5dc80014e322d28fad6b5cb4c7
|
TypeScript
|
shamilsun/crypto-quote-watcher
|
/common/models/events/eventsProps.ts
| 2.53125
| 3
|
export interface IEventsStack {
[actionKey:string]: {
setterKey:string
event: (arr:any)=>void
}[]
}
|
42451831ba8b2ec9162c89fbb2e6a7e0403162af
|
TypeScript
|
tyankatsu0105/types-gridsome
|
/dist/pages.d.ts
| 2.8125
| 3
|
export interface CreatePagesActioons {
/**
* Use the `createPages` hook if you want to create pages.
* Pages created in this hook will be re-created and garbage collected occasionally.
* Use the `createManagedPages` below to have more control over when pages are updated or deleted manually.
* @param options
* @param options.path - Required.
* @param options.component - Required.
* @param options.context - Optional context for the page and `page-query`.
* @param options.queryVariables - Optional context only for `page-query`.
*/
createPage(options: {
path: string;
component: string;
context: object;
queryVariables: object;
}): void;
}
export interface createManagedPagesActioons extends CreatePagesActioons {
/**
* Removes a page created by `createPage`.
* @param page
*/
removePage(page: any): void;
/**
* Removes a page matching the provided path.
* @param path
*/
removePageByPath(path: any): void;
/**
* Removes all pages matching the provided component path.
* @param path
*/
removePagesByComponent(path: any): void;
/**
* Removes all pages matching the provided query.
* @param query
*/
findAndRemovePages(query: any): void;
/**
* Returns all pages matching the provided query.
* @param query
*/
findPages(query: any): void;
/**
* Returns first pages matching the provided query.
* @param query
*/
findPage(query: any): void;
}
|
c1f13c6c94c036e76db09eaffa76290202d3ee6c
|
TypeScript
|
hllfmy/jira-ci-cd-integration
|
/src/utils/logger.ts
| 2.53125
| 3
|
let logger = {
debug: console.debug,
info: console.info,
error: console.error,
}
export function setLogger(newLogger: typeof logger): void {
logger = newLogger
}
export function getLogger(): typeof logger {
return logger
}
|
0934ff68c52f42ea25049ca268d6cab5a7f9b8d0
|
TypeScript
|
iamkirabond/middle.messenger.praktikum.yandex
|
/src/utils/validation.ts
| 2.921875
| 3
|
export function validationForm(inputContent: string, type: string):boolean{
const expression = {
name: /(^[A-Z]{1}[a-z]{1,29}|(^[А-Я]{1}[а-я]{1,29}$))/,//
login: /^[a-zA-Z]([a-zA-Z0-9_-]{1,29})$/,
email: /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/,
password: /(?=.*[A-Z]+)(?=.*[!@#\$%]+)/,
message: /(?=.*[A-Z]+)(?=.*[!@#\$%]+)/,
phone: /^(\+7|8)[0-9]{10}$/,
}
switch (type) {
case 'first_name':
return expression.name.test(inputContent);
case 'second_name':
return expression.name.test(inputContent);
case 'login':
return expression.login.test(inputContent);
case 'email':
return (expression.email.test(inputContent) && inputContent.length > 0);
case 'password':
return expression.password.test(inputContent);
case 'message':
return expression.message.test(inputContent);
case 'phone':
return expression.phone.test(inputContent);
default:
return false;
}
}
|
beeb1dc95f815d9834859258ca9f20d35769c6ec
|
TypeScript
|
Shrilekha1995/CD
|
/frontend/demo-app/src/app/services/location.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable,Observer } from 'rxjs';
interface Location{
latitude:number;
longitude:number;
ip:any;
}
@Injectable({
providedIn: 'root'
})
export class LocationService {
constructor(private http:HttpClient) { }
getLocation(){
return this.http.get<Location>("https://ipapi.co/json/");
}
getLocationUpdate():Observable<Position>{
return Observable.create((observer: Observer<Position>) => {
// Invokes getCurrentPosition method of Geolocation API.
navigator.geolocation.watchPosition(
(position: Position) => {
observer.next(position);
observer.complete();
},
(error: PositionError) => {
console.log('Geolocation service: ' + error.message);
observer.error(error);
}
);
});
}
}
|
11b6b93e64caa6b8074e08e1e6625a645ca70bdc
|
TypeScript
|
Denis101/screeps
|
/src/creep/component/DropComponent.ts
| 2.53125
| 3
|
import { component } from "inversify.config";
import { timed } from "processor/Processor";
import { CreepComponent, TYPE_CREEP_COMPONENT, CreepComponentInput } from "./CreepComponent";
const TYPE: string = 'DropComponent';
@component<CreepComponent>(TYPE_CREEP_COMPONENT, TYPE)
export default class DropComponent implements CreepComponent {
public static readonly TYPE: string = TYPE;
public readonly type: string = TYPE;
canHandle(): boolean {
return true;
}
public handleBegin({ creep }: CreepComponentInput): void {
creep.say('💧');
}
@timed
public handleTick({ creep }: CreepComponentInput): void {
creep.drop(RESOURCE_ENERGY, creep.carry.energy);
}
// tslint:disable-next-line:no-empty
public handleEnd(): void { }
}
|
1f3a6e0fa0b2160dd68c9f5f688c5142db495622
|
TypeScript
|
emonddr/loopback4-mixins-example
|
/src/models/book.model.ts
| 2.5625
| 3
|
import {model, property} from '@loopback/repository';
import {AddCategoryPropertyMixin} from '../mixins/category-property-mixin';
import {BaseEntity} from './base-entity';
@model()
export class Book extends AddCategoryPropertyMixin(
BaseEntity,
) {
constructor(data?: Partial<Book>) {
super(data);
}
@property({
type: 'string',
required: true,
})
title: string;
@property({
type: 'number',
id: true,
generated: true,
})
id?: number;
@property({
type: 'string',
})
description?: string;
@property({
type: 'string',
required: true,
})
isbn: string;
}
export interface BookRelations {
// describe navigational properties here
}
export type BookWithRelations = Book & BookRelations;
|
93af41f39b226967ed28d21fd593386595eafcba
|
TypeScript
|
JohnstonCode/svn-scm
|
/src/ignoreitems.ts
| 2.734375
| 3
|
import * as path from "path";
import { QuickPickItem, Uri, window } from "vscode";
import { Repository } from "./repository";
export class IgnoreSingleItem implements QuickPickItem {
constructor(public expression: string, public recursive: boolean = false) {}
get label(): string {
const text = this.recursive ? " (Recursive)" : "";
return `${this.expression}${text}`;
}
get description(): string {
const text = this.recursive ? " (Recursive)" : "";
return `Add '${this.expression}' to 'svn:ignore'${text}`;
}
}
export async function inputIgnoreList(repository: Repository, uris: Uri[]) {
if (uris.length === 0) {
return false;
}
const regexExtension = new RegExp("\\.[^\\.]+(\\.map)?$", "i");
if (uris.length === 1) {
const uri = uris[0];
const matchExt = uri.fsPath.match(regexExtension);
const ext = matchExt && matchExt[0] ? matchExt[0] : "";
const fileName = path.basename(uri.fsPath);
const dirName = path.dirname(uri.fsPath);
const picks: IgnoreSingleItem[] = [];
picks.push(new IgnoreSingleItem(fileName));
if (ext) {
picks.push(new IgnoreSingleItem("*" + ext));
}
picks.push(new IgnoreSingleItem(fileName, true));
if (ext) {
picks.push(new IgnoreSingleItem("*" + ext, true));
}
const pick = await window.showQuickPick(picks);
if (!pick) {
return false;
}
return repository.addToIgnore([pick.expression], dirName, pick.recursive);
}
const count = uris.length;
const recursive = "(Recursive)";
const ignoreByFileName = `Ignore ${count} by filename`;
const ignoreByExtension = `Ignore ${count} by extension`;
const ignoreByFileNameRecursive = `Ignore ${count} by filename ${recursive}`;
const ignoreByExtensionRecursive = `Ignore ${count} by extension ${recursive}`;
const picks: string[] = [
ignoreByFileName,
ignoreByExtension,
ignoreByFileNameRecursive,
ignoreByExtensionRecursive
];
const pick = await window.showQuickPick(picks);
if (!pick) {
return false;
}
const isByFile = pick.startsWith(ignoreByFileName);
const isRecursive = pick.endsWith(recursive);
const byDir: { [key: string]: string[] } = {};
for (const uri of uris) {
const dirname = path.dirname(uri.fsPath);
const filename = path.basename(uri.fsPath);
const matchExt = uri.fsPath.match(regexExtension);
const ext = matchExt && matchExt[0] ? matchExt[0] : "";
if (typeof byDir[dirname] === "undefined") {
byDir[dirname] = [];
}
if (isByFile) {
byDir[dirname].push(filename);
} else if (ext) {
byDir[dirname].push("*" + ext);
}
}
for (const dir in byDir) {
if (byDir.hasOwnProperty(dir)) {
const files = [...new Set(byDir[dir])]; // Unique list
await repository.addToIgnore(files, dir, isRecursive);
}
}
return true;
}
|
75ca1c5d7c065f4f09d1972c21e52841cbf2a040
|
TypeScript
|
marjisound/dotcom-rendering
|
/apps-rendering/src/themeStyles.ts
| 2.625
| 3
|
// ----- Imports ----- //
import * as palette from '@guardian/src-foundations/palette';
import type { Theme } from '@guardian/types';
import { Pillar, Special } from '@guardian/types';
// ----- Types ----- //
interface ThemeStyles {
kicker: string;
inverted: string;
liveblogBackground: string;
liveblogDarkBackground: string;
link: string;
cameraIcon: string;
cameraIconBackground: string;
}
type ThemeColours = {
[theme in Theme]: ThemeStyles;
};
export const themeColours: ThemeColours = {
[Pillar.News]: {
kicker: palette.news[400],
inverted: palette.news[500],
liveblogBackground: palette.news[300],
liveblogDarkBackground: palette.news[200],
link: palette.news[300],
cameraIcon: palette.news[800],
cameraIconBackground: palette.news[400],
},
[Pillar.Opinion]: {
kicker: palette.opinion[400],
inverted: palette.opinion[500],
liveblogBackground: palette.opinion[300],
liveblogDarkBackground: palette.opinion[200],
link: palette.opinion[300],
cameraIcon: palette.opinion[800],
cameraIconBackground: palette.opinion[400],
},
[Pillar.Sport]: {
kicker: palette.sport[400],
inverted: palette.sport[500],
liveblogBackground: palette.sport[300],
liveblogDarkBackground: palette.sport[200],
link: palette.sport[300],
cameraIcon: palette.sport[800],
cameraIconBackground: palette.sport[400],
},
[Pillar.Culture]: {
kicker: palette.culture[400],
inverted: palette.culture[500],
liveblogBackground: palette.culture[300],
liveblogDarkBackground: palette.culture[200],
link: palette.culture[300],
cameraIcon: palette.culture[800],
cameraIconBackground: palette.culture[400],
},
[Pillar.Lifestyle]: {
kicker: palette.lifestyle[400],
inverted: palette.lifestyle[500],
liveblogBackground: palette.lifestyle[300],
liveblogDarkBackground: palette.lifestyle[200],
link: palette.lifestyle[300],
cameraIcon: palette.lifestyle[800],
cameraIconBackground: palette.lifestyle[400],
},
[Special.SpecialReport]: {
kicker: palette.specialReport[400],
inverted: palette.specialReport[500],
liveblogBackground: palette.specialReport[300],
liveblogDarkBackground: palette.specialReport[200],
link: palette.specialReport[300],
cameraIcon: palette.specialReport[800],
cameraIconBackground: palette.specialReport[400],
},
[Special.Labs]: {
kicker: palette.specialReport[400],
inverted: palette.specialReport[500],
liveblogBackground: palette.specialReport[300],
liveblogDarkBackground: palette.specialReport[200],
link: palette.specialReport[300],
cameraIcon: palette.specialReport[800],
cameraIconBackground: palette.specialReport[400],
},
};
const getThemeStyles = (theme: Theme): ThemeStyles => themeColours[theme];
function themeFromString(theme: string | undefined): Pillar {
switch (theme) {
case 'pillar/opinion':
return Pillar.Opinion;
case 'pillar/sport':
return Pillar.Sport;
case 'pillar/arts':
return Pillar.Culture;
case 'pillar/lifestyle':
return Pillar.Lifestyle;
case 'pillar/news':
default:
return Pillar.News;
}
}
function themeToPillarString(theme: Theme): string {
switch (theme) {
case Pillar.Opinion:
return 'opinion';
case Pillar.Sport:
return 'sport';
case Pillar.Culture:
return 'culture';
case Pillar.Lifestyle:
return 'lifestyle';
case Pillar.News:
default:
return 'news';
}
}
function themeToPillar(theme: Theme): Pillar {
switch (theme) {
case Special.SpecialReport:
case Special.Labs:
return Pillar.News;
default:
return theme;
}
}
const stringToPillar = (pillar: string): Pillar => {
switch (pillar) {
case 'news':
return Pillar.News;
case 'opinion':
return Pillar.Opinion;
case 'culture':
return Pillar.Culture;
case 'sport':
return Pillar.Sport;
case 'lifestyle':
return Pillar.Lifestyle;
default:
return Pillar.News;
}
};
// ----- Exports ----- //
export {
ThemeStyles,
getThemeStyles,
themeFromString,
themeToPillarString,
themeToPillar,
stringToPillar,
};
|
537a721df7aaba4a35dc3be2019a9b594da4b937
|
TypeScript
|
gruberchris/OneSourceConsole
|
/src/result-messages/Message.ts
| 2.953125
| 3
|
import IResultMessage from "./IResultMessage";
class Message implements IResultMessage {
public readonly type: string;
public readonly eid: string;
public readonly message: string;
constructor(eid: string, message: string) {
this.type = 'onMessage';
this.eid = eid;
this.message = message;
}
public toString(): string {
return `${this.eid} | ${this.type}`;
}
}
export default Message;
|
d27b5c016d264359e9f3c24efe4c40f8efe55ee6
|
TypeScript
|
Irega97/Seminari1EA
|
/src/models/user.ts
| 2.8125
| 3
|
//Interfaces
import mongoose, { Schema, Document} from 'mongoose';
import Course, { ICourse } from './course';
//Interfaz para tratar respuesta como documento
export interface IUser extends Document {
nombre: string;
apellidos: string;
edad: number;
correo: string;
telefono: number;
grado: string;
courses: ICourse['_id']; //Relacion con la coleccion courses
}
//Modelo de objeto que se guarda en la BBDD de MongoDB
const userSchema = new Schema({
nombre: {
type: String
},
apellidos: {
type: String
},
edad: {
type: Number
},
correo: {
type : String
},
telefono: {
type:Number
},
grado: {
type:String
},
courses: [{
type: Schema.Types.ObjectId,
ref: Course
}]
});
//Exportamos modelo para poder usarlo
export default mongoose.model<IUser>('User', userSchema);
|
c0da73b8d40136b2efa4d8fcac9b9d693de6381f
|
TypeScript
|
OurSonic/OurSonicTyped
|
/client/src/app/game/level/sonicImage.ts
| 2.765625
| 3
|
export class SonicImage {
Bytes: number[];
Palette: number[][];
Width: number;
Height: number;
constructor(bytes: number[], palette: number[][], width: number, height: number) {
this.Bytes = bytes;
this.Palette = palette;
this.Width = width;
this.Height = height;
}
}
|
c3345c324375b1ac8ca2d6c280168f6669cd9eb2
|
TypeScript
|
benibowalson/angularTest
|
/src/app/heroes/heroes.component.ts
| 2.78125
| 3
|
import { Component, OnInit } from '@angular/core';
import {Hero} from '../hero';
/*import {HEROES} from '../mock-heroes'; */ /*//No longer this import since service will be used now */
import {HeroService } from '../hero.service';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
/*hero = 'Okodokas I'; /* Use single quotes, not double*/
/*
hero: Hero = {
id: 1,
name: 'Okodokas I'
};
*/
heroes: Hero[];
selectedHero: Hero; /* property of type Hero; the Hero class already created */
/*constructor() { } */ /*no longer using default constructor */
constructor(private heroService: HeroService) { } /* HeroService injection now implied; subscribing to hero service */
// respondToHeroClick(aHero: Hero): void { /*a method taking a hero object and returning void */
// this.selectedHero = aHero;
// }
loadMyHeroes(): void {
/* Before: presentMyHeroes() method is in the HeroService Class */
/*this.heroes = this.heroService.presentMyHeroes(); Synchronous*/
/********************** */
/**Now: Asynchronous by subscribing to data service */
this.heroService.presentMyHeroes()
.subscribe(receivedHeroes => this.heroes = receivedHeroes); // receivedHeroes is sent by heroService.presentMyHeroes()
}
saveAHero(name: string): void {
name = name.trim();
if (!name) { return; }
this.heroService.addAHero({ name } as Hero)
.subscribe(aHero => {
this.heroes.push(aHero);
});
}
ngOnInit() {
this.loadMyHeroes();
}
}
|
fa7f6f89061294bd620d938824aa2401353e880f
|
TypeScript
|
drakedey/money-graphql-backend
|
/src/entity/MoneyAccount.ts
| 2.53125
| 3
|
import {
Entity, Column, PrimaryGeneratedColumn, OneToMany,
} from 'typeorm';
// eslint-disable-next-line import/no-cycle
import { MoneyAccountUser } from './MoneyAccountUser';
enum CurrencyType {
Usd = 'USD',
Cop = 'COP',
Vef = 'VEF'
}
@Entity({
name: 'money_account',
})
class MoneyAccount {
@PrimaryGeneratedColumn()
id: number | undefined;
@Column({
name: 'amount',
})
ammount!: number;
@Column({
length: 3,
})
currency: CurrencyType = CurrencyType.Usd;
@OneToMany(
() => MoneyAccountUser,
(moneyAccountUser) => moneyAccountUser.account,
{ eager: true },
)
users!: MoneyAccountUser[];
}
export { MoneyAccount, CurrencyType };
|
5377d6e0dd8b73f451dd8b90ce24498643585f9a
|
TypeScript
|
FlipSs/flipss-common-types
|
/tests/caching/cache/SlidingExpirationCache.spec.ts
| 2.59375
| 3
|
import {testCache} from "./common";
import {SlidingExpirationCache} from "../../../src/caching/internal";
import {TimeSpan} from "../../../src/time/internal";
import {usingAsync} from "../../../src/common/functions";
describe('SlidingExpirationCache', () => {
testCache(SlidingExpirationCache);
it('Should remove value when it not used and expired', async () => {
await usingAsync(new SlidingExpirationCache<string, number>(() => TimeSpan.fromMilliseconds(300), () => TimeSpan.fromMilliseconds(100)),
async cache => {
cache.set('test', 15);
expect(cache.containsKey('test')).toBeTruthy();
for (let i = 0; i < 3; i++) {
await new Promise(resolve => setTimeout(resolve, 200));
expect(cache.containsKey('test')).toBeTruthy();
cache.get('test');
}
await new Promise(resolve => setTimeout(resolve, 350));
expect(cache.containsKey('test')).toBeFalsy();
});
});
});
|
deece270bf980b0c5b2cc12a5fe49fd66f67fc3d
|
TypeScript
|
BookAdda/booksResale
|
/BooksFrontend-master/src/app/pipes/pricee.pipe.ts
| 2.59375
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'pricee'
})
export class PriceePipe implements PipeTransform {
transform(value: any, filterMax : string, propName : string): any {
if(value.length == 0 || filterMax === '' || filterMax == null || filterMax === 'Max price'){
return value;
}
const resultArray = [];
for(const item of value){
if(item[propName]<filterMax){
resultArray.push(item);
}
}
return resultArray;
}
}
|
1323f7e2f0d8352247d6589ff61b765452bead0e
|
TypeScript
|
latticework/jali
|
/packages/@jali-ms/util/src/argument-empty-string-error.ts
| 3.53125
| 4
|
import { default as ArgumentFalsyError } from './argument-falsy-error';
/**
* Represents that an argument erroneously has an empty string value.
*
* Throw this {@link Error} if a parameter must be a non-empty string.
*
* @example <caption>The argument for the parameter lastName is an empty string.</caption>
* throw new ArgumentEmptyStringError('lastName');
*
* @see <a href="manual/overview.html#package-jali-ms-util">
* package <code>@jali-ms/util</code></a>
* @see <a href="manual/overview.html#module-jali-ms-util-errors">
* module <code>@jali-ms/util/errors</code></a>
* @see {@link ArgumentWhitespaceStringError}
* @see {@link verifyNonempty}
* @see {@link verifyTruthy}
* @see {@link verifyNotWhitespace}
* @public
* @since 0.0.1
*/
export default class ArgumentEmptyStringError extends ArgumentFalsyError {
/**
* Initializes a new instance of the {@link ArgumentEmptyStringError} class.
*
* @param {string} [name] -
* The parameter name. Default is no name.
* @param {string} [message] -
* Specified message. Otherwise, a generic message will be used like *Argument must not be an
* empty string. Yours is empty*.
* @public
* @since 0.0.1
*/
constructor(name?: string, message?: string) {
super(name, message || 'Argument must not be an empty string. Yours is empty');
}
}
|
08554a9540c772cdddea73e2ef0e50e28c2984a9
|
TypeScript
|
Ruddickmg/js-wars
|
/front/javascript/src/browser/menu/screen/title.ts
| 2.890625
| 3
|
import {isDefined} from "../../../tools/validation/typeChecker";
import validator, {Validator} from "../../../tools/validation/validator";
import createElement, {Element} from "../../dom/element/element";
export default (function() {
const {validateString}: Validator = validator("title");
return function(initialTitle?: string): Element<any> {
const element: Element<string> = createElement<string>("title", "h1");
if (isDefined(initialTitle) && validateString(initialTitle, "createTitle")) {
element.setText(initialTitle);
}
return element;
};
}());
|
80f04e35954c77238e8d77071236f33f09fbe59d
|
TypeScript
|
andymed-jlp/easymoney
|
/packages/money/src/calculator/calculator.ts
| 3.234375
| 3
|
import { fromNumber } from "../number";
import { customRound } from "./round";
import { assert } from "@easymoney/core";
import { CalculatorBase } from "./types";
export function createCalculator(): CalculatorBase {
const instance = {
compare,
add,
subtract,
multiply,
divide,
ceil,
absolute,
floor,
share,
round,
mod
};
return instance;
}
const subtract: CalculatorBase["subtract"] = function(amount, subtrahend) {
const result = Number(amount) - Number(subtrahend);
assertInteger(result);
return String(result);
};
const compare: CalculatorBase["compare"] = function(a, b) {
const aNumber = Number(a);
const bNumber = Number(b);
return aNumber < bNumber ? -1 : aNumber > bNumber ? 1 : 0;
};
const add: CalculatorBase["add"] = function(amount, addend) {
const result = Number(amount) + Number(addend);
assertInteger(result);
return String(result);
};
const multiply: CalculatorBase["multiply"] = function(amount, multiplier) {
const result = Number(amount) * Number(multiplier);
assertIntegerBounds(result);
return fromNumber(result).toString();
};
function castInteger(amount: any) {
assertIntegerBounds(amount);
return String(parseInt(String(amount), 10));
}
function assertInteger(amount: any) {
const newAmount = Number(amount);
assert(
typeof newAmount === "number" && Number.isInteger(newAmount),
new TypeError("The result of arithmetic operation is not an integer")
);
}
function assertIntegerBounds(amount: any): asserts amount is number {
assert(
!(amount > Number.MAX_SAFE_INTEGER),
new RangeError(
"You overflowed the maximum allowed integer (Number.MAX_SAFE_INTEGER)"
)
);
assert(
!(amount < -Number.MAX_SAFE_INTEGER),
new RangeError(
"You underflowed the minimum allowed integer (-Number.MAX_SAFE_INTEGER)"
)
);
}
const ceil: CalculatorBase["ceil"] = function(number) {
return castInteger(Math.ceil(Number(number)));
};
const floor: CalculatorBase["floor"] = function(number) {
return castInteger(Math.floor(Number(number)));
};
const divide: CalculatorBase["divide"] = function(amount, divisor) {
const result = Number(amount) / Number(divisor);
assertIntegerBounds(result);
return fromNumber(result).toString();
};
const absolute: CalculatorBase["absolute"] = function(number) {
const result = Math.abs(Number(number));
assertIntegerBounds(result);
return String(result);
};
const round: CalculatorBase["round"] = function(number, roundingMode) {
return castInteger(customRound(Number(number), roundingMode));
};
const share: CalculatorBase["share"] = function(amount, ratio, total) {
return castInteger(
Math.floor((Number(amount) * Number(ratio)) / Number(total))
);
};
const mod: CalculatorBase["mod"] = function(amount, divisor) {
const result = Number(amount) % Number(divisor);
assertIntegerBounds(result);
return String(result);
};
|
2a797e5178f48185f0293585e245f57f7c7a6e1b
|
TypeScript
|
arturgieralt/CanonGame
|
/src/Builders/BallBuilder.ts
| 2.625
| 3
|
import { injectable, inject, interfaces} from "inversify";
import { TYPES } from "../IoC/types";
import { IBall } from "../Models/Ball/IBall";
import { IBallBuilder } from "./IBallBuilder";
import { IBallConfiguration } from "../Configurations/IConfiguration";
@injectable()
export class BallBuilder implements IBallBuilder {
private config: IBallConfiguration;
private ballNewable: interfaces.Newable<IBall>;
private a: number;
constructor (@inject(TYPES.BallNewable) ball: interfaces.Newable<IBall>) {
this.ballNewable = ball;
}
public setConfig (config: IBallConfiguration){
this.config = config;
return this;
}
public setAngle (angle: number){
this.a = angle;
return this;
}
public build() {
return new this.ballNewable(this.config.xStartingPosition, this.config.yStartingPosition, this.config.radius, this.config.color, this.config.xSpeed * Math.cos(this.a * Math.PI/180), this.config.ySpeed * Math.sin(this.a * Math.PI/180));
}
}
|
d89caead29d9ea7c4aa37144cf282ad787f16e17
|
TypeScript
|
ankhaa8/cs572-onlineMarket
|
/src/controllers/user.ts
| 2.59375
| 3
|
import {ApiResponse} from '../utils/response';
import {Product} from '../models';
export const updateCart = async (req, res, next) => {
try {
const user = req.user;
const productId = req.body.productId;
const quantity = req.body.quantity;
await user.updateCart(productId, quantity);
res.status(200).send(new ApiResponse(200, 'success', {user: user}));
}
catch (err) {
res.status(401).send(new ApiResponse(200, 'error', { errors: [err.message]}));
}
}
export const getCart = async (req, res, next) => {
try {
let prodIds = req.user.cart.items.map(e => e.productId);
let products = await Product.getPrductsByIds(prodIds);
const responseResult = [];
for (let product of products) {
let item = req.user.cart.items.find(e => e.productId.toString() === product._id.toString());
responseResult.push({product: product, quantity: item.quantity});
}
res.status(200).send(new ApiResponse(200, 'success', {items: responseResult}));
}
catch (err) {
res.status(401).send(new ApiResponse(200, 'error', { errors: [err.message]}));
}
}
|
d14c444230845e3e875b342586df97aab44ac3ed
|
TypeScript
|
forgng/pin-cli
|
/src/commands/search.ts
| 2.59375
| 3
|
import { Command, flags } from '@oclif/command';
import { getPinList } from '../utils';
const { prompt } = require('enquirer');
const chalk = require('chalk');
const execa = require('execa');
export default class Search extends Command {
static description = 'Search for a pin';
static examples = [`$ pin search`];
async run() {
try {
const pinList = getPinList();
if (!pinList.length) {
this.log(
`No pin yet, add your first pin with ${chalk.blue('pin add')}`,
);
this.exit();
}
const { pin } = await prompt({
type: 'autocomplete',
name: 'pin',
message: 'Search a pin',
limit: 30,
choices: pinList.map(pin => `${pin.name} => ${pin.path}`),
});
const pinSelectedPath = pin.split(' => ')[1];
await execa('cd', [pinSelectedPath]);
} catch (error) {
console.log(error);
this.exit();
}
}
}
|
6fc3d23fcbb9337cd11e8e93cf00dccb2d46ee1f
|
TypeScript
|
samuba/pairing-timer
|
/src/common.ts
| 3
| 3
|
export const localStoragePut = (key: string, value: boolean) => localStorage.setItem(key, `${value}`)
export const localStorageGet = (key: string, defaultValue: boolean) => {
const val = localStorage.getItem(key)
if (val === null) return defaultValue
else return val == "true"
}
|
197c5b3cf44c19aed0dea067f7c1200e5bfc3a0d
|
TypeScript
|
icalder/holdingbuddy
|
/modules/controls.ts
| 2.96875
| 3
|
import { lightTheme, darkTheme } from './themes';
type ValueChangedHandler<T> = (old: T, cur: T) => void;
export class Controls {
private track: number = 0;
private trackChangedHandlers: ValueChangedHandler<number>[] = [];
private lefthand: boolean = false;
private lefthandChangedHandlers: ValueChangedHandler<boolean>[] = [];
private heading: number = 0;
private headingChangedHandlers: ValueChangedHandler<number>[] = [];
public useCompass = false;
public menuVisible = false;
addTrackChangedHandler(handler: ValueChangedHandler<number>) {
this.trackChangedHandlers.push(handler);
}
addLefthandChangedHandler(handler: ValueChangedHandler<boolean>) {
this.lefthandChangedHandlers.push(handler);
}
addHeadingChangedHandler(handler: ValueChangedHandler<number>) {
this.headingChangedHandlers.push(handler);
}
set lefthandCheckboxSelector(selector: string) {
document.querySelector(selector)?.addEventListener('change', (evt: Event) => {
const lefthand = (evt.target as HTMLInputElement).checked;
this.lefthandChangedHandlers
.forEach(h => h(this.lefthand, lefthand));
this.lefthand = lefthand;
});
}
set darkThemeCheckboxSelector(selector: string) {
document.querySelector(selector)?.addEventListener('change', (evt: Event) => {
const theme = ((evt.target as HTMLInputElement).checked) ? darkTheme : lightTheme;
for (let [k,v] of Object.entries(theme)) {
document.body.style.setProperty(k, v);
}
});
}
set compassCheckboxSelector(selector: string) {
document.querySelector(selector)?.addEventListener('change', (evt: Event) => {
this.useCompass = (evt.target as HTMLInputElement).checked;
});
}
set trackInputSelector(selector: string) {
document.querySelector(selector)?.addEventListener('change', (evt: Event) => {
// TODO more validation
const track = Number.parseInt((evt.target as HTMLInputElement).value);
this.trackChangedHandlers
.forEach(h => h(this.track, track));
this.track = track;
});
}
set headingInputSelector(selector: string) {
document.querySelector(selector)?.addEventListener('change', (evt: Event) => {
// TODO more validation
const heading = Number.parseInt((evt.target as HTMLInputElement).value);
this.headingChangedHandlers
.forEach(h => h(this.heading, heading));
this.heading = heading;
});
}
set compassDir(dir: number | null) {
if (this.useCompass && dir != null) {
const heading = Math.round(dir);
this.headingChangedHandlers
.forEach(h => h(this.heading, heading));
this.heading = heading;
}
}
};
|
c2ad93fdf3344a8bc810bb2600b8f46d1718b825
|
TypeScript
|
jsyang/360viewer
|
/src/index.ts
| 2.65625
| 3
|
import {
WebGLRenderer, Scene, Mesh, TextureLoader,
Texture, SphereBufferGeometry, MeshBasicMaterial,
PerspectiveCamera, Vector3, Math as THREEMath
} from 'three';
let camera, scene, renderer;
let isUserInteracting = false;
let lastClientX = 0;
let lastClientY = 0;
let lon = 0;
let lastLon = 0;
let lat = 0;
let lastLat = 0;
let phi = 0;
let theta = 0;
let material;
const textureLoader: any = new TextureLoader();
init();
animate();
function init() {
camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1100);
camera.target = new Vector3(0, 0, 0);
scene = new Scene();
const geometry = new SphereBufferGeometry(500, 60, 40) as any;
// invert the geometry on the x-axis so that all of the faces point inward
geometry.scale(-1, 1, 1);
material = new MeshBasicMaterial({map: new Texture(new Image())});
loadTexture();
scene.add(new Mesh(geometry, material));
renderer = new WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
addEventListener('hashchange', loadTexture);
addEventListener('mousedown', onMouseDown);
addEventListener('touchstart', onMouseDown);
addEventListener('mousemove', onMouseMove);
addEventListener('touchmove', onMouseMove);
addEventListener('touchend', onMouseUp);
addEventListener('mouseup', onMouseUp);
addEventListener('wheel', onMouseWheel);
addEventListener('resize', onResize);
addEventListener('keydown', onKeyDown);
}
function loadTexture() {
textureLoader.load(
location.hash.slice(1),
onLoadTexture,
null,
onErrorTexture
);
document.body.classList.add('spinner');
}
function onLoadTexture(texture) {
material.map.image = texture.image;
material.map.needsUpdate = true;
document.body.classList.remove('spinner');
}
function onErrorTexture() {
alert(`There was an issue loading ${location.hash.slice(1)}.`);
document.body.classList.remove('spinner');
}
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onMouseDown(event) {
event.preventDefault();
isUserInteracting = true;
const {touches, clientX, clientY} = event;
if (touches) {
lastClientX = touches[0].clientX;
lastClientY = touches[0].clientY;
} else {
lastClientX = clientX;
lastClientY = clientY;
}
lastLon = lon;
lastLat = lat;
}
function onMouseMove({clientX, clientY, touches}: any) {
if (isUserInteracting === true) {
if (touches) {
clientX = touches[0].clientX;
clientY = touches[0].clientY;
}
lon = (lastClientX - clientX) * 0.1 + lastLon;
lat = -(lastClientY - clientY) * 0.1 + lastLat;
}
}
function onMouseUp() {
isUserInteracting = false;
}
function onMouseWheel(event) {
const fov = camera.fov + event.deltaY * 0.05;
camera.fov = THREEMath.clamp(fov, 10, 75);
camera.updateProjectionMatrix();
}
function onKeyDown(event) {
const Key = {
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
};
const keycode = event.keyCode || event.which;
const step = 3;
switch (keycode) {
case Key.LEFT:
lon -= step;
break;
case Key.UP:
lat += step;
break;
case Key.RIGHT:
lon += step;
break;
case Key.DOWN:
lat -= step;
break;
}
}
function animate() {
requestAnimationFrame(animate);
update();
}
function update() {
lat = Math.max(-85, Math.min(85, lat));
phi = THREEMath.degToRad(90 - lat);
theta = THREEMath.degToRad(lon);
camera.target.x = 500 * Math.sin(phi) * Math.cos(theta);
camera.target.y = 500 * Math.cos(phi);
camera.target.z = 500 * Math.sin(phi) * Math.sin(theta);
camera.lookAt(camera.target);
renderer.render(scene, camera);
}
|
2e551908d57e880dfd77151a2722a780a42403b5
|
TypeScript
|
KkevinLi/nativescript-plugin-firebase
|
/src/app/auth/index.ts
| 2.671875
| 3
|
import * as firebase from "../../firebase";
import { FirebaseEmailLinkActionCodeSettings, LoginType, User } from "../../firebase";
export module auth {
export class Auth {
private authStateChangedHandler;
public currentUser: User | undefined;
public languageCode: string | null;
public onAuthStateChanged(handler: (user: User) => void): void {
this.authStateChangedHandler = handler;
console.log(">> added onAuthStateChanged handler");
};
public signOut(): Promise<any> {
return new Promise((resolve, reject) => {
firebase.logout()
.then(() => {
this.currentUser = undefined;
this.authStateChangedHandler && this.authStateChangedHandler();
resolve();
})
.catch(err => {
reject({
// code: "",
message: err
});
});
});
}
public unlink(providerId: string): Promise<any> {
return new Promise((resolve, reject) => {
firebase.unlink(providerId)
.then(user => {
this.currentUser = user;
resolve(user);
})
.catch(err => {
reject({
// code: "",
message: err
});
});
});
}
public signInWithEmailAndPassword(email: string, password: string): Promise<any> {
return new Promise((resolve, reject) => {
firebase.login({
type: LoginType.PASSWORD,
passwordOptions: {
email: email,
password: password
}
}).then((user: User) => {
this.currentUser = user;
this.authStateChangedHandler && this.authStateChangedHandler(user);
resolve({
additionalUserInfo: user.additionalUserInfo,
credential: null,
operationType: "SignIn",
user: user,
});
}).catch(err => {
let code = 'auth/exception';
let message = err.toString();
// Identify code for android. Note that the IOS implementation doesn't return a code.
if (message.includes('com.google.firebase.auth.FirebaseAuthInvalidCredentialsException')) {
code = 'auth/wrong-password';
} else if (message.includes('com.google.firebase.auth.FirebaseAuthInvalidUserException')) {
code = 'auth/user-not-found';
// Note that Android returns one exception for both user not found and invalid email whereas
// the web api returns seperate codes. Therefore the conditional below can never be satisfied
// for android.
// } else if (message.includes('com.google.firebase.auth.FirebaseAuthInvalidUserException')) {
// code = 'auth/invalid-email'
}
reject({
code: code,
message: message
})
});
});
}
public sendSignInLinkToEmail(email: string, actionCodeSettings: FirebaseEmailLinkActionCodeSettings): Promise<any> {
return new Promise((resolve, reject) => {
firebase.login({
type: LoginType.EMAIL_LINK,
emailLinkOptions: {
email: email,
url: actionCodeSettings.url,
}
}).then((user: User) => {
this.currentUser = user;
this.authStateChangedHandler && this.authStateChangedHandler(user);
resolve();
}, (err => {
reject({
// code: "",
message: err
});
}));
});
}
public createUserWithEmailAndPassword(email: string, password: string): Promise<User> {
return new Promise((resolve, reject) => {
firebase.createUser({
email: email,
password: password
}).then((user: User) => {
this.currentUser = user;
resolve(user);
}).catch(err => reject(err));
})
}
public updateEmail(newEmail: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
firebase.updateEmail(newEmail)
.then(() => resolve())
.catch(err => reject(err));
})
}
public updatePassword(newPassword: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
firebase.updatePassword(newPassword)
.then(() => resolve())
.catch(err => reject(err));
})
}
public sendPasswordResetEmail(email: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
firebase.sendPasswordResetEmail(email)
.then(() => resolve())
.catch(err => reject(err));
})
}
public signInAnonymously(): Promise<any> {
return new Promise((resolve, reject) => {
firebase.login({
type: LoginType.ANONYMOUS
}).then((user: User) => {
this.currentUser = user;
this.authStateChangedHandler && this.authStateChangedHandler(user);
resolve();
}, (err => {
reject({
// code: "",
message: err
});
}));
});
}
public fetchProvidersForEmail(email: string): Promise<any> {
return firebase.fetchProvidersForEmail(email);
}
public fetchSignInMethodsForEmail(email: string): Promise<any> {
return firebase.fetchSignInMethodsForEmail(email);
}
}
}
|
afdeb8c286197d785555b890af4ba28c6e705d50
|
TypeScript
|
yeongjet/demo_shopping_mall
|
/src/member/controller/member.controller.ts
| 2.515625
| 3
|
import { Controller, Get, Param } from '@nestjs/common'
import { Member } from '../interface/member.interface'
import { MemberService } from '../service/member.service'
import { MemberIdPipe } from '../pipe/member.id.pipe'
@Controller('member')
export class MemberController {
constructor(private readonly memberService: MemberService) {}
@Get()
async findAll(): Promise<Member[]> {
console.log('get all member')
return await this.memberService.findAll()
}
@Get(':id')
async findOne(@Param('id', new MemberIdPipe()) id): Promise<Member> {
console.log(`get member: ${id}`)
return await this.memberService.findOne(id)
}
}
|
910b05dae796ccf759308468869d6adc5133635f
|
TypeScript
|
brechtbilliet/typescript-mockify
|
/src/mock/spec/testClass/Bar.ts
| 2.5625
| 3
|
import {IBar} from "./IBar";
export class Bar implements IBar {
public foo: string;
public bar(): string {
return "just a string";
}
}
|
41a3be3483bfb060ccd885939c081d50f33ce7fd
|
TypeScript
|
fe2-gingggg/week11-q9-ts-react-github_profile-submit
|
/src/modules/todos/reducer.ts
| 3.125
| 3
|
import { createReducer } from 'typesafe-actions'
import { ADD_TODO, REMOVE_TODO, TOGGLE_TODO } from './actions'
import { TodosAction, TodosState } from './types'
const initialState: TodosState = []
// typesafe-actions 사용 x
// export default function todos(
// state = initialState,
// action: TodosAction,
// ): TodosState {
// switch (action.type) {
// case ADD_TODO:
// return state.concat({
// id: action.payload.id,
// text: action.payload.text,
// done: false,
// })
// case TOGGLE_TODO:
// return state.map(todo =>
// todo.id === action.payload ? { ...todo, done: !todo.done } : todo,
// )
// case REMOVE_TODO:
// return state.filter(todo => todo.id !== action.payload)
// default:
// return state
// }
// }
const todos = createReducer<TodosState, TodosAction>(initialState, {
[ADD_TODO]: (state, action) =>
state.concat({
...action.payload,
done: false,
}),
[REMOVE_TODO]: (state, action) =>
state.filter(todo => todo.id !== action.payload),
[TOGGLE_TODO]: (state, action) =>
state.map(todo =>
todo.id === action.payload ? { ...todo, done: !todo.done } : todo,
),
})
export default todos
|
c2eef4e75b766557702896c588863686b28842fe
|
TypeScript
|
organicinternet/oauth2-firebase
|
/src/utils/crypto.ts
| 2.890625
| 3
|
import * as crypto from "crypto";
import {Configuration} from "./configuration";
export class Crypto {
static encrypt = (text: string): string => {
const iv = crypto.randomBytes(16)
const cipher = crypto.createCipheriv(
"aes-256-cbc",
Buffer.from(Configuration.instance.crypto_auth_token_secret_key_32, "ascii"),
iv)
let encrypted = cipher.update(text)
encrypted = Buffer.concat([encrypted, cipher.final()])
return `${iv.toString("hex")}:${encrypted.toString("hex")}`
}
static decrypt = (text: string): string => {
const divided = text.split(":")
const iv = Buffer.from(divided.shift()!, "hex")
const encrypted = Buffer.from(divided.join(":"), "hex")
const decipher = crypto.createDecipheriv(
'aes-256-cbc',
Buffer.from(Configuration.instance.crypto_auth_token_secret_key_32, "ascii"),
iv);
let decrypted = decipher.update(encrypted);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
}
|
428bc358ccbdf2fd3278db772cc55b9e57dcf9b6
|
TypeScript
|
Ed-Fi-Exchange-OSS/Student360
|
/SMCISD.Student360.Web/ClientApp/src/app/components/data-grid/grid-helper.ts
| 2.71875
| 3
|
import { Grid, GridHeader } from "./data-grid.component";
export function calculateOrderByForRequest(grid: Grid) {
var result = [];
var sortedHeaders = grid.headers.slice().sort((a, b) => {
if (a.orderNumber > b.orderNumber)
return 1;
if (b.orderNumber > a.orderNumber)
return -1;
return 0;
});
sortedHeaders.forEach(header => {
if (header.order !== undefined) {
result.push({ column: header.columnName, direction: header.order ? 'descending' : 'ascending' });
}
});
return result;
}
export function camelCaseToPascalCase(camelCaseWord: string) {
return camelCaseWord.charAt(0).toUpperCase() + camelCaseWord.slice(1);
}
export function camelCaseToSentence(camelCaseWord: string) {
var result = camelCaseWord.replace(/([A-Z])/g, " $1");
return camelCaseToPascalCase(result);
}
export function calculateHeaders(grid: Grid): GridHeader[] {
var headers = [];
grid.columns.forEach(col => {
headers.push({ name: camelCaseToSentence(col), order: undefined, columnName: camelCaseToPascalCase(col), orderNumber: 0 });
});
return headers;
}
|
23e56f6d6a5fb7aa1a0db9c170705bee1d0b2b51
|
TypeScript
|
souppower/clean-architecture-todo-frontend
|
/src/interface/repository/todo.ts
| 2.84375
| 3
|
import { Todo } from "domain";
import { TodoRepository as ITodoRepository } from "usecase/repository";
import Persistor from "./persistor";
export default class TodoRepository implements ITodoRepository {
constructor(private persistor: Persistor) {}
findAll(): Todo[] {
return this.persistor.getAll();
}
add(text: string) {
const key = Math.floor(Math.random() * 10000);
const todo = {
id: key,
title: text
};
this.persistor.save(todo);
}
edit(id: string, text: string) {
const todo = this.persistor.get(`${id}`);
this.persistor.save({ ...todo, text });
}
delete(id: string) {
const todo = this.persistor.get(`${id}`);
this.persistor.delete(id);
}
deleteAll() {
this.persistor.clear();
}
}
|
44645967e55687b99f8135ab671f250cab4ff650
|
TypeScript
|
eatski/confusers_webFront
|
/model/logic.ts
| 3.046875
| 3
|
import { recur } from "../libs/util";
import { Address, Card, CardBody, CARDS, CardUse, Cell, Direction, DIRECTIONS, MoveCardBody, MoveCardUse, SYMBOLS, SymbolType, Token } from "./types";
const rnd = (num: number) => Math.floor(Math.random() * num);
const pickRnd = <T>(array: T[]): [T, T[]] => {
if(!array.length){
throw new Error("No item remained.")
}
const pickedIndex = rnd(array.length);
const picked = array[pickedIndex];
if (!picked) {
throw new Error("Never")
}
const newArray = array.filter((_, i) => i !== pickedIndex);
return [picked, newArray]
}
const numbersArray = (num:number):number[] => {
return [...Array(num)].map((_, i) => i)
}
export const STARTING_ISLANDS: Address[] = [{ x: 6, y: 6 }, { x: 7, y: 6 }, { x: 6, y: 7 }, { x: 7, y: 7 }];
const allowedProximityNum = 4;
export const createMap = (): Cell[] => {
const MAP_SIZE = numbersArray(14);
const addresses: Address[] = MAP_SIZE.reduce<Address[]>((acc, x) => MAP_SIZE.reduce<Address[]>((acc, y) => [...acc, { x, y }], acc), [])
const isAllowedProximity = (a: Address, b: Address): boolean => {
return (Math.abs(a.x - b.x) + Math.abs(a.y - b.y)) > allowedProximityNum
}
//FIXME: Shuffle??
const [_, symbols] = SYMBOLS.reduce<[Address[], [SymbolType, Address][]]>(([addresses, acc], cur) => {
const [picked, left] = pickRnd(addresses);
const removed = left.filter(
e => isAllowedProximity(e, picked)
)
return [removed, [...acc, [cur, picked]]]
}, [
addresses.filter((address) => !STARTING_ISLANDS.some(start => !isAllowedProximity(address, start))),
[]
]);
return addresses.map<Cell>(({ x, y }) => {
if (STARTING_ISLANDS.some(e => e.x === x && e.y === y)) {
return {
x,
y,
content: {
type: "ISLAND"
}
}
}
const symbolResult = symbols.find(([_, e]) => e.x === x && e.y === y);
if (symbolResult) {
const [symbol] = symbolResult;
return {
x,
y,
content: {
type: "SYMBOL",
symbol
}
}
}
return {
x,
y,
content: {
type: "SEA"
}
}
})
}
export const createCards: () => Card[] = () => {
const cardbodies = CARDS.reduce<CardBody[]>(
(acc,[card,number]) => [...acc,...(numbersArray(number).map(() => card))],
[]
)
return cardbodies.map((body,index) => ({id:index.toString(),body}))
}
export const excludeCards = (excludees:Card[]) => createCards().filter(card => !excludees.some(e => e.id === card.id))
export const pickCards = (cards:Card[],number:number): {picked:Card[],remained:Card[]} => {
return recur((next,cards,number) => {
if(number === 0) return {
picked:[],
remained:cards
}
const res = pickCard(cards);
const {picked,remained} = next(res.remained,number - 1)
return {
picked:[res.picked,...picked],
remained
}
},cards,number)
}
export const pickCard = (cards:Card[]): {picked:Card,remained:Card[]} => {
const [picked,remained] = pickRnd(cards);
return {picked,remained}
}
const toCellsMap = (cells: Cell[]): CellsMap => {
const generateKey = (cell: Address) => `${cell.x}-${cell.y}`;
const map = new Map<string, Cell>(cells.map<[string, Cell]>((cell) => [generateKey(cell), cell]))
return {
get(address) {
return map.get(generateKey(address)) || null
}
}
}
type CellsMap = {
get: (address: Address) => Cell | null
}
type MoveChunk = {
direction: Direction,
number: number
}
const simpleMove = (current: Address, direction: Direction): Address => {
const dirToXY: Record<Direction, Address> = {
"X+": { x: 1, y: 0 },
"X-": { x: -1, y: 0 },
"Y+": { x: 0, y: 1 },
"Y-": { x: 0, y: -1 }
}
const xy = dirToXY[direction];
return {
x: current.x + xy.x,
y: current.y + xy.y,
}
}
export type MoveResult = {
ok: true,
address: Address
} | {
ok: false,
cause: "TOKEN_IS_HERE" | "OUT_OF_CELLS" | "CANNOT_STOP" | "BLOCKED"
}
const move = (current: Address, chunks: MoveChunk[], cells: CellsMap, tokens: Token[]): MoveResult => {
const fn = (cur: Address, chunkNumber: number, number: number): MoveResult => {
const cell = cells.get(cur);
if (!cell) {
return {
ok: false,
cause: "OUT_OF_CELLS"
}
}
const chunk = chunks[chunkNumber];
if (!chunk) {
const stop =
(cell.content.type === "ISLAND" || cell.content.type === "SYMBOL")
&& !tokens.find(token => token.x === cell.x && token.y === cell.y)
return stop ? {
ok: true,
address: cur
} : {
ok: false,
cause: "CANNOT_STOP"
}
}
const passable = cell.content.type === "SEA"
if (!passable && (chunkNumber !== 0 || number !== 0)) {
return {
ok: false,
cause: "BLOCKED"
}
}
const next = simpleMove(cur, chunk.direction);
return chunk.number === number + 1 ?
fn(next, chunkNumber + 1, 0) :
fn(next, chunkNumber, number + 1)
}
return fn(current, 0, 0);
}
type AvailableDestinations = { use: MoveCardUse, next: Address }
export const getAvailableDestinations = (card: MoveCardBody, cells: Cell[], cur: Address, tokens: Token[]): AvailableDestinations[] => {
const map = toCellsMap(cells);
const opposeDirection: Record<Direction, Direction> = {
"X+": "X-",
"X-": "X+",
"Y+": "Y-",
"Y-": "Y+"
}
switch (card.type) {
case "Straight":
return DIRECTIONS.reduce<AvailableDestinations[]>((acc, dir) => {
const chunks: MoveChunk[] = [
{ direction: dir, number: card.number }
]
const res = move(cur, chunks, map, tokens);
if (res.ok) {
const use: CardUse = {
type: "Straight",
direction: dir
}
return [...acc, {
use, next: res.address
}]
}
return acc
}, [])
case "Curved":
return DIRECTIONS.reduce<AvailableDestinations[]>(
(acc, dir1) => {
return DIRECTIONS
.filter(dir2 => dir1 !== dir2 && dir1 !== opposeDirection[dir2])
.reduce<AvailableDestinations[]>((acc, dir2) => {
const chunks: MoveChunk[] = [
{ direction: dir1, number: card.number[0] },
{ direction: dir2, number: card.number[1] }
]
const res = move(cur, chunks, map, tokens);
if (res.ok) {
const use: CardUse = {
type: "Curved",
direction: [dir1, dir2]
}
return [...acc, {
use, next: res.address
}]
}
return acc
}, acc)
}
, [])
}
}
type __PickOne<Target, Extend> = Target extends Extend ? Target : never
export type CardUseWithBody<T extends CardBody["type"] = CardBody["type"]> = T extends never ? never : {
type: T,
body: __PickOne<CardBody, { type: T }>,
use: __PickOne<CardUse, { type: T }>,
}
export const toCardUseWithBody = (body: CardBody, use: CardUse): CardUseWithBody => {
if (body.type === "Straight" && use.type === "Straight") {
return { type: "Straight", use, body }
}
if (body.type === "Curved" && use.type === "Curved") {
return { type: "Curved", use, body }
}
if (body.type === "AnywhereBuild" && use.type === "AnywhereBuild") {
return { type: "AnywhereBuild", use, body }
}
throw new Error(`不正なカード使用です。 body:${body.type} use:${use.type}`);
}
export const moveWithCard = (card: CardUseWithBody<"Curved" | "Straight">, cur: Address, cells: Cell[], tokens: Token[]): Address => {
const map = toCellsMap(cells);
switch (card.type) {
case "Curved": {
const chunks: MoveChunk[] = [
{ direction: card.use.direction[0], number: card.body.number[0] },
{ direction: card.use.direction[1], number: card.body.number[1] }
]
const result = move(cur, chunks, map, tokens);
if (!result.ok) {
throw new Error(`Invalid Card Using. Cause:${result.cause}`)
}
return result.address;
}
case "Straight": {
const chunks: MoveChunk[] = [
{ direction: card.use.direction, number: card.body.number },
]
const result = move(cur, chunks, map, tokens);
if (!result.ok) {
throw new Error(`Invalid Card Using. Cause:${result.cause}`)
}
return result.address;
}
}
}
export const canPutIslandChecker = (cells: Cell[], tokens: Token[], yourCode: number): (address: Address) => boolean => {
const map = toCellsMap(cells);
const isSea = (cell: Cell): boolean => {
return cell.content.type === "SEA"
}
const isNotNextToIsland = (cell: Cell): boolean => {
return !DIRECTIONS.some(dir => {
const next = simpleMove(cell, dir);
const nextCell = map.get(next);
return nextCell && (nextCell.content.type === "ISLAND" || nextCell.content.type === "SYMBOL")
})
}
const isNearToken = (cell: Cell): boolean => {
return tokens.some(token => token.code !== yourCode && (Math.abs(token.x - cell.x) + Math.abs(token.y - cell.y)) <= 4)
}
const filtered = cells
.filter(isSea)
.filter(isNotNextToIsland)
.filter(isNearToken)
const filteredMap = toCellsMap(filtered)
return (address: Address): boolean => {
return !!filteredMap.get(address)
}
}
export const exportForTest = {
toCellsMap
}
|
8d52b65cb7070776cff70986a366fad5108242c9
|
TypeScript
|
gitalez/webAviatel
|
/src/app/services/info-pagina.service.ts
| 2.875
| 3
|
// al colocar root , ya no hace falta cargar este servicio en el app.module
// para que se vea el console.log o cualquier otra cosa
// tenemos que inyectar este servicio en algun componente
// por ejemplo lo inyectamos en el constructor del app.component.ts
// aqui leemos el json
// necesito un modulo http
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { InfoPagina } from '../interfaces/info-pagina.interface';
@Injectable({
providedIn: 'root'
})
export class InfoPaginaService {
info: InfoPagina = {};
equipo: any[] =[];
cargada = false;
// cuando se dispare este servicio , leera el json por http
constructor( private http: HttpClient) {
this.cargarInfo();
this.cargarEquipo();
}
private cargarInfo(){
console.log('servicio info-pagina listo');
this.http.get('assets/data/data-pagina.json')
.subscribe((resp: InfoPagina) => {
// resp ya no es un json , es un obj de js
this.cargada = true;
this.info = resp; // esto lo hacemos para poder utilizar la info de resp en otros lados
console.log(resp);
// este clg se usa cuando resp es de tipo any , cuando se lo asignamos a una interface ya se puede hacer
// resp.twitter
console.log(resp['twitter']); // de la respuesta me interesa la propiedad twitter
});
}
// no hicimos una inteerface de equipo
private cargarEquipo(){
this.http.get('https://producto-db-avia.firebaseio.com/equipo.json')
.subscribe((resp: any[]) => {
// resp ya no es un json , es un obj de js
this.equipo = resp // esto lo hacemos para poder utilizar la info de resp en otros lados
console.log(resp);
});
}
}
|
e81eca6457ba4a4ff16ad036ec9f5f47db303b5a
|
TypeScript
|
zxch3n/blog
|
/twice_linear/solve.ts
| 3.25
| 3
|
import { LinkedList } from "https://deno.land/x/mighty_promise@v0.0.1/mod.ts";
const ans: number[] = [1];
// 2 * x + 1
const a: LinkedList<number> = new LinkedList([3]);
// 3 * x + 1
const b: LinkedList<number> = new LinkedList([4]);
export function solve(index: number) {
if (ans.length > index) {
return ans[index];
}
while (ans.length <= index) {
let v: number;
if (a.tail! < b.tail!) {
v = a.pop()!;
} else if (a.tail! > b.tail!) {
v = b.pop()!;
} else {
v = b.pop()!;
a.pop();
}
const newAValue = v * 2 + 1;
const newBValue = v * 3 + 1;
a.pushFront(newAValue);
b.pushFront(newBValue);
ans.push(v);
}
return ans[index];
}
|
f258d7aec84a03358f26b64a64e5a0bdfc9ce026
|
TypeScript
|
seyfarash/side
|
/SideScroller/Scripts/states/menu.ts
| 2.671875
| 3
|
/// <reference path="../objects/gameobject.ts" />
/// <reference path="../objects/cloud.ts" />
/// <reference path="../objects/island.ts" />
/// <reference path="../objects/ocean.ts" />
/// <reference path="../objects/plane.ts" />
module states {
export function menuState() {
ocean.update();
plane.update();
}
export function Menu() {
var mailPilotText, instr: createjs.Text;
var play, instruction;
game = new createjs.Container();
ocean = new objects.Ocean(game);
plane = new objects.Plane(game);
//Game name and Title
mailPilotText = new createjs.Text("Space Ace", constants.GAME_FONT, constants.FONT_COLOUR);
mailPilotText.regX = mailPilotText.getBounds().width * 0.5;
mailPilotText.regY = 200;
mailPilotText.x = stage.canvas.width * 0.5;
mailPilotText.y = stage.canvas.height * 0.5;
game.addChild(mailPilotText);
//Play Button
play = new createjs.Bitmap("assets/images/play.png");
play.regX = play.getBounds().width * 0.5;
play.regY = 100;
play.x = stage.canvas.width * 0.5;
play.y = stage.canvas.height * 0.5;
game.addChild(play);
//Instructions Button
instruction = new createjs.Bitmap("assets/images/instruction.png");
instruction.regX = instruction.getBounds().width * 0.5;
instruction.regY = -30;
instruction.x = stage.canvas.width * 0.5;
instruction.y = stage.canvas.height * 0.5;
game.addChild(instruction);
//Click event listeners for two buttons below
play.addEventListener("click", function (e) {
stage.removeChild(game);
game.removeAllChildren();
game.removeAllEventListeners();
currentState = constants.PLAY_STATE;
changeState(currentState);
});
instruction.addEventListener("click", function (e) {
instr = new createjs.Text("Avoid asteroids, collect fuel!", constants.GAME_FONT, constants.FONT_COLOUR);
instr.regX = instr.getBounds().width * 0.5;
instr.regY = -100;
instr.x = stage.canvas.width * 0.5;
instr.y = stage.canvas.height * 0.5;
game.addChild(instr);
});
stage.addChild(game);
}
}
|
980867d2ee321e64888262cbafb3cb45a94e09ac
|
TypeScript
|
MrMory/boardgamegeekjsclient
|
/test/unit/client/BggClients.test.ts
| 2.59375
| 3
|
import fs from 'fs';
import path from 'path';
import { BggFamilyClient, BggThingClient } from '../../../src/client';
import { BggFamilyDtoParser, BggThingDtoParser } from '../../../src/dto';
import { TextFetcher } from '../../../src/fetcher';
import { GenericBuilder } from '../../../src/query';
import { IFamilyRequest, IThingRequest } from '../../../src/request';
import { XmlResponseParser } from '../../../src/responseparser';
const textResponseByEndpoint: Record<string, string> =
{
"https://www.boardgamegeek.com/xmlapi2/thing?id=174430": fs.readFileSync(path.join(__dirname, '..', '__fixtures__/response_thing_174430.xml'), 'utf-8'),
"https://www.boardgamegeek.com/xmlapi2/thing?id=999999": fs.readFileSync(path.join(__dirname, '..', '__fixtures__/response_notExisting_999999.xml'), 'utf-8'),
"https://www.boardgamegeek.com/xmlapi2/thing?id=35424,35421,234669,328182,322903&type=boardgame&versions=1&comments=1&ratingcomments=1&marketplace=1&stats=1&videos=1&page=1": fs.readFileSync(path.join(__dirname, '..', '__fixtures__/response_thing_multipleids.xml'), 'utf-8'),
"https://www.boardgamegeek.com/xmlapi2/family?id=8374": fs.readFileSync(path.join(__dirname, '..', '__fixtures__/response_family_8374.xml'), 'utf-8'),
// "https://www.boardgamegeek.com/xmlapi2/family?id=8374,22184,59218,1029,2076&type=boardgamefamily": fs.readFileSync(path.join(__dirname, '..', '__fixtures__/response_family_multipleids.xml'), 'utf-8')
}
const mockedFetcher: TextFetcher = new TextFetcher();
mockedFetcher.doFetch = jest.fn((query: string) => {
return new Promise((resolve) => {
resolve(textResponseByEndpoint[query]);
});
});
describe('Test clients with dependencies', () => {
describe('IBggThingClient', () => {
const thingClient: BggThingClient = new BggThingClient(new GenericBuilder<IThingRequest>(), mockedFetcher, new XmlResponseParser(), new BggThingDtoParser());
test('should query Thing endpoint and get an array of single item with id 174430', async () => {
const data = await thingClient.query({ id: 174430 });
const { id } = data[0];
expect(data.length).toBe(1);
expect(thingClient.fetcher.doFetch).toHaveBeenCalledTimes(1);
expect(id).toBe(174430);
});
test('should query Thing endpoint and get undefined if id not exists', async () => {
const data = await thingClient.query({ id: 999999 });
expect(data).toBe(undefined);
});
test('should query Thing endpoint whit multiple ids with filter of type', async () => {
const data = await thingClient.query({ id: [35424, 35421, 234669, 328182, 322903], type: "boardgame", versions: 1, comments: 1, ratingcomments: 1, marketplace: 1, stats: 1, videos: 1, page: 1 });
expect(data.length).toBe(2);
expect(data[0].id).toBe(35421);
expect(data[1].id).toBe(234669);
});
});
describe('IBggFamilyClient', () => {
const familyClient: BggFamilyClient = new BggFamilyClient(new GenericBuilder<IFamilyRequest>(), mockedFetcher, new XmlResponseParser(), new BggFamilyDtoParser());
test('should query Family endpoint and get an array of single item with id 8374', async () => {
const data = await familyClient.query({ id: 8374 });
const { id } = data[0];
expect(data.length).toBe(1);
expect(id).toBe(8374);
});
// test('should query Family endpoint whit multiple ids with filter of type', async () => {
// const data = await familyClient.query({ id: [8374, 22184, 59218, 1029, 2076], type: "boardgamefamily" });
// expect(data.length).toBe(3);
// expect(data[0].id).toBe(8374);
// expect(data[1].id).toBe(22184);
// expect(data[2].id).toBe(59218);
// });
});
});
|
029c1f350208a1cd48eda8ed4e65a043e475762e
|
TypeScript
|
DanielRamosAcosta/rxjs-marble-testing
|
/src/01-simple-interval/basic-map.ts
| 2.5625
| 3
|
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
export const numTwoTimes = (obs: Observable<number>) =>
obs.pipe(map((x: number) => x * 2))
|
171047dd72116835a0b8d0e79460137d4e8540ce
|
TypeScript
|
lsqaisen/micro-frontend
|
/login/src/components/form/checks.ts
| 3.265625
| 3
|
export function checkPassword(rule: any, value: any, callback: Function) {
let pattern1 = /[^\!\@\#\$\%\^\&\*\(\\\)\-\=\_\+\,\.\?\/\:\;\{\}\[\]\~\w]/g;
let pattern2 = /[a-z]+/;
let pattern3 = /[A-Z]+/;
let pattern4 = /[0-9]+/;
let pattern5 = /[\!\@\#\$\%\^\&\*\(\\\)\-\=\_\+\,\.\?\/\:\;\{\}\[\]\~]+/;
// let a = !(pattern2.test(value));
// let b = !(pattern3.test(value));
// let c = !(pattern4.test(value));
// let d = !(pattern5.test(value));
let count = 0;
if (pattern2.test(value)) {
count++;
}
if (pattern3.test(value)) {
count++;
}
if (pattern4.test(value)) {
count++;
}
if (pattern5.test(value)) {
count++;
}
if (!value) {
callback();
} else if (value.length < 8) {
callback('必须输入8个以上的字符');
} else if (pattern1.test(value)) {
callback('输入的字符不能为!@#$%^&*(\)-_=+,.?/:;{}[]~字母数字之外的');
} else if (count < 2) {
callback('输入包含大写,小写字母,数字,字符两种及以上');
} else {
callback();
}
}
|
959786d19c710d9e22fefe2345b33fcaef5f3996
|
TypeScript
|
MarcusViniciusCavalcanti/flex-template
|
/src/app/theme/component/icon/icon.ts
| 2.546875
| 3
|
import { FlexFontIconPackParams, FlexIconPackParams } from './icon-pack';
export interface FlexIconOptions {
[name: string]: any;
}
export interface FlexIcon {
getClasses(options?: FlexIconOptions): string[];
getContent(options?: FlexIconOptions): string;
}
export class FlexFontIcon implements FlexIcon {
constructor(protected name, protected content: any, protected params: FlexFontIconPackParams = {}) {}
getClasses(options?: FlexIconOptions): string[] {
const classes = [];
if (this.params.packClass) {
classes.push(this.params.packClass);
}
const name = this.params.iconClassPrefix ? `${this.params.iconClassPrefix}-${this.name}` : this.name;
classes.push(name);
return classes;
}
getContent(options?: FlexIconOptions): string {
return this.content;
}
}
export class FlexSvgIcon implements FlexIcon {
constructor(protected name, protected content: any, protected params: FlexIconPackParams = {}) {}
getClasses(options?: FlexIconOptions): string[] {
const classes = [];
if (this.params.packClass) {
classes.push(this.params.packClass);
}
return classes;
}
getContent(options?: FlexIconOptions): string {
return this.content;
}
}
|
067114da7434d24648da62d359a1f415eedf7458
|
TypeScript
|
AdithyaBhat17/stripe-metered-subscriptions
|
/client/src/utils/pricing.ts
| 2.609375
| 3
|
export const price = {
vm: 10,
o365: 5,
csp: {
aws: 1,
azure: 1,
gcp: 2,
},
};
export function totalPrice(
vm?: string,
o365?: string,
csp?: keyof typeof price["csp"] | undefined
) {
let vmCost = vm ? Number(vm) * price.vm : 0;
let o365Cost = o365 ? Number(o365) * price.o365 : 0;
let cspCost = !csp ? 0 : price.csp[csp];
return {
amount: vmCost + o365Cost,
metered: cspCost,
};
}
|
2e0e96dcc7d67a68d942b4645df3156914eb67ee
|
TypeScript
|
BM-laoli/TodoMaxRn
|
/src/modules/TestModule1/Store/Todo.ts
| 2.5625
| 3
|
import { action, observable } from 'mobx';
class TodoStore {
@observable
count = 1;
// 设置值
@action
setCount = () => {
this.count++;
}
@action
getCount = () => {
return this.count
}
// 如果有副作用的话请在这里处理
// 如果涉及到多播操作也在这里处理
}
export default TodoStore
|
406bcad4dc4b4cf7d20f47af7b719a5d4b676ae3
|
TypeScript
|
JarnDev/axis-todo
|
/src/shared/validators/businessRules.ts
| 2.84375
| 3
|
import { BadRequestException } from '@nestjs/common';
import { ValidDateRule } from './dateValidator';
export default function businessRulesValidator(name: string, date: string) {
if (name.length < 8 || name.length > 16) {
throw new BadRequestException('Name must have size 8-16');
}
const dateValidator = new ValidDateRule();
if (!dateValidator.validate(date)) {
throw new BadRequestException('Date should not be at weekend');
}
}
|
d2d41d32ff1d0b840be328cff5b95a0270e284f4
|
TypeScript
|
andrelmlins/previsao-ondas
|
/src/entities/State.ts
| 3.171875
| 3
|
import City from './City';
/**
* Estado
* @typedef {object} State
* @property {string} abreviatura - Abreviatura do estado
* @property {string} url - Url de detalhes do estado
* @property {array<City>} cidades - Lista de cidades do estado
*/
class State {
abreviatura: string;
url: string;
cidades?: City[];
constructor(abreviatura: string, url: string, cidades?: City[]) {
this.abreviatura = abreviatura;
this.url = url;
this.cidades = cidades;
}
}
export default State;
|
eeb9dd66aab757bab1d406219816323ed7b60243
|
TypeScript
|
mfarfanr/Angular-proj003
|
/src/app/app.component.ts
| 2.828125
| 3
|
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = "Angular-proj003";
degreesControl = new FormControl("32");
typeControl = new FormControl("F");
resultsControl = new FormControl("");
results: String = "";
constructor() {
// Make first call with default values
this.onClick();
}
onClick(): void {
// Check if degrees is a number
if ((this.degreesControl.value).trim().length == 0 || Number.isNaN(Number(this.degreesControl.value))) {
window.alert('Degrees must be numeric');
this.results = "N/A";
}
else {
// Chech for onversion method
switch (this.typeControl.value) {
// Convert Celsius to Farenheit
case 'C': {
this.results = String(((9 / 5) * Number(this.degreesControl.value) + 32).toFixed(2)) + "º F";
break;
}
// Convert Farenheit to Celsius
case 'F': {
this.results = String(((Number(this.degreesControl.value) - 32) * (5 / 9)).toFixed(2)) + "º C";
break;
}
default: {
break;
}
}
}
}
}
|
a9fed4272b4f94e6cb3330561031352ace4fc3b7
|
TypeScript
|
bgoonz/UsefulResourceRepo2.0
|
/MY_REPOS/WEB-DEV-TOOLS-HUB/MAIN/2_web-dev-util-pkg/mout/src/string/trim.ts
| 2.8125
| 3
|
import toString from '../lang/toString';
import WHITE_SPACES from './WHITE_SPACES';
import ltrim from './ltrim';
import rtrim from './rtrim';
/**
* Remove white-spaces from beginning and end of string.
*/
function trim(str, chars?: string[]) {
str = toString(str);
chars = chars || WHITE_SPACES;
return ltrim(rtrim(str, chars), chars);
}
export default trim;
|
2e8a48d68936b3db785af042b3a4740bf1f5337d
|
TypeScript
|
avakumov/yandex-map-taxi
|
/src/api/index.ts
| 2.921875
| 3
|
import _ from "lodash"
import { v1 as uuidv1 } from "uuid"
import { getDistance } from "../utils"
export interface CrewI {
crew_id: string
car_mark: string
car_model: string
car_color: string
car_number: string
driver_phone: string
driver_name: string
lat: number
lon: number
distance: number
}
interface GetTaxiResponseI {
code: number
descr: string
data: {
crews_info: Array<CrewI>
}
}
interface GetTaxiI {
source_time: string
addresses: Array<LocationI>
}
interface LocationI {
address: string
lat: number
lon: number
}
interface OrderI extends GetTaxiI {
crew_id: string
}
export interface OrderResponseI {
code: number
descr: string
data: {
order_id: string
order_req: any
}
}
async function getTaxi(getTaxi: GetTaxiI) {
const destLat = getTaxi.addresses[0].lat
const destLon = getTaxi.addresses[0].lon
function getCar() {
const lat = getRandomLat()
const lon = getRandomLon()
const distance = getDistance(lat, lon, destLat, destLon)
return {
crew_id: uuidv1(),
car_mark: _.sample(["Toyota", "VAZ", "Renault"]) || "",
car_model: _.sample(["Lachetti", "Supra", "Vesta"]) || "",
car_color: _.sample(["белый", "серый", "красный"]) || "",
car_number: _.sample(["D945HF", "A945HF", "C945HF"]) || "",
driver_name: _.sample(["Petrov", "Ivanov", "Putin"]) || "",
driver_phone: "7788",
lat: lat,
lon: lon,
distance: 10 * Math.round(distance / 10),
}
}
return new Promise<GetTaxiResponseI>((resolve, reject) => {
setTimeout(() => {
resolve({
code: 0,
descr: "OK",
data: {
crews_info: [getCar(), getCar(), getCar(), getCar()],
},
})
}, 200)
})
}
async function order(order: OrderI) {
return new Promise<OrderResponseI>((resolve, reject) => {
setTimeout(() => {
resolve({
code: 0,
descr: "OK",
data: {
order_id: uuidv1(),
order_req: order,
},
})
}, 1000)
})
}
function getRandomLat(): number {
return Math.random() * (56.87326729612429 - 56.83753847268933) + 56.83753847268933
}
function getRandomLon(): number {
return Math.random() * (53.28441339721679 - 53.19793546714898) + 53.19793546714898
}
// [56.87326729612429, 53.19793546714898]
// [56.83753847268933, 53.28441339721679]
export const api = { getTaxi, order }
|
968d948ea72347f5a4a8efe9f08c290b8c4b6a84
|
TypeScript
|
nadavsinai/session-heartbeat
|
/src/app/shared.interfaces.ts
| 3
| 3
|
export interface ISessionTransport {
clientId: string;
dispatchAction(action: any): void;
addEventListener(onMessage: (action: any) => void): void;
getPlayerID(): Promise<any>;
}
export class HeartBeatSessionAction {
readonly type = "HEARTBEAT";
constructor(public hasBeenActive: boolean) {
}
}
export class SessionTransportMock implements ISessionTransport {
createMockEvent: (action: any) => void;
private playerID: Promise<any> = Promise.resolve('testID');
constructor(public clientId: string) {
// here we're expected to work with the physical transport (eg. websocket) and resolve the playerID promise with the PlayerID once conncted and
// the server assigned us with a playerID;
}
dispatchAction(event: any): void {
const playerID = 'testID';
event.playerID = playerID;
console.log(event);
}
addEventListener(onMessage: (action: any) => void): void {
this.createMockEvent = onMessage;
}
public getPlayerID(): Promise<any> {
return this.playerID;
}
}
|
c60ef8e13c4e61b90d74492cf1ef6a7e3183126d
|
TypeScript
|
basedalexander/steam-trade-app
|
/server/application/services/session-provider.ts
| 2.765625
| 3
|
import * as uuid from 'node-uuid';
export interface ISession {
username: string;
}
export class SessionProvider {
static sessions: Map<string, ISession> = new Map<string, ISession>();
static get(id: string): ISession {
return SessionProvider.sessions.get(id);
}
static set(session: ISession): string {
let id: string = SessionProvider.generateId();
SessionProvider.sessions.set(id, session);
return id;
}
static generateId(): string {
return uuid.v4();
}
}
|
6fce52e68e3c4cf12547f889f802e475646d3817
|
TypeScript
|
dev-bas/CrazyCabman
|
/src/parser.ts
| 3.375
| 3
|
/**
* This class is part of the "Zorld of Wuul" application.
* "Zorld of Wuul" is a very simple, text based adventure game.
*
* This parser reads user input and tries to interpret it as an "Adventure"
* command. Every time it is called it reads a line from the terminal and
* tries to interpret the line as a two word command.
*
* The parser has a set of known command words. It checks user input against
* the known commands, and invokes a relevant method on the Game object.
*
* @author Michael K�lling, David J. Barnes and Bugslayer
* @version 2017.03.30
*/
class Parser {
input: HTMLInputElement;
private game: Game;
private commands : { [key: string]: Command} = {};
default : Default;
/**
* Creates the parser object.
*
* @param game the game object to prse commands for
* @param input the HTMLInputElement to parse the value from
*/
constructor(game: Game, input: HTMLInputElement) {
this.game = game;
this.input = input;
this.default = new Default(game);
this.commands["help"] = new Help(game);
this.commands["quit"] = new Quit(game);
this.commands["go"] = new Go(game);
this.commands["turn"] = new Turn(game);
this.commands["drive"] = new Drive(game);
this.commands["pick-up"] = new Pickup(game);
this.commands["drop-off"] = new Dropoff(game);
input.onkeyup = (e) => { // event handler function
if (e.keyCode == 13 && this.game.isOn) {
// Invoke parse method wehen user pressed enter
let command = this.input.value;
this.game.out.println(command);
this.parse(command.split(" "));
this.input.value = ""; // clears the input element
this.game.out.print(">");
}
}
}
/**
* Parses the specified words and invokes the corresponding method
* on the game object.
*
* @param words an array of words to parse
*/
parse(words: string[]): void {
let wantToQuit = false;
let params = words.slice(1);
if (words[0] === "")
{
return;
}
let command : Command;
command = this.commands[words[0]];
if (command == null)
{
command = this.default;
}
wantToQuit = command.execute(params);
if (wantToQuit) {
this.input.disabled = true;
this.game.gameOver();
}
}
}
|
76a46e17216f580c37cfe7a2579901f0962cb6ab
|
TypeScript
|
discoveranirban/TS-Sort-Design-Pattern
|
/src/index.ts
| 3.90625
| 4
|
import {Sorter} from './Sorter';
import {NumbersCollection} from './NumbersCollection';
import {CharacterCollection} from './CharacterCollection';
// // way 1
// class Sorter {
// constructor(public collection: number[]) {}
// sort(): void {
// const {length} = this.collection;
// for(let i=0;i<length;i++){
// for(let j=0;j<length-i-1;j++){
// if(this.collection[j]>this.collection[j+1]) {
// const temp = this.collection[j];
// this.collection[j]=this.collection[j+1];
// this.collection[j+1]=temp;
// }
// }
// }
// }
// }
// // way 2
// class Sorter2 {
// constructor(public collection: number[] | string) {}
// sort(): void {
// const {length} = this.collection;
// for(let i=0;i<length;i++){
// for(let j=0;j<length-i-1;j++){
// if(this.collection instanceof Array) { //TypeGuard for everything other than primitive values(string, boolean, number), referrecne to the constructor function
// if(this.collection[j]>this.collection[j+1]) {
// const temp = this.collection[j];
// this.collection[j]=this.collection[j+1];
// this.collection[j+1]=temp;
// }
// }
// if(typeof this.collection === 'string'){ //TypeGuard for primitive value
// }
// }
// }
// }
// }
// way 1 & 2
// const sorter = new Sorter([10,3,-5,0]);
// sorter.sort();
// console.log(sorter.collection);
// way 3 & 4
// const numbersCollection = new NumbersCollection([10,-3,-5,0]);
// const sorter = new Sorter(numbersCollection);
// sorter.sort();
// console.log(numbersCollection.data);
// const characterCollection = new CharacterCollection('Xaayb');
// const sorter = new Sorter(characterCollection);
// sorter.sort();
// console.log(characterCollection.data);
// way 5
const numbersCollection = new NumbersCollection([10,-3,-5,0]);
numbersCollection.sort();
console.log(numbersCollection.data);
|
fc909521825d217b5272ed5e06c18e9d42d09505
|
TypeScript
|
DimensionDev/MaskWebAuthn
|
/src/api/index.ts
| 2.578125
| 3
|
/// <reference path="./global.d.ts" />
import type {
PublicKeyAuthenticatorProtocol,
_FederatedAuthenticatorProtocol,
_PasswordAuthenticatorProtocol,
} from '../types/interface'
export interface CreateCredentialsContainerOptions {
publicKeyAuthenticator?: PublicKeyAuthenticatorProtocol
federatedAuthenticator?: _FederatedAuthenticatorProtocol
passwordAuthenticator?: _PasswordAuthenticatorProtocol
}
export function createCredentialsContainer(options: CreateCredentialsContainerOptions): CredentialsContainer {
const { federatedAuthenticator, passwordAuthenticator, publicKeyAuthenticator } = options
const supported: string[] = []
if (passwordAuthenticator) supported.push('password')
if (federatedAuthenticator) supported.push('federated')
if (publicKeyAuthenticator) supported.push('publicKey')
return {
async create(opts = {}) {
const fed = federatedAuthenticator ? opts.federated : undefined
const password = passwordAuthenticator ? opts.password : undefined
const pub = publicKeyAuthenticator ? opts.publicKey : undefined
if (fed) {
if (password || pub) throw NotSupported(supported)
// use federatedAuthenticator
} else if (password) {
if (fed || pub) throw NotSupported(supported)
// use passwordAuthenticator
} else if (pub) {
if (fed || password) throw NotSupported(supported)
return publicKeyAuthenticator!.create(pub as PublicKeyCredentialCreationOptions, opts.signal)
}
throw NotSupported(supported)
},
async get(opts = {}) {
const fed = federatedAuthenticator ? opts.federated : undefined
const password = passwordAuthenticator ? opts.password : undefined
const pub = publicKeyAuthenticator ? opts.publicKey : undefined
if (fed) {
if (password || pub) throw NotSupported(supported)
// use federatedAuthenticator
} else if (password) {
if (fed || pub) throw NotSupported(supported)
// use passwordAuthenticator
} else if (pub) {
if (fed || password) throw NotSupported(supported)
// use publicKeyAuthenticator
return publicKeyAuthenticator!.get(pub as PublicKeyCredentialRequestOptions, opts.signal)
}
throw NotSupported(supported)
},
async store(_cred) {
// Not supported by PublicKeyCredential. No need to implement.
throw NotSupported(supported)
},
async preventSilentAccess() {
throw new Error('Not implemented')
},
}
}
function NotSupported(supported: readonly string[]) {
const list = new (Intl as any).ListFormat('en').format(supported.map((x) => `'${x}'`))
return new DOMException(`Only exactly one of ${list} credential types are currently supported.`)
}
|
baf161648d4272ac580146c1215b0cb73c880b9b
|
TypeScript
|
JackBister/ts-roguelike
|
/src/Entity.ts
| 2.890625
| 3
|
import * as ROT from "rot-js";
import { GameMap } from "./GameMap";
import { RenderOrder } from "./RenderOrder";
export class Entity {
public static distanceTo(from: Entity, to: Entity) {
return Entity.distanceToPos(from.x, from.y, to.x, to.y);
}
public static distanceToPos(fromX: number, fromY: number, toX: number, toY: number) {
const dx = toX - fromX;
const dy = toY - fromY;
return Math.sqrt(dx * dx + dy * dy);
}
public static move(entity: Entity, dx: number, dy: number) {
entity.x += dx;
entity.y += dy;
}
public static moveAstar(mover: Entity, target: Entity, map: GameMap, entities: Entity[]) {
const pather = new ROT.Path.AStar(target.x, target.y, (x, y) => {
return !GameMap.isBlocked(map, x, y);
});
let hasStepped = false;
pather.compute(mover.x, mover.y, (x, y) => {
if (hasStepped
|| (x === mover.x && y === mover.y)
|| entities.some((e) => e.isBlocking && e.x === x && e.y === y)
) {
return;
}
hasStepped = true;
mover.x = x;
mover.y = y;
});
if (!hasStepped) {
this.moveTowards(mover, target.x, target.y, map, entities);
}
}
public static moveTowards(mover: Entity, targetX: number, targetY: number, map: GameMap, entities: Entity[]) {
let dx = targetX - mover.x;
let dy = targetY - mover.y;
const distance = Math.sqrt(dx * dx + dy * dy);
dx = Math.round(dx / distance);
dy = Math.round(dy / distance);
if (!GameMap.isBlocked(map, mover.x + dx, mover.y + dy)
&& !entities.some((e) => e.x === mover.x + dx && e.y === mover.y + dy)
) {
Entity.move(mover, dx, dy);
}
}
constructor(
public mapId: number,
public id: number,
public x: number,
public y: number,
public color: string,
public symbol: string,
public isBlocking: boolean,
public name: string,
public renderOrder: RenderOrder,
public isActive: boolean = true,
) { }
}
|
cb388822ab7b7ff9743ff7d638e2814136a3351d
|
TypeScript
|
dmitriypereverza/gatsby-blog
|
/src/libs/filter/rules/filterFieldIsEmptyArray.ts
| 2.53125
| 3
|
import { path } from "ramda";
import { FilterFuncInterface } from "libs/filter";
export const filterFieldIsEmptyArray = ({
filterField,
}: {
filterField: string;
}): FilterFuncInterface =>
function (filter: any) {
const filterValue = path(filterField.split("."), filter);
if (!Array.isArray(filterValue)) return undefined;
return filterValue.length === 0;
};
|
f17e4fa9db56035965682d363237ec6e72ef4148
|
TypeScript
|
typescript-fastcampus/rxjs-for-you
|
/lib/test-source.ts
| 2.75
| 3
|
import {from} from "rxjs/observable/from";
import {concatMap, delay, timeout} from "rxjs/operators";
import {of} from "rxjs/observable/of";
export interface Point {
id: string,
x: number,
y: number
}
const points1: Point[] = [
{id: '0', x: 1, y: 1}, {id: '1', x: 1, y: 2}, {id: '2', x: 1, y: 2}, {id: '3', x: 1, y: 3}, {id: '4', x: 3, y: 3},
{id: '5', x: 3, y: 4}, {id: '6', x: 4, y: 5}, {id: '7', x: 4, y: 5}, {id: '8', x: 5, y: 6}, {id: '9', x: 5, y: 7},
{id: '10', x: 6, y: 7}, {id: '11', x: 6, y: 7}, {id: '12', x: 7, y: 7}, {id: '13', x: 8, y: 7}, {id: '14', x: 8, y: 7},
{id: '15', x: 9, y: 8}, {id: '16', x: 9, y: 9}, {id: '17', x: 9, y: 8}, {id: '18', x: 9, y: 7}, {id: '19', x: 8, y: 7},
{id: '20', x: 7, y: 7}, {id: '21', x: 6, y: 7}, {id: '22', x: 5, y: 7}, {id: '23', x: 5, y: 6}, {id: '24', x: 5, y: 5},
{id: '25', x: 4, y: 4}, {id: '26', x: 1, y: 1}, {id: '27', x: 1, y: 1}, {id: '28', x: 1, y: 1}, {id: '29', x: 1, y: 1}
];
export const distance = 1.1;
export const source1 = from(points1).pipe(
concatMap((point: Point) => of(point).pipe(delay(1000)))
);
|
0d013912ae45b3ef77783a76f6e6e9b554c4a44c
|
TypeScript
|
microsoft/FluidFramework
|
/examples/apps/presence-tracker/src/FocusTracker.ts
| 2.53125
| 3
|
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { Signaler } from "@fluid-experimental/data-objects";
import { IEvent } from "@fluidframework/common-definitions";
import { TypedEventEmitter } from "@fluidframework/common-utils";
import { IContainer } from "@fluidframework/container-definitions";
import { ITinyliciousAudience } from "@fluidframework/tinylicious-client";
import { IMember } from "fluid-framework";
export interface IFocusTrackerEvents extends IEvent {
(event: "focusChanged", listener: () => void): void;
}
export interface IFocusSignalPayload {
userId: string;
focus: boolean;
}
export class FocusTracker extends TypedEventEmitter<IFocusTrackerEvents> {
private static readonly focusSignalType = "changedFocus";
private static readonly focusRequestType = "focusRequest";
/**
* Local map of focus status for clients
*
* @example
* ```typescript
* Map<userId, Map<clientid, hasFocus>>
* ```
*/
private readonly focusMap = new Map<string, Map<string, boolean>>();
private readonly onFocusSignalFn = (clientId: string, payload: IFocusSignalPayload) => {
const userId: string = payload.userId;
const hasFocus: boolean = payload.focus;
let clientIdMap = this.focusMap.get(userId);
if (clientIdMap === undefined) {
clientIdMap = new Map<string, boolean>();
this.focusMap.set(userId, clientIdMap);
}
clientIdMap.set(clientId, hasFocus);
this.emit("focusChanged");
};
constructor(
container: IContainer,
public readonly audience: ITinyliciousAudience,
private readonly signaler: Signaler,
) {
super();
this.audience.on("memberRemoved", (clientId: string, member: IMember) => {
const focusClientIdMap = this.focusMap.get(member.userId);
if (focusClientIdMap !== undefined) {
focusClientIdMap.delete(clientId);
if (focusClientIdMap.size === 0) {
this.focusMap.delete(member.userId);
}
}
this.emit("focusChanged");
});
this.signaler.on("error", (error) => {
this.emit("error", error);
});
this.signaler.onSignal(
FocusTracker.focusSignalType,
(clientId: string, local: boolean, payload: IFocusSignalPayload) => {
this.onFocusSignalFn(clientId, payload);
},
);
this.signaler.onSignal(FocusTracker.focusRequestType, () => {
this.sendFocusSignal(document.hasFocus());
});
window.addEventListener("focus", () => {
this.sendFocusSignal(true);
});
window.addEventListener("blur", () => {
this.sendFocusSignal(false);
});
container.on("connected", () => {
this.signaler.submitSignal(FocusTracker.focusRequestType);
});
this.signaler.submitSignal(FocusTracker.focusRequestType);
}
/**
* Alert all connected clients that there has been a change to a client's focus
*/
private sendFocusSignal(hasFocus: boolean) {
this.signaler.submitSignal(FocusTracker.focusSignalType, {
userId: this.audience.getMyself()?.userId,
focus: hasFocus,
});
}
public getFocusPresences(): Map<string, boolean> {
const statuses: Map<string, boolean> = new Map<string, boolean>();
this.audience.getMembers().forEach((member, userId) => {
member.connections.forEach((connection) => {
const focus = this.getFocusPresenceForUser(userId, connection.id);
if (focus !== undefined) {
statuses.set((member as any).userName, focus);
}
});
});
return statuses;
}
/**
* Returns focus status of specified client
*/
public getFocusPresenceForUser(userId: string, clientId: string): boolean | undefined {
return this.focusMap.get(userId)?.get(clientId);
}
}
|
9f07742b3f01f917d495b35fc3f3d627a313c812
|
TypeScript
|
NooMiD96/Rails
|
/CoreVueTypeScript/ClientApp/src/components/fetchdata/IFetchdata.ts
| 2.65625
| 3
|
export interface WeatherForecast {
id: string;
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
export interface IState {
forecasts: WeatherForecast[];
pending: Boolean;
}
|
5be92d52d46336ca81aa9d2bd5666896f940c35d
|
TypeScript
|
Ciaxur/Athens-Central
|
/src/ServerInterfaces/Requests.ts
| 2.953125
| 3
|
// Interface for RGB Data
export interface RGB {
r: number,
g: number,
b: number
}
// Available Node Actions
export type NodeAction = 'setPower' | 'blink' | 'rgb' | 'setCold' | 'setWarm';
// Node Event Execution Request
export interface NodeEventExec { // Event Execution Object
action: NodeAction,
value: RGB | number | boolean,
}
// Node Event Request
export interface NodeEventRequest {
type: 'event', // Request Type
address?: string, // Node Address
}
|
69fbb6a746c4f6bf17aa763dff2ee0e6a3c6633f
|
TypeScript
|
olegbevz/TaskTracker
|
/TaskTracker/ClientApp/app/models/task.ts
| 2.984375
| 3
|
import * as moment from "moment";
import { Moment, Duration } from "moment";
export type TaskStatus = 'active' | 'completed';
export type SortOrder = 'name' | 'priority' | 'added' | 'duration';
export class Task {
public id: number;
public name: string;
public description: string;
public priority: number;
public added: Moment;
public edited: Moment;
public duration: Duration;
public status?: TaskStatus;
public static fromJson(json: any): Task {
return <Task>{
...json,
duration: moment.duration(json.duration),
added: moment(json.added),
edited: moment(json.edited),
}
}
public static json(task: Task): any {
return {
...task,
duration: moment().startOf('day').add(task.duration).format("hh:mm:ss"),
added: task.added.format("YYYY-MM-DD hh:mm:ss"),
edited: task.edited.format("YYYY-MM-DD hh:mm:ss")
}
}
}
|
18cbad4df522f6cc2476751f255103c33b451282
|
TypeScript
|
sillsdev/web-languagedepot-api
|
/src/routes/api/v2/projects/[projectCode]/user/[username]/index.ts
| 2.515625
| 3
|
import type { RequestHandler } from '@sveltejs/kit';
import { Project, defaultRoleId } from '$lib/db/models';
import { dbs } from '$lib/db/dbsetup';
import { missingRequiredParam } from '$lib/utils/commonErrors';
import { onlyOne } from '$lib/utils/commonSqlHandlers';
import { addUserWithRoleByProjectCode, removeUserFromProjectByProjectCode } from '$lib/utils/db/usersAndRoles';
import { allowSameUserOrProjectManagerOrAdmin } from '$lib/utils/db/authRules';
// GET /api/v2/projects/{projectCode}/user/{username} - return user's role
// Security: must be user whose role is being looked up, a project manager on the project in question, or a site admin
export const GET: RequestHandler = async ({ params, url, request: { headers } }) => {
if (!params.projectCode) {
return missingRequiredParam('projectCode', 'URL');
}
if (!params.username) {
return missingRequiredParam('username', 'URL');
}
const db = url.searchParams.get('private') ? dbs.private : dbs.public;
const authResult = await allowSameUserOrProjectManagerOrAdmin(db, { params, headers });
if (authResult.status === 200) {
const dbQuery = Project.query(db)
.where('identifier', params.projectCode)
.withGraphJoined('members.[user, role]')
;
return onlyOne(dbQuery, 'projectCode', 'project code',
async (project: any) => {
const users = project.members.filter((member: any) => member.user.login === params.username && member.role && member.role.name);
return onlyOne(users, 'username', 'username', (member: any) => ({ status: 200, body: { user: member.user, role: member.role.name }}));
});
} else {
return authResult;
}
}
// HEAD /api/v2/projects/{projectCode}/user/{username} - is user a member of the project?
// Security: must be user whose role is being looked up, a project manager on the project in question, or a site admin
// Possible return codes:
// 200 if user is member of project (with any role)
// 404 if he/she is not, or if user or project not found
export const HEAD: RequestHandler = async (event) => {
const result = await GET(event)
return { ...result, body: {} }
}
// DELETE /api/v2/projects/{projectCode}/user/{username} - remove user from project
// Security: must be user being removed, a project manager on the project in question, or a site admin
export const DELETE: RequestHandler = async ({ params, url, request: { headers } }) => {
if (!params.projectCode) {
return missingRequiredParam('projectCode', url.pathname);
}
if (!params.username) {
return missingRequiredParam('username', url.pathname);
}
const db = url.searchParams.get('private') ? dbs.private : dbs.public;
const authResult = await allowSameUserOrProjectManagerOrAdmin(db, { params, headers });
if (authResult.status === 200) {
return removeUserFromProjectByProjectCode(db, params.projectCode, params.username);
} else {
return authResult;
}
}
// POST /api/v2/projects/{projectCode}/user/{username} - add user to project or update role
// Role should be given in POST body; either a string or integer, or a JSON object with a `role`, `roleId`, or `roleName` property
// If no role specified, defaults to Contributor
// Security: must be user being removed, a project manager on the project in question, or a site admin
export const POST: RequestHandler = async ({ params, url, request }) => {
if (!params.projectCode) {
return missingRequiredParam('projectCode', url.pathname);
}
if (!params.username) {
return missingRequiredParam('username', url.pathname);
}
const db = url.searchParams.get('private') ? dbs.private : dbs.public;
const authResult = await allowSameUserOrProjectManagerOrAdmin(db, { params, headers: request.headers });
if (authResult.status === 200) {
let roleName: string | number;
const text = await request.text();
let body;
try {
body = JSON.parse(text);
} catch (_) {
body = text;
}
if (body && typeof body === "string") {
roleName = body;
} else if (body && typeof body === "number") {
roleName = body;
} else if (body) {
roleName = body.role || body.roleId || body.roleName || defaultRoleId;
} else {
roleName = defaultRoleId;
}
return addUserWithRoleByProjectCode(db, params.projectCode, params.username, roleName);
} else {
return authResult;
}
}
|
bfe4bb77b3ea556631946af9d6b5936abcf0d235
|
TypeScript
|
Frikki/typed
|
/packages/list/src/update/types.ts
| 2.671875
| 3
|
import { List } from '../types'
export type UpdateArity3 = {
<A>(index: number, value: A, list: List<A>): Array<A>
(index: number): UpdateArity2
<A>(index: number, value: A): UpdateArity1<A>
}
export type UpdateArity2 = {
<A>(value: A, list: List<A>): Array<A>
<A>(value: A): UpdateArity1<A>
}
export type UpdateArity1<A> = {
(list: List<A>): Array<A>
}
|
86868d4f1dbaa93c371674704aa2548a3f7d9ef2
|
TypeScript
|
Knuddels/typescript-building-blocks
|
/packages/std/test/LocaleId.test.ts
| 2.640625
| 3
|
import { expect } from 'chai';
import { LocaleId } from '../src';
describe('LocaleId', () => {
it('basics', () => {
const en = new LocaleId('en');
expect(en.localeCode).to.equal('en');
expect(en.language).to.equal('en');
expect(en.country).to.be.undefined;
const enUS = new LocaleId('en', 'us');
expect(enUS.localeCode).to.equal('en-US');
expect(enUS.language).to.equal('en');
expect(enUS.country).to.equals('us');
});
it('locale code', () => {
expect(LocaleId.fromLocaleCode('en')!.localeCode).to.equal('en');
expect(LocaleId.fromLocaleCode('en-us')!.localeCode).to.equal('en-US');
expect(LocaleId.fromLocaleCode('eN-uS')!.localeCode).to.equal('en-US');
expect(LocaleId.fromLocaleCode('eN-uS-')).to.be.undefined;
});
it('predefined language ids', () => {
expect(LocaleId.deDE.localeCode).to.equal('de-DE');
expect(LocaleId.enUS.localeCode).to.equal('en-US');
});
});
|
5c2e840bd58ea3c66269258f3f6be94f42d82a74
|
TypeScript
|
torounit/firebase-chat
|
/src/store/messages/saga.ts
| 2.53125
| 3
|
import { call, cancelled, ForkEffect, put, take, takeEvery, takeLatest } from "redux-saga/effects"
import { Action } from "typescript-fsa"
import { Message } from "./state"
import { database } from "../../firebase"
import { receive } from "./actions"
import { eventChannel } from "redux-saga"
const messageChannel = (threadName: string = "general") => {
return eventChannel(emit => {
const messagesPath = `messages/${threadName}`
const ref = database.ref(messagesPath)
ref.on("value", snapshot => {
if (snapshot) {
const messagesMap: Object = snapshot.val() || {}
const messages = Object.entries(messagesMap).map(([id, value]) => ({ ...value, id }))
emit(messages)
}
})
return () => {
ref.off()
}
})
}
const subscribeMessages = function*(action: Action<string>) {
const threadName = action.payload
const channel = yield call(messageChannel, threadName)
try {
while (true) {
const messages = yield take(channel)
if (messages) {
yield put(receive(messages))
}
}
} finally {
if (yield cancelled()) {
channel.close()
}
}
}
const addMessage = function*(action: Action<{ thread: string; message: Message }>) {
const message = action.payload.message
const threadName = action.payload.thread
const messagesPath = `messages/${threadName}`
yield call(message => database.ref(messagesPath).push(message), message)
}
const removeMessage = function*(action: Action<{ thread: string; id: string }>) {
const id = action.payload.id
const threadName = action.payload.thread
const messagesPath = `messages/${threadName}`
if (id && threadName) {
yield call(id => {
return database
.ref(`${messagesPath}/${id}`)
.remove()
.catch((err: Error) => console.log(err.message))
}, id)
}
}
const effects: ForkEffect[] = [
takeLatest("SUBSCRIBE_MESSAGES", subscribeMessages),
takeEvery("ADD_MESSAGE", addMessage),
takeEvery("REMOVE_MESSAGE", removeMessage),
]
export default effects
|
dc856d93f57c71969de3102879213b329335e88b
|
TypeScript
|
ryo4004/rts
|
/client/src/Types/FileInfo.ts
| 2.8125
| 3
|
type SenderInfo = {
// Sender用プロパティ
// 読み込み状態
load: boolean
// receiverへfileInfo送信フラグ
preSendInfo: boolean
// ファイル送信フラグ
send: number | null
// packet追加用
idBuffer: Uint8Array
// packetCount
sendPacketCount: number
// 送受信処理終了フラグ
receiveComplete: boolean
// 送受信結果
receiveResult: boolean
}
export type SendFileInfo = {
// 基本情報
id: string
timestamp: number
add: boolean
delete: boolean
err: boolean
// ファイルサイズ情報
byteLength: number
sendTime: number
rest: number
// ファイル情報
lastModified: number
name: string
size: number
type: string
// file object (FileReaderで利用)
// 送信直前に開くのでここではファイルにアクセスしない
file: File
} & SenderInfo
export type ReceiveFileInfo = Omit<
SendFileInfo,
// keyof SenderInfo
'load' | 'preSendInfo' | 'send' | 'sendPacketCount' | 'idBuffer' | 'file'
> & {
// Receiver用プロパティ(Sender側でファイルリスト送信時に追加する)
receive: number | null
preReceiveInfo: boolean
receivePacketCount: number
}
|
5b14263c9e79b294973aa943ed2962ce3b96a29c
|
TypeScript
|
Youmenomi/catch-first
|
/src/index.ts
| 3.15625
| 3
|
export const CatchFirst = {
caught: 1,
done: 2,
} as const;
export function safeAwait<T>(promise: Promise<T>) {
return promise
.then((data) => {
return [null, data] as [null, T];
})
.catch((error) => {
return [error] as [unknown];
});
}
export function safeCall<T extends any[], R>(
thisArg: unknown,
value: (...args: T) => R,
...args: T
) {
try {
return [null, value.call(thisArg, ...args)] as [null, R];
} catch (error) {
return [error] as [unknown];
}
}
export function safeApply<T extends any[], R>(
thisArg: unknown,
value: (...args: T) => R,
args?: T
) {
try {
return [
null,
args === undefined ? value.apply(thisArg) : value.apply(thisArg, args),
] as [null, R];
} catch (error) {
return [error] as [unknown];
}
}
|
6e7ca70535ba113f2e2cd93a08282d8fb60f6aaa
|
TypeScript
|
origamirobot/inventory
|
/server/models/router/table.model.ts
| 3.09375
| 3
|
import { Chain } from './chain.model';
/**
* Tables are files that join similar actions. A table consists of several chains
*/
export class Table {
public chains: Chain[] = [];
constructor(init?: Partial<Table>) {
Object.assign(this, init);
}
}
/** The Filter table is the most frequently used one. It acts as a bouncer, deciding who gets in and out of your network. */
export class FilterTable extends Table {
/** The rules in this chain control the packets received by the server. */
public input: Chain;
/** This chain controls the packets for outbound traffic. */
public output: Chain;
/** This set of rules controls the packets that are routed through the server */
public forward: Chain;
constructor(init?: Partial<FilterTable>) {
super();
Object.assign(this, init);
}
}
/**
* This table contains NAT (Network Address Translation) rules for routing packets to networks that cannot be accessed directly.
* When the destination or source of the packet has to be altered, the NAT table is used. It includes the following chains:
*/
export class NatTable extends Table {
/** This chain assigns packets as soon as the server receives them. */
public prerouting: Chain;
/** Works the same as the output chain in the filter table. */
public output: Chain;
/** Rules in this chain allow making changes to packets after they leave the output chain. */
public postrouting: Chain;
constructor(init?: Partial<NatTable>) {
super();
Object.assign(this, init);
}
}
/** The Raw table is used to exempt packets from connection tracking. */
export class MangleTable extends Table {
/** This chain assigns packets as soon as the server receives them. */
public prerouting: Chain;
/** Works the same as the output chain in the filter table. */
public output: Chain;
constructor(init?: Partial<MangleTable>) {
super();
Object.assign(this, init);
}
}
/** Some versions of Linux also use a Security table to manage special access rules. */
export class SecurityTable extends Table {
/** The rules in this chain control the packets received by the server. */
public input: Chain;
/** This chain controls the packets for outbound traffic. */
public output: Chain;
/** This set of rules controls the packets that are routed through the server */
public forward: Chain;
constructor(init?: Partial<SecurityTable>) {
super();
Object.assign(this, init);
}
}
|
268ca6e49930ba2c992823a59ae2877b326d16c5
|
TypeScript
|
dragonmaster-alpha/smarthealth
|
/smarthealth-javascript/EntityUpdateList.d.ts
| 2.578125
| 3
|
import EntityType from './EntityType';
/**
* Transfer object created from Java object au.com.smarthealth.server.rest.data.EntityUpdateList
*
* A list of entities to update
*
* Generated by Maven. See Java class GenerateTypeScript.
*/
interface EntityUpdateList<T> {
/** List entries need to correspond to the EntityType */
entities: T[];
type: EntityType;
}
export default EntityUpdateList;
|
1867873e35e0816ffe20337820b0dfcfeb1314e0
|
TypeScript
|
ArkEcosystem/core
|
/packages/core-snapshots/src/repositories/abstract-repository.ts
| 2.671875
| 3
|
import { Repositories } from "@arkecosystem/core-database";
import { ObjectLiteral } from "typeorm";
interface WhereExpression {
where: string;
parameters: ObjectLiteral;
}
export class AbstractRepository<TEntity extends ObjectLiteral> extends Repositories.AbstractRepository<TEntity> {
public async fastCount(where?: WhereExpression): Promise<number> {
const totalCountQueryBuilder = this.createQueryBuilder().select("COUNT(*) AS total_count");
if (where) {
totalCountQueryBuilder.where(where.where, where.parameters);
}
const totalCountRow = await totalCountQueryBuilder.getRawOne();
return parseFloat(totalCountRow["total_count"]);
}
}
|
dc2690f14b0d320abece820bcd3d57751bc3573d
|
TypeScript
|
hararm/RxJs_Course
|
/main_07.ts
| 3.4375
| 3
|
import * as Rx from "rxjs";
import {createSubscriber} from "./util/util";
/*
function arrayMap(array, projection) {
const returnArray = [];
for (let item of array) {
const projected = projection(item);
returnArray.push(projected);
}
return returnArray;
}
arrayMap([1, 2, 3], a => a * a);
function arrayMergeMap(array, projection) {
const returnArray = [];
for (let item of array) {
const projectedArray = projection(item);
for(let projected of projectedArray) {
returnArray.push(projected);
}
}
return returnArray;
}
const albums = [
{title: "album 1", tracks: [{id: 1,title: "Track 1"}]},{title: "album 2", tracks: [{id: 2,title: "Track 1"}]},
{title: "album 3", tracks: [{id: 3,title: "Track 5"}]},{title: "album 4", tracks: [{id: 4,title: "Track 123"}]}
];
const tracksWrong = arrayMap(albums, album => album.tracks);
const tracksRight = arrayMergeMap(albums, album => album.tracks);
console.log(JSON.stringify(tracksWrong));
console.log(JSON.stringify(tracksRight));*/
/*Rx.Observable.range(2, 3)
.mergeMap(i => Rx.Observable.timer(i * 2000).map(() => `After ${i * 2} Seconds`))
.subscribe(createSubscriber("mergeMap"));*/
/*
Rx.Observable.fromPromise(getTracks())
.mergeMap((tracks: any) => Rx.Observable.from(tracks))
.subscribe(createSubscriber('tracks'));
function getTracks() {
return new Promise((resolve,reject) => {
setTimeout(()=> {
resolve(['track1','track2','track3']);
},1000);
});
}
*/
Rx.Observable.of('my query')
.do(()=> console.log('Querying'))
.mergeMap(a=>query(a))
.do(()=>console.log('After querying'))
.subscribe(createSubscriber('tracks'));
function query(value) {
return new Promise((resolve,reject) => {
setTimeout(()=> {
resolve(`THIS IS A VALUE ${value}`);
},1000);
});
}
|
2475aeac5a2a4764637464406c802130460f152d
|
TypeScript
|
juliethaguti/LaboratorioIII
|
/ClaseTypeScript/Perro.ts
| 3.265625
| 3
|
namespace animal{
export class Perro implements Animal{
private nombre:string = ""; //Por defecto público //si es privado hacer getter setter
//No existe la sobrecarga se haria el constructor con parametros y ?
constructor(nombre?:string){
if(nombre != undefined){
this.nombre = nombre;
}
}
hacerRuido():string{
return "Guau!!";
}
getNombre():string{
return this.nombre;
}
setNombre(nombre:string):void{
this.nombre = nombre;
}
}
}
|
caf8fc1ffb99c7c00100c5d549af2c216f764d3b
|
TypeScript
|
taiyokato/tsnode-template
|
/src/helpers/index.ts
| 2.609375
| 3
|
import * as crypto from 'crypto';
import { IRequestData } from '../interfaces/index';
export async function encodeUserData(userdata: IRequestData): Promise<string> {
try {
const shasum = crypto.createHash('sha1');
shasum.update(`${userdata.username}${userdata.password}`);
const digest: string = shasum.digest('hex');
return digest;
} catch (error) {
throw error;
}
}
|
a0a8c2d538ac35915fb687eb2dfaf618e257dc2f
|
TypeScript
|
tmalahie/neo4j-workbench
|
/electron/storage.ts
| 2.546875
| 3
|
import * as storage from "electron-json-storage";
export const getItem = <T>({ key, defaultVal }): Promise<T> => new Promise((resolve, reject) => {
storage.has(key, (error, hasKey) => {
if (error)
reject(error);
resolve(hasKey);
});
}).then((hasKey) => new Promise<T>((resolve, reject) => {
if (!hasKey)
resolve(defaultVal);
storage.get(key, (error, data) => {
if (error)
reject(error);
resolve(data as any);
});
}));
export const setItem = ({ key, value }) => new Promise((resolve) => {
storage.set(key, value, () => resolve(undefined));
});
export const deleteItem = ({ key, value }) => new Promise((resolve) => {
storage.remove(key, () => resolve(undefined));
});
|
657aa525de113dc04cd533ca12e75097d01d2a75
|
TypeScript
|
ilyachenko/Functional-TypeScript
|
/src/averageSalary_3.ts
| 3.390625
| 3
|
import Employee from './Employee';
type Predicate = (e: Employee) => boolean;
function and(predicates: Predicate[]): Predicate {
return (e) => predicates.every(p => p(e));
}
export default function averageSalary(employees: Employee[], conditions: Predicate[]): number {
let total = 0;
let count = 0;
employees.forEach((e) => {
if(and(conditions)(e)){
total += e.salary;
count += 1;
}
});
return (count == 0) ? 0 : total / count;
}
|
7b0078501520cdc392f21ca6f626cf6070ea6186
|
TypeScript
|
talohana/remote-client-extension
|
/src/content_script.ts
| 2.640625
| 3
|
import { Messages } from "./models/messages.model";
let fps;
const times = [];
(function fpsHandler() {
window.requestAnimationFrame(() => {
const now = performance.now();
while (times.length > 0 && times[0] <= now - 1000) {
times.shift();
}
times.push(now);
fps = times.length;
fpsHandler();
});
})()
chrome.runtime.onMessage.addListener(function (messageData, sender, sendResponse) {
if (messageData.type === Messages.FPS_RECORD_INIT) {
startRecording(messageData.fpsRecordTime / 1000);
}
});
function startRecording(fpsRecordTime) {
const fpsRecord = [];
const interval = setInterval(() => {
fpsRecord.push(fps);
if (fpsRecordTime <= fpsRecord.length / 2) {
postRecord(fpsRecord);
clearInterval(interval);
}
}, 500);
}
function postRecord(fpsRecord) {
chrome.runtime.sendMessage({ type: Messages.FPS_RECORD_DONE, fpsRecord }, console.log);
}
|
e9a78446e7b8aa197684044e22adfc7ee0c14701
|
TypeScript
|
ZeeEssDoubleU/mathe
|
/src/utils/abbreviate.ts
| 2.984375
| 3
|
export const abbreviate = (input: string): string => {
switch (input) {
case "GRAMS":
return "g"
case "KILOGRAMS":
return "kg"
case "OUNCES":
return "oz"
case "POUNDS":
return "lb"
default:
return input
}
}
|
c97d62a6ff845d90f16d9c06361e26bdf3c9f137
|
TypeScript
|
kidchenko/angular-typescript
|
/src/common/services/websiteService.ts
| 2.515625
| 3
|
/// <reference path="../../_app.d.ts"/>
module WebsiteService {
export class WebsiteItems {
static $inject = ['localStorage'];
constructor(public localStorage: StorageService.localStorage) {
}
// website model
website_items = this.localStorage.get("website_items") || [];
getItems(): Array<any> {
return this.website_items;
}
// add element
add(element: string, index: number): void {
var element_object = {
dom_element:element,
value:"<empty text>"
};
this.website_items.splice(index+1, 0, element_object);
}
// delete element
remove(index: number): void {
this.website_items.splice(index, 1);
}
save(newValue: any): void {
this.localStorage.set("website_items",newValue);
}
}
}
angular
.module('WebsiteService',[])
.service('WebsiteItems', WebsiteService.WebsiteItems);
|
0971f4db42a4a2030d312356fba1dae43cf7621f
|
TypeScript
|
quantumalexa/BookWorks
|
/maxTS/courseWorkspace/typescript-complete-course/app_section5.ts
| 3.84375
| 4
|
// class Person {
// name: string;
// private type: string = 'default'; //from within the object
// protected age: number = 27; // accessible from inheritors of this class
//
// constructor(name: string, public username: string) {
// this.name = name;
// }
// printAge() {
// console.log(this.age);
// this.setType("old guy");
// }
//
// setType(type:string) {
// this.type = type;
// console.log(this.type);
// }
// }
//
// const person4 = new Person("Max", "max");
// console.log(person4);
// console.log(person4.name, person4.username);
//
// person4.setType("Cool guy");
// person4.printAge();
//
//
// //Inheritance
// class Maximillian extends Person {
// //name = "Maximillian";
//
// constructor(username:string) {
// super("Maximillian", username);
// this.age = 31;
// }
// }
//
// const max = new Maximillian("max");
// console.log(max);
//
// //GETTERS & SETTERS
// class Plant {
// private _species: string = "Def";
// get species() {
// return this._species;
// }
// set species(value: string){
// if(value.length > 3) {
// this._species = value;
// }
// else{
// this._species = "Default"
// }
// }
// }
//
// const plant = new Plant();
// console.log(plant.species);
// plant.species = "ab";
// console.log(plant.species);
// plant.species = "Philofilus";
// console.log(plant.species);
//
// //STATIC PROPERIES AND METHODS
// class Helpers {
// static PI: number = 3.14;
// static calcCircumference(diameter:number):number {
// return this.PI * diameter;
// }
// }
//
// console.log(2 * Helpers.PI);
// console.log(Helpers.calcCircumference(8));
//
//
// //Abstract Classes
// abstract class Project {
// projectName: string = "Default";
// budget: number = 1000;
//
// abstract changeName(name:string):void;
//
// //in child class
// calcBudget() {
// return this.budget * 2;
// }
// }
//
// class ITProject extends Project {
// changeName(name: string): void {
// this.projectName = name;
// }
// }
//
// let newProject = new ITProject();
// console.log(newProject);
// newProject.changeName("Super IT Project");
// console.log(newProject);
//
//
// // private constructors
// class OnlyOne {
// private static instance: OnlyOne;
// private constructor(public readonly name: string) {}
//
// static getInstance(){
// if(OnlyOne.instance){
// console.log(`got it`);
// }
// if(!OnlyOne.instance){
// OnlyOne.instance = new OnlyOne('The Only One');
// console.log("new one");
// }
// return OnlyOne.instance;
// }
// }
//
// //let wrong = new OnlyOne('The Only One');
// let right = OnlyOne.getInstance();
// console.log(right.name);
// //right.name = "something else";
// let rightToo = OnlyOne.getInstance();
// console.log(rightToo.name);
|
6a183975afa11306a103742569e7ef540d8147f5
|
TypeScript
|
hieuxlu/typescript-questions
|
/bowling/bowling.ts
| 3.046875
| 3
|
import { Frame, FRAME_COUNT } from './frame';
export default class Bowling {
/**
* Acknowledgement: I have never played bowling
*/
constructor(private rolls: number[]) {}
score(): number {
if (!this.rolls) {
throw new Error('Rolls can not be null or empty');
}
let index = 0;
let frameIdx = 0;
let frames: Frame[] = [];
while (index < this.rolls.length) {
if (frameIdx > FRAME_COUNT - 1) {
throw new Error('Should not be able to roll after game is over');
}
const frame = Frame.getFrame(this.rolls, index, frameIdx === FRAME_COUNT - 1);
frame.forceValidation();
frames.push(frame);
frameIdx++;
index += frame.rolls.length;
}
if (frames.length < FRAME_COUNT) {
throw new Error('Score cannot be taken until the end of the game');
}
return frames.reduce((a, b) => a + b.point, 0);
}
}
|
681a000380836c3c51f1aa894c5a5c84756910a9
|
TypeScript
|
David--K/WED2-testat
|
/src/services/todoStore.ts
| 2.6875
| 3
|
import Datastore = require('nedb');
import Todo = require('../models/todo');
const db = new Datastore({ filename: './data/todo.db', autoload: true });
class TodoStore {
add(todo: Todo, callback: (err: Error | null, newDoc: Todo) => void) {
console.log('add todo');
db.insert(todo, function (err: Error | null, newDoc: Todo) {
console.log('succesfully inserted Todo with id: ' + newDoc._id);
if (callback) {
callback(err, newDoc);
}
});
}
update(id: string, todo: Todo, callback: (err: Error | null, success: boolean) => void) {
db.update({ _id: id }, todo, {}, function (err, numDocs) {
callback(err, numDocs === 1);
});
}
get(id: string, callback: (err: Error | null, doc: Todo) => void) {
db.findOne({ _id: id }, function (err, doc) {
callback(err, doc);
});
}
all(
callback: (err: Error | null, newDoc: Todo[]) => void,
sortBy: string,
ascending: boolean,
onlyFinished: boolean,
) {
const filter = onlyFinished ? { finished: true } : {};
db.find(filter)
.sort({ [sortBy]: ascending ? 1 : -1 })
.exec(function (err: Error | null, docs: Todo[]) {
callback(err, docs);
});
}
}
export = new TodoStore();
|
e2c06e3dae7884ef5a5cad8f55d226e0a8e944db
|
TypeScript
|
TOnodera/chatterman
|
/app/server/Domain/Message/MessageEditor.ts
| 2.765625
| 3
|
import AuthenticationException from '../../Exception/AuthenticationException';
import Exception from '../../Exception/Exception';
import Datetime from '../../Utility/Datetime';
import IMessageRepository from './Interface/IMessageRepository';
import MessageRepositoryFactory from './Factory/MessageRepositoryFactory';
import IUser from '../User/Interface/IUser';
import IMessageEditor from './Interface/IMessageEditor';
/**
* 既存メッセージを扱うクラス
*/
class MessageEditor implements IMessageEditor {
private repository: IMessageRepository;
message_id: string;
message: string;
user: IUser;
room_id: string;
options?: Options;
created_at: Datetime;
constructor(message_id: string, message: string, user: IUser, room_id: string, created_at: Datetime, options?: Options) {
this.repository = MessageRepositoryFactory.create();
this.message_id = message_id;
this.message = message;
this.user = user;
this.room_id = room_id;
this.created_at = created_at;
this.options = options;
}
async edit(newMessage: string): Promise<boolean> {
if ((await this.isEditable(this)) == false) {
throw new AuthenticationException('このメッセージを編集できません。');
}
this.message = newMessage;
return await this.repository.save(this);
}
async isEditable(message: IMessageEditor): Promise<boolean> {
return await this.repository.hasMessage(message);
}
async delete(): Promise<boolean> {
if (!this.message_id) {
throw new Exception('message_idがない状態でdelete()は呼び出せません。');
}
if ((await this.isEditable(this)) == false) {
throw new AuthenticationException('このメッセージを編集できません。');
}
return await this.repository.delete(this.message_id);
}
}
export default MessageEditor;
|