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
|
|---|---|---|---|---|---|---|
6beb209d92f78b15a522c143a1e4525d2a78e1a1
|
TypeScript
|
keyur2714/E_7_Angular_8
|
/DirectiveDemo/src/app/directives/my-directive.ts
| 2.515625
| 3
|
import { Directive, OnInit, ElementRef, Input } from '@angular/core';
@Directive({
selector : '[app-my-directive]'
})
export class MyDirective implements OnInit{
@Input()
color : string = 'orange';
constructor(private elementRef : ElementRef){
console.log("App My Directive Object Created...!");
}
ngOnInit(){
console.log(this.elementRef.nativeElement);
this.elementRef.nativeElement.style.color = this.color;
}
}
|
e273b8d9dc4a665374a33b76feacc47d713e996f
|
TypeScript
|
Nemog17/today
|
/packages/shared/utils/uuid.ts
| 2.859375
| 3
|
function uuid(): string {
function generate(char: string): string {
const r = (Math.random() * 16) | 0;
return (char === 'x' ? r : (r & 0x3) | 0x8).toString(16);
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, generate);
}
export default uuid;
|
5adeeed1948c4c8c391369f0941c3cfc6a4258f4
|
TypeScript
|
bitclave/base-client-js
|
/src/repository/source/http/SignInterceptor.ts
| 2.5625
| 3
|
import { MessageSigner } from '../../../utils/keypair/MessageSigner';
import { HttpInterceptor } from './HttpInterceptor';
import { InterceptorCortege } from './InterceptorCortege';
import SignedRequest from './SignedRequest';
export enum ExcludeSignatureType {
EXCLUDE_SIG = 'EXCLUDE_SIG',
EXCLUDE_WRAPPER = 'EXCLUDE_WRAPPER'
}
export const ExcludeSignature = (exclude: ExcludeSignatureType = ExcludeSignatureType.EXCLUDE_SIG) =>
(target: object) => Reflect.defineMetadata(SignInterceptor.DECORATOR_KEY, exclude, target);
export default class SignInterceptor implements HttpInterceptor {
public static DECORATOR_KEY = 'decorator:ExcludeSignature';
private messageSigner: MessageSigner;
constructor(messageSigner: MessageSigner) {
this.messageSigner = messageSigner;
}
public async onIntercept(cortege: InterceptorCortege): Promise<InterceptorCortege> {
if (cortege.data) {
let sig = '';
let publicKey = '';
const metaKeys = cortege.originalData && Reflect.getMetadataKeys(cortege.originalData.constructor);
if (!metaKeys || metaKeys.length <= 0 || metaKeys.indexOf(SignInterceptor.DECORATOR_KEY) <= -1) {
sig = await this.messageSigner.signMessage(JSON.stringify(cortege.data));
publicKey = this.messageSigner.getPublicKey();
} else {
const metaData = Reflect.getMetadata(SignInterceptor.DECORATOR_KEY, cortege.originalData!.constructor);
if (ExcludeSignatureType[metaData as string] === ExcludeSignatureType.EXCLUDE_WRAPPER) {
return cortege;
}
}
cortege.data = new SignedRequest(
cortege.data as object,
publicKey,
sig,
0
);
}
return cortege;
}
}
|
5adcb796aa848946ffd636243a97ed315f774f1a
|
TypeScript
|
pytime-osu/web
|
/src/store/types.ts
| 2.609375
| 3
|
export const UPDATE_SEARCH = 'UPDATE_SEARCH';
interface UpdateSearchAction {
type: typeof UPDATE_SEARCH
terms: string[]
}
export type ActionTypes = UpdateSearchAction;
export interface RootState {
searchTerms: string[];
}
|
84e480f752e25d4dbc6811fcca5548b487242fdb
|
TypeScript
|
landrito/pandemic-dot-cards
|
/src/components/setup-pandemic/reducer.ts
| 2.59375
| 3
|
import { chooseInfectionCard } from './actions/choose-infection-cards';
import { chooseMonth } from './actions/choose-month';
import { chooseMonthPhase } from './actions/choose-month-phase';
import { nextStep } from './actions/next-step';
import { previousStep } from './actions/previous-step';
import { BASE_SETUP_STATE, SetupPandemicState } from './model';
import { SetupPandemicAction } from './setup-pandemic-action';
export function reducer(
s: SetupPandemicState | undefined,
a: SetupPandemicAction
): SetupPandemicState {
s = s || BASE_SETUP_STATE;
switch (a.type) {
case 'setup-pandemic/choose-infection-card':
return chooseInfectionCard(s, a);
case 'setup-pandemic/choose-month-phase':
return chooseMonthPhase(s, a);
case 'setup-pandemic/choose-month':
return chooseMonth(s, a);
case 'setup-pandemic/next-step':
return nextStep(s);
case 'setup-pandemic/previous-step':
return previousStep(s);
default:
((_: never) => void _)(a);
}
return s;
}
|
acdf9a7c144f39f2d33e98f74995a77064a57afb
|
TypeScript
|
Raz1990/Chat_React_Redux_SQL
|
/src/Redux/reducers.ts
| 2.625
| 3
|
import {AnyAction} from "redux";
import {AppState} from "./../Interfaces/appState";
import {User} from "../Classess/User";
import {Group} from "../Classess/Group";
import ICanChat from "../Interfaces/ChatEntity";
const handlers = {
"SET_CURRENT_USER": setCurrentUser,
"SET_ALL_USERS": setAllUsers,
"SET_ALL_GROUPS": setAllGroups,
"SET_ALL_ENTITIES": setAllEntities,
"SET_IN_CHAT_WITH":setInChatWith,
"SET_CHAT_ELEMENT":setChatElement,
"SET_IN_CHAT_WITH_&_SET_CHAT_ELEMENT": setInChatWithAndElement,
"REFRESH": refresh,
};
export function rootReducer(state: AppState, action: AnyAction): AppState {
const handler = handlers[action.type];
if(handler) {
return handler(state, action.value);
}
return state;
}
function refresh(state: AppState) {
return {
...state,
}
}
function setCurrentUser(state: AppState, user: User): AppState {
return {
...state,
currentUser: user,
}
}
function setAllUsers(state: AppState, users: User[]): AppState {
return {
...state,
allUsers: users,
}
}
function setAllGroups(state: AppState, groups: Group[]): AppState {
return {
...state,
allGroups: groups,
}
}
function setAllEntities(state: AppState, entities: ICanChat[]): AppState {
return {
...state,
allEntities: entities,
}
}
function setInChatWith(state: AppState, chatElement: ICanChat): AppState {
return {
...state,
inChatWith: chatElement,
}
}
function setChatElement(state: AppState, element: HTMLElement): AppState {
return {
...state,
chatElement: element,
}
}
function setInChatWithAndElement(state: AppState, elementAndEntity): AppState {
return {
...state,
inChatWith: elementAndEntity.entity,
chatElement: elementAndEntity.element,
}
}
|
34a905ba219f64ace5d6885f270536fa5d6be13c
|
TypeScript
|
burlistic/perth-code-dojo-3-garden
|
/Garden/TypeScriptHTMLApp1/modernLowMaintenanceGarden.ts
| 2.640625
| 3
|
/// <reference path="Garden.ts" />
class ModernLowMaintenanceGarden extends Garden
{
artificialLawns: ArtificialLawn[];
constructor(width: number, height: number, soilType: string, lastWatered: string) {
super(width, height, soilType, lastWatered);
this.artificialLawns = new Array<ArtificialLawn>();
}
addArtificalLawns(artificalLawn: ArtificialLawn) {
this.artificialLawns.push(artificalLawn);
}
}
|
f139b2257ae80f78d1be8c8e1889d68711add877
|
TypeScript
|
shivetay/react_typescript
|
/src/redux/Actions.ts
| 2.5625
| 3
|
import { ActionType } from './ActionTypes';
interface SearchReposAction {
type: ActionType.SEARCH_REPO;
}
interface SearchRepoActionSuccess {
type: ActionType.SEARCH_REPO_SUCCESS;
payload: string[];
}
interface SearchReposActionError {
type: ActionType.SEARCH_REPO_ERROR;
payload: string;
}
export type Action =
| SearchReposAction
| SearchRepoActionSuccess
| SearchReposActionError;
|
b8d958ee5a9ceb0643ed6f6a349c9c6dd94f6933
|
TypeScript
|
uedsonreis/ionic_react_todo_list
|
/src/domain/todo.list.ts
| 3.09375
| 3
|
import { Task } from './task';
export const CREATE = 'CREATE';
export const UPDATE = 'UPDATE';
export const DELETE = 'DELETE';
type Action = { type: string, payload: Task };
export const creators = {
createCreate: (task: Task) => ({ type: CREATE, payload: task }),
createUpdate: (task: Task) => ({ type: UPDATE, payload: task }),
createDelete: (task: Task) => ({ type: DELETE, payload: task }),
};
const initialState: Task[] = [
{ id: 1, text: 'Desenvolvimento de Apps Mobile', isDone: false },
{ id: 2, text: 'Ferramentas, tecnologias e recomendações', isDone: false },
{ id: 3, text: 'Principais características do React Native', isDone: false },
{ id: 4, text: 'Criar e rodar um projeto com Expo', isDone: false },
{ id: 5, text: 'State e Props', isDone: false },
{ id: 6, text: 'Componentização', isDone: false },
{ id: 7, text: 'Utilizando o React Native Elements', isDone: false },
];
export function reducer(todoList = initialState, action: any) {
const { type, payload } = action as Action;
switch(type) {
case CREATE: {
const lastId = (todoList.length > 0) ? todoList[todoList.length-1].id! : todoList.length
const task = { ...payload, id: lastId + 1 };
return [ ...todoList, task ];
}
case UPDATE: {
const task: Task | undefined = todoList.find(todo => todo.id === payload.id);
if (task) {
if (task.text) task.text = payload.text;
task.isDone = payload.isDone;
return [...todoList];
}
return todoList;
};
case DELETE: {
return todoList.filter(todo => todo.id !== payload.id);
};
default: return todoList;
}
}
|
65add42f99d282be8735984f298def8eb6222e8e
|
TypeScript
|
NeedsSoySauce/Random-Bookmark
|
/src/storage.ts
| 2.71875
| 3
|
import { AnyValue, BookmarkSelectionMethod, HistoryRetentionPeriod, IconStyle } from './types.js';
export interface HistoryItem {
date: string;
url: string;
title: string;
}
export interface SyncStorageState {
includeSubfolders: boolean;
openInNewTab: boolean;
reuseTab: boolean;
selectionMethod: BookmarkSelectionMethod;
iconStyle: IconStyle;
folderId: string;
isHistoryEnabled: boolean;
historyRetentionPeriod: HistoryRetentionPeriod;
}
export interface LocalStorageState {
tabId: number | null;
selectedNodeIds: string[];
history: HistoryItem[];
}
export const defaultSyncStorageState: SyncStorageState = {
includeSubfolders: true,
openInNewTab: true,
reuseTab: true,
selectionMethod: BookmarkSelectionMethod.RANDOM,
iconStyle: IconStyle.GRAY,
folderId: '0',
isHistoryEnabled: false,
historyRetentionPeriod: HistoryRetentionPeriod.TWENTY_FOUR_HOURS
};
export const defaultLocalStorageState: LocalStorageState = {
tabId: null,
selectedNodeIds: [],
history: []
};
type Filter<T> = Partial<AnyValue<T>>;
export function getSyncStorage<T extends Filter<SyncStorageState>>(
keys: T
): Promise<{ [K in keyof SyncStorageState as undefined extends T[K] ? never : K]: SyncStorageState[K] }>;
export function getSyncStorage(): Promise<SyncStorageState>;
export async function getSyncStorage<T extends Filter<SyncStorageState>>(keys?: T) {
const filterKeys = Object.keys(keys ?? defaultSyncStorageState);
const items = await chrome.storage.sync.get(filterKeys);
const defaultItemValues = Object.fromEntries(
Object.entries(defaultSyncStorageState).filter(([k]) => filterKeys.includes(k))
);
return { ...defaultItemValues, ...items };
}
export function getLocalStorage<T extends Filter<LocalStorageState>>(
keys: T
): Promise<{ [K in keyof LocalStorageState as undefined extends T[K] ? never : K]: LocalStorageState[K] }>;
export function getLocalStorage(): Promise<LocalStorageState>;
export async function getLocalStorage<T extends Filter<LocalStorageState>>(keys?: T) {
const filterKeys = Object.keys(keys ?? defaultLocalStorageState);
const items = await chrome.storage.local.get(filterKeys);
const defaultItemValues = Object.fromEntries(
Object.entries(defaultLocalStorageState).filter(([k]) => filterKeys.includes(k))
);
return { ...defaultItemValues, ...items };
}
export const updateSyncStorage = <T extends Partial<SyncStorageState>>(state: T): Promise<void> => {
return chrome.storage.sync.set(state);
};
export const updateLocalStorage = <T extends Partial<LocalStorageState>>(state: T): Promise<void> => {
return chrome.storage.local.set(state);
};
export const observeHistory = (listener: (oldValue: HistoryItem[], newValue: HistoryItem[]) => void) => {
chrome.storage.onChanged.addListener(
(changes: { [key: string]: chrome.storage.StorageChange }, areaName: 'sync' | 'local' | 'managed') => {
if (areaName !== 'local') return;
if (!('history' in changes)) return;
const { oldValue, newValue } = changes.history;
listener(oldValue ?? [], newValue ?? []);
}
);
};
|
990e29bf8758974b5a319dc7401d8c5b1054ce7c
|
TypeScript
|
banjankri/angular-webpack2-starter
|
/src/app/features/lazy/lazy.reducer.ts
| 2.75
| 3
|
import { Store, ActionReducer, Action } from '@ngrx/store';
import { AppState, createNewRootReducer } from './../../reducers';
import { LazyActions } from './lazy.actions';
export interface LazyState {
counter: number;
}
const INITIAL_STATE: LazyState = {
counter: 0
};
export function lazyReducer(state: LazyState = INITIAL_STATE, action: Action) {
switch (action.type) {
case LazyActions.DECREMENT:
return {
...state,
counter: state.counter - 1
};
case LazyActions.INCREMENT:
return {
...state,
counter: state.counter + 1
};
case LazyActions.RESET:
return {
...state,
counter: 0
};
default:
return state;
}
}
export interface AppStateWithLazy extends AppState {
lazy: LazyState;
}
export class StoreWithLazy extends Store<AppStateWithLazy> { }
export function lazyStoreFactory(appStore: Store<AppState>) {
appStore.replaceReducer(createNewRootReducer({ lazy: lazyReducer }));
return appStore;
}
|
83b6c5feba8932c2d78a3a2cbd7359a476d5e6a5
|
TypeScript
|
borbert/hrsa-findings-dashboard
|
/dashboard/src/app/components/searchCard/ducks/reducers.ts
| 2.890625
| 3
|
import { SearchActionTypes } from './types'
import { combineReducers } from 'redux'
function entityKeyword(state = '', action: SearchActionTypes): string {
switch (action.type) {
case 'SET_ENTITY_KEYWORDS': {
const { keyword } = action.payload
return keyword
}
default:
return state
}
}
function findingsKeyword(state = '', action: SearchActionTypes): string {
switch (action.type) {
case 'SET_FINDINGS_KEYWORDS': {
const { keyword } = action.payload
return keyword
}
default:
return state
}
}
const searchReducer = combineReducers({
entityKeyword,
findingsKeyword,
})
export default searchReducer
|
c2edb4d518bdbde51141f070edc3cd55594be3f7
|
TypeScript
|
cloudsmithconsulting/cds-for-code
|
/src/commands/cs.cds.deployment.addSolutionComponent.ts
| 2.53125
| 3
|
import * as cs from "../cs";
import * as vscode from 'vscode';
import { CdsWebApi } from '../api/cds-webapi/CdsWebApi';
import { CdsSolutions } from '../api/CdsSolutions';
import ApiRepository from '../repositories/apiRepository';
import Quickly from '../core/Quickly';
import { Utilities } from '../core/Utilities';
import ExtensionContext from "../core/ExtensionContext";
import logger from "../core/framework/Logger";
import SolutionManager from "../components/Solutions/SolutionManager";
/**
* This command can be invoked by the Command Palette or the Dynamics TreeView and adds a solution component to a solution.
* @export run command function
* @param {vscode.Uri} [file] that invoked the command
* @returns void
*/
export default async function run(this: SolutionManager, config?:CdsWebApi.Config, solution?:any, componentId?:string, componentType?:CdsSolutions.SolutionComponent, addRequiredComponents?:boolean, doNotIncludeSubcomponents?:boolean, componentSettings?:string): Promise<any> {
config = config || await Quickly.pickCdsOrganization(ExtensionContext.Instance, "Choose a CDS Organization", true);
if (!config) {
logger.warn(`Command: ${cs.cds.deployment.addSolutionComponent} Organization not chosen, command cancelled`);
return;
}
solution = solution || await Quickly.pickCdsSolution(config, "Choose a solution", true);
if (!solution) {
logger.warn(`Command: ${cs.cds.deployment.addSolutionComponent} Solution not chosen, command cancelled`);
return;
}
componentType = componentType || await Quickly.pickCdsSolutionComponentType("Choose a component to add", [
CdsSolutions.SolutionComponent.Entity,
CdsSolutions.SolutionComponent.OptionSet,
CdsSolutions.SolutionComponent.PluginAssembly,
CdsSolutions.SolutionComponent.WebResource,
CdsSolutions.SolutionComponent.Workflow
]);
if (!componentType) {
logger.warn(`Command: ${cs.cds.deployment.addSolutionComponent} Component Type not chosen, command cancelled`);
return;
}
if (Utilities.$Object.isNullOrEmpty(componentId)) {
const pickResponse = await Quickly.pickCdsSolutionComponent(config, solution, componentType, "Choose a component to add");
if (!pickResponse) {
logger.warn(`Command: ${cs.cds.deployment.addSolutionComponent} Component not chosen, command cancelled`);
return;
}
componentId = pickResponse.componentId;
}
addRequiredComponents = addRequiredComponents || await Quickly.pickBoolean("Add all dependent components?", "Yes", "No");
doNotIncludeSubcomponents = doNotIncludeSubcomponents || !await Quickly.pickBoolean("Include subcomponents?", "Yes", "No");
const api = new ApiRepository(config);
logger.info(`Adding ${componentId} to ${solution.uniquename}`);
return await api.addSolutionComponent(solution, componentId, componentType, addRequiredComponents, doNotIncludeSubcomponents, componentSettings)
.then(() => solution)
.catch(async error => await Quickly.error(
`Could not add ${componentType.toString()} to solution. The error returned was: ${error.message}`,
undefined,
"Retry",
() => vscode.commands.executeCommand(cs.cds.deployment.addSolutionComponent, config, solution, componentId, componentType)));
}
|
6ce96da1ee3c8cca6cb7abcfb9c6bfd68b1ed678
|
TypeScript
|
renzol2/lineage
|
/src/pages/api/pairings.ts
| 2.75
| 3
|
import type { NextApiRequest, NextApiResponse } from 'next';
import {
getPairings,
addPairing,
updatePairing,
deletePairing,
getAllPairings,
} from '../../firebase/pairings';
import { Pairing } from '../../fixtures/Pairings';
import { PairingApiResult } from './types/pairings';
export default async (req: NextApiRequest, res: NextApiResponse) => {
switch (req.method) {
case 'GET':
return await apiGetPairings(req, res);
case 'POST':
return await apiCreatePairing(req, res);
case 'PUT':
return await apiUpdatePairing(req, res);
case 'DELETE':
return await apiDeletePairing(req, res);
default:
return res.status(501).send({});
}
};
const apiGetPairings = async (req: NextApiRequest, res: NextApiResponse) => {
const { semesterAssigned } = req.query;
let pairings: Pairing[];
if (typeof semesterAssigned === 'string') {
pairings = await getPairings(semesterAssigned);
} else {
pairings = await getAllPairings();
}
return res.status(200).json(pairings);
};
const apiCreatePairing = async (
req: NextApiRequest,
res: NextApiResponse<PairingApiResult>
) => {
const { akId, adingId, semester } = req.body;
const result: PairingApiResult = await addPairing(akId, adingId, semester);
const status = result.success ? 200 : 400;
return res.status(status).send(result);
};
const apiUpdatePairing = async (
req: NextApiRequest,
res: NextApiResponse<PairingApiResult>
) => {
const updatedPairing: Pairing = req.body;
const result = await updatePairing(updatedPairing.id, updatedPairing);
const status = result.success ? 200 : 500;
return res.status(status).send(result);
};
const apiDeletePairing = async (
req: NextApiRequest,
res: NextApiResponse<PairingApiResult>
) => {
const { id: pairingId } = req.body;
const result = await deletePairing(pairingId);
const status = result.success ? 200 : 500;
return res.status(status).send(result);
};
|
ac20b2c4555f8ca0f68fe0e2aaaa7fba16eaa150
|
TypeScript
|
hasparus/power-of-preconditions
|
/04.ts
| 2.75
| 3
|
// #region
import { Flavor } from "nom-ts";
export type Username = Flavor<string, "Username">;
export type Email = Flavor<string, "Email">;
export interface User {
name: Username;
email: Email;
}
export type Id = Flavor<string | number, "Id">;
// #endregion
export interface Meeting {
id: Id;
author: User;
title: string;
published_at?: Date;
created_at: Date;
}
declare const meeting: Meeting;
// ts(2551) -- bit easier to notice mistake now, huh?
const authorName = meeting.autor.name;
|
0a21b4ee5ef44ea02cc8415604ddf4ee4f2097e4
|
TypeScript
|
fredguth/risque-rabisque
|
/src/utils/curve.ts
| 2.796875
| 3
|
import Point from './point';
// // Based on SignaturePad
// // https://github.com/szimek/signature_pad
// // https://medium.com/square-corner-blog/smoother-signatures-be64515adb33
export function addPointToCurve(point:Point, points:Array<Point>, velocity, width, minWidth, maxWidth) {
if (points.length > 2) {
if (points.length === 3) points.unshift(points[0]);
let temp = getCurveControlPoints(points[0], points[1], points[2]);
const a = temp.c2;
temp = getCurveControlPoints(points[1], points[2], points[3]);
const b = temp.c1;
const curve = new Bezier(points[1], a, b, points[2]);
const { widths } = calculateCurveWidths(curve, velocity, width, minWidth, maxWidth);
points.shift();
return { curve, widths };
}
return { curve: null, widths: {start:width, end:width, velocity}};
}
// //https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Higher-order_curves
export function drawCurve (ctx, curve, startWidth, endWidth) {
const drawSteps = Math.floor(curve.length());
const widthDelta = endWidth - startWidth;
ctx.beginPath();
for (let i = 0; i < drawSteps; i += 1) {
// Calculate the Bezier (x, y) coordinate for this step.
const t = i / drawSteps;
const tt = t * t;
const ttt = tt * t;
const u = 1 - t;
const uu = u * u;
const uuu = uu * u;
let x = uuu * curve.startPoint.x;
x += 3 * uu * t * curve.control1.x;
x += 3 * u * tt * curve.control2.x;
x += ttt * curve.endPoint.x;
let y = uuu * curve.startPoint.y;
y += 3 * uu * t * curve.control1.y;
y += 3 * u * tt * curve.control2.y;
y += ttt * curve.endPoint.y;
// context.arc(x,y,r,sAngle,eAngle,counterclockwise);
// x The x-coordinate of the center of the circle
// y The y-coordinate of the center of the circle
// r The radius of the circle
// sAngle The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
// eAngle The ending angle, in radians
// counterclockwise Optional.
const width = startWidth + (ttt * widthDelta);
ctx.moveTo(x, y);
ctx.arc(x, y, width, 0, 2 * Math.PI, false);
}
ctx.closePath();
ctx.fill();
return ctx;
};
function getCurveControlPoints (s1, s2, s3) {
// deltas
const dx1 = s1.x - s2.x;
const dy1 = s1.y - s2.y;
const dx2 = s2.x - s3.x;
const dy2 = s2.y - s3.y;
// midpoints
const m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
const m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
// distances
const l1 = Math.sqrt((dx1 * dx1) + (dy1 * dy1));
const l2 = Math.sqrt((dx2 * dx2) + (dy2 * dy2));
// midpoints delta
const dxm = (m1.x - m2.x);
const dym = (m1.y - m2.y);
const k = l2 / (l1 + l2);
const cm = { x: m2.x + (dxm * k), y: m2.y + (dym * k) };
const tx = s2.x - cm.x;
const ty = s2.y - cm.y;
return {
c1: new Point(m1.x + tx, m1.y + ty),
c2: new Point(m2.x + tx, m2.y + ty),
};
};
function calculateCurveWidths (curve, lastvelocity, lastWidth, minWidth, maxWidth, velocityFilterWeight=0.7,) {
const startPoint = curve.startPoint;
const endPoint = curve.endPoint;
const widths = { start: null, end: null, velocity:lastvelocity };
const velocity = (velocityFilterWeight * endPoint.velocityFrom(startPoint))
+ ((1 - velocityFilterWeight) * lastvelocity);
const newWidth = Math.max(maxWidth / (velocity + 1), minWidth);
widths.start = lastWidth;
widths.end = newWidth;
widths.velocity = velocity;
return { widths };
};
class Bezier {
startPoint: Point;
control1: Point;
control2: Point;
endPoint: Point;
constructor(startPoint, control1, control2, endPoint) {
this.startPoint = startPoint;
this.control1 = control1;
this.control2 = control2;
this.endPoint = endPoint;
}
length() {
const steps = 10;
let length = 0;
let px;
let py;
for (let i = 0; i <= steps; i += 1) {
const t = i / steps;
const cx = this.calcPoint(
t,
this.startPoint.x,
this.control1.x,
this.control2.x,
this.endPoint.x,
);
const cy = this.calcPoint(
t,
this.startPoint.y,
this.control1.y,
this.control2.y,
this.endPoint.y,
);
if (i > 0) {
const xdiff = cx - px;
const ydiff = cy - py;
length += Math.sqrt((xdiff * xdiff) + (ydiff * ydiff));
}
px = cx;
py = cy;
}
return length;
}
calcPoint (t, start, c1, c2, end) {
return ( start * (1.0 - t) * (1.0 - t) * (1.0 - t))
+ (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)
+ (3.0 * c2 * (1.0 - t) * t * t)
+ ( end * t * t * t);
};
}
|
2b7a22af8c93e162ca7c229937e7ffda1362a4af
|
TypeScript
|
JerduarV/2P1S2020
|
/src/app/Compilador/ExpresionJ/CallFun2.ts
| 2.578125
| 3
|
import { ExpresionJ } from './ExpresionJ';
import { Tipo } from '../TSJ/Tipo';
import { ErrorLup } from 'src/app/Auxiliares/Error';
import { DecFun } from '../InstruccionJ/DecFun';
import { getTempAct, concatCodigo, genTemp, conectarNodo, getIdNodo } from 'src/app/Auxiliares/Utilidades';
import { CallFun } from './CallFun';
export class ParamT2 {
nombre: string;
exp: ExpresionJ;
constructor(nombre: string, exp: ExpresionJ) {
this.nombre = nombre;
this.exp = exp;
}
}
export class CallFun2 extends CallFun {
private readonly lista_param: ParamT2[];
constructor(id: string, lista: ParamT2[], fila: number, col: number) {
super(id, null, fila, col);
this.lista_param = lista;
}
public getTipo(ts: import("../TSJ/TablaSimbJ").TablaSimbJ): Object {
let lista_tipos: Tipo[] = [];
for (let i = 0; i < this.lista_param.length; i++) {
let o: Object = this.lista_param[i].exp.getTipo(ts);
if (o instanceof ErrorLup) {
return o;
}
lista_tipos.push(<Tipo>o);
}
let funcion: DecFun = ts.BuscarFuncion2(this.id, this.lista_param, lista_tipos);
if (funcion == null) {
return ts.GenerarError('No se encuentra la función ' + this.id, this.getFila(), this.getCol());
}
//console.log(funcion);
return funcion.getTipoRet();
}
public Traducir(ts: import("../TSJ/TablaSimbJ").TablaSimbJ): void {
//#region BUSQUEDA FUNCIÓN
let lista_tipos: Tipo[] = [];
for (let i = 0; i < this.lista_param.length; i++) {
let o: Object = this.lista_param[i].exp.getTipo(ts);
if (o instanceof ErrorLup) {
return;
}
lista_tipos.push(<Tipo>o);
}
let funcion: DecFun = ts.BuscarFuncion2(this.id, this.lista_param, lista_tipos);
if (funcion == null) {
return;
}
//#endregion
//RESOLUCIÓN DE PARAMETROS ACTUALES
let lista_temp_param: string[] = [];
this.lista_param.forEach(param => {
param.exp.Traducir(ts);
let p: string = getTempAct();
lista_temp_param.push(p);
//ts.guardarTemporal(p);
});
//ESCRIBO SALIDA DE LA FUNCIÓN ACTUAL
concatCodigo('P = P + ' + ts.getTamanioFunTotal() + ';');
//GUARDADO DE TEMPORALES
concatCodigo('#* GUARDANDO TEMPORALES *#')
let cont: number = 0;
ts.tabla_temporales.forEach(temp => {
let t1: string = genTemp();
concatCodigo(t1 + ' = P + ' + (cont++) + ';');
concatCodigo('Stack[' + t1 + '] = ' + temp + ';');
});
concatCodigo('#* FIN GUARDADO TEMPORALES *#');
//ESCRIBO SALIDA DEL ESPACIO DE TEMPORALES GUARDADOS
concatCodigo('P = P + ' + ts.tabla_temporales.size + ';');
//PASO DE PARAMETROS
concatCodigo('#* PASANDO PARAMETROS *#');
for (let i = 0; i < funcion.getParamatrosFormales().length; i++) {
let t1: string = genTemp();
concatCodigo(t1 + ' = P + ' + (i + 1) + ';');
concatCodigo('Stack[' + t1 + '] = ' + lista_temp_param[this.BuscarTemporal(funcion.getParamatrosFormales()[i].nombre)] + ';');
}
concatCodigo('#* FIN PASO DE PARAMETROS *#');
concatCodigo('#* LLAMANDO FUNCION *#');
concatCodigo('call ' + funcion.getNombreLlamada() + ';');
let tr: string = genTemp();
concatCodigo(tr + ' = Stack[P];');
//REGRESO AL AREA DE TEMPORALES GUARDADOS
concatCodigo('P = P - ' + ts.tabla_temporales.size + ';');
//RECUPERANDO TEMPORALES
concatCodigo('#* RECUPERANDO TEMPORALES *#')
cont = 0;
ts.tabla_temporales.forEach(temp => {
let t1: string = genTemp();
concatCodigo(t1 + ' = P + ' + (cont++) + ';');
concatCodigo(temp + ' = Stack[' + t1 + '];');
});
concatCodigo('#* FIN RECUPERACION DE TEMPORALES *#')
let trest: string = genTemp();
//REGRESANDO A LA FUNCIÓN ACTUAL
concatCodigo('P = P - ' + ts.getTamanioFunTotal() + ';');
concatCodigo(trest + ' = ' + tr + ';');
ts.guardarTemporal(trest);
lista_temp_param.forEach(temp => {
ts.SacarTemporal(temp);
});
}
private BuscarTemporal(nombre_param: string): number {
for (let i = 0; i < this.lista_param.length; i++) {
if (this.lista_param[i].nombre.toUpperCase() == nombre_param.toUpperCase()) {
return i;
}
}
console.log('No encontre el parametro');
return 0;
}
public dibujar(padre: string): void {
let n: string = getIdNodo('CALL_FUN2');
conectarNodo(padre, n);
conectarNodo(n, getIdNodo(this.id));
let lparam: string = getIdNodo('L_PARAM');
conectarNodo(n, lparam);
this.lista_param.forEach(param => {
let p: string = getIdNodo('PARAM');
conectarNodo(lparam, p);
conectarNodo(p, param.nombre);
param.exp.dibujar(p);
});
}
}
|
b47f5c16265a4fc270245dc19904adcf13889391
|
TypeScript
|
fureweb-com/nuxtswagger
|
/src/TemplateCommon.ts
| 2.859375
| 3
|
/* eslint-disable no-control-regex */
import { Options } from './index'
import { camelCase } from './utils'
import * as v2 from './schema/v2/Spec'
import * as v3 from './schema/v3/Spec'
import { LoDashStatic } from 'lodash'
type ParameterIn = v2.ParameterIn| v3.ParameterIn | '$body' | '$config'
interface Parameter { type: string, required: boolean, name: string, valName:string, pos: ParameterIn }
type Response = v2.Response | v3.Response
type TypeDefs = v2.Types | v2.ParameterTypes | v3.Types | v3.ParameterTypes | {} | Boolean
type Spec = v2.Spec | v3.Spec
type Method = v2.Method | v3.Method
type Schemas = v2.Definitions | v3.Schemas
enum MethodTypes {get = 'get', post = 'post', put = 'put', patch = 'patch', delete = 'delete', head = 'head', options = 'options'}
export type TemplateOptions = Options & { relTypePath: string }
const _:LoDashStatic = require('lodash')
const typeMatch = ['integer', 'long'].map(x => `type ${x} = number`).join('\n')
const entriesCompare = <T>([a]:[string, T], [b]:[string, T]) => a.localeCompare(b)
const exists = <TValue>(value: TValue | null | undefined): value is TValue => !!value
const noInspect = '/* eslint-disable */\n// noinspection ES6UnusedImports,JSUnusedLocalSymbols\n'
const escapeRegExp = (string:string) => string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const replaceAll = (string: string, searchValue: string, replaceValue: string) => string.replace(new RegExp(escapeRegExp(searchValue), 'g'), replaceValue)
const genericVar = (i: number) => {
const arr = ['T', 'U', 'V']
return i < arr.length ? arr[i] : `T${i + 1 - arr.length}`
}
export abstract class TemplateCommon {
protected abstract spec:Spec
protected readonly relTypePath:string
protected readonly basePath:string
protected readonly inject:string
protected readonly className:string
protected readonly skipHeader:boolean
protected constructor (spec:Spec, { pluginName, basePath, inject, skipHeader, relTypePath }:TemplateOptions) {
this.relTypePath = relTypePath
this.basePath = basePath
this.skipHeader = skipHeader
this.inject = inject.replace(/^[^a-zA-Z]+/, '').replace(/^[A-Z]/, x => x.toLowerCase())
this.className = pluginName.replace(/^[^a-zA-Z]+/, '').replace(/^[a-z]/, x => x.toUpperCase())
this.fixRefDeep(spec)
}
protected abstract get schemas():Schemas
protected abstract getResponseType(response:Response):string
protected fixTypeName = (name: string) => name
.replace(/^#\/(components\/schemas|definitions)\//, '')
.replace(/«/g, '<').replace(/»/g, '>')
.replace(/List<(.+?)>/g, 'Array<$1>')
.replace(/[^0-9a-zA-Z_$<>, ]/g, '')
.replace(/.+/, camelCase)
.replace(/[ ]+$/g, '')
protected comment (comment?:string|number|boolean|object, onlyText = false) {
if (comment === undefined) { return '' }
if (comment === Object(comment)) comment = JSON.stringify(comment)
const string = comment.toString().trim()
if (onlyText) return string
const lines = string.split('\n')
if (lines.length === 1) { return ` // ${lines[0]}` }
return ['\n/**', ...lines.map(x => ` * ${x}`), ' */'].join('\n')
}
protected makeComment (typeObj: Exclude<TypeDefs, boolean>, onlyText = false) {
const title = 'title' in typeObj ? this.comment(typeObj.title, true) : ''
const description = 'description' in typeObj ? this.comment(typeObj.description, true) : ''
const example = 'example' in typeObj ? this.comment(typeObj.example, true) : ''
let comment: string
if (title && description) comment = title + (/\n/.test(description) ? '\n' : ' - ') + description
else comment = title + description
if (example) comment += (/\n/.test(comment + example)) ? `\n${example}` : ` (${example})`
return comment && this.comment(comment, onlyText)
}
protected typeDeep (typeObj:TypeDefs, maxIndent = -1, noComment = false):string {
if (typeof typeObj === 'boolean') return 'any'
const canComment = maxIndent >= 0 && !noComment
const indentProps = maxIndent > 0
const comment = canComment ? this.makeComment(typeObj) : ''
const typeDeep = (typeObj:TypeDefs) :string => {
if ('schema' in typeObj) return typeDeep(typeObj.schema)
if ('$ref' in typeObj) return (typeObj.$ref in this.schemas) ? typeObj.$ref : 'any'
if ('enum' in typeObj) {
return `(${typeObj.enum.map(x => JSON.stringify(x).replace(/"/g, '\'')).join(' | ')})`
}
if (!('type' in typeObj)) return 'any'
if (typeObj.type === 'array') return `Array<${typeDeep(typeObj.items)}>`
if (typeObj.type === 'object') {
const { properties, additionalProperties, required = [] } = typeObj
const entries:[string, TypeDefs][] = Object.entries(properties || {})
if (additionalProperties) entries.push(['[key in any]', additionalProperties])
if (!entries.length) return 'any'
const items = entries.map(([name, value]) => {
const is = { required: false, ...value }
const optional = (is.required || required.includes(name)) ? '' : '?'
return `${name + optional}: ${this.typeDeep(value, maxIndent - 1)}`
})
if (!indentProps) return `{ ${items.join(', ')} }`
return `{\n${items.join('\n').replace(/^./gm, ' $&')}\n}`
}
return typeObj.type
}
return typeDeep(typeObj) + comment
}
protected toArgs (parameters: Parameter[]) {
const classify = (params:Parameter[] = []) => {
const [names, all, required, optional] = [[], [], [], []] as string[][]
params.forEach((p) => {
names.push(p.valName)
const type = `${p.valName}${p.required ? '' : '?'}: ${p.type}`
all.push(type)
p.required ? required.push(type) : optional.push(type)
})
return { names, types: { all, required, optional, ordered: [...required, ...optional] } }
}
const toArgs = (parameters:Parameter[]) => {
const { path = [], body = [], $config, ...others } = _.groupBy(parameters, x => x.pos)
if ((parameters.length - (path.length + body.length)) < 5) return classify(parameters).types.ordered
const pathBody = classify([...path, ...body]).types.all // should be no optional type in path and body
const { names, types } = classify(Object.values(others).flat())
const objectArg = `{ ${names.join(', ')} }: { ${types.all.join(', ')} }`
return [pathBody, objectArg, classify($config).types.all].flat()
}
return toArgs(parameters).join(', ')
}
protected fixKeys<T extends object> (o:T):T {
const ret:any = {}
Object.entries(o).forEach(([key, value]) => { ret[this.fixTypeName(key)] = value })
return ret
}
protected fixRefDeep (spec:Spec) {
const deep = (o:any) => {
if (!(o instanceof Object)) return
if ('$ref' in o) o.$ref = this.fixTypeName(o.$ref)
else if (o instanceof Array) o.forEach(deep)
else Object.values(o).forEach(deep)
}
deep(spec)
}
protected importTypes () {
const withoutGeneric = Object.keys(this.schemas).map(x => x.replace(/<.+>/, ''))
return `import { ${_.uniq(withoutGeneric).sort().join(', ')} } from '${this.relTypePath}'`
}
public definitions () {
const types = Object.entries(this.schemas).sort(entriesCompare)
.map(([rawName, type]) => {
const [, name = rawName, genericString = ''] = rawName.match(/(.+?)<(.+)>/) || []
const genericReplacer = (str:string) => {
const generics = genericString
.replace(/<.+>/, x => x.replace(/,/g, '\x00'))
.split(',')
.map(x => x.replace(/\x00/g, ','))
.filter(x => x)
generics
.map((x, i) => [x, genericVar(i)])
.sort(([a], [b]) => b.length - a.length) // length desc
.forEach(([x, t]) => { str = replaceAll(str, x, t) })
return str
}
return { name, rawName, genericReplacer, type }
})
const exports = Object.values(_.groupBy(types, x => x.name)).map(arr => {
const [{ rawName, genericReplacer, type }] = arr
const comments = arr.map(x => this.makeComment(x.type, true)).filter(x => x)
const comment = comments.length ? this.comment(comments.join('\n')).trim() + '\n' : ''
return `${comment}export type ${genericReplacer(`${rawName} = ${this.typeDeep(type, 1, true)}`)}`
})
return [noInspect, typeMatch, ...exports, ''].join('\n')
}
public plugin () {
const { paths } = this.spec
const propTree:{[paths:string]:string} = {}
const base = this.basePath
Object.entries(paths).sort(entriesCompare).forEach(([path, methods]) => {
const keyPath = (path.startsWith(base + '/') ? path.replace(base, '') : path)
.replace(/[^/{}\w]/g, '_')
.replace(/([a-z\d])_([a-z])/g, (_, p1, p2) => p1 + p2.toUpperCase()) // foo_bar => fooBar
.replace(/{(\w+)}/g, '_$1') // {foo} => _foo
.replace(/\/$/, '/$root')
.split('/').slice(1)
if (/^v\d+$/.test(keyPath[0])) keyPath.push(keyPath.shift() || '')
Object.entries(methods).sort(entriesCompare).forEach(([key, method]) => {
if (!(key in MethodTypes)) return
const methodType = key as MethodTypes
_.set(propTree, [...keyPath, methodType], this.axiosCall(path, methodType, method as Method))
})
})
const properties = Object.entries(propTree).map(([property, child]) => {
const code = JSON.stringify(child, null, ' ')
.replace(/".+?"/g, JSON.parse)
.replace(/^([ ]*)(.*)\/\*((.|\n)+?)\*\//gm, (_, indent, code, comment) => {
const prependComment = [this.comment(comment), code].join('\n')
return prependComment.trim().replace(/^/gm, indent)
})
return `${property} = ${code}\n`
}).join('\n').trim().replace(/^./mg, ' $&')
return this.pluginTemplate({ properties })
}
protected axiosCall (path: string, method: MethodTypes, methodSpec: Method) {
const { parameters, responses, summary = '' } = methodSpec
const pathParams: { [key in string]?: Parameter } = _(path.match(/{.+?}/g))
.map((x) => x.replace(/[{}]/g, '')).zipObject().value()
let body: Parameter | undefined
const [headers, query]: { [x in string]: Parameter }[] = [{}, {}]
parameters?.forEach((parameter) => {
const type = this.typeDeep(parameter)
const { in: pos, required = false, name } = parameter
const valName = camelCase(name)
if (!this.skipHeader && pos === 'header') { headers[name] = { name, valName, pos, type, required } }
if (pos === 'query') { query[name] = { name, valName, pos, type, required } }
if (pos === 'body') { body = { name: '$body', valName: '$body', pos, type, required: true } }
if (pos === 'path') { pathParams[name] = { name, valName, pos, type, required: true } }
})
if (('requestBody' in methodSpec) && methodSpec.requestBody) {
const pos = '$body'
const { required = false, content } = methodSpec.requestBody
const { schema } = content['application/json'] || {}
if (schema) body = { name: pos, valName: pos, pos, type: this.typeDeep(schema), required }
}
const arrOf = { queries: Object.values(query), headers: Object.values(headers) }
const params = Object.values(pathParams).filter((x): x is Parameter => !!x)
params.push(...arrOf.queries)
if (body) { params.push(body) }
params.push(...arrOf.headers)
const $config:Parameter = {
name: '$config', valName: '$config', pos: '$config', type: 'AxiosRequestConfig', required: false
}
params.push($config)
const axiosParams = [`\`${path.replace(/{/g, '${')}\``]
if (body) { axiosParams[1] = body.name }
{
const noBody = /get|delete/.test(method)
if (arrOf.headers.length || arrOf.queries.length) {
const join = (arr: Parameter[]) => arr.map(x =>
x.name === x.valName ? x.name : `'${x.name}': ${x.valName}`
).join(', ')
const headers = arrOf.headers.length ? `headers: { ${join(arrOf.headers)} }` : ''
const params = arrOf.queries.length ? `params: { ${join(arrOf.queries)} }` : ''
axiosParams[noBody ? 1 : 2] = `{ ${[headers, params, '...' + $config.valName].filter(x => x).join(', ')} }`
} else axiosParams[noBody ? 1 : 2] = $config.valName
}
const type = responses[200] ? this.getResponseType(responses[200]) : 'any'
const statusList = Object.keys(responses)
const description = statusList
.map(key => {
const [status, { description }] = [+key, responses[+key] || {}]
return description ? { status, description } : undefined
}).filter(exists)
.filter((x, _, { length }) => !(length === 1 && x.status === 200 && /^(OK|Successful)$/i.test(x.description)))
.map(x => `${x.status}: ${x.description}`)
.join('\n')
const comment = description ? `${summary}\n${description}` : summary
const paramsString = [...axiosParams].map(x => x || 'undefined').join(', ')
const code = `(${this.toArgs(params)}): Promise<${type}> => this.$axios.$${method}(${paramsString})`
return comment ? code + `/*${comment}*/` : code
}
protected pluginTemplate ({ properties }: { properties: string }) {
return `
${noInspect}
import { Plugin } from '@nuxt/types'
import { AxiosRequestConfig } from 'axios'
import { NuxtAxiosInstance } from '@nuxtjs/axios'
${this.importTypes()}
${typeMatch}
class ${this.className} {
public $axios: NuxtAxiosInstance
constructor ($axios: NuxtAxiosInstance) {
this.$axios = $axios
}
${properties}
}
declare module '@nuxt/types' {
interface NuxtAppOptions { $${this.inject}: ${this.className} }
}
declare module 'vue/types/vue' {
interface Vue { $${this.inject}: ${this.className} }
}
declare module 'vuex/types/index' {
interface Store<S> { $${this.inject}: ${this.className} }
}
const plugin: Plugin = ({ $axios }, inject) => {
inject('${this.inject}', new ${this.className}($axios))
}
export default plugin
`.trimStart()
}
}
|
27e4ceeb4caef637e5ece4761b61d95fdfa7bf7d
|
TypeScript
|
degrize/jhipster-sample-application
|
/src/main/webapp/app/entities/decision/decision.model.ts
| 2.5625
| 3
|
import { INouveau } from 'app/entities/nouveau/nouveau.model';
import { DecisionType } from 'app/entities/enumerations/decision-type.model';
export interface IDecision {
id?: number;
decision?: DecisionType;
nouveaus?: INouveau[] | null;
}
export class Decision implements IDecision {
constructor(public id?: number, public decision?: DecisionType, public nouveaus?: INouveau[] | null) {}
}
export function getDecisionIdentifier(decision: IDecision): number | undefined {
return decision.id;
}
|
53f53dcadfddac57f2ec3f35b5d0d5430b0e5bd8
|
TypeScript
|
dmorosinotto/angular-poc-uno
|
/src/app/shared/ui-codfisc.component.ts
| 2.5625
| 3
|
import { Component, OnInit, Input, forwardRef } from "@angular/core";
import {
FormControl,
ControlValueAccessor,
NG_VALUE_ACCESSOR,
NG_VALIDATORS,
Validator,
ValidationErrors,
AbstractControl
} from "@angular/forms";
import { BaseCtrl } from "../base/base-ctrl.component";
const IMPLEMENT_VALIDATE_LOGIC = null;
@Component({
selector: "ui-codfisc",
template: `
<label
>CODICE FISCALE:
<input type="text" [formControl]="ctrl" />
{{ ctrl.valid }} {{ ctrl.errors | json }}
</label>
`,
providers: [
{ provide: NG_VALUE_ACCESSOR, multi: true, useExisting: forwardRef(() => UiCodfiscComponent) },
{ provide: NG_VALIDATORS, multi: true, useExisting: forwardRef(() => UiCodfiscComponent) }
],
})
export class UiCodfiscComponent extends BaseCtrl<string> implements Validator {
constructor() {
super();
this.ctrl.setValidators(this.validate);
}
modelToView(modelValue: string): string {
console.log("CF M->V", modelValue);
return modelValue || "";
}
viewToModel(viewValue: string): string {
console.log("CF v->m", viewValue);
return (viewValue || "").toUpperCase();
}
validate(control: AbstractControlTyped<string>): ValidationErrors | null {
console.log("CF VALIDATE", control.value);
if (!control.value || control.value.length != 16) return { codfisc: "INVALID LENGHT CODICE FISCALE" };
if (control.value.match(/^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/g)) return null;
//GRAZIE A MARKETTO
//OK LUNGO 16 + MATCHA LA REGEX
else return { codfisc: "INVALID FORMAT CODICE FISCALE" };
}
}
|
283ca9ac6497e4038094f0323b2929e3ff6f29d2
|
TypeScript
|
Gintez/exchange
|
/src/services/currency-exchange/compose-exchange-pair.ts
| 2.84375
| 3
|
import { ExchangePair } from 'types';
interface ComposeExchangePair {
currencyChange: Partial<ExchangePair>;
currentCurrencyPair: ExchangePair;
}
export default function composeExchangePair({
currencyChange,
currentCurrencyPair,
}: ComposeExchangePair) {
let buy = currencyChange.buy;
let sell = currencyChange.sell;
if (buy) {
sell =
currentCurrencyPair.sell === buy
? currentCurrencyPair.buy
: currentCurrencyPair.sell;
} else {
buy =
currentCurrencyPair.buy === sell
? currentCurrencyPair.sell
: currentCurrencyPair.buy;
}
return { buy, sell };
}
|
017882eb9ad83bd1d1283018a44b31cbbf9f66ee
|
TypeScript
|
tamanugi/mono_tech_training
|
/mono-front/src/repositories/user.ts
| 2.578125
| 3
|
import axios from 'axios'
import { User } from '@/types/'
const API_ENDPOINT = 'http://localhost:8080/users';
export async function findByName(name: string) {
return axios.get<{users: User[]}>(API_ENDPOINT, {params: {name}}).then(({data}) => data.users)
}
export async function findById(id: string) {
return axios.get<User>(API_ENDPOINT + `/${id}`)
.then(({data}) => {
return data;
})
}
export async function postUser(name: string) {
return axios.post(API_ENDPOINT, {name})
.then(({data}) => console.log(data))
}
export async function updateUser(user: User) {
return axios.patch(API_ENDPOINT + `/${user.id}`, {...user}).then(({data}) => data)
}
export async function deleteUser(user: User) {
return axios.delete(API_ENDPOINT + `/${user.id}`)
}
|
f8fda733177c6c4276d438fe54746e867dd6708c
|
TypeScript
|
Sazar24/nestable-notes-manager
|
/__tests__/services/NotesManagerService/deleteNoteAndDescendants.test.ts
| 2.6875
| 3
|
import { INote, Note } from './../../../src/models/Note';
import NotesManager from '../../../src/services/NotesManager';
describe('NotesManager .deleteNoteAndDescendants ', () => {
const notesManager = new NotesManager();
it('should delete proper values', () => {
const notesInState: INote[] = [
Note.newEmpty("1", null),
Note.newEmpty("22", "1"),
Note.newEmpty("33", "1"),
Note.newEmpty("2", null),
];
const expectedResult: INote[] = [
Note.newEmpty("2", null),
];
const result: INote[] = notesManager.deleteNoteAndDescendants("1", notesInState);
expect(result).toEqual(expectedResult);
});
});
|
3ef1ed2964ee0fa7252e54e3f28ecce2d2d9fcad
|
TypeScript
|
onaio/js-tools
|
/packages/reducer-registry/src/tests/ducks/users.ts
| 2.953125
| 3
|
import { ActionCreator, AnyAction, Store } from 'redux';
import reducerRegistry from '../..';
export const reducerName = 'users';
interface User {
username: string;
}
interface AddUserAction extends AnyAction {
payload?: User;
type: typeof ADD_USER;
}
interface UserState {
users: User[];
}
const initialState: UserState = {
users: []
};
export default function reducer(state = initialState, action: AddUserAction): UserState {
switch (action.type) {
case ADD_USER:
if (action.payload) {
return { users: [...state.users, action.payload] };
}
return state;
default:
return state;
}
}
reducerRegistry.register(reducerName, reducer);
// actions
export const ADD_USER = 'redux-registry/reducer/ADD_USER';
// action creators
export const addUser: ActionCreator<AddUserAction> = (newUser: User) => ({
payload: newUser,
type: ADD_USER
});
// selectors
export function selectAllUsers(state: Partial<Store>) {
return (state as any)[reducerName].users;
}
|
6d938d2e1390949a9ba698ab7cb689a301374e0f
|
TypeScript
|
cliffordfajardo/mini-rdms
|
/test/nodes/ProjectionNode.test.ts
| 2.671875
| 3
|
import { MemoryscanNode } from '../../src/nodes/MemoryscanNode';
import { ProjectionNode } from "../../src/nodes/ProjectionNode";
// TEST DATA
const movies_table = [
{movieId:"0", title: "Apple Computer History"},
{movieId:"1", title: "Ben and Jerrys Documentary"}
];
const DatabaseInMemory = {"movies": movies_table}
describe('ProjectionNode -', () => {
describe("Methods - ", () => {
describe('next - ', () => {
it("should return a record with only the fields in the columnList", () => {
const fileScanNode = new MemoryscanNode(DatabaseInMemory, 'movies');
const projectionNode = new ProjectionNode(fileScanNode, ['title']);
const result1 = projectionNode.next();
const result2 = projectionNode.next();
expect(result1).toEqual({title: "Apple Computer History"})
expect(result2).toEqual({title: "Ben and Jerrys Documentary"})
})
})
// describe('reset', () => {
// it('', () => {
// })
// });
});
});
|
8e647d3f124d281cbea2553d09cc1e481a8a5734
|
TypeScript
|
CarbonLDP/sparqler
|
/src/tokens/BaseToken.spec.ts
| 3.0625
| 3
|
import { BaseToken } from "./BaseToken";
import { IRIRefToken } from "./IRIRefToken";
describe( "BaseToken", ():void => {
it( "should exists", ():void => {
expect( BaseToken ).toBeDefined();
expect( BaseToken ).toEqual( jasmine.any( Function ) );
} );
describe( "BaseToken.constructor", ():void => {
it( "should be instantiable", ():void => {
const iri:IRIRefToken = new IRIRefToken( "http://example.com/" );
const token:BaseToken = new BaseToken( iri );
expect( token ).toBeDefined();
} );
it( "should store the provided iri", ():void => {
const iri:IRIRefToken = new IRIRefToken( "http://example.com/" );
const token:BaseToken = new BaseToken( iri );
expect( token.iri ).toBe( iri );
} );
it( "should assign the `base` as token name", ():void => {
expect( new BaseToken( new IRIRefToken( "http://example.com/" ) ).token ).toBe( "base" );
expect( new BaseToken( new IRIRefToken( "http://example.com/resource/" ) ).token ).toBe( "base" );
} );
} );
describe( "BaseToken.toString", ():void => {
it( "should override toString method", ():void => {
const token:BaseToken = new BaseToken( new IRIRefToken( "http://example.com/" ) );
expect( token.toString ).toBeDefined();
expect( token.toString ).not.toBe( Object.prototype.toString );
} );
it( "should return SPARQL BASE prologue", ():void => {
const iri:IRIRefToken = new IRIRefToken( "http://example.com/" );
expect( new BaseToken( iri ).toString() ).toBe( `BASE <http://example.com/>` );
} );
} );
} );
|
f106eb27d7af450b3eb854efd8517714c2c47fd9
|
TypeScript
|
arosh/icfpc2016
|
/web/app/browser/d3renderer.ts
| 2.515625
| 3
|
import { IPoint, ISegment } from "./store";
const renderSize = 555;
const margin = 50;
const edgeRadius = 5;
class Color {
public static BLACK = "#212121";
public static RED = "#F44336";
}
export class D3Renderer {
private el: d3.Selection<any>;
private xScale: d3.scale.Linear<number, number>;
private yScale: d3.scale.Linear<number, number>;
private silhouetteVertexEl: d3.Selection<any>;
private silhouetteEdgeEl: d3.Selection<any>;
private skeletonEdgeEl: d3.Selection<any>;
private xAxisEl: d3.Selection<any>;
private yAxisEl: d3.Selection<any>;
constructor(elementId: string) {
this.el = d3.select(elementId).append("svg")
.attr({ width: renderSize, height: renderSize })
.classed("center-block", true);
// 順番重要
this.skeletonEdgeEl = this.el.append("g");
this.silhouetteVertexEl = this.el.append("g");
this.silhouetteEdgeEl = this.el.append("g");
this.xAxisEl = this.el.append("g");
this.yAxisEl = this.el.append("g");
}
public render(silhouette: IPoint[][], skeleton: ISegment[]) {
this.computeScaler(silhouette, skeleton);
this.renderSilhouetteVertex(silhouette);
this.renderSilhouetteEdge(silhouette);
this.renderSkeletonEdge(skeleton);
this.xAxisEl.call(d3.svg.axis().scale(this.xScale).orient("bottom"));
this.yAxisEl.call(d3.svg.axis().scale(this.yScale).orient("right"));
}
private renderSilhouetteVertex(silhouette: IPoint[][]) {
const silhouetteVertex: IPoint[] = [];
for (const poly of silhouette) {
silhouetteVertex.push(...poly);
}
const silhouetteVertexCircle = this.silhouetteVertexEl.selectAll("circle").data(silhouetteVertex);
silhouetteVertexCircle.enter().append("circle");
silhouetteVertexCircle.exit().remove();
silhouetteVertexCircle.attr({
cx: (d, i) => this.xScale(d.x),
cy: (d, i) => this.yScale(d.y),
fill: Color.BLACK,
r: edgeRadius,
});
}
private renderSilhouetteEdge(silhouette: IPoint[][]) {
const silhouetteEdge: ISegment[] = [];
for (const poly of silhouette) {
for (let i = 0; i < poly.length; ++i) {
const j = (i + 1) % poly.length;
silhouetteEdge.push({ st: poly[i], en: poly[j] });
}
}
const silhouetteEdgeLine = this.silhouetteEdgeEl.selectAll("line").data(silhouetteEdge);
silhouetteEdgeLine.enter().append("line");
silhouetteEdgeLine.exit().remove();
silhouetteEdgeLine.attr({
stroke: Color.BLACK,
"stroke-width": 2,
x1: (d, i) => this.xScale(d.st.x),
y1: (d, i) => this.yScale(d.st.y),
x2: (d, i) => this.xScale(d.en.x),
y2: (d, i) => this.yScale(d.en.y),
});
}
private renderSkeletonEdge(skeleton: ISegment[]) {
const skeletonEdgeLine = this.skeletonEdgeEl.selectAll("line").data(skeleton);
skeletonEdgeLine.enter().append("line");
skeletonEdgeLine.exit().remove();
skeletonEdgeLine.attr({
stroke: Color.RED,
"stroke-width": 2,
x1: (d, i) => this.xScale(d.st.x),
y1: (d, i) => this.yScale(d.st.y),
x2: (d, i) => this.xScale(d.en.x),
y2: (d, i) => this.yScale(d.en.y),
});
}
private computeScaler(vertex: IPoint[][], skeleton: ISegment[]) {
const xs: number[] = [];
const ys: number[] = [];
for (const poly of vertex) {
for (const point of poly) {
xs.push(point.x);
ys.push(point.y);
}
}
for (const seg of skeleton) {
xs.push(seg.st.x, seg.en.x);
ys.push(seg.st.y, seg.en.y);
}
const xmin = Math.min(...xs);
const xmax = Math.max(...xs);
const ymin = Math.min(...ys);
const ymax = Math.max(...ys);
const xlen = xmax - xmin;
const ylen = ymax - ymin;
if (xlen > ylen) {
this.xScale = d3.scale.linear()
.domain([xmin, xmax])
.range([0 + margin, renderSize - margin]);
this.yScale = d3.scale.linear()
.domain([(ymin + ymax) / 2 - xlen / 2, (ymin + ymax) / 2 + xlen / 2])
.range([renderSize - margin, 0 + margin]);
} else {
this.xScale = d3.scale.linear()
.domain([(xmin + xmax) / 2 - ylen / 2, (xmin + xmax) / 2 + ylen / 2])
.range([0 + margin, renderSize - margin]);
this.yScale = d3.scale.linear()
.domain([ymin, ymax])
.range([renderSize - margin, 0 + margin]);
}
}
}
|
bbf115e1f1fe5049bde81dc13321e86222850351
|
TypeScript
|
yuriy-tk/theme-app
|
/libs/utils/src/lib/colorUtil.ts
| 2.984375
| 3
|
import * as Color from 'color';
function darken(color: string, amt: number = 0.2) {
return Color(color)
.darken(amt)
.hex();
}
function lighten(color: string, amt: number = 0.2) {
return Color(color)
.lighten(amt)
.hex();
}
function saturate(color: string, amt: number = 0.2) {
return Color(color)
.lighten(amt)
.hex();
}
function desaturate(color: string, amt: number = 0.2) {
return Color(color)
.lighten(amt)
.hex();
}
function grayscale(color: string) {
return Color(color)
.grayscale()
.hex();
}
function whiten(color: string, amt: number = 0.2) {
return Color(color)
.whiten(amt)
.hex();
}
function blacken(color: string, amt: number = 0.2) {
return Color(color)
.blacken(amt)
.hex();
}
function invert(color: string) {
return Color(color)
.negate()
.hex();
}
function isDark(color: string) {
return Color(color).isDark();
}
export {
darken,
lighten,
saturate,
desaturate,
grayscale,
whiten,
blacken,
invert,
isDark,
};
|
fa67b8632359a39f12acad9352c32b8d83a63a59
|
TypeScript
|
stevekeol/remax
|
/packages/remax-runtime/src/polyfills/Function.ts
| 2.609375
| 3
|
/* eslint-disable prefer-rest-params */
/* istanbul ignore next */
if (typeof Function.prototype.call === 'undefined') {
Function.prototype.call = function (context: any) {
context = context || window;
context.fn = this;
const args = [...arguments].slice(1);
const result = context.fn(...args);
delete context.fn;
return result;
};
}
/* istanbul ignore next */
if (typeof Function.prototype.apply === 'undefined') {
Function.prototype.apply = function (context) {
context = context || window;
context.fn = this;
let result;
if (arguments[1]) {
result = context.fn(...arguments[1]);
} else {
result = context.fn();
}
delete context.fn;
return result;
};
}
|
20775699b26871ad4432c92caffd7eabfdb4aae7
|
TypeScript
|
LOKE/http-client
|
/index.ts
| 2.8125
| 3
|
import got from "got";
import { Counter, Histogram, Registry } from "prom-client";
import { resolve as resolveUrl } from "url";
import urlTemplate from "url-template";
const requestsCount = new Counter({
name: "http_client_requests_total",
help: "Total number of http client requests",
labelNames: ["base", "method", "path", "code"],
registers: []
});
const requestDuration = new Histogram({
name: "http_client_request_duration_seconds",
help: "Latencies for http client requests",
labelNames: ["base", "method", "path"],
registers: []
});
const requestStageDuration = new Histogram({
name: "http_client_request_stage_duration_seconds",
help: "Latencies for http client requests",
labelNames: ["base", "stage"],
registers: []
});
export function registerMetrics(registry: Registry) {
registry.registerMetric(requestsCount);
registry.registerMetric(requestDuration);
registry.registerMetric(requestStageDuration);
}
function memoize<K, V>(fn: (key: K) => V): (key: K) => V {
const cache = new Map<K, V>();
return (key: K) => {
if (cache.has(key)) {
return cache.get(key) as V;
}
const val = fn(key);
cache.set(key, val);
return val;
};
}
interface Expander {
expand(parameters: any): string;
}
type Parse = (pathTemplate: string) => Expander;
export const parseUrlTemplate: Parse = memoize((pathTemplate: string) =>
urlTemplate.parse(pathTemplate)
);
interface Headers {
[header: string]: number | string | string[] | undefined;
}
interface Options {
baseUrl: string;
headers: Headers;
}
interface Timings {
start?: number;
socket?: number;
lookup?: number;
connect?: number;
upload?: number;
response?: number;
end?: number;
error?: number;
phases: {
wait?: number;
dns?: number;
tcp?: number;
request?: number;
firstByte?: number;
download?: number;
total?: number;
};
}
interface Result {
timings?: Timings;
statusCode?: number;
}
type RequestOptions =
| got.GotJSONOptions
| got.GotFormOptions<string | null>
| got.GotBodyOptions<string | null>;
type Method =
| "GET"
| "PUT"
| "POST"
| "PATCH"
| "DELETE"
| "HEAD"
| "OPTIONS"
| "TRACE"
| "CONNECT";
/**
* Class that can be usefully extended to abstract calls to a http apis.
* @example
* class ExampleCient extends HTTPClient {
* constructor() {
* super({ baseUrl: 'https://example.com/'});
* }
* getThing(id) {
* return this.request('GET', '/thing/{id}', {id});
* }
* }
*/
export class HTTPClient {
baseUrl: string;
headers: Headers;
/**
* Create a HTTPClient
* @param {string} baseUrl base url to use for each request
* @param {Object} headers headers to attach to each request
*/
constructor(opts: Options) {
const { baseUrl, headers } = opts;
this.baseUrl = baseUrl;
this.headers = headers;
// this.agent = agent;
}
/**
* execute request based an path template and params,
* Note that the path is always appended to the baseUrl, a leading /
* does not eliminate the path from the baseUrl.
* @param {string} method http method
* @param {string} pathTemplate RFC 6570 path template string
* @param {Object} [params={}] parameters to be injected into pathTemplate
* @param {Object} [body] body that will be json encoded and sent
* @return {Promise<Result>} result of request, (after passing through handlers)
*/
request(
method: Method,
pathTemplate: string,
params = {},
body?: {},
options?: RequestOptions
) {
const path = parseUrlTemplate(pathTemplate);
const url = resolveUrl(this.baseUrl, path.expand(params));
const stopTimer = requestDuration.startTimer();
const recordDone = (result: Result) => {
stopTimer({ method, path: pathTemplate, base: this.baseUrl });
if (result.timings) {
for (const [stage, value] of Object.entries(result.timings.phases)) {
if (stage === "total") {
continue;
}
if (typeof value !== "number") {
continue;
}
requestStageDuration.observe(
{ stage, base: this.baseUrl },
value / 1000
);
}
}
requestsCount.inc({
method,
path: pathTemplate,
code: result.statusCode || -1,
base: this.baseUrl
});
};
const defaultOptions: got.GotJSONOptions = {
method: method.toUpperCase(),
body,
headers: Object.assign({}, this.headers),
json: true,
retry: 0,
timeout: 60000
// agent: this.agent
};
return got(url, Object.assign(defaultOptions, options)).then(
(res: any) => {
recordDone(res);
return this._handlerResponse(res);
},
(err: got.GotError) => {
recordDone(err.response || err);
return this._handlerError(err);
}
);
}
/**
* map response to result (for overloading)
* @param {Object} res http response
* @return {(Result|Promise<Result>)}
*/
_handlerResponse(res: any) {
return res;
}
/**
* map response error to result (for overloading)
* @param {Object} err error from http response
* @param {Object} err.statusCode http status code
* @param {Object} err.response original http response
* @return {(Result|Promise<Result>)}
*/
_handlerError(err: Error) {
throw err;
}
}
|
3724db1956890b6fd2e16986c23b4c4ee13d20ec
|
TypeScript
|
design-automation/mobius-parametric-modeller-0-5-6
|
/assets/core/modules/basic/virtual.ts
| 3
| 3
|
/**
* The `virtual` module has functions for creating virtual geometric constructs.
* They are called 'virtual' due to the fact that they are not saved in the model.
* Currently there are two types of virtual constructs: planes and rays.
* Most of these functions neither make nor modify anything in the model.
* The exception is the `Vis` functions, that generate some polylines and polygons in the model
* to aid with visualizing these virtual constructs.
*/
/**
*
*/
import { TId, Txyz, EEntType, TPlane, TRay, TEntTypeIdx, TBBox } from '@libs/geo-info/common';
import { checkCommTypes, checkIDs, TypeCheckObj, IDcheckObj } from '../_check_args';
import { GIModel } from '@libs/geo-info/GIModel';
import { idsMake, idsBreak, getArrDepth } from '@libs/geo-info/id';
import { vecSub, vecMakeOrtho, vecNorm, vecCross, vecAdd, vecMult, vecFromTo, vecDiv, newellNorm, vecSum } from '@libs/geom/vectors';
import { _normal } from './calc';
// ================================================================================================
/**
* Creates a ray, centered at the origin.
* A ray is defined by a list of two lists, as follows: [origin, direction_vector].
*
* @param __model__
* @param origin Origin of ray: Position, Vertex, Point, or a list of three numbers
* @param dir_vec Direction of Ray: Vector, or list of three numbers
* @returns A list consisting of an origin and a vector, [origin, vector].
* @example virtual.Ray([1,2,3],[4,3,2])
* @example_info Creates a ray from [1,2,3] with the vector [4,3,2].
*
*/
export function Ray(__model__: GIModel, origin: TId|Txyz, dir_vec: Txyz): TRay {
// --- Error Check ---
const fn_name = 'virtual.Ray';
const ents_arr = checkCommTypes(fn_name, 'origin', origin, [TypeCheckObj.isOrigin]);
checkCommTypes(fn_name, 'dir_vec', dir_vec, [TypeCheckObj.isVector]);
// --- Error Check ---
if (!Array.isArray(origin)) {
const [ent_type, index]: [EEntType, number] = ents_arr as [EEntType, number];
const posi_i: number = __model__.geom.query.navAnyToPosi(ent_type, index)[0];
origin = __model__.attribs.query.getPosiCoords(posi_i);
}
return [
origin,
vecNorm(dir_vec)
];
}
// ================================================================================================
/**
* Creates a plane.
* A plane is define by a list of three lists, as folows: [origin, x_vector, xy_vector].
*
* @param __model__
* @param origin Origin of plane: Position, Vertex, Point, or a list of three numbers
* @param x_vec X axis vector of the plane: List of three numbers
* @param xy_vec A vector in the xy plane (not parallel to the x axis vector): List of three numbers
* @returns A list consisting of an origin and two normalised perpendicular vectors.
* @example virtual.Plane ([1,2,3],[4,3,2],[1,1,1])
* @example_info Creates a plane with its origin positioned at [1,2,3] and two normalised perpendicular vectors
* [0.74..., 0.56..., 0.37...] and [-0.53..., 0.15..., 0.83...] representing the X and Y axes of the plane.
*/
export function Plane(__model__: GIModel, origin: TId|Txyz, x_vec: Txyz, xy_vec: Txyz): TPlane {
// --- Error Check ---
const fn_name = 'virtual.Plane';
const ents_arr = checkCommTypes(fn_name, 'origin', origin, [TypeCheckObj.isOrigin]);
checkCommTypes(fn_name, 'x_vec', x_vec, [TypeCheckObj.isVector]);
checkCommTypes(fn_name, 'xy_vec', xy_vec, [TypeCheckObj.isVector]);
// --- Error Check ---
if (!Array.isArray(origin)) {
const [ent_type, index]: [EEntType, number] = ents_arr as [EEntType, number];
const posi_i: number = __model__.geom.query.navAnyToPosi(ent_type, index)[0];
origin = __model__.attribs.query.getPosiCoords(posi_i);
}
return [
origin,
vecNorm(x_vec),
vecNorm(vecMakeOrtho(xy_vec, x_vec))
];
}
// ================================================================================================
/**
* Create a ray, from a plane.
* The direction will be along the z axis.
* A plane is define by a list of three lists, as folows: [origin, x_vector, y_vector].
* A ray is defined by a list of two lists, as follows: [origin, direction_vector].
*
* @param __model__
* @param plane Plane or list of planes.
* @returns Ray or list of rays.
*/
export function RayFromPlane(planes: TPlane|TPlane[]): TRay|TRay[] {
// --- Error Check ---
// checkCommTypes('virtual.RayFromPlane', 'origin', planes, [TypeCheckObj.isPlane]); //TODO accept a list of planes
// TODO allow list of planes
// --- Error Check ---
return _rayFromPlane(planes);
}
function _rayFromPlane(planes: TPlane|TPlane[]): TRay|TRay[] {
if (getArrDepth(planes) === 2) {
const plane: TPlane = planes as TPlane;
return [plane[0], vecCross(plane[1], plane[2])];
} else {
return (planes as TPlane[]).map( plane => _rayFromPlane(plane)) as TRay[];
}
}
// ================================================================================================
/**
* Returns a ray for an edge, a face, or a polygons. For edges, it returns a ray along the edge, from teh start vertex to the end vertex
* For a face or polygon, it returns the ray that is the z-axis of the plane.
* ~
* For an edge, the ray vector is not normalised. For a face or polygon, the ray vector is normalised.
*
* @param __model__
* @param entities An edge, a face, or a polygon, or a list.
* @returns The ray.
*/
export function GetRay(__model__: GIModel, entities: TId|TId[]): TRay|TRay[] {
// --- Error Check ---
const ents_arr = checkIDs('virtual.GetRay', 'entities', entities,
[IDcheckObj.isID, IDcheckObj.isIDList], [EEntType.EDGE, EEntType.FACE, EEntType.PGON]) as TEntTypeIdx|TEntTypeIdx[];
// --- Error Check ---
return _getRay(__model__, ents_arr);
}
function _getRayFromEdge(__model__: GIModel, ent_arr: TEntTypeIdx): TRay {
const posis_i: number[] = __model__.geom.query.navAnyToPosi(ent_arr[0], ent_arr[1]);
const xyzs: Txyz[] = posis_i.map( posi_i => __model__.attribs.query.getPosiCoords(posi_i));
return [xyzs[0], vecSub(xyzs[1], xyzs[0])];
}
function _getRayFromFace(__model__: GIModel, ent_arr: TEntTypeIdx): TRay {
const plane: TPlane = _getPlane(__model__, ent_arr) as TPlane;
return _rayFromPlane(plane) as TRay;
}
function _getRay(__model__: GIModel, ents_arr: TEntTypeIdx|TEntTypeIdx[]): TRay|TRay[] {
if (getArrDepth(ents_arr) === 1) {
const ent_arr: TEntTypeIdx = ents_arr as TEntTypeIdx;
if (ent_arr[0] === EEntType.EDGE) {
return _getRayFromEdge(__model__, ent_arr);
} else if (ent_arr[0] === EEntType.FACE) {
return _getRayFromFace(__model__, ent_arr);
} else { // must be a polygon
const face_i: number = __model__.geom.query.navPgonToFace(ent_arr[1]);
return _getRayFromFace(__model__, [EEntType.FACE, face_i]);
}
} else {
return (ents_arr as TEntTypeIdx[]).map( ent_arr => _getRay(__model__, ent_arr)) as TRay[];
}
}
// ================================================================================================
/**
* Returns a plane from a polygon, a face, a polyline, or a wire.
* For polylines or wires, there must be at least three non-colinear vertices.
* ~
* The winding order is counter-clockwise.
* This means that if the vertices are ordered counter-clockwise relative to your point of view,
* then the z axis of the plane will be pointing towards you.
*
* @param entities Any entities
* @returns The plane.
*/
export function GetPlane(__model__: GIModel, entities: TId|TId[]): TPlane|TPlane[] {
// --- Error Check ---
const ents_arr = checkIDs('virtual.GetPlane', 'entities', entities, [IDcheckObj.isID, IDcheckObj.isIDList], null); // takes in any
// TODO [EEntType.PGON, EEntType.FACE, EEntType.PLINE, EEntType.WIRE]);
// --- Error Check ---
return _getPlane(__model__, ents_arr as TEntTypeIdx|TEntTypeIdx[]);
}
function _getPlane(__model__: GIModel, ents_arr: TEntTypeIdx|TEntTypeIdx[]): TPlane|TPlane[] {
if (getArrDepth(ents_arr) === 1) {
const ent_arr = ents_arr as TEntTypeIdx;
const posis_i: number[] = __model__.geom.query.navAnyToPosi(ent_arr[0], ent_arr[1]);
const unique_posis_i = Array.from(new Set(posis_i));
if (unique_posis_i.length < 3) { throw new Error('Too few points to calculate plane.'); }
const unique_xyzs: Txyz[] = unique_posis_i.map( posi_i => __model__.attribs.query.getPosiCoords(posi_i));
const origin: Txyz = vecDiv(vecSum(unique_xyzs), unique_xyzs.length);
// const normal: Txyz = newellNorm(unique_xyzs);
const normal: Txyz = _normal(__model__, ent_arr, 1) as Txyz;
const x_vec: Txyz = vecNorm(vecFromTo(unique_xyzs[0], unique_xyzs[1]));
const y_vec: Txyz = vecCross(normal, x_vec); // must be z-axis, x-axis
return [origin, x_vec, y_vec] as TPlane;
} else {
return (ents_arr as TEntTypeIdx[]).map(ent_arr => _getPlane(__model__, ent_arr)) as TPlane[];
}
}
// ================================================================================================
/**
* Returns the bounding box of the entities.
* The bounding box is an imaginary box that completley contains all the geometry.
* The box is always aligned with the global x, y, and z axes.
* The bounding box consists of a list of lists, as follows [[x, y, z], [x, y, z], [x, y, z], [x, y, z]].
* - The first [x, y, z] is the coordinates of the centre of the bounding box.
* - The second [x, y, z] is the corner of the bounding box with the lowest x, y, z values.
* - The third [x, y, z] is the corner of the bounding box with the highest x, y, z values.
* - The fourth [x, y, z] is the dimensions of the bounding box.
* @param __model__
* @param entities The etities for which to calculate the bounding box.
* @returns The bounding box consisting of a list of four lists.
*/
export function GetBBox(__model__: GIModel, entities: TId|TId[]): TBBox {
if (!Array.isArray(entities)) { entities = [entities]; }
// --- Error Check ---
const ents_arr: TEntTypeIdx[] = checkIDs('virtual.BBox', 'entities', entities, [IDcheckObj.isIDList], null) as TEntTypeIdx[]; // all
// --- Error Check ---
return _getBoundingBox(__model__, ents_arr);
}
function _getBoundingBox(__model__: GIModel, ents_arr: TEntTypeIdx[]): TBBox {
const posis_set_i: Set<number> = new Set();
for (const ent_arr of ents_arr) {
const ent_posis_i: number[] = __model__.geom.query.navAnyToPosi(ent_arr[0], ent_arr[1]);
for (const ent_posi_i of ent_posis_i) {
posis_set_i.add(ent_posi_i);
}
}
const unique_posis_i = Array.from(posis_set_i);
const unique_xyzs: Txyz[] = unique_posis_i.map( posi_i => __model__.attribs.query.getPosiCoords(posi_i));
const corner_min: Txyz = [Infinity, Infinity, Infinity];
const corner_max: Txyz = [-Infinity, -Infinity, -Infinity];
for (const unique_xyz of unique_xyzs) {
if (unique_xyz[0] < corner_min[0]) { corner_min[0] = unique_xyz[0]; }
if (unique_xyz[1] < corner_min[1]) { corner_min[1] = unique_xyz[1]; }
if (unique_xyz[2] < corner_min[2]) { corner_min[2] = unique_xyz[2]; }
if (unique_xyz[0] > corner_max[0]) { corner_max[0] = unique_xyz[0]; }
if (unique_xyz[1] > corner_max[1]) { corner_max[1] = unique_xyz[1]; }
if (unique_xyz[2] > corner_max[2]) { corner_max[2] = unique_xyz[2]; }
}
return [
[(corner_min[0] + corner_max[0]) / 2, (corner_min[1] + corner_max[1]) / 2, (corner_min[2] + corner_max[2]) / 2],
corner_min,
corner_max,
[corner_max[0] - corner_min[0], corner_max[1] + corner_min[1], corner_max[2] + corner_min[2]]
];
}
// ================================================================================================
/**
* Visualises a ray by creating a line.
*
* @param __model__
* @param rays A list of two list of three coordinates [origin, vector]: [[x,y,z],[x',y',z']]
* @returns entities, a line representing the ray.
* @example ray1 = virtual.visRay([[1,2,3],[0,0,1]])
*/
export function VisRay(__model__: GIModel, rays: TRay|TRay[], scale: number): TId[] {
// --- Error Check ---
const fn_name = 'virtual.visRay';
checkCommTypes(fn_name, 'ray', rays, [TypeCheckObj.isRay]); // TODO rays can be a list // add isRayList to enable check
checkCommTypes(fn_name, 'scale', scale, [TypeCheckObj.isNumber]);
// --- Error Check ---
return idsMake(_visRay(__model__, rays, scale)) as TId[];
}
function _visRay(__model__: GIModel, rays: TRay|TRay[], scale: number): TEntTypeIdx[] {
if (getArrDepth(rays) === 2) {
const ray: TRay = rays as TRay;
const origin: Txyz = ray[0];
const vec: Txyz = vecMult(ray[1], scale);
const end: Txyz = vecAdd(origin, vec);
// create orign point
const origin_posi_i: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(origin_posi_i, origin);
const point_i = __model__.geom.add.addPoint(origin_posi_i);
// create pline
const end_posi_i: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(end_posi_i, end);
const pline_i = __model__.geom.add.addPline([origin_posi_i, end_posi_i]);
// return the geometry IDs
return [
[EEntType.POINT, point_i],
[EEntType.PLINE, pline_i]
];
} else {
const ents_arr: TEntTypeIdx[] = [];
for (const ray of rays) {
const ray_ents: TEntTypeIdx[] = _visRay(__model__, ray as TRay, scale);
for (const ray_ent of ray_ents) {
ents_arr.push(ray_ent);
}
}
return ents_arr;
}
}
// ================================================================================================
/**
* Visualises a plane by creating a polygon and axis lines.
*
* @param __model__
* @param plane A list of lists
* @returns Entities, a polygon and two polyline representing the plane.
* @example plane1 = virtual.visPlane(position1, vector1, [0,1,0])
* @example_info Creates a plane with position1 on it and normal = cross product of vector1 with y-axis.
*/
export function VisPlane(__model__: GIModel, planes: TPlane|TPlane[], scale: number): TId[] {
// --- Error Check ---
const fn_name = 'virtual.visPlane';
checkCommTypes(fn_name, 'planes', planes, [TypeCheckObj.isPlane]); // TODO planes can be a list // add isPlaneList to enable check
checkCommTypes(fn_name, 'scale', scale, [TypeCheckObj.isNumber]);
// --- Error Check ---
return idsMake(_visPlane(__model__, planes, scale)) as TId[];
}
function _visPlane(__model__: GIModel, planes: TPlane|TPlane[], scale: number): TEntTypeIdx[] {
if (getArrDepth(planes) === 2) {
const plane: TPlane = planes as TPlane;
const origin: Txyz = plane[0];
const x_vec: Txyz = vecMult(plane[1], scale);
const y_vec: Txyz = vecMult(plane[2], scale);
let x_end: Txyz = vecAdd(origin, x_vec);
let y_end: Txyz = vecAdd(origin, y_vec);
const z_end: Txyz = vecAdd(origin, vecMult(vecCross(x_vec, y_vec), 0.1));
const plane_corners: Txyz[] = [
vecAdd(x_end, y_vec),
vecSub(y_end, x_vec),
vecSub(vecSub(origin, x_vec), y_vec),
vecSub(x_end, y_vec),
];
x_end = vecAdd(x_end, vecMult(x_vec, 0.1));
y_end = vecSub(y_end, vecMult(y_vec, 0.1));
// create the point
const origin_posi_i: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(origin_posi_i, origin);
const point_i = __model__.geom.add.addPoint(origin_posi_i);
// create the x axis
const x_end_posi_i: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(x_end_posi_i, x_end);
const x_pline_i = __model__.geom.add.addPline([origin_posi_i, x_end_posi_i]);
// create the y axis
const y_end_posi_i: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(y_end_posi_i, y_end);
const y_pline_i = __model__.geom.add.addPline([origin_posi_i, y_end_posi_i]);
// create the z axis
const z_end_posi_i: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(z_end_posi_i, z_end);
const z_pline_i = __model__.geom.add.addPline([origin_posi_i, z_end_posi_i]);
// create pline for plane
const corner_posis_i: number[] = [];
for (const corner of plane_corners) {
const posi_i: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(posi_i, corner);
corner_posis_i.push(posi_i);
}
const plane_i = __model__.geom.add.addPline(corner_posis_i, true);
// return the geometry IDs
return [
[EEntType.POINT, point_i],
[EEntType.PLINE, x_pline_i],
[EEntType.PLINE, y_pline_i],
[EEntType.PLINE, z_pline_i],
[EEntType.PLINE, plane_i]
];
} else {
const ents_arr: TEntTypeIdx[] = [];
for (const plane of planes) {
const plane_ents: TEntTypeIdx[] = _visPlane(__model__, plane as TPlane, scale);
for (const plane_ent of plane_ents) {
ents_arr.push(plane_ent);
}
}
return ents_arr;
}
}
// ================================================================================================
/**
* Visualises a bounding box by adding geometry to the model.
*
* @param __model__
* @param bboxes A list of lists.
* @returns Entities, twelve polylines representing the box.
* @example bbox1 = virtual.viBBox(position1, vector1, [0,1,0])
* @example_info Creates a plane with position1 on it and normal = cross product of vector1 with y-axis.
*/
export function VisBBox(__model__: GIModel, bboxes: TBBox|TBBox): TId[] {
// --- Error Check ---
const fn_name = 'virtual.visBBox';
checkCommTypes(fn_name, 'bbox', bboxes, [TypeCheckObj.isBBox]); // TODO bboxs can be a list // add isBBoxList to enable check
// --- Error Check ---
return idsMake(_visBBox(__model__, bboxes)) as TId[];
}
function _visBBox(__model__: GIModel, bboxs: TBBox|TBBox[]): TEntTypeIdx[] {
if (getArrDepth(bboxs) === 2) {
const bbox: TBBox = bboxs as TBBox;
const min: Txyz = bbox[1];
const max: Txyz = bbox[2];
// bottom
const ps0: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(ps0, min);
const ps1: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(ps1, [max[0], min[1], min[2]]);
const ps2: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(ps2, [max[0], max[1], min[2]]);
const ps3: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(ps3, [min[0], max[1], min[2]]);
// top
const ps4: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(ps4, [min[0], min[1], max[2]]);
const ps5: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(ps5, [max[0], min[1], max[2]]);
const ps6: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(ps6, max);
const ps7: number = __model__.geom.add.addPosi();
__model__.attribs.add.setPosiCoords(ps7, [min[0], max[1], max[2]]);
// plines bottom
const pl0 = __model__.geom.add.addPline([ps0, ps1]);
const pl1 = __model__.geom.add.addPline([ps1, ps2]);
const pl2 = __model__.geom.add.addPline([ps2, ps3]);
const pl3 = __model__.geom.add.addPline([ps3, ps0]);
// plines top
const pl4 = __model__.geom.add.addPline([ps4, ps5]);
const pl5 = __model__.geom.add.addPline([ps5, ps6]);
const pl6 = __model__.geom.add.addPline([ps6, ps7]);
const pl7 = __model__.geom.add.addPline([ps7, ps4]);
// plines vertical
const pl8 = __model__.geom.add.addPline([ps0, ps4]);
const pl9 = __model__.geom.add.addPline([ps1, ps5]);
const pl10 = __model__.geom.add.addPline([ps2, ps6]);
const pl11 = __model__.geom.add.addPline([ps3, ps7]);
// return
return [pl0, pl1, pl2, pl3, pl4, pl5, pl6, pl7, pl8, pl9, pl10, pl11].map(pl => [EEntType.PLINE, pl]) as TEntTypeIdx[];
} else {
const ents_arr: TEntTypeIdx[] = [];
for (const bbox of bboxs) {
const bbox_ents: TEntTypeIdx[] = _visBBox(__model__, bbox as TBBox);
for (const bbox_ent of bbox_ents) {
ents_arr.push(bbox_ent);
}
}
return ents_arr;
}
}
// ================================================================================================
|
6bad61e7ea5c57e3066f70f69326a1b730005a1b
|
TypeScript
|
Pupix/rift-explorer
|
/app/util/createSpec.ts
| 2.625
| 3
|
/**
* Legacy code from @Pupix which won't be updated.
* @since 2.0.1
*/
/* eslint-disable */
import { AxiosInstance } from "axios";
import { Agent } from "https";
import mixin from "mixin-deep";
import axios from "axios";
interface createSpecInterface {
address: string;
port: number;
protocol: string;
username: string;
password: string;
}
interface rpInterface {
uri: string;
json: any;
}
/**
* Simple axios instance with disabled SSL to allow the self signed cert
*/
const instance: AxiosInstance = axios.create({
httpsAgent: new Agent({
rejectUnauthorized: false,
}),
});
/**
* Since were using legacy code and not using request-promise we just create a
* small work wrapper
* @param uri {string}
* @param json {boolean}
*/
async function rp({ uri, json }: rpInterface): Promise<any> {
const request = await instance.get(uri);
return request.data;
}
/**
* @param address
* @param port
* @param username
* @param password
* @param protocol
* @returns {Promise<{basePath: string, paths: {}, host: string, produces: [string, string, string], schemes: [*], definitions: {}, swagger: string, consumes, info: {description: string, title: string, version: *}}>}
*/
export default async ({
address = "127.0.0.1",
port,
username = "riot",
password,
protocol = "https",
}: createSpecInterface): Promise<any> => {
const helpConsole = await rp({
uri: `${protocol}://${username}:${password}@${address}:${port}/help?format=Console`,
json: true,
});
const helpFull = await rp({
uri: `${protocol}://${username}:${password}@${address}:${port}/help?format=Full`,
json: true,
});
const builds = await rp({
uri: `${protocol}://${username}:${password}@${address}:${port}/system/v1/builds`,
json: true,
});
const swagger = {
host: `${address}:${port}`,
schemes: [protocol],
consumes: [
"application/json",
"application/vnd.api+json",
"application/x-yaml",
"application/x-msgpack",
"application/octet-stream",
"application/x-www-form-urlencoded",
"multipart/form-data",
],
definitions: {},
paths: {},
info: {
description: "Always up to date LCU API documentation",
title: "Rift Explorer 7",
version: builds.version,
},
produces: [
"application/json",
"application/x-yaml",
"application/x-msgpack",
],
swagger: "2.0",
components: {
securitySchemes: {
basicAuth: {
type: "http",
scheme: "basic",
},
},
},
security: {
basicAuth: [],
},
};
// Mix helps to get a more complete version
const funcs = {};
const types = {};
const events = {};
helpFull.functions.forEach((func) => {
funcs[func.name] = func;
});
helpFull.types.forEach((type) => {
types[type.name] = type;
});
helpFull.events.forEach((event) => {
events[event.name] = event;
});
helpFull.functions = funcs;
helpFull.types = types;
helpFull.events = events;
const help = mixin({}, helpConsole, helpFull);
Object.keys(help.types).forEach((type) => {
swagger.definitions[type] = {};
if (help.types[type].description) {
swagger.definitions[type].description = help.types[type].description;
}
// Object
if (help.types[type].fields) {
swagger.definitions[type].properties = {};
help.types[type].fields.forEach((field) => {
const fieldKey = field.name;
swagger.definitions[type].properties[fieldKey] = {};
swagger.definitions[type].properties[fieldKey].type = field.type.type;
if (field.description) {
swagger.definitions[type].properties[fieldKey].description =
field.description;
}
// Check if the type of the field is an (u)int
if (
/^u?int/.test(swagger.definitions[type].properties[fieldKey].type)
) {
swagger.definitions[type].properties[fieldKey].format =
swagger.definitions[type].properties[fieldKey].type;
swagger.definitions[type].properties[fieldKey].type = "integer";
return;
}
// Check if the type of the field is a double
if (swagger.definitions[type].properties[fieldKey].type === "string") {
return;
}
// Check if the type of the field is a double
if (swagger.definitions[type].properties[fieldKey].type === "double") {
swagger.definitions[type].properties[fieldKey].format =
swagger.definitions[type].properties[fieldKey].type;
swagger.definitions[type].properties[fieldKey].type = "number";
return;
}
// Check if the type of the field is a float
if (swagger.definitions[type].properties[fieldKey].type === "float") {
swagger.definitions[type].properties[fieldKey].format =
swagger.definitions[type].properties[fieldKey].type;
swagger.definitions[type].properties[fieldKey].type = "number";
return;
}
// Check if the type of the field is signed as `object`
if (swagger.definitions[type].properties[fieldKey].type === "object") {
swagger.definitions[type].properties[
fieldKey
].additionalProperties = true;
return;
}
// Check if the type of the field is signed as `boolean`
if (swagger.definitions[type].properties[fieldKey].type === "bool") {
swagger.definitions[type].properties[fieldKey].type = "boolean";
return;
}
if (swagger.definitions[type].properties[fieldKey].type === "map") {
swagger.definitions[type].properties[fieldKey].type = "object";
if (field.type.elementType === "object") {
swagger.definitions[type].properties[
fieldKey
].additionalProperties = {
additionalProperties: true,
type: "object",
};
return;
}
if (field.type.elementType === "string") {
swagger.definitions[type].properties[
fieldKey
].additionalProperties = {
type: "string",
};
return;
}
if (/^u?int/.test(field.type.elementType)) {
swagger.definitions[type].properties[
fieldKey
].additionalProperties = {
format: field.type.elementType,
type: "integer",
};
return;
}
if (
field.type.elementType === "double" ||
field.type.elementType === "float"
) {
swagger.definitions[type].properties[
fieldKey
].additionalProperties = {
format: field.type.elementType,
type: "number",
};
return;
}
swagger.definitions[type].properties[
fieldKey
].additionalProperties = {
$ref: `#/definitions/${field.type.elementType}`,
};
return;
}
if (swagger.definitions[type].properties[fieldKey].type === "vector") {
swagger.definitions[type].properties[fieldKey].type = "array";
if (field.type.elementType === "object") {
swagger.definitions[type].properties[fieldKey].items = {
additionalProperties: true,
type: "object",
};
return;
}
if (field.type.elementType === "string") {
swagger.definitions[type].properties[fieldKey].items = {
type: "string",
};
return;
}
if (/^u?int/.test(field.type.elementType)) {
swagger.definitions[type].properties[fieldKey].items = {
format: field.type.elementType,
type: "integer",
};
return;
}
if (
field.type.elementType === "double" ||
field.type.elementType === "float"
) {
swagger.definitions[type].properties[fieldKey].items = {
format: field.type.elementType,
type: "number",
};
return;
}
swagger.definitions[type].properties[fieldKey].items = {
$ref: `#/definitions/${field.type.elementType}`,
};
return;
}
// Check if the type is an actual object
// this is the case when a ref to another definition is made
// if (typeof swagger.definitions[type].properties[fieldKey].type === 'object') {
swagger.definitions[type].properties[
fieldKey
].$ref = `#/definitions/${swagger.definitions[type].properties[fieldKey].type}`;
delete swagger.definitions[type].properties[fieldKey].type;
// }
});
swagger.definitions[type].type = "object";
}
// String
if (help.types[type].values && help.types[type].values.length) {
swagger.definitions[type].type = "string";
swagger.definitions[type].enum = [];
help.types[type].values.forEach((value) => {
swagger.definitions[type].enum[value.value] = value.name;
});
swagger.definitions[type].enum = swagger.definitions[type].enum.filter(
(item) => !!item
);
}
});
const functions = {};
Object.keys(help.functions).forEach((func) => {
const helpFunc = help.functions[func];
if (!functions[helpFunc.url]) {
functions[helpFunc.url] = [];
}
functions[helpFunc.url].push(
Object.assign({ name: func }, help.functions[func])
);
});
Object.keys(functions).forEach((key) => {
const func = functions[key];
const result = {};
func.forEach((funcDef) => {
const method = funcDef.http_method || "";
result[method.toLowerCase()] = {
operationId: funcDef.name,
tags: funcDef.url
? [`Plugins ${funcDef.url.match("^/([^/]*)")[1]}`]
: funcDef.tags,
};
if (funcDef.description) {
result[method.toLowerCase()].summary = funcDef.description;
}
if (!result[method.toLowerCase()].tags.length) {
result[method.toLowerCase()].tags = ["Untagged"];
}
result[method.toLowerCase()].parameters = funcDef.arguments.map(
(argument) => {
let argumentLocation = "body";
if (new RegExp(`{${argument.name}}`).test(funcDef.url)) {
argumentLocation = "path";
// These are the only known header arguments
} else if (["JWT", "if-none-match"].includes(argument.name)) {
argumentLocation = "header";
}
const parameter = {
in: argumentLocation,
name: argument.name,
required: !argument.optional,
format: argument.format,
type: argument.type,
additionalProperties: argument.additionalProperties,
items: argument.items,
schema: argument.schema,
};
if (/^u?int/.test(argument.type.type)) {
parameter.format = argument.type.type;
parameter.type = "integer";
return parameter;
}
// Check if the type of the field is a double
if (argument.type.type === "string") {
parameter.type = argument.type.type;
}
// Check if the type of the field is a double
if (
argument.type.type === "double" ||
argument.type.type === "float"
) {
parameter.format = argument.type.type;
parameter.type = "number";
return parameter;
}
// Check if the type of the field is signed as `object`
if (argument.type.type === "object") {
parameter.additionalProperties = true;
parameter.type = argument.type.type;
return parameter;
}
// Check if the type of the field is signed as `boolean`
if (argument.type.type === "bool") {
parameter.type = "boolean";
return parameter;
}
if (argument.type.type === "map") {
parameter.type = "object";
if (argument.type.elementType === "object") {
parameter.additionalProperties = {
additionalProperties: true,
type: "object",
};
return parameter;
}
if (argument.type.elementType === "string") {
parameter.additionalProperties = {
type: "string",
};
return parameter;
}
if (/^u?int/.test(argument.type.elementType)) {
parameter.additionalProperties = {
format: argument.type.elementType,
type: "integer",
};
return parameter;
}
if (
argument.type.elementType === "double" ||
argument.type.elementType === "float"
) {
parameter.additionalProperties = {
format: argument.type.elementType,
type: "number",
};
return parameter;
}
parameter.additionalProperties = {
$ref: `#/definitions/${argument.type.elementType}`,
};
return parameter;
}
if (argument.type.type === "vector") {
parameter.type = "array";
if (argument.type.elementType === "object") {
parameter.items = {
additionalProperties: true,
type: "object",
};
return parameter;
}
if (argument.type.elementType === "string") {
parameter.items = {
type: "string",
};
return parameter;
}
if (/^u?int/.test(argument.type.elementType)) {
parameter.items = {
format: argument.type.elementType,
type: "integer",
};
return parameter;
}
if (
argument.type.elementType === "double" ||
argument.type.elementType === "float"
) {
parameter.items = {
format: argument.type.elementType,
type: "number",
};
return parameter;
}
parameter.items = {
$ref: `#/definitions/${argument.type.elementType}`,
};
return parameter;
}
parameter.schema = { $ref: `#/definitions/${argument.type.type}` };
delete parameter.type;
return parameter;
}
);
if (funcDef.http_method === "GET" || funcDef.http_method === "POST") {
if (funcDef.returns.type === "object") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
additionalProperties: true,
type: "object",
},
},
};
return;
}
if (funcDef.returns.type === "string") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "string",
},
},
};
return;
}
if (
funcDef.returns.type === "double" ||
funcDef.returns.type === "float"
) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
format: funcDef.returns.type,
type: "number",
},
},
};
return;
}
if (funcDef.returns.type === "bool") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "boolean",
},
},
};
return;
}
if (/^u?int/.test(funcDef.returns.type)) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "integer",
},
},
};
return;
}
// Check if the type of the field is signed as array of definitions
if (funcDef.returns.type === "vector") {
if (funcDef.returns.elementType === "object") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
additionalProperties: true,
type: funcDef.returns.elementType,
},
},
},
};
return;
}
if (funcDef.returns.elementType === "string") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
type: funcDef.returns.elementType,
},
},
},
};
return;
}
if (
funcDef.returns.elementType === "double" ||
funcDef.returns.elementType === "float"
) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
format: funcDef.returns.elementType,
type: "number",
},
},
},
};
return;
}
if (funcDef.returns.elementType === "bool") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
type: "boolean",
},
},
},
};
return;
}
if (/^u?int/.test(funcDef.returns.elementType)) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
type: "integer",
},
},
},
};
return;
}
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "array",
items: {
$ref: `#/definitions/${funcDef.returns.elementType}`,
},
},
},
};
return;
}
if (funcDef.returns.type === "map") {
if (funcDef.returns.elementType === "object") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
additionalProperties: true,
type: funcDef.returns.elementType,
},
},
},
};
return;
}
if (funcDef.returns.elementType === "string") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
type: funcDef.returns.elementType,
},
},
},
};
return;
}
if (
funcDef.returns.elementType === "double" ||
funcDef.returns.elementType === "float"
) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
format: funcDef.returns.elementType,
type: "number",
},
},
},
};
return;
}
if (funcDef.returns.elementType === "bool") {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
type: "boolean",
},
},
},
};
return;
}
if (/^u?int/.test(funcDef.returns.elementType)) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
type: "integer",
},
},
},
};
return;
}
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
type: "object",
additionalProperties: {
type: funcDef.returns.elementType,
},
},
},
};
return;
}
if (funcDef.returns.type) {
result[method.toLowerCase()].responses = {
200: {
description: "Successful response",
schema: {
$ref: `#/definitions/${Object.keys(funcDef.returns)[0]}`,
},
},
};
return;
}
result[method.toLowerCase()].responses = {
204: {
description: "No content",
},
};
// Check if the type of the field is signed as map of definitions
// if (/^map of .*$/.test(swagger.definitions[type].properties[fieldKey].type)) {
// const [, def] = swagger.definitions[type].properties[fieldKey].type.match(/^map of (.*)$/);
// swagger.definitions[type].properties[fieldKey].type = 'object';
// swagger.definitions[type].properties[fieldKey].additionalProperties = {
// $ref: `#/definitions/${def}`,
// };
// }
}
if (funcDef.http_method === "DELETE") {
result[method.toLowerCase()].responses = {
204: {
description: "No content",
},
};
}
});
functions[key] = result;
});
swagger.paths = functions;
return swagger;
};
/* eslint-enable */
|
137d65bd17e1195397ca8f5d6c26da63befeb864
|
TypeScript
|
end5/CoC-UEE-Web
|
/classes/classes/Perks/PiercedIcestonePerk.ts
| 2.75
| 3
|
import { PerkType } from "../PerkType";
import { Perk } from "../Perk";
/**
* Created by aimozg on 27.01.14.
*/
export class PiercedIcestonePerk extends PerkType {
public desc(params: Perk): string {
return "Reduces minimum lust by " + Math.round(params.value1) + ".";
}
public constructor() {
super("Pierced: Icestone", "Pierced: Icestone",
"You've been pierced with Icestone and your lust seems to stay a bit lower than before.");
}
}
|
27348c7c44a6d8e92f73803215e0f54626db1f8c
|
TypeScript
|
gmackie/home-cal
|
/src/types/index.ts
| 2.6875
| 3
|
export enum ProteinType {
CHICKEN = 'Chicken',
BEEF = 'Beef',
FISH = 'Fish',
SEAFOOD = 'Seafood',
TOFU = 'Tofu',
VEGETABLE = 'Vegetable',
}
export interface Meal {
mealName: string;
proteinType: ProteinType;
}
export interface MealCalendar {
meal: Meal;
date: Date;
}
|
679e6ea9c34feaa8bcf29ee166612634a9af55d6
|
TypeScript
|
ShotsOnTarget/RoRBuilder
|
/import/validateDescription.ts
| 2.96875
| 3
|
import colors from 'colors';
import { Ability } from '../src/helpers/abilities';
import { AbilityData } from './structureAbilities';
export const escapeRegExp = (string: string) => {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
};
// From a description, extract an array of all the replacements needed
export const extractComponentValueNames = (description: string): string[] => {
const regexp = /\{([A-Z\d_]+)\}/g;
return Array.from(description.matchAll(regexp)).map(m => m[1]);
};
export const descriptionRegexp = (description: string): string => {
return extractComponentValueNames(description).reduce((ret, val): string => {
return ret
.replace(`\\{${val}\\}`, '(.*)')
.replace(/ +/g, '\\s+')
.replace('<BR>', '<br>');
}, escapeRegExp(description));
};
// Create the map of componentValues based on old description
export const extractComponentValues = (
ability: Ability,
gameAbility: AbilityData,
): Partial<Ability> => {
const componentValueNames = extractComponentValueNames(
gameAbility.Description,
);
const matches = Array.from(
ability.description.matchAll(
new RegExp(descriptionRegexp(gameAbility.Description)),
),
);
if (matches.length > 0) {
const componentValues = Object.fromEntries(
componentValueNames.map((compValue, index) => {
const num = matches[0][1 + index].match(/(\d+)/);
return [compValue, Number(num ? num[0] : '0')];
}),
);
return { rawDescription: gameAbility.Description, componentValues };
} else {
console.log(
`No match for ${colors.cyan(ability.name)} (${colors.red(
gameAbility.AbilityID.toString(),
)})`,
);
console.log(colors.yellow(ability.description));
console.log(gameAbility.Description);
console.log(colors.gray(descriptionRegexp(gameAbility.Description)));
return {
rawDescription: gameAbility.Description,
componentValues: Object.fromEntries(
componentValueNames.map(compValue => [compValue, 0]),
),
};
}
return {};
};
// Convert something like COM_0_VAL0_DAMAGE, 100 to '100 health'
const componentValueToText = (name: string, number: number): string => {
if (name.endsWith('_DAMAGE')) {
return `${number} damage`;
} else if (name.endsWith('_TOD_SPIRITDAMAGE')) {
return `${number} Spirit damage`;
} else if (name.endsWith('_SPIRITDAMAGE')) {
return `${number} Spirit damage`;
} else if (name.endsWith('_TOD_CORPOREALDAMAGE')) {
return `${number} Corporeal damage`;
} else if (name.endsWith('_CORPOREALDAMAGE')) {
return `${number} Corporeal damage`;
} else if (name.endsWith('_TOD_ELEMENTALDAMAGE')) {
return `${number} Elemental damage`;
} else if (name.endsWith('_ELEMENTALDAMAGE')) {
return `${number} Elemental damage`;
} else if (name.endsWith('_DURA_SECONDS')) {
return `${number} seconds`;
} else if (name.endsWith('_FREQ_SECONDS')) {
return `${number} seconds`;
} else if (name.endsWith('_SECONDS')) {
return `${number} seconds`;
} else if (name.endsWith('_DURA_MINUTES')) {
return `${number} minutes`;
} else if (name.endsWith('_DURA_HOURS')) {
return `${number} hours`;
} else if (name.endsWith('_RADI_FEET')) {
return `${number} feet`;
} else if (name.endsWith('_ACTIONPOINTS')) {
return `${number} Action Points`;
} else if (name.endsWith('_HEALTH')) {
return `${number} health`;
}
return number.toString();
};
export const validateDescription = (
ability: Ability,
gameAbility: AbilityData,
): Partial<Ability> => {
const componentValues = ability.componentValues;
if (
componentValues === undefined ||
(componentValues && Object.values(componentValues).includes(0))
) {
console.log(
`Missing componentValues for ${colors.cyan(ability.name)} (${colors.red(
gameAbility.AbilityID.toString(),
)})`,
);
return {
rawDescription: gameAbility.Description,
};
}
const componentValueNames = extractComponentValueNames(
gameAbility.Description,
);
if (
Array.from(new Set(componentValueNames))
.sort()
.toString() !==
Object.keys(componentValues)
.sort()
.toString()
) {
console.log(
`componentValues mismatch for ${colors.cyan(ability.name)} (${colors.red(
gameAbility.AbilityID.toString(),
)}) expected:`,
componentValueNames,
);
return {
rawDescription: gameAbility.Description,
};
}
const description = componentValueNames.reduce((ret, name) => {
return ret.replace(
`{${name}}`,
componentValueToText(name, componentValues[name] || 0),
);
}, gameAbility.Description);
if (ability.description !== description) {
console.log(
`Description for ${colors.cyan(ability.name)} (${colors.red(
gameAbility.AbilityID.toString(),
)})`,
);
console.log(colors.red('From:'), ability.description);
console.log(colors.green('To:'), description);
return {
description,
rawDescription: gameAbility.Description,
};
}
return {
rawDescription: gameAbility.Description,
};
};
/*
const calculateDamage = (
ability: AbilityData,
component: AbilityData['Components'][0],
valIndex: number,
level: number,
effectiveLevel: number,
mastery: number,
staticLevel: number,
) => {
const multIndex = 0;
let num1 = 1;
if (component.Interval > 0) {
num1 = component.Duration / component.Interval;
}
let num2 = level;
if (level != effectiveLevel) {
let num3 = effectiveLevel <= 25 ? effectiveLevel : 25;
if (effectiveLevel > 40) {
num3 += effectiveLevel - 40;
} else if (level < 25) {
num3 = effectiveLevel;
}
num2 = num3 + mastery;
}
level = num2;
if (staticLevel > 0) {
num2 = staticLevel;
level = staticLevel;
}
let num4 = component.Values[valIndex];
let multiplier = component.Multipliers[multIndex];
let num5 = 0.166667;
let num6 = 1;
let num7 = 3;
if (component.Operation == ComponentOP.STAT_CHANGE) {
num5 = 1;
}
if (component.Duration > 0 && component.Interval > 0) {
num6 = component.Duration / component.Interval;
}
//num7 = component.A07;
//if (ability.Components[compIndex].A07 == 32)
if (component.A07 == 32) {
return num4;
}
let num8 = (((num2 - 1) * num5 * num4 + num4) * multiplier) / 100;
if (num6 > 1 && ability.ChannelInterval <= 0) num8 *= num6;
return num8;
};
*/
|
c8cdf75db582dd487e3f699a8202d0949bfe0622
|
TypeScript
|
webrats/NgRx-Angular-Complete
|
/src/app/counter1/state/counter.state.ts
| 2.515625
| 3
|
export interface CounterState {
counter :number ,
desc :String ,
}
export const initialState = {
counter : 0,
desc:"Default Desc"
}
|
10ee5e762fb1e6934462babe6c61c08e30d72f5b
|
TypeScript
|
mittalprince/Everyday-Stuff
|
/Angular/Form-validation/src/app/calender/calender.component.ts
| 2.75
| 3
|
import { Component, OnInit } from '@angular/core'
import * as Moment from 'moment'
import { extendMoment } from 'moment-range'
const moment = extendMoment(Moment)
@Component({
selector: 'app-calender',
templateUrl: './calender.component.html',
styleUrls: ['./calender.component.css']
})
export class CalenderComponent implements OnInit{
weekDays: any = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
]
calender: any ={
weeks: [],
current_month_string: moment().format('MMMM'), // Get Current Month Name
current_month_number: moment().month() + 1, // Get Current Month Number
current_date: moment().startOf('month'), // Get start date of current month
current_year: moment().year(), // Get current year
current_days_count: moment().daysInMonth(), // Get no of days of current month
first_day_number: moment().startOf('month').weekday() // Gets the day of the week
}
constructor(){
console.log(this.calender)
this.createCalenderFirstWeek()
}
createCalenderFirstWeek(){
let temp_first_week = []
for(let i = 0; i<this.calender.first_day_number; i++){
temp_first_week.push(null)
}
let temp_length = this.calender.first_day_number
for(let j=1; j<=(7 - temp_length); j++){
temp_first_week.push(j)
}
this.calender.weeks[0] = temp_first_week
this.createOtherWeeks()
}
createOtherWeeks(){
let start_point = this.calender.weeks[0][this.calender.weeks[0].length -1] + 1
this.calender.weeks[1] = []
let week_no = 1
for(let k=start_point; k<=this.calender.current_days_count; k++){
if(this.calender.weeks[week_no].length < 7){
this.calender.weeks[week_no].push(k)
}
else{
week_no += 1
this.calender.weeks[week_no] = [k]
}
}
var index_of_last_week = this.calender.weeks.length - 1
var length_of_last_week = this.calender.weeks[index_of_last_week].length
for(let i=length_of_last_week; i<7; i++){
this.calender.weeks[index_of_last_week].push(null)
}
}
dayActiveClassCheck(day){
let current_year = moment().year()
let current_month = moment().month() + 1
if(current_year == this.calender.current_year){
if(current_month == this.calender.current_month_number){
if(moment().date() > day){
return false
}
else{
return true
}
}
else if (current_month > this.calender.current_month_number) {
return false
}
else {
return true
}
}
else if (current_year > this.calender.current_year) {
return false
}
else {
return true
}
}
todayClassCheck(day){
if(moment().year() == this.calender.current_year){
if((moment().month()+1) == this.calender.current_month_number){
if(moment().date() == day){
return true
}
else{
return false
}
}
else{
return false
}
}
}
currentMonthChange(operation) {
var current_date = moment(this.calender.current_date)
if (operation == 'previous') {
this.calender.current_date = current_date.subtract(1, 'month')
} else if (operation == 'next') {
this.calender.current_date = current_date.add(1, 'month')
}
console.log(current_date)
this.calender.current_month_string = current_date.format('MMMM')
this.calender.current_year = current_date.year()
this.calender.current_days_count = current_date.daysInMonth()
this.calender.first_day_number = current_date.startOf('month').weekday()
this.calender.current_month_number = current_date.month() + 1
this.calender.weeks = []
this.createCalenderFirstWeek()
}
ngOnInit(){}
}
|
cad8d44b9eb0c277b92e349b9a4e1a27a29aa5af
|
TypeScript
|
KyleMayes/advent-of-code-2019
|
/source/day17.ts
| 3.28125
| 3
|
import * as _ from "lodash";
import { Grid2d } from "./common/grid2d";
import * as input from "./common/input";
import { execute } from "./common/intcode";
import { iota } from "./common/array";
type Move = "L" | "R" | number;
const memory = input.csv("day17.txt").map(c => parseInt(c, 10));
function view(): string {
let lines: string = "";
execute(
memory,
() => 0,
value => (lines += String.fromCharCode(value)),
);
return lines;
}
export function solve(): [number, number] {
let robotX = 0;
let robotY = 0;
let direction: "up" | "down" | "left" | "right" = "up";
const grid = new Grid2d<"visited" | "unvisited">();
let y = -1;
for (const line of view().split("\n")) {
y += 1;
for (let x = 0; x < line.length; ++x) {
const c = line.charAt(x);
if (c === "#") {
grid.write(x, y, "unvisited");
} else if (c === "^") {
grid.write(x, y, "visited");
robotX = x;
robotY = y;
}
}
}
let part1 = 0;
for (const [[x, y]] of grid.entries()) {
if (
grid.read(x + 1, y) !== undefined &&
grid.read(x - 1, y) !== undefined &&
grid.read(x, y + 1) !== undefined &&
grid.read(x, y - 1) !== undefined
) {
part1 += x * y;
}
}
let moves: Move[] = [];
const move = (dx: number, dy: number) => {
if (grid.read(robotX + dx, robotY + dy) === "unvisited") {
if (dx === 1) {
moves.push(direction === "up" ? "R" : "L");
direction = "right";
} else if (dx === -1) {
moves.push(direction === "down" ? "R" : "L");
direction = "left";
} else if (dy === 1) {
moves.push(direction === "right" ? "R" : "L");
direction = "down";
} else if (dy === -1) {
moves.push(direction === "left" ? "R" : "L");
direction = "up";
}
let tdx = 0;
let tdy = 0;
while (grid.read(robotX + dx, robotY + dy) !== undefined) {
robotX += dx;
robotY += dy;
grid.write(robotX, robotY, "visited");
tdx += dx;
tdy += dy;
}
moves.push(Math.max(Math.abs(tdx), Math.abs(tdy)));
return true;
} else {
return false;
}
};
while (move(1, 0) || move(-1, 0) || move(0, 1) || move(0, -1)) {}
// Built functions by hand.
const m: ("A" | "B" | "C")[] = [];
const a: Move[] = ["R", 6, "L", 10, "R", 10, "R", 10];
const b: Move[] = ["L", 10, "L", 12, "R", 10];
const c: Move[] = ["R", 6, "L", 12, "L", 10];
for (let i = 0; i < moves.length; ) {
if (_.isEqual(a, moves.slice(i, i + a.length))) {
i += a.length;
m.push("A");
continue;
}
if (_.isEqual(b, moves.slice(i, i + b.length))) {
i += b.length;
m.push("B");
continue;
}
if (_.isEqual(c, moves.slice(i, i + c.length))) {
i += c.length;
m.push("C");
continue;
}
console.log(moves.slice(i));
process.exit(1);
}
let string = m.join(",") + "\n" + a.join(",") + "\n" + b.join(",") + "\n" + c.join(",") + "\nn\n";
let ascii = iota(0, string.length).map(i => string.charCodeAt(i));
let part2 = 0;
execute(
memory,
() => ascii.shift()!,
value => (part2 = value),
[[0, 2]],
);
return [part1, part2];
}
if (require.main === module) {
const [part1, part2] = solve();
console.log(`Part 1: ${part1}`);
console.log(`Part 2: ${part2}`);
}
|
3d1a75e71e4a30fdea09a55455c0c520777a41bb
|
TypeScript
|
simultechnology/my-typescript-samples
|
/src/lib/ch1/main.ts
| 2.890625
| 3
|
/**
* get a price after discount
*
* @param price
* @param discount
*/
export function getFinalPrice(price: number, discount: number): number {
return price - (discount === 0 ? 0 : price / discount);
}
|
4f5b3dee35c6613fd1b784f0d3aa34d14361198e
|
TypeScript
|
gravyboat/syniti-take-home
|
/src/__tests__/validateData.tests.ts
| 2.734375
| 3
|
import { readFileSync } from 'fs';
import {
userAddressFormat,
validZipCode,
readJsonFile,
validateAndOptionallyWriteData,
} from '../validateData';
import path from 'path';
describe('read in data', () => {
test('reads in JSON aray file to confirm local file access', () => {
expect(readJsonFile('data/testData/data.json')).toBeInstanceOf(Array);
});
});
describe('checks zipcodes for validity', () => {
test('checks if a null zipcode is valid', () => {
expect(validZipCode(null)).toThrowError;
});
test('rhecks if an undefined zipcode is valid', () => {
expect(validZipCode(null)).toThrowError;
});
test('checks if a short zipcode is valid', () => {
expect(validZipCode('9810')).toBe(false);
});
test('checks if a long zipcode is valid', () => {
expect(validZipCode('981011')).toBe(false);
});
test('checks if a valid zipcode is valid', () => {
expect(validZipCode('98101')).toBe(true);
});
});
describe('validates JSON data', () => {
test('reads JSON array to ensure valid values are correct', () => {
expect(validateAndOptionallyWriteData('data/testData/data.json')).toBeInstanceOf(Array);
});
test('reads JSON array to ensure valid data is created and writes to the output file when only an output path is provided', () => {
validateAndOptionallyWriteData('data/testData/data.json', 'data/testData/valid.json');
expect(
readFileSync(
path.join(
__dirname,
'../../data/testData/mockResults/valid.json'
)
)
).toEqual(
readFileSync(path.join(__dirname, '../../data/testData/valid.json'))
);
});
test('reads JSON array to ensure valid data is created and writes to a file', () => {
validateAndOptionallyWriteData(
'data/testData/data.json',
'data/testData/valid.json',
'data/testData/invalid.json'
);
expect(
readFileSync(
path.join(
__dirname,
'../../data/testData/mockResults/valid.json'
)
)
).toEqual(
readFileSync(path.join(__dirname, '../../data/testData/valid.json'))
);
});
test('reads JSON array to ensure invalid data is created and writes to a file', () => {
validateAndOptionallyWriteData(
'data/testData/data.json',
'data/testData/valid.json',
'data/testData/invalid.json'
);
expect(
readFileSync(
path.join(
__dirname,
'../../data/testData/mockResults/invalid.json'
)
)
).toEqual(
readFileSync(
path.join(__dirname, '../../data/testData/invalid.json')
)
);
});
});
|
e63d139c3c64abda5b0856bb699afb65d7bf134d
|
TypeScript
|
kobajs/analytics-dashboard
|
/src/features/PortsSelection/PortsSelection.reducer.ts
| 2.78125
| 3
|
import { createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { createGenericSlice, GenericState } from '../../store/createGenericSlice';
import { Port } from '../../entities/Port';
import { PortsAPI } from '../../api/PortsAPI';
interface PortsSelectionState {
availablePorts: Port[];
origin: string;
destination: string;
}
type State = GenericState<PortsSelectionState>;
const initialState: State = {
data: {
availablePorts: [],
origin: '',
destination: '',
},
status: 'finished',
error: null,
};
export const getAllAvailablePorts = createAsyncThunk<
PortsSelectionState['availablePorts'],
null,
{
rejectValue: { code: string; message: string };
}
>('ports/getAllAvailablePorts', async (_, { rejectWithValue }) => {
try {
const availablePorts = await new PortsAPI().getAllPorts();
return availablePorts;
} catch (e) {
return rejectWithValue({ code: e.code, message: e.message });
}
});
const portsSlice = createGenericSlice({
name: 'ports',
initialState,
reducers: {
changePort(
state,
action: PayloadAction<{
location: 'origin' | 'destination';
value: string;
}>,
) {
state.data[action.payload.location] = action.payload.value;
},
},
extraReducers: (builder) => {
builder.addCase(getAllAvailablePorts.pending, (state, { payload }) => {
state.status = 'loading';
});
builder.addCase(getAllAvailablePorts.fulfilled, (state, { payload }) => {
state.status = 'finished';
state.data = {
...state.data,
availablePorts: payload,
// origin: payload[0].code,
// destination: payload[1].code,
origin: 'CNSGH',
destination: 'NLRTM',
};
});
builder.addCase(getAllAvailablePorts.rejected, (state, { payload }) => {
state.status = 'error';
state.error = {
name: payload.code,
message: payload.message,
};
});
},
});
const { actions, reducer } = portsSlice;
const { changePort } = actions;
export { changePort };
export default reducer;
|
57d7f7589a28ce7289a8aad7e082b0cdf6d7ea28
|
TypeScript
|
JakLind/octra
|
/src/app/media-components/obj/Line.ts
| 3.484375
| 3
|
/***
* Creates new Line Object for the canvas
* @param number
* @param size {width:w, height:h}
* @param pos {x: x, y: y}
* @constructor
*/
export class Line {
public number = -1;
mouseIn = function (x, y) {
const result =
(x > this.pos.x && x < (this.pos.x + this.size.width)) &&
(y > this.pos.y && y < (this.pos.y + this.size.height));
return result;
};
private size = {
width: 0,
height: 0
};
private pos = {
x: 0,
y: 0
};
/*
GETTER / SETTER
*/
private isMouseIn = false;
get Size(): any {
return {
width: this.size.width,
height: this.size.height
};
}
set Size(any) {
this.size.width = any.width;
this.size.height = any.height;
}
get Pos(): any {
return this.pos;
}
set Pos(any) {
this.pos.x = any.x;
this.pos.y = any.y;
}
constructor(number: number, size: any, pos: any) {
this.number = number;
this.size = {
width: size.width,
height: size.height
};
this.pos = {
x: pos.x,
y: pos.y
};
}
}
|
1298a03c12eb5a0619141c3cbfe4539a3572ebae
|
TypeScript
|
x-wk/redux-kangking-examples
|
/src/pages/home/counter.state.ts
| 2.953125
| 3
|
import AppState from '../../redux/state';
import {PayloadAction, ReduxStateProcessor} from 'redux-kangking';
import {ReduxStateObserver} from 'redux-kangking/observable';
import {Observable, of} from 'rxjs';
import {delay, filter, mergeMap} from 'rxjs/operators';
import {createSlice} from '../../redux/store';
// 前2个处理器不直接处理状态, 逻辑集中在第三个处理器中
const [incrementAsync, decrement, increment] =
createSlice((appState: AppState) => {
return appState.count || 0;
})
.addProcessor()
.addProcessor()
.addObserver({
actionName: 'increment',
// 处理状态
handleState(appState: AppState, prevState: number, payload: number) {
appState.count = prevState + payload;
},
// 监听并响应感兴趣的 Action , 返回值(流)会触发新的Action以改变自身的状态
observe(action$: Observable<PayloadAction<number>>, state$: Observable<AppState>): Observable<number> {
return action$.pipe(
filter(({type}) => type === incrementAsync.actionName || type === decrement.actionName),
mergeMap(({type, payload}) => {
if (type === decrement.actionName) {
// 减法
return of(-1 * payload!);
}
// 延迟加法
return of(payload!).pipe(delay(1000));
})
);
}
})
.getProcessors();
//////////////////////// 另一种使用方式(类继承) /////////////////////////////////////
abstract class CounterProcessor extends ReduxStateProcessor<AppState, number> {
getSliceState(appState: AppState): number {
return appState.count || 0;
}
}
class DecrementProcessor extends CounterProcessor {
}
export class IncrementAsyncProcessor extends CounterProcessor {
}
class CounterObserver extends ReduxStateObserver<AppState, number> {
getSliceState(appState: AppState): number {
return appState.count || 0;
}
// 更新状态
protected handleState(appState: AppState, prevState: number, actionData: number): void {
appState.count = prevState + actionData;
}
observe(action$: Observable<PayloadAction<any>>, appState$: Observable<AppState>): Observable<number> {
return action$.pipe(
filter(({type}) => type === incrementAsync.actionName || type === decrement.actionName),
mergeMap(({type, payload}) => {
if (type === decrement.actionName) {
return of(-1 * payload);
} else {
return of(payload).pipe(delay(1000));
}
})
);
}
}
// 可以提供一个更有意义的actionType, 否则随机生成一个
// export const incrementProcessor = new CounterObserver({actionName: 'increment'});
// export const decrementProcessor = new DecrementProcessor();
// const incrementAsyncProcessor = new IncrementAsyncProcessor();
export {increment as incrementProcessor, decrement as decrementProcessor, incrementAsync as incrementAsyncProcessor};
|
de290f6c749b9500e2be9d77867d72dbaab9c591
|
TypeScript
|
JordhanMadec/markdown-editor
|
/src/app/services/html-parser.service.ts
| 3.078125
| 3
|
export function parseMdTitleToHtml(markdown: string): string {
return !markdown ? '' : markdown
.replace(/######(.+)(\n|$)/g, '<h6>$1</h6>') // Parse h6
.replace(/#####(.+)(\n|$)/g, '<h5>$1</h5>') // Parse h5
.replace(/####(.+)(\n|$)/g, '<h4>$1</h4>') // Parse h4
.replace(/###(.+)(\n|$)/g, '<h3>$1</h3>') // Parse h3
.replace(/##(.+)(\n|$)/g, '<h2>$1</h2>') // Parse h2
.replace(/#(.+)(\n|$)/g, '<h1>$1</h1>'); // Parse h1
}
export function parseMdBoldToHtml(markdown: string): string {
return !markdown ? '' : markdown
.replace(/\*\*((.+| )+)\*\*/gm, '<strong>$1</strong>') // Parse bold text
.replace(/__((.+| )+)__/gm, '<strong>$1</strong>'); // Parse bold text alternative
}
export function parseMdItalicToHtml(markdown: string): string {
return !markdown ? '' : markdown
.replace(/\*((.+| )+)\*/gm, '<em>$1</em>') // Parse italic text
.replace(/_((.+| )+)_/gm, '<em>$1</em>'); // Parse italic text alternative
}
export function parseMdLinkToHtml(markdown: string): string {
return !markdown ? '' : markdown
.replace(/\[((.+| )+)\]\((.+)\)/g, '<a href="$3">$1</a>'); // Parse links
}
export function parseMdLinebreaksToHtml(markdown: string): string {
return !markdown ? '' : markdown
.replace(/\n{3,}/g, '<br/><br/>') // Parse multiple line break
.replace(/\n{2}/g, '<br/>') // Parse double line break
.replace(/\n/g, ''); // Parse single line break
}
export default function parseMdToHtml(markdown: string): string {
let parsed = markdown || '';
parsed = parseMdTitleToHtml(parsed);
parsed = parseMdLinebreaksToHtml(parsed);
parsed = parseMdBoldToHtml(parsed);
parsed = parseMdItalicToHtml(parsed);
parsed = parseMdLinkToHtml(parsed);
return parsed;
}
|
aed03d7d1fcd7c6ace84a0bb056d29a9877a2552
|
TypeScript
|
sheinsight/shineout
|
/src/utils/validate/regExp.ts
| 2.625
| 3
|
import nullable from './nullable'
export default (regExp: string | RegExp | undefined, options: {message: string}) =>
nullable((value: unknown, _formdata: any, callback: (x: boolean | Error) => void) => {
const { message } = options
const reg = typeof regExp === 'string' ? new RegExp(regExp) : regExp
if (!reg) {
callback(new Error(message))
return
}
if (reg.global) reg.lastIndex = 0
if (reg.test(value as string)) {
callback(true)
} else {
callback(new Error(message))
}
})
|
dee830560561b7cb0d8e42967eda930b71cdfd24
|
TypeScript
|
tmilos1/learning-ionic-favorite-quotes
|
/src/services/settings.ts
| 2.75
| 3
|
export class SettingsService
{
private alternativeColor: boolean = false;
setAlternativeColor(altColor: boolean) {
this.alternativeColor = altColor;
}
isAlternativeColor() : boolean {
return this.alternativeColor;
}
}
|
cf657b9eebd4f438390cf206dd98695dffcccead
|
TypeScript
|
jweber96/Secure-Login
|
/api/src/controller/UserController.ts
| 2.859375
| 3
|
import { Request, Response } from "express";
import { getRepository } from "typeorm";
import { validate } from "class-validator";
const otplib = require('otplib');
import { User } from "../entity/User";
import { Note } from "../entity/Note";
class UserController{
static getOneById = async (req: Request, res: Response) => {
//Get the ID from the url
const id: number = +res.locals.jwtPayload.userId;
//Get the User from database
const UserRepository = getRepository(User);
try {
const user = await UserRepository.findOne({
//select: ["Email", "FirstName", "LastName", "Phone", "Notes"],
//relations: ["note"],
where: { Id: id },
join: {
alias: "user",
leftJoinAndSelect: {
Notes: "user.Notes"
}
}
});
res.status(200).send(user);
} catch (error) {
res.status(404).send("User not found");
}
};
static newUser = async (req: Request, res: Response) => {
//Get parameters from the body
let { FirstName, LastName, Phone, Email, Password } = req.body;
let user = new User();
user.FirstName = FirstName;
user.LastName = LastName;
user.Phone = Phone;
user.Email = Email;
user.Password = Password;
user.TotpSecret = otplib.authenticator.generateSecret();
user.Role = 2;
//Validade if the parameters are ok
const errors = await validate(User);
if (errors.length > 0) {
res.status(400).send(errors);
return;
}
//Hash the Password, to securely store on DB
user.hashPassword();
//Try to save. If fails, the Email is already in use
const UserRepository = getRepository(User);
try {
await UserRepository.save(user);
} catch (e) {
res.status(409).send("Email already in use");
return;
}
//If all ok, send 201 response
res.status(201).send(user.TotpSecret);
};
static newNote = async (req: Request, res: Response) => {
//Get parameters from the body
let noteText = req.body.note;
const id: number = +res.locals.jwtPayload.userId;
const UserRepository = getRepository(User);
const user = await UserRepository.findOne({
where: { Id: id }
});
let note = new Note();
note.Note = noteText;
note.User = user;
//Validade if the parameters are ok
const errors = await validate(Note);
if (errors.length > 0) {
res.status(400).send(errors);
return;
}
//Try to save
const NoteRepository = getRepository(Note);
try {
await NoteRepository.save(note);
} catch (e) {
res.status(404).send("Failed to save note");
return;
}
//If all ok, send 201 response
res.status(201).send("Note created");
};
};
export default UserController;
|
2ed7690ad6bf7680d4ebbe8801dbc7d5fcc88e27
|
TypeScript
|
aklom/GetMeMyWeather
|
/src/interfaces.ts
| 2.671875
| 3
|
export enum Pages {
weather, sun
}
export enum Unit {
METRIC = "metric",
IMPERIAL = "imperial"
}
export interface stateInterface {
temperature: string | undefined;
weather: string | undefined;
windSpeed: string | undefined;
unit: Unit;
icon: string | undefined;
longitude: number | undefined;
latitude: number | undefined;
city: string | undefined;
activePage: Pages;
sunrise: number | undefined;
sunset: number | undefined;
currentTime: number | undefined;
timezone: number;
}
export interface actionInterface {
type: string;
payload: any;
}
|
2e553c5ad15da7ea7ad14fca05820207a987a2ed
|
TypeScript
|
luisneto98/rick-proxy
|
/src/app.controller.ts
| 2.6875
| 3
|
import { Controller, Get, Param, Query } from '@nestjs/common';
import { AppService } from './app.service';
import axios from 'axios';
import { identity } from 'rxjs';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
async getHello(
@Query('page') page: number,
@Query('limit') limit: number,
@Query('filter') filter: string
) {
const { data } = await axios.get('https://rickandmortyapi.com/api/character');
const results = data.results.filter(ch => ch.name.includes(filter || ''));
const count = results.length;
const pages = Math.ceil(count/limit);
const init = 0 + (page -1) * limit;
const end = 0 + limit * page;
console.log({
count,
pages,
init,
end
})
const newResult = results.slice(init, end);
const newInfo = {
pages,
count,
}
return {
info: newInfo,
results: newResult
};
}
@Get('/:id')
async getOne(
// @Query('page') page: number,
// @Query('limit') limit: number,
// @Query('filter') filter: string
@Param('id') id: number,
) {
const { data } = await axios.get(`https://rickandmortyapi.com/api/character/${id}`);
return data;
}
@Get('episode/:id')
async getEpisodes(
// @Query('page') page: number,
// @Query('limit') limit: number,
// @Query('filter') filter: string
@Param('id') id: number,
) {
const { data } = await axios.get(`https://rickandmortyapi.com/api/character/${id}`);
const { episode } = data
const episodeIds = episode.map(ep => ep.split('episode/')[1])
const { data: episodes } = await axios.get(`https://rickandmortyapi.com/api/episode/${episodeIds.join(',')}`);
return episodes;
}
}
|
9d2bb8794ca6d30c459a5f930ef1d591d6ada682
|
TypeScript
|
hotellaapp/WebApp
|
/hotella/src/app/pages/informacoes/components/inputs/components/smartTables/smartTables.service.ts
| 2.59375
| 3
|
import {Injectable} from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Informacao } from '../../../../../informacao';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class SmartTablesService {
private baseUrl: string = 'https://hotella.herokuapp.com/api';
constructor(private http : Http){
}
getAll(): Observable<Informacao[]>{
return this.http.get(`${this.baseUrl}/informacao/all`).map((res:Response) =>res.json()).catch(handleError);
}
saveInformation(data):Observable<Informacao[]> {
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
return this.http.post(`${this.baseUrl}/informacao/new`, JSON.stringify(data),options)
.catch(handleError);
}
deleteInformation(data):Observable<Informacao[]> {
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers,
body: JSON.stringify(data)
});
return this.http.delete(`${this.baseUrl}/informacao/remove`, options)
.catch(handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
updateInformation(data):Observable<Informacao[]>{
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
return this.http.put(`${this.baseUrl}/informacao/update/{id}`,JSON.stringify(data),options)
.catch(handleError);
}
}
// this could also be a private method of the component class
function handleError (error: any) {
// log error
// could be something more sofisticated
let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
console.error(errorMsg);
// throw an application level error
return Observable.throw(errorMsg);
}
|
a9de12a7b8e07887c38217f26103cfd19f2067cc
|
TypeScript
|
navelist89/AutochekChart
|
/food-lens-chart.ts
| 2.5625
| 3
|
import * as Highcharts from 'highcharts'
import { AutochekChartOption, chartCommon } from '@AutochekChart/chart.option'
import * as moment from 'moment'
import { DaySummaryWithArray, FoodlensDaySummary, FoodlensMeasurement } from 'autochek-base/objects/device-data-object'
chartCommon(Highcharts)
export function drawFoodLensChart(canvas: string, data: FoodlensMeasurement[] | FoodlensDaySummary[], opt?: AutochekChartOption) {
// recent 에서는 선 그래프 with 누적 cal
// 기간 별로는 선 그래프 total sumcal
let chartOption: any = {}
if (data.length > 0) {
chartOption = setFoodLensOption(data, opt)
Highcharts.chart(canvas, chartOption)
} else {
Highcharts.chart(canvas, {title: {text: ''}})
}
}
const options: any = {
title: {
text: 'temp'
},
chart: {
type: 'area'
},
time: {
timezone: 'Asia/Seoul'
},
xAxis: {
type: 'datetime',
title: {
text: '시간',
enabled: false
},
min: undefined,
max: undefined
},
yAxis: {
title: {
text: ''
},
startOnTick: false,
endOnTick: false
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: '칼로리',
data: []
}]
}
function setFoodLensOption(data: FoodlensDaySummary[] | FoodlensMeasurement[], opt?: AutochekChartOption) {
if (data[0] instanceof FoodlensMeasurement) {
const sTime = moment().startOf('day').valueOf()
const eTime = moment().endOf('day').valueOf()
options.chart.type = 'line'
options.title.text = '오늘 하루 시간별 섭취 칼로리'
options.xAxis.min = sTime
options.xAxis.max = eTime
const tempArray = []
tempArray.push({x: sTime, y: 0})
data.forEach(food => {
let sumCal = 0
food.composition.forEach(eachFood => {
sumCal += eachFood.calories
})
tempArray.push({x: food.date.getTime(), y: sumCal})
})
tempArray.push({x: eTime, y: 0})
options.series[0].data = tempArray
return options
} else {
options.chart.type = 'column'
options.title.text = '일자별 섭취 칼로리 차트'
const tempArray = []
data.forEach(foodSummary => {
tempArray.push({x: foodSummary.date.getTime(), y: foodSummary.sumCalories})
})
if (opt && opt.start) {
options.xAxis.min = opt.start.getTime()
}
if (opt && opt.end) {
options.xAxis.max = opt.end.getTime()
}
options.series[0].data = tempArray
return options
}
}
|
e4e5d076d0bd72485a4d5f11adfe644a05f3cbdc
|
TypeScript
|
sa-express-news/2018-primaries-server
|
/src/google-sheets/index.ts
| 2.640625
| 3
|
import * as fs from "fs";
import * as readlineSync from "readline-sync";
import { promisify } from "util";
import primaryIDMap from "../data-store/primaryIDMap";
import { Candidate, Primary, Race } from "../types";
const google = require("googleapis");
const googleAuth = require("google-auth-library");
import { GoogleCredentials } from "../types";
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
const SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"];
const TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + "/.credentials/";
const TOKEN_PATH = TOKEN_DIR + "2018-texas-primaries.json";
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
const authorize = async (credentials: GoogleCredentials): Promise<any> => {
const clientSecret = credentials.installed.client_secret;
const clientId = credentials.installed.client_id;
const redirectUrl = credentials.installed.redirect_uris[0];
const auth = new googleAuth();
const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
try {
const token = await readFile(TOKEN_PATH);
oauth2Client.credentials = JSON.parse(token.toString());
return oauth2Client;
} catch (e) {
return getNewToken(oauth2Client);
}
};
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
*/
const getNewToken = async (oauth2Client: any): Promise<any> => {
const authUrl = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: SCOPES,
});
console.log(`Authorize this app by visiting this url: ${authUrl}`);
const code = readlineSync.question("Enter the code from that page here: ");
try {
// Google's API for fetching a token requires a promise wrap
const getTokenPromise = () => {
return new Promise((resolve, reject) => {
oauth2Client.getToken(code, (error: any, tokens: any, response: any) => {
if (error) {
reject(error);
} else {
resolve(tokens);
}
});
});
};
const token = await getTokenPromise();
oauth2Client.credentials = token;
await storeToken(token);
return oauth2Client;
} catch (error) {
console.log(`Error while trying to receive access token: ${error}`);
}
};
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
const storeToken = async (token: object): Promise<void> => {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code !== "EEXIST") {
throw err;
}
}
try {
await writeFile(TOKEN_PATH, JSON.stringify(token));
console.log(`Token stored to ${TOKEN_PATH}`);
} catch (error) {
console.log(`Error storing token: ${error}`);
}
};
// Load client secrets from a local file.
const loadGoogleCredentials = async (): Promise<GoogleCredentials> => {
try {
const rawCredentials = await readFile("client_secret.json");
const credentials: GoogleCredentials = JSON.parse(rawCredentials.toString());
return credentials;
} catch (e) {
throw new Error(`Error loading credentials file: ${e}`);
}
};
/**
* Fetches all rows in a provided range for a given spreadsheet.
*/
const fetchData = async (auth: any, spreadsheetId: string, range: string): Promise<string[][]> => {
const sheets = google.sheets("v4");
const get = promisify(sheets.spreadsheets.values.get);
try {
const data: { values: string[][] } = await get({
auth,
range,
spreadsheetId,
});
return data.values;
} catch (error) {
throw error;
}
};
/**
* Fetches all rows in a provided range for a given spreadsheet.
* @param {string} spreadsheetID The ID of a Google spreadsheet, which is the long string after "/d/" in the URL.
* @param {string} spreadsheetRange The range to pull from the spreadsheet, formatted as "{Sheet Name}!Row:Column"
*/
export const fetchGoogleSheetData = async (spreadsheetID: string, spreadsheetRange: string): Promise<string[][]> => {
try {
const credentials = await loadGoogleCredentials();
const oAuthClient = await authorize(credentials);
const data = await fetchData(oAuthClient, spreadsheetID, spreadsheetRange);
return data;
} catch (error) {
throw new Error(`Error fetching data from Google Sheets: ${error}`);
}
};
// Construct an array of Primary data objects from an array of string arrays
export const buildPrimaries = (data: string[][]): Primary[] => {
const primaries: Primary[] = [];
const uniqueRaceNames = new Set<string>(getAllAtSubarrayIndex(data, 0));
uniqueRaceNames.forEach((raceName: string) => {
const raceRows = data.filter((row: string[]) => row[0] === raceName && isPrimaryRow(row));
const races: Race[] = raceRows.map((row) => buildRace(row));
primaries.push({
id: primaryIDMap.get(raceName),
races,
title: raceName,
});
});
return primaries;
};
// Construct a Race object from an array of strings formatted like so:
// [race name, isRepublican, candidate, votes, candidate, votes, ... candidate, votes]
export const buildRace = (array: string[]): Race => {
return {
candidates: buildCandidates(array.slice(2)),
isRepublican: array[1].toLowerCase() === "true",
title: array[0],
};
};
// Given an array of arrays, get the (i)th element of every subarray.
export const getAllAtSubarrayIndex = (arrays: any[][], index: number): any[] => {
const itemsAtI: any[] = [];
arrays.forEach((array: any[]) => {
if (array.length - 1 >= index) {
itemsAtI.push(array[index]);
}
});
return itemsAtI;
};
// Assumes array is structured like ['candidate', '#', 'candidate', '#']
export const buildCandidates = (array: string[]): Candidate[] => {
const scrubSignifiers = (string: string): string => {
let returnString = string;
returnString = returnString.replace("✔", "");
returnString = returnString.replace("(i)", "");
returnString = returnString.replace("(runoff)", "");
return returnString;
}
const candidates: Candidate[] = [];
for (let i = 0; i < array.length - 1; i += 2) {
if (array[i].length > 0) {
const voteCount = parseInt(array[i + 1], 10);
const isIncumbent = array[i].includes("(i)");
const isWinner = array[i].includes("✔");
const isRunoff = array[i].includes("(runoff)");
const candidate: Candidate = {
name: scrubSignifiers(array[i]),
votes: isNaN(voteCount) ? 0 : voteCount,
incumbent: isIncumbent,
winner: isWinner,
runoff: isRunoff,
};
candidates.push(candidate);
}
}
return candidates;
};
// Evaluates whether an array of strings matches the data structure we use in Google Sheets:
// [race title, isRepublican, candidate, votes, candidate, votes, ... candidate, votes]
// Stops evaluating after the first candidate - vote pair, because the candidate-building function
// will omit garbage data if necessary.
export const isPrimaryRow = (array: string[]): boolean => {
if (array.length < 4) {
return false;
} else if (array[0].length === 0 || array[1].length === 0 || array[2].length === 0 || array[3].length === 0) {
return false;
}
let isPrimary = true;
if (!array[0] || array[0] === "") {
isPrimary = false;
}
const secondItem = array[1].toLowerCase();
if (secondItem !== "true" && secondItem !== "false") {
isPrimary = false;
}
return isPrimary;
};
|
972d04806be9c3183ac63e8fa3fdf2b8a7718b32
|
TypeScript
|
IvanPopov/akra-engine-core
|
/src/akra-ui/ui/Vector.ts
| 2.609375
| 3
|
/// <reference path="../idl/IUILabel.ts" />
/// <reference path="../idl/IUIVector.ts" />
/// <reference path="Component.ts" />
module akra.ui {
import Vec2 = math.Vec2;
import Vec3 = math.Vec3;
import Vec4 = math.Vec4;
function prettifyNumber(x: float): string {
if (x === math.floor(x)) {
return "" + x + ".";
}
return <string><any>x.toFixed(2);
}
class ChangedSignal extends Signal<IUIVector> {
emit(pLabel: IUILabel, sValue: string): void {
var pVector: Vector = <Vector>this.getSender();
if (pVector.$lock.prop("checked")) {
//pVector.x.setText(pVector.y.setText(pVector.z.setText(pVector.w.setText(sValue;
pVector.x.setText(sValue);
pVector.y.setText(sValue);
pVector.z.setText(sValue);
pVector.w.setText(sValue);
}
super.emit(pVector.getValue());
}
}
export class Vector extends Component implements IUIVector {
changed: ISignal<{ (pVector: IUIVector, v: any): void; }>;
x: IUILabel;
y: IUILabel;
z: IUILabel;
w: IUILabel;
totalComponents: uint = 4;
protected _iFixed: uint = 2;
protected _bEditable: boolean = false;
protected $lock: JQuery;
constructor(ui, options?, eType: EUIComponents = EUIComponents.VECTOR) {
super(ui, options, eType);
this.template("Vector.tpl");
this.x = <IUILabel>this.findEntity('x');
this.y = <IUILabel>this.findEntity('y');
this.z = <IUILabel>this.findEntity('z');
this.w = <IUILabel>this.findEntity('w');
//this.connect(this.x, SIGNAL(changed), SLOT(changed));
//this.connect(this.y, SIGNAL(changed), SLOT(changed));
//this.connect(this.z, SIGNAL(changed), SLOT(changed));
//this.connect(this.w, SIGNAL(changed), SLOT(changed));
this.x.changed.connect(this.changed);
this.y.changed.connect(this.changed);
this.z.changed.connect(this.changed);
this.w.changed.connect(this.changed);
this.$lock = this.getElement().find("input[type=checkbox]:first");
this.setVec4(Vec4.temp(0.));
}
protected setupSignals(): void {
this.changed = this.changed || new ChangedSignal(this);
super.setupSignals();
}
getValue(): any {
switch (this.totalComponents) {
case 2: return this.toVec2();
case 3: return this.toVec3();
case 4: return this.toVec4();
}
return null;
}
_createdFrom($comp: JQuery): void {
var bValue: boolean = isDefAndNotNull($comp.attr("editable")) || false;
var sPostfix: string = $comp.attr("postfix") || null;
this.x.setPostfix(sPostfix);
this.y.setPostfix(sPostfix);
this.z.setPostfix(sPostfix);
this.w.setPostfix(sPostfix);
this.editable(bValue);
}
editable(bValue: boolean = true): void {
if (bValue) {
this.getElement().addClass("editable");
this.$lock.show();
}
else {
this.getElement().removeClass("editable");
this.$lock.hide();
}
this.x.editable(bValue);
this.y.editable(bValue);
this.z.editable(bValue);
this.w.editable(bValue);
this._bEditable = bValue;
}
isEditable(): boolean {
return this._bEditable;
}
protected useComponents(n: uint): void {
if (n === this.totalComponents) {
return;
}
var pSpanList: JQuery = this.getElement().find(">span");
switch (n) {
case 2:
$(pSpanList[3]).css("display", "none");
$(pSpanList[2]).css("display", "none");
break;
case 3:
$(pSpanList[3]).css("display", "none");
$(pSpanList[2]).css("display", "-block");
break;
case 4:
$(pSpanList[3]).css("display", "-block");
$(pSpanList[2]).css("display", "-block");
}
this.totalComponents = n;
}
setVec2(v: IVec2): void {
var n: uint = this._iFixed;
this.x.setText(prettifyNumber(v.x));
this.y.setText(prettifyNumber(v.y));
this.useComponents(2);
}
setVec3(v: IVec3): void {
var n: uint = this._iFixed;
this.x.setText(prettifyNumber(v.x));
this.y.setText(prettifyNumber(v.y));
this.z.setText(prettifyNumber(v.z));
this.useComponents(3);
}
setVec4(v: IVec4): void {
var n: uint = this._iFixed;
this.x.setText(prettifyNumber(v.x));
this.y.setText(prettifyNumber(v.y));
this.z.setText(prettifyNumber(v.z));
this.w.setText(prettifyNumber(v.w));
this.useComponents(4);
}
setColor(c: IColorValue): void {
this.x.setText(prettifyNumber(c.r));
this.y.setText(prettifyNumber(c.g));
this.z.setText(prettifyNumber(c.b));
this.w.setText(prettifyNumber(c.a));
this.useComponents(4);
}
toVec2(): IVec2 {
return Vec2.temp(
parseFloat(this.x.getText()),
parseFloat(this.y.getText()));
}
toVec3(): IVec3 {
return Vec3.temp(
parseFloat(this.x.getText()),
parseFloat(this.y.getText()),
parseFloat(this.z.getText()));
}
toVec4(): IVec4 {
return Vec4.temp(
parseFloat(this.x.getText()),
parseFloat(this.y.getText()),
parseFloat(this.z.getText()),
parseFloat(this.w.getText()));
}
protected finalizeRender(): void {
super.finalizeRender();
this.getElement().addClass("component-vector");
}
}
register("Vector", Vector);
}
|
f74206606f639c69d1668d0e74e11647725b16fa
|
TypeScript
|
nojaf/thunderstone
|
/tasks/thunderstoneProcessor.ts
| 2.546875
| 3
|
/// <reference path="interface.ts" />
/// <reference path="../typings/tsd.d.ts" />
import cheerio = require("cheerio");
import _ = require("underscore");
//#region parse html
export function parseHtmlFiles(htmlFiles: IHtmlFile[], cssFiles: ICssFile[]): void {
"use strict";
for (var h: number = 0; h < htmlFiles.length; h++) {
parseHtmlFile(htmlFiles[h], cssFiles);
}
}
function parseHtmlFile(htmlFile: IHtmlFile, cssFiles: ICssFile[]): void {
"use strict";
var $ = cheerio.load(htmlFile.content);
for (var c: number = 0; c < cssFiles.length; c++) {
parseHtmlFileWithCssFile(htmlFile, cssFiles[c], $);
sortHtmlResult(htmlFile);
}
}
function parseHtmlFileWithCssFile(htmlFile: IHtmlFile, cssFile: ICssFile, $: CheerioStatic): void {
"use strict";
if(doesHtmlReferenceStyleSheet($, cssFile)) {
for (var s: number = 0; s < cssFile.selectors.length; s++) {
parseHtmlFileWithCssFileAndSelector(htmlFile, cssFile, $, cssFile.selectors[s]);
}
}
}
function sortHtmlResult(htmlFile: IHtmlFile):void {
htmlFile.selectorResults = _.sortBy(htmlFile.selectorResults,
(result: ISelectorResult) => {
result.matchingSelectors = _.sortBy(result.matchingSelectors,
(selector: string) => {
return selector;
});
return result.cssFile.fileName;
});
}
function parseHtmlFileWithCssFileAndSelector(htmlFile: IHtmlFile, cssFile: ICssFile, $: CheerioStatic, selector: string) {
"use strict";
var selectorInHtml: Cheerio = $(selector);
if (selectorInHtml.length > 0) {
addSelectorMathching(htmlFile, selector, cssFile);
}
}
function addSelectorMathching(htmlFile: IHtmlFile, selector: string, cssFile: ICssFile): void {
"use strict";
var existingResultFile: ISelectorResult = findExistingSelectorMatch(htmlFile, cssFile);
if (existingResultFile) {
existingResultFile.matchingSelectors.push(selector);
} else {
addNewSelectorMatchToHtmlFile(htmlFile, selector, cssFile);
}
}
function findExistingSelectorMatch(htmlFile: IHtmlFile, cssFile: ICssFile): ISelectorResult {
"use strict";
return _.find(htmlFile.selectorResults,(result: ISelectorResult) => {
return (result.cssFile === cssFile);
});
}
function addNewSelectorMatchToHtmlFile(htmlFile: IHtmlFile, selector: string, cssFile: ICssFile): void {
"use strict";
var result: ISelectorResult = {
cssFile: cssFile,
matchingSelectors: [selector]
};
htmlFile.selectorResults.push(result);
}
//#endregion
//#region parse css
export function parseCssFiles(cssFiles: ICssFile[], htmlFiles: IHtmlFile[]): void {
"use strict";
for (var i: number = 0; i < cssFiles.length; i++) {
parseCssFile(cssFiles[i], htmlFiles);
}
}
function parseCssFile(cssFile: ICssFile, htmlFiles: IHtmlFile[]): void {
"use strict";
for (var i: number = 0; i < htmlFiles.length; i++) {
parseCssFileWithGivenHtmlFile(cssFile, htmlFiles[i]);
sortCssResult(cssFile);
}
}
function parseCssFileWithGivenHtmlFile(cssFile: ICssFile, htmlFile: IHtmlFile): void{
"use strict";
var $: CheerioStatic = cheerio.load(htmlFile.content);
if(doesHtmlReferenceStyleSheet($, cssFile)) {
for (var s: number = 0; s < cssFile.selectors.length; s++) {
parseCssFileWithGivenHtmlFileAndGivenSelector(cssFile, htmlFile,$, cssFile.selectors[s]);
}
}
}
function doesHtmlReferenceStyleSheet($: CheerioStatic, cssFile:ICssFile):boolean{
return ($("html").text().indexOf(cssFile.fileName) !== -1) || ($("link[href*='" + cssFile.fileName + "']").length > 0);
}
function sortCssResult(cssFile: ICssFile): void {
cssFile.usageResults = _.sortBy(cssFile.usageResults,
(usage: IHtmlUsageResult) => {
usage.matchingSelectors = _.sortBy(usage.matchingSelectors,
(htmlSelector: IHtmlCssSelectorMatch) => {
return htmlSelector.selector;
});
return usage.htmlFile.fileName;
});
}
function parseCssFileWithGivenHtmlFileAndGivenSelector(cssFile: ICssFile, htmlFile: IHtmlFile, $: CheerioStatic, selector: string): void {
"use strict";
var matchingSelector = $(selector);
if (matchingSelector.length > 0) {
addHtmlPageToUsage(cssFile, htmlFile, selector, matchingSelector.length);
}
}
function addHtmlPageToUsage(cssFile: ICssFile, htmlFile: IHtmlFile, selector: string, count: number): void {
"use strict";
var existingUsageResult: IHtmlUsageResult = findExistingHtmlUsageResult(cssFile, htmlFile);
if (existingUsageResult) {
addSelectorToExistingUsage(existingUsageResult, selector, count);
} else {
addNewUsageToCssFile(cssFile, htmlFile, selector, count);
}
}
function findExistingHtmlUsageResult(cssFile: ICssFile, htmlFile: IHtmlFile): IHtmlUsageResult {
"use strict";
return _.find(cssFile.usageResults,(usageResult: IHtmlUsageResult): boolean => {
return (usageResult.htmlFile === htmlFile);
});
}
function addNewUsageToCssFile(cssFile: ICssFile, htmlFile: IHtmlFile, selector: string, count: number): void {
"use strict";
cssFile.usageResults.push({
htmlFile: htmlFile,
matchingSelectors: [{
count: count,
selector:selector
}]
});
}
function addSelectorToExistingUsage(usageResult: IHtmlUsageResult, selector: string, count: number): void {
"use strict";
usageResult.matchingSelectors.push({
selector: selector,
count:count
});
}
//#endregion
|
0867e5e6096679d5ce2a78eb2e08faccac74618a
|
TypeScript
|
lulzzz/topical
|
/packages/botbuilder-topical/src/SimpleForm.ts
| 2.84375
| 3
|
import { Topic, TopicInstance, TextPrompt, TopicWithChild } from './topical';
import { BotContext } from 'botbuilder';
export interface SimpleFormMetadata {
type: 'string';
prompt: string;
}
export interface SimpleFormSchema {
[field: string]: SimpleFormMetadata;
}
export interface SimpleFormData {
[field: string]: string;
}
export interface SimpleFormState {
form: SimpleFormData;
schema: SimpleFormSchema;
child: string;
}
export interface SimpleFormInitArgs {
schema: SimpleFormSchema
}
export interface SimpleFormReturnArgs {
form: SimpleFormData;
}
interface SimpleFormPromptState {
prompt: string;
}
export class SimpleForm <
Context extends BotContext = BotContext
> extends TopicWithChild<SimpleFormInitArgs, SimpleFormState, SimpleFormReturnArgs, Context> {
private textPrompt: TextPrompt<SimpleFormPromptState, Context>;
constructor (
name?: string
) {
super(name);
this.textPrompt = new TextPrompt<SimpleFormPromptState, Context>(this.name)
.maxTurns(100)
.prompter(async (context, instance, result) => {
await context.sendActivity(instance.state.promptState.prompt);
});
this
.onChildReturn(this.textPrompt, async (context, instance, childInstance) => {
const metadata = instance.state.schema[childInstance.returnArgs.name];
if (metadata.type !== 'string')
throw `not expecting type "${metadata.type}"`;
instance.state.form[childInstance.returnArgs.name] = childInstance.returnArgs.result.value;
this.clearChild(context, instance);
await this.doNext(context, instance.name);
});
}
async init(
context: Context,
instance: TopicInstance<SimpleFormState, SimpleFormReturnArgs>,
args: SimpleFormInitArgs
) {
instance.state.schema = args.schema;
instance.state.form = {};
await this.doNext(context, instance);
}
async next(
context: Context,
instance: TopicInstance<SimpleFormState, SimpleFormReturnArgs>,
) {
for (let name of Object.keys(instance.state.schema)) {
if (!instance.state.form[name]) {
const metadata = instance.state.schema[name];
if (metadata.type !== 'string')
throw `not expecting type "${metadata.type}"`;
this.setChild(context, instance, await this.textPrompt.createInstance(context, instance, {
name,
promptState: {
prompt: metadata.prompt,
},
}));
break;
}
}
if (!this.hasChild(context, instance)) {
this.returnToParent(instance, {
form: instance.state.form
});
}
}
async onReceive(
context: Context,
instance: TopicInstance<SimpleFormState, SimpleFormReturnArgs>,
) {
if (!await this.dispatchToChild(context, instance))
throw "a prompt should always be active";
}
}
|
e2a5580aae5115c5e096169046f135c949a6aa70
|
TypeScript
|
Jitzek/jitzek.github.io-old
|
/static/js/linux/commands.ts
| 3.046875
| 3
|
function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function removeWhiteSpaceEntries(array: Array<string>) {
return array.filter(function (str: string) { return /\S/.test(str); })
}
class Command {
id: string;
help: string;
man: Object;
fs: Filesystem;
terminal: Terminal;
forcestop: boolean = false;
constructor(fs: Filesystem, terminal: Terminal) {
this.fs = fs;
this.terminal = terminal;
};
async execute(args: Array<any>, user: Object, print: boolean): Promise<any> { }
print(output: any): void { }
async stop(): Promise<void> {
this.forcestop = true;
}
}
class Cat extends Command {
id = 'cat';
help: string = 'concatenate files and print on the standard output';
man = {};
constructor(fs: Filesystem, terminal: Terminal) {
super(fs, terminal);
}
execute(args: Array<any>, user: Object = null, print = true): any {
if (args.length < 1) {
// Display help
if (print) this.print('cat: help placeholder text');
return;
}
// Determine additional parameters ('-', '--')
//
// Get location of file
let location = args[0] instanceof mFile || args[0] instanceof mDirectory ? args[0] : this.fs.getLocation(args[0]);
// Check if location is file
if (!this.fs.isFile(location)) {
let output = `cat: cannot open ${args[0]}`;
if (print) this.print(output);
return output;
}
let output = location.content;
if (print) this.print(output);
// Output is content of file
return output;
}
print(output: any) {
this.terminal.ui.innerHTML += `${this.terminal.tline_start}${output}${this.terminal.tline_end}`;
}
}
class Clear extends Command {
id = 'clear';
help = 'clear the terminal screen';
man = {};
constructor(fs: Filesystem, terminal: Terminal) {
super(fs, terminal);
}
async execute(args: string[], user: Object = null, print = false): Promise<any> {
// Determine additional parameters ('-', '--')
//
this.terminal.ui.innerHTML = '';
//if (print) this.print();
return false;
}
print(output: any = null) {
return;
}
}
class Echo extends Command {
id = 'echo';
help = 'write arguments to the standard output.';
man: {};
constructor(fs: Filesystem, terminal: Terminal) {
super(fs, terminal);
}
/// TODO: -e escape characters
async execute(args: any[], user: Object = null, print = true): Promise<any> {
// Determine additional parameters ('-', '--')
//
let valid = true;
for (let i = 0; i < args.length; i++) {
if (typeof args[i] !== "string") {
valid = false;
break;
}
}
let output: string = valid ? args.join(' ') : '\xa0';
if (print) this.print(output);
return output;
}
print(output: any) {
this.terminal.ui.innerHTML += `${this.terminal.tline_start} ${output} ${this.terminal.tline_end}`;
}
}
class Help extends Command {
id: string = 'help';
help: string = 'display info of supported commands';
man: Object = {};
constructor(fs: Filesystem, terminal: Terminal) {
super(fs, terminal);
}
async execute(args: string[], user: Object, print: boolean = true): Promise<any> {
if (args.length == 0) {
let output: string[] = [];
let commands: Command[] = [];
CommandFactory.command_ids.forEach(id => {
commands.push(CommandFactory.getCommand(id, this.fs, this.terminal));
});
commands.forEach(command => {
output.push(`${command.id} - ${command.help}`);
});
if (print) this.print(output);
return output;
}
if (args.length > 2) {
let output = 'help: too many arguments';
if (print) this.print(output);
return output;
}
// Catch argument as command
let command = CommandFactory.getCommand(args[0], this.fs, this.terminal);
let output: string;
if (!command) output = `help: '${args[0]}' is not a supported command`;
else output = `${command.id} - ${command.help}`;
if (print) this.print(output);
return output;
}
print(output: any): void {
if (output instanceof Array) {
let n_output = '';
output.forEach(element => { n_output += `${element}<br>`; });
this.terminal.ui.innerHTML += `${this.terminal.tline_start}${n_output}${this.terminal.tline_end}`;
return;
}
this.terminal.ui.innerHTML += `${this.terminal.tline_start}${output}${this.terminal.tline_end}`;
}
}
class Ls extends Command {
id: string = 'ls';
help: string = 'list directory contents';
man: Object;
constructor(fs: Filesystem, terminal: Terminal) {
super(fs, terminal);
}
async execute(args: any[], user: Object, print: boolean): Promise<any> {
// Determine additional parameters ('-', '--')
//
let path = args[0];
let content: any[];
let output: string[] = [];
if (typeof path === 'string') {
let location: any = this.fs.getLocation(path);
if (!this.fs.isDirectory(location)) {
return;
}
let directory: mDirectory = location;
content = directory.getContent();
content.forEach(e => {
output.push(e.name);
});
} else if (path === 'mDirectory') {
} else {
return;
}
if (print) this.print(content);
return;
}
print(output: any): void {
throw new Error("Method not implemented.");
}
}
class Sudo extends Command {
id = 'sudo';
help = 'execute a command as another user';
man = {};
sub_command: Command = null;
constructor(fs: Filesystem, terminal: Terminal) {
super(fs, terminal);
}
async execute(args: string[], user: Object, print = true): Promise<any> {
if (args.length < 1) {
// Display help
if (print) this.print('sudo: help placeholder text');
return;
}
// Do some password checks
// Execute command as root user
let command = CommandFactory.getCommand(args[0], this.fs, this.terminal);
if (!command) {
if (print) this.print(`sudo: ${args[0]}: command not found`);
}
if (command) this.sub_command = command;
let result = this.sub_command.execute(args.slice(1), user = null /* root */, print = true);
return result;
}
print(output: any): void {
if (this.sub_command != undefined && this.sub_command != null) {
this.sub_command.print(output);
return;
}
this.terminal.ui.innerHTML += `${this.terminal.tline_start} ${output} ${this.terminal.tline_end}`;
}
async stop(): Promise<void> {
this.forcestop = true;
this.sub_command.stop();
}
}
class CommandFactory {
static command_ids: string[] = ['cat', 'clear', 'echo', 'help', /*'ls'*/, 'sudo'];
static command_classes: typeof Command[] = [Cat, Clear, Echo, Help, /*Ls*/, Sudo];
static getCommand(id: string, filesystem: Filesystem, terminal: Terminal): any {
let index = this.command_ids.indexOf(id);
return index != -1 ? new this.command_classes[index](filesystem, terminal) : false;
}
}
|
4a59aaed7539bf08760bd6cadd3064b9edc8400c
|
TypeScript
|
PauloMoss/banana-game
|
/src/AutonomousDraw.ts
| 2.65625
| 3
|
import Game from "./Game";
import { randomIntFromInterval } from "./helpers";
import Illustration from "./Illustration";
export default class AutonomousDraw extends Illustration {
canvas;
speedY;
constructor(
canvas: HTMLCanvasElement,
context: CanvasRenderingContext2D,
img: HTMLImageElement
) {
super(context, 0, 0, img);
this.canvas = canvas;
const randomInitialPosition = randomIntFromInterval(0, this.canvas.width - 80);
this.x = randomInitialPosition;
this.speedY = 5;
}
move() {
this.y += this.speedY;
}
}
|
669d0e2c524a3ebbd2c3b940c1b91c786c7f1610
|
TypeScript
|
xiaohong-yang/vue3-learn
|
/src/views/demo/hooks/useRequest.ts
| 2.59375
| 3
|
import { ref, getCurrentInstance } from 'vue'
export default function <T>(url: string) {
// 加载的状态
const loading = ref(true)
// 请求成功的数据
const data = ref<T | null>(null) // 坑
// 错误信息
const errorMsg = ref('')
// 发送请求
// @ts-ignore
const { proxy } = getCurrentInstance()
setTimeout(() => {
// @ts-ignore
proxy.$axios.get(url).then(response => {
// console.log(response.data)
// 改变加载状态
loading.value = false
data.value = response.data
}).catch((error: { message: string }) => {
// 改变加载状态
loading.value = false
errorMsg.value = error.message || '未知错误'
})
}, 2000)
return {
loading,
data,
errorMsg
}
}
|
f97c7cc6ee269324e7d3ebdd43a01b22fc53a0ec
|
TypeScript
|
Metarock/club_backend
|
/src/entities/Post.ts
| 2.578125
| 3
|
import { Field, ObjectType } from "type-graphql";
import { BaseEntity, Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
import { Page } from "./Page";
@ObjectType()
@Entity()
export class Post extends BaseEntity {
@Field()
@PrimaryGeneratedColumn()
id!: number; //string is also supported
@Field()
@Column()
title!: string;
@Field()
@Column()
text!: string;
@Field()
@Column()
postCreatorId: number;
@Field(() => String, { nullable: true })
@Column({ nullable: true })
postimgUrl!: string;
@ManyToOne(() => Page, (page) => page.posts, { cascade: true })
@JoinColumn()
postCreator: Page;
@Field(() => String)
@CreateDateColumn()
createdAt: Date;
@Field(() => String)
@UpdateDateColumn()
updatedAt: Date;
}
|
0e2706bb2c8124ec9aac9455b440830407b4f744
|
TypeScript
|
erikaxe/Corona-Dashboard
|
/src/app/components/user-interactive-chart/user-interactive-chart.component.ts
| 2.875
| 3
|
// Imports
import { Component, OnInit, ViewChild} from '@angular/core';
// Service import
import { ApiDataService } from './../../services/api-data.service';
// Apex chart imports
import {
ApexAxisChartSeries,
ApexChart,
ChartComponent,
ApexDataLabels,
ApexXAxis,
ApexPlotOptions,
ApexTitleSubtitle,
ApexYAxis,
} from 'ng-apexcharts';
// Export chart options
export type ChartOptions = {
series: ApexAxisChartSeries;
chart: ApexChart;
dataLabels: ApexDataLabels;
plotOptions: ApexPlotOptions;
xaxis: ApexXAxis;
yaxis: ApexYAxis;
title: ApexTitleSubtitle;
};
@Component({
selector: 'app-user-interactive-chart',
templateUrl: './user-interactive-chart.component.html',
styleUrls: ['./user-interactive-chart.component.scss']
})
export class UserInteractiveChartComponent implements OnInit {
@ViewChild('chart') chart!: ChartComponent;
public chartOptions!: Partial<ChartOptions>;
// Array that contains all countries from the API
countriesArray = [] as any;
// Array that contains the country the user selected
country = [] as any;
// Variables containing data to the chart
cases = [] as any;
recovered = [] as any;
deaths = [] as any;
// Force xaxis to be ApexXAxis
xaxis = {
categories: []
} as ApexXAxis;
constructor(private apiDataService: ApiDataService) {
// Chart starts
this.chartOptions = {
// Chart bars for each category
series: [
{
name: 'Confirmed',
data: []
},
{
name: 'Recovered',
data: []
},
{
name: 'Deaths',
data: []
}
],
title: {
text: 'Compare countries',
align: 'left'
},
chart: {
type: 'bar',
height: 350
},
plotOptions: {
bar: {
horizontal: false,
dataLabels: {
position: 'top'
}
}
},
dataLabels: {
enabled: true,
offsetY: -20,
style: {
fontSize: '12px',
colors: ['#304758']
}
},
xaxis: this.xaxis,
yaxis: {
title: {
text: 'Cases'
}
},
};
// Chart ends
}
ngOnInit(): void {
// Get the data from service, and subscribe
this.apiDataService.getCountries().subscribe((data) => {
// Place the subscribed data into countriesArray
this.countriesArray = data;
});
}
// Function that holds the country the user selected
// tslint:disable-next-line: typedef
getCountry(country: any){
// Null check to get around "possible null error" on select element
if (country.value !== null){
this.country = country.value;
}
}
// Function to get data of specified country
getData(): void {
// Get the specified data from the API
this.apiDataService.getRealtimeData(this.country).subscribe((data) => {
// Call setData and put in the data
this.setData(data);
});
}
// Update chart with new country
setData(country: any): void {
// Push new data
this.cases.push(country.cases);
this.recovered.push(country.recovered);
this.deaths.push(country.deaths);
// Update categories with country names
this.xaxis.categories.push(country.country);
// Update chart series with new data
this.chartOptions.series = [
{
name: 'Confirmed',
data: this.cases
},
{
name: 'Recovered',
data: this.recovered
},
{
name: 'Deaths',
data: this.deaths
}
];
}
// Function to reset the chart
resetChart(): void {
// Empty the arrays
this.cases = [];
this.recovered = [];
this.deaths = [];
// "Reset" to default ApexXAxis
this.xaxis = {
categories: []
} as ApexXAxis;
// Empty series
this.chartOptions.series = [
{
name: 'Confirmed',
data: this.cases
},
{
name: 'Recovered',
data: this.recovered
},
{
name: 'Deaths',
data: this.deaths
}
];
// Force chart update
this.chartOptions.xaxis = this.xaxis;
}
// Function to trigger disabled property
// tslint:disable-next-line: typedef
disable(){}
}
|
96707ca3ea7453e42682293e479e9e823905e9ed
|
TypeScript
|
sugrinov/hacker-news
|
/src/app/submissions/submissions.component.ts
| 2.546875
| 3
|
import { Component, OnInit, Input } from '@angular/core';
import { RESULTS_PER_PAGE } from '../constants/constants';
@Component({
selector: 'app-submissions',
templateUrl: './submissions.component.html',
styleUrls: ['./submissions.component.css']
})
export class SubmissionsComponent implements OnInit {
@Input() submissions = [];
currentPage = 0;
noNext = false;
noPrev = true;
constructor() { }
ngOnInit() {
this.submissions = this.submissions
.reduce((acc, curr, idx) => {
const currentPage = Math.floor(idx / RESULTS_PER_PAGE);
const currentSubmissions = acc[currentPage] ? acc[currentPage] : [];
currentSubmissions.push(curr);
return {
...acc,
[currentPage]: currentSubmissions
};
}, {});
}
getNext(): number[] {
this.currentPage++;
if (!this.hasNext()) {
this.noNext = true;
}
if (this.hasPrev()) {
this.noPrev = false;
}
return this.submissions[this.currentPage];
}
getPrev(): number[] {
this.currentPage--;
if (!this.hasPrev()) {
this.noPrev = true;
}
if (this.hasNext()) {
this.noNext = false;
}
return this.submissions[this.currentPage];
}
hasNext(): boolean {
return !!this.submissions[this.currentPage + 1];
}
hasPrev(): boolean {
return !!this.submissions[this.currentPage - 1];
}
}
|
63bb3bad29b395f6d49b213aa778e5fbe0a70454
|
TypeScript
|
Activiti/activiti-modeling-app
|
/projects/process-editor/src/services/bpmn-js/EventBusMock.ts
| 2.59375
| 3
|
/* eslint-disable */
import {
isFunction,
isArray,
isNumber,
bind,
assign
} from 'min-dash';
var FN_REF = '__fn';
var DEFAULT_PRIORITY = 1000;
var slice = Array.prototype.slice;
export default function EventBusMock() {
this._listeners = {};
this.on('diagram.destroy', 1, this._destroy, this);
}
EventBusMock.prototype.on = function (events, priority, callback, that) {
events = isArray(events) ? events : [events];
if (isFunction(priority)) {
that = callback;
callback = priority;
priority = DEFAULT_PRIORITY;
}
if (!isNumber(priority)) {
throw new Error('priority must be a number');
}
var actualCallback = callback;
if (that) {
actualCallback = bind(callback, that);
// make sure we remember and are able to remove
// bound callbacks via {@link #off} using the original
// callback
actualCallback[FN_REF] = callback[FN_REF] || callback;
}
var self = this;
events.forEach(function (e) {
self._addListener(e, {
priority: priority,
callback: actualCallback,
next: null
});
});
};
EventBusMock.prototype.once = function (event, priority, callback, that) {
var self = this;
if (isFunction(priority)) {
that = callback;
callback = priority;
priority = DEFAULT_PRIORITY;
}
if (!isNumber(priority)) {
throw new Error('priority must be a number');
}
function wrappedCallback() {
var result = callback.apply(that, arguments);
self.off(event, wrappedCallback);
return result;
}
wrappedCallback[FN_REF] = callback;
this.on(event, priority, wrappedCallback);
};
EventBusMock.prototype.off = function (events, callback) {
events = isArray(events) ? events : [events];
var self = this;
events.forEach(function (event) {
self._removeListener(event, callback);
});
};
EventBusMock.prototype.createEvent = function (data) {
var event = new InternalEvent();
event.init(data);
return event;
};
EventBusMock.prototype.fire = function (type, data) {
var event,
firstListener,
returnValue,
args;
args = slice.call(arguments);
if (typeof type === 'object') {
data = type;
type = data.type;
}
if (!type) {
throw new Error('no event type specified');
}
firstListener = this._listeners[type];
if (!firstListener) {
return;
}
// we make sure we fire instances of our home made
// events here. We wrap them only once, though
if (data instanceof InternalEvent) {
// we are fine, we already have an event
event = data;
} else {
event = this.createEvent(data);
}
// ensure we pass the event as the first parameter
args[0] = event;
// original event type (in case we delegate)
var originalType = event.type;
// update event type before delegation
if (type !== originalType) {
event.type = type;
}
try {
returnValue = this._invokeListeners(event, args, firstListener);
} finally {
// reset event type after delegation
if (type !== originalType) {
event.type = originalType;
}
}
// set the return value to false if the event default
// got prevented and no other return value exists
if (returnValue === undefined && event.defaultPrevented) {
returnValue = false;
}
return returnValue;
};
EventBusMock.prototype.handleError = function (error) {
return this.fire('error', { error: error }) === false;
};
EventBusMock.prototype._destroy = function () {
this._listeners = {};
};
EventBusMock.prototype._invokeListeners = function (event, args, listener) {
var returnValue;
while (listener) {
// handle stopped propagation
if (event.cancelBubble) {
break;
}
returnValue = this._invokeListener(event, args, listener);
listener = listener.next;
}
return returnValue;
};
EventBusMock.prototype._invokeListener = function (event, args, listener) {
var returnValue;
try {
// returning false prevents the default action
returnValue = invokeFunction(listener.callback, args);
// stop propagation on return value
if (returnValue !== undefined) {
event.returnValue = returnValue;
event.stopPropagation();
}
// prevent default on return false
if (returnValue === false) {
event.preventDefault();
}
} catch (e) {
if (!this.handleError(e)) {
console.error('unhandled error in event listener');
console.error(e.stack);
throw e;
}
}
return returnValue;
};
EventBusMock.prototype._addListener = function (event, newListener) {
var listener = this._getListeners(event),
previousListener;
// no prior listeners
if (!listener) {
this._setListeners(event, newListener);
return;
}
// ensure we order listeners by priority from
// 0 (high) to n > 0 (low)
while (listener) {
if (listener.priority < newListener.priority) {
newListener.next = listener;
if (previousListener) {
previousListener.next = newListener;
} else {
this._setListeners(event, newListener);
}
return;
}
previousListener = listener;
listener = listener.next;
}
// add new listener to back
previousListener.next = newListener;
};
EventBusMock.prototype._getListeners = function (name) {
return this._listeners[name];
};
EventBusMock.prototype._setListeners = function (name, listener) {
this._listeners[name] = listener;
};
EventBusMock.prototype._removeListener = function (event, callback) {
var listener = this._getListeners(event),
nextListener,
previousListener,
listenerCallback;
if (!callback) {
// clear listeners
this._setListeners(event, null);
return;
}
while (listener) {
nextListener = listener.next;
listenerCallback = listener.callback;
if (listenerCallback === callback || listenerCallback[FN_REF] === callback) {
if (previousListener) {
previousListener.next = nextListener;
} else {
// new first listener
this._setListeners(event, nextListener);
}
}
previousListener = listener;
listener = nextListener;
}
};
/**
* A event that is emitted via the event bus.
*/
function InternalEvent() { }
InternalEvent.prototype.stopPropagation = function () {
this.cancelBubble = true;
};
InternalEvent.prototype.preventDefault = function () {
this.defaultPrevented = true;
};
InternalEvent.prototype.init = function (data) {
assign(this, data || {});
};
function invokeFunction(fn, args) {
return fn.apply(null, args);
}
|
76b1b9c579b543aee6e010d61121cb6250d1b48f
|
TypeScript
|
serge-web/serge
|
/packages/components/src/local/molecules/editable-row/types/props.d.ts
| 2.6875
| 3
|
import { EDITABLE_SELECT_ITEM, EDITABLE_SWITCH_ITEM } from '..'
export interface Option {
name: string
uniqid: string
[property: string]: any
}
export interface SelectItem {
readonly uniqid: string
type: typeof EDITABLE_SELECT_ITEM
title?: string
active?: Array<number>
multiple?: boolean
emptyTitle?: string
options: Array<Option>
}
export interface SwitchItem {
readonly uniqid: string
type: typeof EDITABLE_SWITCH_ITEM
title?: string
active?: boolean
emptyTitle?: string
}
export type Item = SelectItem | SwitchItem
export default interface PropTypes {
items: Array<Item>
onChange: (nextItems: Array<Item>, changedKey: number) => Array<Item>
onSave?: (nextItems: Array<Item>, participantKey?: number) => void
onRemove?: (participantKey?: number) => void
actions?: boolean
defaultMode: 'view' | 'edit'
noSwitchOnReset?: boolean
isGenerator?: boolean
participantKey?: number
/**
* for multiple selection entries, display then as a
* vertical list
*/
presentAsList?: boolean
}
|
e27e36a8642abea569da2c5e0515f449237c392b
|
TypeScript
|
moritzmyrz/Driver-TS
|
/src/events/message.ts
| 2.609375
| 3
|
import BaseEvent from '../utils/structures/BaseEvent';
import { Message } from 'discord.js';
import DiscordClient from '../client/client';
export default class MessageEvent extends BaseEvent {
constructor() {
super('message');
}
async run(client: DiscordClient, message: Message) {
if (message.author.bot) return;
if (message.channel.id !== '726574778747715615') {
if (message.content.startsWith('!lmgtfy')) {}
else if (message.content.startsWith('!') || message.content.startsWith('-')) {
if (message.author.id !== '381453904749002756') {
message.delete({ timeout: 15000 });
message.channel.send(`<@${message.author.id}>, vi har en egen kanal for kommandoer. ->> <#726574778747715615> <<-`)
.then(message => message.delete({ timeout: 15000 }));
}
}
}
if (message.content.startsWith(client.prefix)) {
const [cmdName, ...cmdArgs] = message.content
.slice(client.prefix.length)
.trim()
.split(/\s+/);
const command = client.commands.get(cmdName);
if (command) {
command.run(client, message, cmdArgs);
}
}
}
}
|
41e919e1601d1162b4c97bbb83ae31c87d30d3d0
|
TypeScript
|
williamfligor/slider
|
/src/convert.ts
| 2.640625
| 3
|
import * as fileUpload from "express-fileupload";
import * as imagemagick from "imagemagick";
import * as fs from "fs";
import * as path from "path";
export const SLIDES_DIR = __dirname + "/../data/slides";
async function moveFile(file: fileUpload.UploadedFile) {
return new Promise((resolve, reject) => {
file.mv(SLIDES_DIR + "/presentation.pdf", err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
async function convertFile() {
return new Promise((resolve, reject) => {
const cmd = [
SLIDES_DIR + "/presentation.pdf",
"-density",
300,
"-quality",
100,
SLIDES_DIR + "/presentation-%02d.jpg"
];
console.debug(`Running imagemagick with "${cmd.join(" ")}"`);
imagemagick.convert(cmd, (err, stdout) => {
if (err) {
reject(err);
} else {
resolve(stdout);
}
console.debug("imagemagick done");
});
});
}
async function deleteFile(fname: string): Promise<void> {
return new Promise((resolve, reject) => {
fs.unlink(fname, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
export async function listFiles(directory: string): Promise<string[]> {
return new Promise((resolve, reject) => {
fs.readdir(SLIDES_DIR, (err, fileNames) => {
if (err) {
reject(err);
} else {
resolve(fileNames);
}
});
});
}
async function deleteExistingFiles() {
const files = await listFiles(SLIDES_DIR);
for (const fname of files) {
if (fname.startsWith("presentation-")) {
await deleteFile(SLIDES_DIR + "/" + fname);
console.debug("deleted", fname);
}
}
}
export async function pdfToImages(
file: fileUpload.UploadedFile[] | fileUpload.UploadedFile
) {
if (Array.isArray(file)) {
file = file[0];
}
await deleteExistingFiles();
await moveFile(file);
await convertFile();
}
|
144b7b9d641e18994a18f4bede91227d9098aeda
|
TypeScript
|
jtamminga/boids
|
/src/obsticle.ts
| 2.875
| 3
|
import { Renderable, GameState, DEBUG_MODE, Vision, Avoidable, BOID_SPEED } from "./game";
import Point from "./point";
import { closestPointLine, min } from "./utils";
import Segment from "./segment";
import GameElement from "./element";
import Vector from "./vector";
export default class Obsticle implements Renderable, Avoidable {
private points: Point[]
private segments: Segment[]
constructor(points: Point[]) {
this.points = points
this.segments = this.generateSegments(points)
}
private generateSegments(points: Point[]): Segment[] {
return points.map((p, i) => {
let j = i + 1 == points.length ? 0 : i + 1
return new Segment(points[i], points[j])
})
}
/**
* Calculate for a given point, the distance to this obsticle, the closest point
* and the line segments the closest point is apart of
*/
private calc(point: Point): { closest: Point, distance: number, segments: Segment[] } {
let closestPoints = this.segments.map(segment =>
({ segment, closest: closestPointLine(point, segment.a, segment.b) }))
let distance: number = Number.MAX_VALUE
let closest: Point = null
let segments: Segment[] = []
for (const p of closestPoints) {
let dist = point.distance(p.closest)
if (dist < distance) {
distance = dist
closest = p.closest
segments = [p.segment]
} else if (dist == distance) {
segments.push(p.segment)
}
}
return { closest, distance, segments }
}
closestPoint(point: Point): Point {
return this.calc(point).closest
}
distance(element: GameElement): number {
return this.calc(element.pos).distance
}
force(element: GameElement & Vision): Vector {
let { closest, distance, segments } = this.calc(element.pos)
let mult = element.fov.range - (Math.pow(distance, 2) / element.fov.range)
return Vector.mean(segments.map(s => s.vector)).mult(mult * BOID_SPEED * 0.01)
}
render({ context }: GameState) {
context.strokeStyle = 'white'
context.fillStyle = '#444'
context.beginPath()
for (const point of this.points) {
context.lineTo(point.x, point.y)
}
context.closePath()
context.fill()
context.stroke()
if (DEBUG_MODE) {
context.strokeStyle = 'green'
for (const seg of this.segments) {
context.beginPath()
let mid = seg.midPoint
let vec = seg.vector.mult(20)
let end = mid.apply(vec)
context.moveTo(mid.x, mid.y)
context.lineTo(end.x, end.y)
context.stroke()
}
}
}
}
|
f76b90df9182e2506d90074abf909b832cfdd3ad
|
TypeScript
|
guardian/dotcom-rendering
|
/dotcom-rendering/src/model/enhanceTableOfContents.test.ts
| 2.578125
| 3
|
import { Explainer as ExampleArticle } from '../../fixtures/generated/articles/Explainer';
import { blockMetaData } from '../../fixtures/manual/block-meta-data';
import { enhanceTableOfContents } from './enhanceTableOfContents';
describe('Enhance Table of Contents', () => {
it('does not generate a toc where an existing table of contents exists', () => {
const input: Block[] = [
{
...blockMetaData,
elements: [
{
_type: 'model.dotcomrendering.pageElements.InteractiveContentsBlockElement',
elementId: 'mocOne',
subheadingLinks: [],
},
],
},
];
expect(enhanceTableOfContents(ExampleArticle.format, input)).toEqual(
undefined,
);
});
it('correctly generate a toc from h2s', () => {
const input: Block[] = [
{
...blockMetaData,
elements: [
{
_type: 'model.dotcomrendering.pageElements.SubheadingBlockElement',
elementId: 'h2One',
html: "<h2 id='first-h2-text'><strong>First h2 text</strong></h2>",
},
{
_type: 'model.dotcomrendering.pageElements.SubheadingBlockElement',
elementId: 'h2Two',
html: "<h2 id='second-h2-text'><strong>Second h2 text</strong></h2>",
},
{
_type: 'model.dotcomrendering.pageElements.SubheadingBlockElement',
elementId: 'h2Three',
html: "<h2 id='third-h2-text'><strong>Third h2 text</strong></h2>",
},
],
},
];
expect(enhanceTableOfContents(ExampleArticle.format, input)).toEqual([
{
id: 'first-h2-text',
title: 'First h2 text',
},
{
id: 'second-h2-text',
title: 'Second h2 text',
},
{
id: 'third-h2-text',
title: 'Third h2 text',
},
]);
});
it('will not return a toc if the are fewer than 3 h2s', () => {
const input: Block[] = [
{
...blockMetaData,
elements: [
{
_type: 'model.dotcomrendering.pageElements.SubheadingBlockElement',
elementId: 'h2One',
html: '<h2>This is the h2 text</h2>',
},
{
_type: 'model.dotcomrendering.pageElements.SubheadingBlockElement',
elementId: 'h2Two',
html: '<h2>This is the h2 text</h2>',
},
],
},
];
expect(enhanceTableOfContents(ExampleArticle.format, input)).toEqual(
undefined,
);
});
});
|
6f857c4be93ac7d3261b20a53bb422b1c27dfc8b
|
TypeScript
|
SadlyOfficical/ghostybot
|
/src/features/MemberCount.ts
| 2.640625
| 3
|
import { Guild } from "discord.js";
import Bot from "../structures/Bot";
import Feature from "../structures/Feature";
export default class MemberCountFeature extends Feature {
constructor(bot: Bot) {
super(bot, "member-count");
}
async execute(bot: Bot) {
const timeout = 60 * 1000 * 15; // 15 minutes
async function updateMembers(guild: Guild) {
const g = await bot.utils.getGuildById(guild.id);
if (!g) return;
if (!bot.user) return;
if (!g.member_count_channel_id || g.member_count_channel_id === "Disabled") return;
const channel = guild.channels.cache.get(g.member_count_channel_id);
if (!channel) return;
if (!channel.permissionsFor(bot.user.id)?.has("MANAGE_CHANNELS")) return;
channel.setName(`Members: ${guild.memberCount.toString()}`);
}
setInterval(() => {
bot.guilds.cache.forEach((guild) => {
updateMembers(guild);
});
}, timeout);
}
}
|
b9b808d611b5207c8d8fcc2a30e199e04f6959e4
|
TypeScript
|
iamwaswa/email
|
/frontend/content/attachFiles/chips/index.ts
| 2.75
| 3
|
import * as React from "react";
import { Box, Chip } from "@material-ui/core";
type Props = {
values: Email;
setValues: React.Dispatch<React.SetStateAction<Email>>;
setTotalFileSizeInMB: React.Dispatch<React.SetStateAction<number>>;
};
export default (props: Props): JSX.Element[] => {
if (props.values.attachments && props.values.attachments.length > 0) {
return props.values.attachments.map(
(attachment: Attachment): JSX.Element => {
return (
<Box key={attachment.filename} marginBottom={1} marginRight={1}>
<Chip
label={`${attachment.filename} - ${attachment.sizeInMB.toFixed(
2
)}MB`}
onDelete={(event: any): void => {
props.setTotalFileSizeInMB((previousTotal: number): number => {
const newTotal = previousTotal - attachment.sizeInMB;
return Math.round(newTotal) <= 0 ? 0 : newTotal;
});
props.setValues({
...props.values,
attachments: props.values.attachments
? props.values.attachments.filter(
({ filename }: Attachment): boolean =>
filename !== attachment.filename
)
: []
});
}}
/>
</Box>
);
}
);
}
return [
<Box key="text" marginTop={-2}>
No attachments
</Box>
];
};
|
0ebaae42f71733de8d254405579a08d6945fda82
|
TypeScript
|
Kennypt/react-native-cinema
|
/server/src/middlewares/errorHandler.ts
| 2.828125
| 3
|
import path from 'path';
import statusCodes from 'http-status-codes';
import config from '../config';
import errorCodesEnum from '../enums/errorCodes';
const DEFAULT_ERROR_MESSAGE = 'Unfortunately we are unable to fulfil your request at this time.';
export const buildErrorResponse = (
message = DEFAULT_ERROR_MESSAGE,
devMessage,
code,
stack,
action?
) => ({
status: 'error',
code,
error: message,
action,
devError: config.isDebugMode ? devMessage : undefined,
stack: config.isDebugMode ? stack : undefined,
});
// Make error message cleaner and easier to read
const getErrorStack = err =>
(err.stack || '')
.split('\n')
.map(line => line.trim())
.map(line => line.split(path.sep).join('/'))
.map(line =>
line.replace(
process
.cwd()
.split(path.sep)
.join('/'),
'.'
)
);
// Handle known errors in a specific way
const handleKnownErrors = (err, res) => {
return false;
};
// Handle our own internal custom errors
const handleCustomErrors = (err, res) => {
/*
If Custom Error then handle it for:
- expose or not the message to the client;
- show stack error only in dev mode
- show private message if in dev mode
*/
// It means that was thrown from a CustomError
if (err.custom) {
let devMessage;
let message = err.publicMessage || DEFAULT_ERROR_MESSAGE;
const status = err.status || statusCodes.INTERNAL_SERVER_ERROR;
const { code = errorCodesEnum.INTERNAL_ERROR } = err;
if (err.expose) {
// eslint-disable-next-line prefer-destructuring
message = err.message;
} else {
devMessage = err.message;
}
res.status(status).json(buildErrorResponse(message, devMessage, code, getErrorStack(err)));
return true;
}
return false;
};
// Handle unknown errors
const handleGenericErrors = (err, res) => {
const { message } = err;
// Generic error message
res
.status(statusCodes.INTERNAL_SERVER_ERROR)
.json(
buildErrorResponse(
DEFAULT_ERROR_MESSAGE,
message,
err.code || errorCodesEnum.INTERNAL_ERROR,
getErrorStack(err)
)
);
return true;
};
/**
* @name errorHandler
* @description Application Exception Handler
* @param {Error} err Application Error
* @param {HttpRequest} req
* @param {HttpResponse} res
* @callback next
*/
// eslint-disable-next-line no-unused-vars
export default (err, req, res, next) => {
console.log('[Error Handler]', err);
return (
handleKnownErrors(err, res) || handleCustomErrors(err, res) || handleGenericErrors(err, res)
);
};
|
2e1cd5689a7af0b27fbdd91763866b6ed4b00983
|
TypeScript
|
vaibhavbhandare/Assignment1-Sports
|
/src/app/store/reducers/auth.reducers.spec.ts
| 2.8125
| 3
|
import { reducer, State } from './auth.reducers';
import { LogIn, LogInFailure, LogInSuccess,
SignUpFailure, SignUpSuccess, LogOut } from '../actions/auth.action';
import { User, Sport } from '../model/user';
const initialState = {
isAuthenticated: false,
user: null,
errorMessage: null,
};
const dummyUser: User = {
username: 'test',
password: 'test123',
};
const validatedUser: User = {
username: 'test',
password: 'test123',
};
const invalidUser: User = {
username: 'aa@zz.com',
password: 'test1233',
};
describe('reducer', () => {
it('should return the initial state', () => {
expect(reducer(undefined, Object.assign({}))).toEqual(
{
isAuthenticated: false,
user: null,
errorMessage: null,
}
);
});
});
describe('LogIn', () => {
it('should return the user post verifying the user credentials', () => {
const loginAction = new LogIn(dummyUser);
const passedState: State = {
isAuthenticated: true,
user: dummyUser,
errorMessage: null,
};
expect(reducer(passedState, loginAction)).toEqual(passedState);
});
});
describe('LogInSuccess', () => {
it('should return the validated user after login successful', () => {
const loginAction = new LogInSuccess(dummyUser);
const passedState: State = {
isAuthenticated: true,
user: validatedUser,
errorMessage: null,
};
expect(reducer(passedState, loginAction)).toEqual(passedState);
});
});
|
2e3e612bf7b7fae44e6d44ea4acc9f8e691c2bb7
|
TypeScript
|
microsoft/fluentui
|
/packages/date-time-utilities/src/dateMath/dateMath.test.ts
| 3.28125
| 3
|
import { DayOfWeek, DateRangeType } from '../dateValues/dateValues';
import * as DateMath from './dateMath';
enum Months {
Jan = 0,
Feb = 1,
Mar = 2,
Apr = 3,
May = 4,
Jun = 5,
Jul = 6,
Aug = 7,
Sep = 8,
Oct = 9,
Nov = 10,
Dec = 11,
}
describe('DateMath', () => {
it('can add days', () => {
const startDate = new Date(2016, Months.Apr, 1);
const result = DateMath.addDays(startDate, 5);
const expected = new Date(2016, Months.Apr, 6);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can add days across a month boundary', () => {
const startDate = new Date(2016, Months.Mar, 30);
const result = DateMath.addDays(startDate, 5);
const expected = new Date(2016, Months.Apr, 4);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can add days across multiple month boundaries', () => {
const startDate = new Date(2016, Months.Mar, 31);
const result = DateMath.addDays(startDate, 65);
const expected = new Date(2016, Months.Jun, 4);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can add days across leap day boundaries', () => {
const startDate = new Date(2016, Months.Feb, 28);
const result = DateMath.addDays(startDate, 2);
const expected = new Date(2016, Months.Mar, 1);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can add months', () => {
const startDate = new Date(2015, Months.Dec, 31);
let result = DateMath.addMonths(startDate, 1);
let expected = new Date(2016, Months.Jan, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 2);
expected = new Date(2016, Months.Feb, 29);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 3);
expected = new Date(2016, Months.Mar, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 4);
expected = new Date(2016, Months.Apr, 30);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 5);
expected = new Date(2016, Months.May, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 6);
expected = new Date(2016, Months.Jun, 30);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 7);
expected = new Date(2016, Months.Jul, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 8);
expected = new Date(2016, Months.Aug, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 9);
expected = new Date(2016, Months.Sep, 30);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 10);
expected = new Date(2016, Months.Oct, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 11);
expected = new Date(2016, Months.Nov, 30);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 12);
expected = new Date(2016, Months.Dec, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, 14);
expected = new Date(2017, Months.Feb, 28);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can add years', () => {
let startDate = new Date(2016, Months.Feb, 29);
let result = DateMath.addYears(startDate, 1);
let expected = new Date(2017, Months.Feb, 28);
expect(result.getTime()).toEqual(expected.getTime());
startDate = new Date(2016, Months.Feb, 29);
result = DateMath.addYears(startDate, 4);
expected = new Date(2020, Months.Feb, 29);
expect(result.getTime()).toEqual(expected.getTime());
startDate = new Date(2016, Months.Jan, 1);
result = DateMath.addYears(startDate, 1);
expected = new Date(2017, Months.Jan, 1);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can subtract days', () => {
const startDate = new Date(2016, Months.Apr, 30);
const result = DateMath.addDays(startDate, -5);
const expected = new Date(2016, Months.Apr, 25);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can subtract days across a month boundry', () => {
const startDate = new Date(2016, Months.Apr, 1);
const result = DateMath.addDays(startDate, -5);
const expected = new Date(2016, Months.Mar, 27);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can subtract days across multiple month boundaries', () => {
const startDate = new Date(2016, Months.Jul, 4);
const result = DateMath.addDays(startDate, -65);
const expected = new Date(2016, Months.Apr, 30);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can subtract days across leap day boundaries', () => {
const startDate = new Date(2016, Months.Mar, 1);
const result = DateMath.addDays(startDate, -2);
const expected = new Date(2016, Months.Feb, 28);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can subtract months', () => {
const startDate = new Date(2016, Months.Dec, 31);
let result = DateMath.addMonths(startDate, -12);
let expected = new Date(2015, Months.Dec, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -11);
expected = new Date(2016, Months.Jan, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -10);
expected = new Date(2016, Months.Feb, 29);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -9);
expected = new Date(2016, Months.Mar, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -8);
expected = new Date(2016, Months.Apr, 30);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -7);
expected = new Date(2016, Months.May, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -6);
expected = new Date(2016, Months.Jun, 30);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -5);
expected = new Date(2016, Months.Jul, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -4);
expected = new Date(2016, Months.Aug, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -3);
expected = new Date(2016, Months.Sep, 30);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -2);
expected = new Date(2016, Months.Oct, 31);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -1);
expected = new Date(2016, Months.Nov, 30);
expect(result.getTime()).toEqual(expected.getTime());
result = DateMath.addMonths(startDate, -22);
expected = new Date(2015, Months.Feb, 28);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can subtract years', () => {
let startDate = new Date(2016, Months.Feb, 29);
let result = DateMath.addYears(startDate, -1);
let expected = new Date(2015, Months.Feb, 28);
expect(result.getTime()).toEqual(expected.getTime());
startDate = new Date(2016, Months.Feb, 29);
result = DateMath.addYears(startDate, -4);
expected = new Date(2012, Months.Feb, 29);
expect(result.getTime()).toEqual(expected.getTime());
startDate = new Date(2016, Months.Jan, 1);
result = DateMath.addYears(startDate, -1);
expected = new Date(2015, Months.Jan, 1);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can set the month', () => {
let startDate = new Date(2016, Months.Jan, 31);
let result = DateMath.setMonth(startDate, Months.Feb);
let expected = new Date(2016, Months.Feb, 29);
expect(result.getTime()).toEqual(expected.getTime());
startDate = new Date(2016, Months.Jun, 1);
result = DateMath.setMonth(startDate, Months.Feb);
expected = new Date(2016, Months.Feb, 1);
expect(result.getTime()).toEqual(expected.getTime());
});
it('can compare dates', () => {
let date1 = new Date(2016, 4, 1);
let date2 = new Date(2016, 4, 1);
expect(DateMath.compareDates(date1, date2)).toBe(true);
date1 = new Date(2016, 4, 1, 12, 30, 0);
date2 = new Date(2016, 4, 1, 10, 0, 0);
expect(DateMath.compareDates(date1, date2)).toBe(true);
date1 = new Date(2016, 4, 1);
date2 = new Date(2016, 4, 2);
expect(DateMath.compareDates(date1, date2)).toBe(false);
date1 = new Date(2016, 4, 1);
date2 = new Date(2016, 5, 1);
expect(DateMath.compareDates(date1, date2)).toBe(false);
date1 = new Date(2016, 4, 1);
date2 = new Date(2017, 4, 1);
expect(DateMath.compareDates(date1, date2)).toBe(false);
});
it('can get date range array', () => {
const date = new Date(2017, 2, 16);
// Date range: day
let dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Day, DayOfWeek.Sunday);
expect(dateRangeArray.length).toEqual(1);
expect(DateMath.compareDates(dateRangeArray[0], date)).toBe(true);
// Date range: week
let expectedDates = Array(7).map((val: undefined, i: number) => new Date(2017, 2, 12 + i));
dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Week, DayOfWeek.Sunday);
Array(7).forEach((val: undefined, i: number) =>
expect(DateMath.compareDates(dateRangeArray[i], expectedDates[i])).toBe(true),
);
// Date range: work week
const workWeekDays = [DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Thursday, DayOfWeek.Friday];
expectedDates = [new Date(2017, 2, 13), new Date(2017, 2, 14), new Date(2017, 2, 16), new Date(2017, 2, 17)];
dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Week, DayOfWeek.Sunday, workWeekDays);
Array(4).forEach((val: undefined, i: number) =>
expect(DateMath.compareDates(dateRangeArray[i], expectedDates[i])).toBe(true),
);
// work week defaults
expectedDates = [
new Date(2017, 2, 13),
new Date(2017, 2, 14),
new Date(2017, 2, 15),
new Date(2017, 2, 16),
new Date(2017, 2, 17),
];
dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Week, DayOfWeek.Sunday);
Array(4).forEach((val: undefined, i: number) =>
expect(DateMath.compareDates(dateRangeArray[i], expectedDates[i])).toBe(true),
);
// Date range: month
expectedDates = Array(31).map((val: undefined, i: number) => new Date(2017, 2, 1 + i));
dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Month, DayOfWeek.Sunday);
Array(31).forEach((val: undefined, i: number) =>
expect(DateMath.compareDates(dateRangeArray[i], expectedDates[i])).toBe(true),
);
// First day of week: Tuesday
expectedDates = Array(7).map((val: undefined, i: number) => new Date(2017, 2, 14 + i));
dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Week, DayOfWeek.Tuesday);
Array(7).forEach((val: undefined, i: number) => expect(DateMath.compareDates(dateRangeArray[i], date)).toBe(true));
});
// Generating week numbers array per month
it('can calculate week numbers from selected date', () => {
// firstDayOfWeek is Monday, firstWeekOfYear is firstFullWeek
let date = new Date(2017, 0, 4);
let result = DateMath.getWeekNumbersInMonth(6, 1, 1, date);
let expected = 52;
expect(result[0]).toEqual(expected);
// firstDayOfWeek is Sunday, firstWeekOfYear is firstFullWeek
date = new Date(2000, 11, 31);
result = DateMath.getWeekNumbersInMonth(6, 0, 1, date);
expected = 53;
expect(result[5]).toEqual(expected);
// firstDayOfWeek is Sunday, firstWeekOfYear is firstFullWeek
date = new Date(2010, 0, 1);
result = DateMath.getWeekNumbersInMonth(6, 0, 1, date);
expected = 52;
expect(result[0]).toEqual(expected);
// firstDayOfWeek is Sunday, firstWeekOfYear is firstFourDayWeek
date = new Date(2018, 11, 31);
result = DateMath.getWeekNumbersInMonth(6, 0, 2, date);
expected = 1;
expect(result[5]).toEqual(expected);
});
// First week of year set to FirstWeekOfYear.FirstDay
it('can calculate week numbers - option 0', () => {
// firstDayOfWeek is Sunday
let date1 = new Date(2018, 0, 1);
let result = DateMath.getWeekNumber(date1, 0, 0);
let expected = 1;
expect(result).toEqual(expected);
// firstDayOfWeek is Sunday
date1 = new Date(2010, 0, 1);
result = DateMath.getWeekNumber(date1, 0, 0);
expected = 1;
expect(result).toEqual(expected);
// firstDayOfWeek is Sunday
date1 = new Date(2019, 0, 1);
result = DateMath.getWeekNumber(date1, 0, 0);
expected = 1;
expect(result).toEqual(expected);
// firstDayOfWeek is Monday
date1 = new Date(2010, 11, 31);
result = DateMath.getWeekNumber(date1, 1, 0);
expected = 53;
expect(result).toEqual(expected);
});
// First week of year set to FirstWeekOfYear.FirstFullWeek
it('can calculate week numbers - option 1', () => {
// firstDayOfWeek is Sunday
let date1 = new Date(2018, 0, 1);
let result = DateMath.getWeekNumber(date1, 0, 1);
let expected = 53;
expect(result).toEqual(expected);
// firstDayOfWeek is Sunday
date1 = new Date(2017, 11, 31);
result = DateMath.getWeekNumber(date1, 0, 1);
expected = 53;
expect(result).toEqual(expected);
// firstDayOfWeek is Sunday
date1 = new Date(2010, 11, 31);
result = DateMath.getWeekNumber(date1, 0, 1);
expected = 52;
expect(result).toEqual(expected);
// firstDayOfWeek is Monday
date1 = new Date(2011, 0, 1);
result = DateMath.getWeekNumber(date1, 1, 1);
expected = 52;
expect(result).toEqual(expected);
// firstDayOfWeek is Sunday
date1 = new Date(2021, 0, 1);
result = DateMath.getWeekNumber(date1, 0, 1);
expected = 52;
expect(result).toEqual(expected);
// firstDayOfWeek is Monday
date1 = new Date(2021, 0, 1);
result = DateMath.getWeekNumber(date1, 1, 1);
expected = 52;
expect(result).toEqual(expected);
});
// First week of year set to FirstWeekOfYear.FirstFourDayWeek
it('can calculate week numbers - option 2', () => {
// firstDayOfWeek is Sunday
let date1 = new Date(2019, 0, 5);
let result = DateMath.getWeekNumber(date1, 0, 2);
let expected = 1;
expect(result).toEqual(expected);
// firstDayOfWeek is Sunday
date1 = new Date(2018, 0, 6);
result = DateMath.getWeekNumber(date1, 0, 2);
expected = 1;
expect(result).toEqual(expected);
// firstDayOfWeek is Sunday
date1 = new Date(2014, 11, 31);
result = DateMath.getWeekNumber(date1, 0, 2);
expected = 53;
expect(result).toEqual(expected);
// firstDayOfWeek is Sunday
date1 = new Date(2015, 0, 1);
result = DateMath.getWeekNumber(date1, 0, 2);
expected = 53;
expect(result).toEqual(expected);
// firstDayOfWeek is Sunday
date1 = new Date(2010, 11, 31);
result = DateMath.getWeekNumber(date1, 0, 2);
expected = 52;
expect(result).toEqual(expected);
// firstDayOfWeek is Monday
date1 = new Date(2011, 0, 1);
result = DateMath.getWeekNumber(date1, 1, 2);
expected = 52;
expect(result).toEqual(expected);
// firstDayOfWeek is Sunday
date1 = new Date(2021, 0, 1);
result = DateMath.getWeekNumber(date1, 0, 2);
expected = 53;
expect(result).toEqual(expected);
// firstDayOfWeek is Monday
date1 = new Date(2021, 0, 1);
result = DateMath.getWeekNumber(date1, 1, 2);
expected = 53;
expect(result).toEqual(expected);
});
it('can get the month start and end', () => {
const date = new Date('Dec 15 2017');
// First day of month
expect(DateMath.compareDates(new Date('Dec 1 2017'), DateMath.getMonthStart(date))).toBe(true);
// Last day of month
expect(DateMath.compareDates(new Date('Dec 31 2017'), DateMath.getMonthEnd(date))).toBe(true);
});
it('can get the year start and end', () => {
const date = new Date('Dec 15 2017');
// First day of year
expect(DateMath.compareDates(new Date('Jan 1 2017'), DateMath.getYearStart(date))).toBe(true);
// Last day of year
expect(DateMath.compareDates(new Date('Dec 31 2017'), DateMath.getYearEnd(date))).toBe(true);
});
it('can get start date of week', () => {
const date = new Date('Aug 2 2020');
expect(DateMath.compareDates(new Date('Jul 28 2020'), DateMath.getStartDateOfWeek(date, DayOfWeek.Tuesday))).toBe(
true,
);
});
it('can get end date of week', () => {
const date = new Date('Sep 29 2020');
expect(DateMath.compareDates(new Date('Oct 5 2020'), DateMath.getEndDateOfWeek(date, DayOfWeek.Tuesday))).toBe(
true,
);
});
});
|
8132ddc6695e9e44e13e9f87e2de67cfdd325453
|
TypeScript
|
dev-marlon/rca-api
|
/src/user/user.service.ts
| 2.71875
| 3
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './user.entity';
import { Repository } from 'typeorm';
export interface User {
userId: number;
firstname: string;
lastname: string;
username: string;
password: string;
}
@Injectable()
export class UserService {
private readonly users: User[];
constructor(@InjectRepository(User) private userRepository: Repository<User>) {
this.users = [
{
id: 1,
firstname: 'Geronimo',
lastname: 'Cadillac',
username: 'Frank',
email: 'foo@gmx.de',
password: '12345',
},
];
}
async findOne(username: string): Promise<User | undefined> {
// this.userRepository.findOne(1);
return this.users.find((user: User) => {
return user.username === username;
});
}
async findAll(): Promise<User[]> {
return this.userRepository.find();
}
async add(): Promise<User> {
return this.userRepository.create({
id: 1,
firstname: 'Geronimo',
lastname: 'Cadillac',
username: 'Frank',
email: 'foo@gmx.de',
password: '12345',
});
}
}
|
5ef4eebc636f8f29a6cef7ee8db2045ba9940f59
|
TypeScript
|
jvitorssouza/nestjs-authentication
|
/src/shared/utils/document-validate.ts
| 2.703125
| 3
|
import { BadRequestException } from '@nestjs/common';
import HapiJoi from '@hapi/joi';
import validator, { cnpj, cpf } from 'cpf-cnpj-validator';
export class DocumentValidateService {
execute(documentStr: string) {
try {
const Joi = HapiJoi.extend(validator);
const document = documentStr.match(/\d+/g).join('');
const cnpjSchema = Joi.document().cnpj();
const cpfSchema = Joi.document().cpf();
if (!cpfSchema.validate(document) && !cnpjSchema.validate(document)) {
throw new BadRequestException(
'O CPF/CNPJ fornecido está em um formato inválido!',
);
}
if (!cpf.isValid(document) && !cnpj.isValid(document)) {
return false;
}
return true;
} catch (error) {
throw error;
}
}
}
|
081cc244cb38797205d4775f9ea21deb6b13d426
|
TypeScript
|
yasmim-moon/dsdeliver-sds2
|
/front-web/src/api.ts
| 2.53125
| 3
|
import axios from "axios";
import { OrderPlayload } from "./Orders/types";
const API_URL = process.env.REACT_APP_API_URL;
//requisação nessa url que irá buscar os produtos
const mapboxToken = process.env.REACT_APP_ACESS_TOKEN_MAP_BOX;
export function fetcProducts(){
return axios(`${API_URL}/products`)
//conctenar uma variavel com uma string
}
export function fetchLocalMapBox(local: string){
return axios(`https://api.mapbox.com/geocoding/v5/mapbox.places/${local}.json?access_token=${mapboxToken}`)
}
export function saveOrder(payload: OrderPlayload){
return axios.post(`${API_URL}/orders`, payload)
}
|
ce26e3e46957a1f9c53edcf01ac27de3ad060a74
|
TypeScript
|
fireflysemantics/is
|
/projects/fs-is/src/lib/IsFQDN.ts
| 3.09375
| 3
|
import { IsFQDNOptions as vtsIsFQDNOptions, isFQDN as vtsIsFQDN } from '@fireflysemantics/validatorts'
/**
* Checks if the string is a fully qualified domain name (e.g. domain.com).
* If given value is not a string, then it returns false.
*
* @param value The value being checked.
* @param options The options configuration {@link IsFQDNOptions}
* @return True if the string is a fully qualified domain name, false otherwise.
*/
export function isFQDN(value: string, options?: vtsIsFQDNOptions): boolean {
return typeof value === "string" && vtsIsFQDN(value, options);
}
/**
* Reexport the options
*/
export type IsFQDNOptions = vtsIsFQDNOptions
|
aa59db52bab7b790b33401c3dd7b8b9974da3f36
|
TypeScript
|
andrewscwei/node-mongodb-odm
|
/src/utils/typeIsUpdateFilter.ts
| 2.984375
| 3
|
import _ from 'lodash'
import { UpdateFilter } from 'mongodb'
import { AnyProps, Document } from '../types'
/**
* Checks if a value is an {@link UpdateFilter}.
*
* @param value - Value to check.
*
* @returns `true` if value is an {@link UpdateFilter}, `false` otherwise.
*/
export default function typeIsUpdateFilter<P extends AnyProps = AnyProps>(value: any): value is UpdateFilter<Document<P>> {
if (!_.isPlainObject(value)) return false
return Object.keys(value).some(val => val.startsWith('$'))
}
|
217411ab275d6305394f3d410d35b633cf5239ff
|
TypeScript
|
Steady5063/steady5063.github.io
|
/common-ui/projects/common-ui/src/lib/tables/static-control/static-control-element.component.ts
| 2.5625
| 3
|
import {Component, Input} from '@angular/core';
/**
* @Component: Static Control Element
* @description This component generates the static control element.
*/
@Component({
selector: '[citi-static-control-element]',
template: `
<th scope="row" [innerHtml]="(labelText === null ? '' : labelText)"></th>
<td [class.nowrap-content]="(isNoWrapContent ? true : null)"
[ngClass]="{'cbolui-table-rightAlign':isRightAligned}"
[innerHtml]="(valueText === null ? '' : valueText)">
</td>
`,
styleUrls: ['./static-control-element.component.css']
})
export class StaticControlElementComponent{
/**
* @property idStr
* @description Defines the id of static row element
* @return string
*/
@Input() idStr: string;
/**
* @property labelText
* @description Defines the label of static row element
* @return string
*/
@Input() labelText: string = null;
/**
* @property valueText
* @description Defines the value of static row element
* @return string
*/
@Input() valueText: string = null;
/**
* @property valueText
* @description Enables the right alignment of value/text in static row element
* @return string
*/
@Input() isRightAligned = false;
/**
* @property isNoWrapContent
* @description Enables text wrapping onto the next line in static row element
* @return string
*/
@Input() isNoWrapContent = false;
}
|
5ba81e971a828917836b463f5ce958d3006fa568
|
TypeScript
|
W-R126/Stopover-poc
|
/src/Models/HotelOfferModel.ts
| 2.78125
| 3
|
import { CoordinateModel } from './CoordinateModel';
import { PriceModel } from './FlightOfferModel';
export interface HotelOfferModel {
checkIn: Date;
checkOut: Date;
hotels: HotelModel[];
}
export interface HotelModel {
images: ImageModel[];
rooms: RoomModel[];
chain: {
code?: string;
name?: string;
};
checkIn?: string;
checkOut?: string;
free: boolean;
name: string;
code: string;
rating: number;
recommended: boolean;
reviews: ReviewModel[];
categories: string[];
coordinates: CoordinateModel;
contact: {
phone: string;
fax?: string;
};
address: AddressModel;
amenities: AmenityModel[];
}
function getMinMaxPrice(
func: (a: number, b: number) => boolean,
): (hotels: HotelModel[]) => [HotelModel, number] {
return (hotels: HotelModel[]): [HotelModel, number] => {
let result = hotels[0];
let { total } = result.rooms[0].offers[0].price;
hotels.forEach(
(hotel) => {
hotel.rooms.forEach(
(room) => {
room.offers.forEach(
(offer) => {
if (func(offer.price.total, total)) {
result = hotel;
total = offer.price.total;
}
},
);
},
);
},
);
return [result, total];
};
}
export const getCheapestHotelPrice = getMinMaxPrice((a: number, b: number) => a < b);
export const getMostExpensiveHotelPrice = getMinMaxPrice((a: number, b: number) => a > b);
export function getCheapestHotelPrices(hotels: HotelModel[]): number[] {
return hotels.map((hotel) => getCheapestHotelPrice([hotel])[1]);
}
export function getMostExpensiveHotelPrices(hotels: HotelModel[]): number[] {
return hotels.map((hotel) => getMostExpensiveHotelPrice([hotel])[1]);
}
export interface ImageModel {
thumb: string;
original: string;
code: string;
description: string;
}
export interface RoomModel {
occupancy: {
min: number;
max: number;
};
amenities: AmenityModel[];
category: string;
type: {
name: string;
description: string;
code: string;
};
offers: RoomOfferModel[];
}
export interface RoomOfferModel {
available: number;
includedMeals: {
breakfast: boolean;
dinner: boolean;
lunch: boolean;
lunchOrDinner: boolean;
};
free: boolean;
checkInTime: string;
checkOutTime: string;
checkIn: Date;
checkOut: Date;
hashCode: string;
id: string;
price: PriceModel;
hotelName: string;
title: string;
cancelPenalty: {
price: PriceModel;
deadline: Date;
};
discounts: {
total: number;
code: number;
name: string;
}[];
}
export function parseRoomOffer(data?: any): RoomOfferModel | undefined {
if (!data) {
return undefined;
}
const {
checkIn,
checkOut,
cancelPenalty,
...restProps
} = data;
return {
checkIn: new Date(checkIn),
checkOut: new Date(checkOut),
cancelPenalty: {
price: cancelPenalty.price,
deadline: new Date(cancelPenalty.deadline),
},
...restProps,
};
}
export interface ReviewModel {
rating: number;
count: number;
type: string;
}
export interface AddressModel {
line1: string;
city: {
name: string;
code: string;
};
country: {
name: string;
code: string;
};
state: {
name: string;
code: string;
};
}
export interface AmenityModel {
code: number;
description: string;
value?: string;
complimentary: boolean;
}
export function getHotelRoomOfferChain(hotels?: HotelModel[], roomOffer?: RoomOfferModel): [
HotelModel | undefined,
RoomModel | undefined,
RoomOfferModel | undefined,
] {
if (!hotels) {
return [undefined, undefined, undefined];
}
let room: RoomModel | undefined;
let offer: RoomOfferModel | undefined;
const hotel = hotels.find(
(h) => {
room = h.rooms.find(
(r) => {
offer = r.offers.find(
(o) => {
if (roomOffer?.id === undefined) {
return o;
}
return o.id === roomOffer.id;
},
);
return offer ? r : undefined;
},
);
return room ? h : undefined;
},
);
return [hotel, room, offer];
}
|
34b4b2459f219666db0243d6d5df5ebf1f770812
|
TypeScript
|
marcelopimeireles/storybook-poc-2
|
/src/components/form-elements/input/input.ts
| 2.515625
| 3
|
/**
* Sunrise UI - Input
*/
import {html, css, LitElement, property, unsafeCSS, customElement, CSSResult, TemplateResult} from 'lit-element';
import {classMap} from 'lit-html/directives/class-map';
import styles from './input.scss';
/**
* This component is not complete and is mostly used as a placeholder.
* Angular Material input should be used instead
*/
@customElement ('srui-input')
export class Input extends LitElement {
@property({type: String}) value: string = '';
@property({type: String}) placeholder: string = '';
@property({type: String}) size: string = 'default';
@property({type: String}) type: string = 'text';
@property({type: String}) element: string = '';
@property({type: Boolean}) noBorder: boolean = false;
static get styles(): CSSResult {
return css`${unsafeCSS(styles)}`;
}
constructor() {
super();
}
render(): TemplateResult {
const sizeClass: string = this.size === 'small' || this.size === 'large' ?
'sr-input--size-' + this.size : 'sr-input--size-default';
const inputClasses: { [p: string]: boolean } = {
[sizeClass]: true,
'sr-input--no-border': this.noBorder
};
return html`
${this.type === 'search' ? html` <img class="sr-input__search-icon" src='/assets/images/icons/search24px.svg'/>` : ''}
<input
placeholder=${this.placeholder}
class="sr-input ${classMap(inputClasses)}"
type=${this.type}
element=${this.element}
value=${this.value}
/>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'srui-input': Input;
}
}
|
ac5e159f89fbcfbf700c6d8d40b4754f0eefad33
|
TypeScript
|
ErickWendel/palestra-vscode-extensions
|
/capi-ext/src/RecorrencyController.ts
| 2.59375
| 3
|
import { Disposable, window, StatusBarItem, StatusBarAlignment } from 'vscode'
import { activate } from './extension';
export default class RecorrencyController {
private _disposable: Disposable;
private _statusBarItem: StatusBarItem;
constructor() {
this._statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left);
// subscribe to selection change and editor activation events
let subscriptions: Disposable[] = [];
window.onDidChangeTextEditorSelection(this._onEvent, this, subscriptions);
window.onDidChangeActiveTextEditor(this._onEvent, this, subscriptions);
this.check('Erick');
// create a combined disposable from both event subscriptions
this._disposable = Disposable.from(...subscriptions);
}
public check(name: string) {
const editor = window.activeTextEditor;
if (!editor) {
this._statusBarItem.hide();
return;
}
editor.edit(builder => {
const document = editor.document.getText();
const recorrencies = document.split(name).length -1;
this._statusBarItem.text = `The word ${name} haves ${recorrencies} recorrencies`;
this._statusBarItem.show();
})
}
dispose() {
this._disposable.dispose();
}
private _onEvent() {
this.check('Erick');
}
}
|
1d5f1f54d0dc7ef9e91e019a409f6717b5375599
|
TypeScript
|
itaied246/daas
|
/src/models/interfaces/index.ts
| 2.5625
| 3
|
export interface IModel {
name: string;
body: IField[];
description?: string;
}
export interface IField {
field: IInfo;
input?: IInfo;
}
export interface IInfo {
name: string;
type: string;
}
|
fe4b9de58316af32d4370aec87585bd475104f2d
|
TypeScript
|
joanmaciasaguirre/ionic-instagram-backend
|
/middlewares/autenticacion.ts
| 2.625
| 3
|
import { Response, Request, NextFunction } from 'express';
import Token from '../classes/token';
export const verificaToken = (req: any, resp: Response, next: NextFunction) => {
// con el método get podemos acceder al header del request
// x-token es como vamos a llamar a la key del token en el header
const userToken = req.get('x-token') || ''; // Evitamos el null que daría error
Token.comprobarToken(userToken).then((decoded: any) => {
// El token es válido
console.log('Decoded', decoded);
req.usuario = decoded.usuario;
next();
}).catch(err => {
// El token no es válido
resp.json({
ok: false,
mensaje: 'Token no es válido'
});
});
}
|
2c09938145b90f42a4b37813040ea66d0588b40d
|
TypeScript
|
Islandman93/black-screen
|
/src/shell/Aliases.ts
| 2.890625
| 3
|
import {executeCommandWithShellConfig} from "../PTY";
import * as _ from "lodash";
export const aliasesFromConfig: Dictionary<string> = {};
export async function loadAliasesFromConfig(): Promise<void> {
const lines = await executeCommandWithShellConfig("alias");
lines.map(parseAlias).forEach(parsed => aliasesFromConfig[parsed.name] = parsed.value);
}
export function parseAlias(line: string) {
let [short, long] = line.split("=");
if (short && long) {
const nameCapture = /(alias )?(.*)/.exec(short);
const valueCapture = /'?([^']*)'?/.exec(long);
if (nameCapture && valueCapture) {
return {
name: nameCapture[2],
value: valueCapture[1],
};
} else {
throw `Alias line is incorrect: ${line}`;
}
} else {
throw `Can't parse alias line: ${line}`;
}
}
export class Aliases {
private storage: Dictionary<string>;
constructor(aliases: Dictionary<string>) {
this.storage = _.clone(aliases);
}
add(name: string, value: string) {
this.storage[name] = value;
}
has(name: string): name is ExistingAlias {
return name in this.storage;
}
get(name: ExistingAlias): string {
return this.storage[name];
}
getNameByValue(value: string): string | undefined {
return _.findKey(this.storage, storageValue => storageValue === value);
}
remove(name: string) {
delete this.storage[name];
}
toObject(): Dictionary<string> {
return this.storage;
}
}
|
7da4d01a8c114a60596682a6e0fa7476b4d9f7d3
|
TypeScript
|
subodhsubhedar/angular2
|
/my-angular-single-page-profile-app/src/app/contact-me/contact.ts
| 2.984375
| 3
|
export class Contact {
salutation: string;
userName: string;
mobileNum: number;
email: string;
remarks: string;
constructor(userNm: string, mobNum: number, emailAddrss: string, remrks: string) {
this.userName = userNm;
this.mobileNum = mobNum;
this.email = emailAddrss;
this.remarks = remrks;
}
public toString(): string {
return "\n User name: " + this.userName + "\n Mob num : " + this.mobileNum + "\n Email : " + this.email
+ "\n Remarks : " + this.remarks;
}
}
|
5d335ad73ec078d55124d13c6bb77eb8060c6b67
|
TypeScript
|
christopher-caldwell/ts-migration-helpers
|
/test/ui/src/stores/dateIntegrity/dateIntegrityActions.ts
| 2.53125
| 3
|
import { STORE_BOARD_METADATA, RECEIVE_BOARD_METADATA } from '../actionTypes';
const receiveDateIntegrity = () => ({ type: RECEIVE_BOARD_METADATA });
const storeDateIntegrity = (payload: any) => ({
type: STORE_BOARD_METADATA,
payload
});
export const requestDateIntegrity = () => (dispatch: any) => dispatch(receiveDateIntegrity());
export const updateDateIntegrity = (params: any) => (dispatch: any) => {
dispatch(requestDateIntegrity());
dispatch(storeDateIntegrity(params));
};
|
73f8eadd05bc378e804a54d72ac982bf695123f6
|
TypeScript
|
TheUnderScorer/show-me-the-hooks
|
/src/ts/app/hooks/toggleVisibility.ts
| 2.59375
| 3
|
import { showHooks, toggleHooks } from './utils/visibility';
import { hooksToggle } from './selectors';
import HooksState from '../types/HooksState';
import ElementEvent from '../types/ElementEvent';
import { getVisibleHooksCount } from './count';
const localStorageState = localStorage.getItem( 'smth_hooks_state' );
const defaultState: HooksState = {
hooksHidden: true
};
export const state: HooksState = localStorageState ? JSON.parse( localStorageState ) : { ...defaultState };
export default ( event: ElementEvent<HTMLButtonElement> ) =>
{
const btn = event.currentTarget;
toggleHooks();
state.hooksHidden = !state.hooksHidden;
changeLabel( btn );
handleLocalStorage();
}
const handleLocalStorage = (): void =>
{
localStorage.setItem( 'smth_hooks_state', JSON.stringify( state ) );
};
export const changeLabel = ( button: HTMLButtonElement ): void =>
{
const text = button.querySelector( '.smth-button-text' );
let label: string;
state.hooksHidden ?
label = 'Show hooks' :
label = 'Hide hooks';
text.textContent = `${ label } (${ getVisibleHooksCount() })`;
};
const init = (): void =>
{
if ( !state.hooksHidden ) {
showHooks();
}
changeLabel( hooksToggle );
document.addEventListener( 'smth.hooks.filtered', () => changeLabel( hooksToggle ) );
};
init();
|
51f30c83250843771c6cd4f5e4232511fb90088c
|
TypeScript
|
aviacommerce/mobileapp-nativescript
|
/app/search/reducers/search.reducers.ts
| 2.625
| 3
|
import { Product } from "~/core/models/product";
import { SearchActions } from "../action/search.actions";
import { IsearchState, searchStateRecord } from "./search.state";
export const initialState: IsearchState = new searchStateRecord() as IsearchState;
export function reducer(state = initialState, { type, payload }: any): IsearchState {
switch (type) {
case SearchActions.GET_SEARCHED_PRODUCTS:
const _searchedProducts: Array<Product> = payload.products;
const _paginationData = payload.pagination;
let _productsLoader: boolean;
if (payload.products.lenght) {
_productsLoader = true;
}
return state.merge({
searchedProducts: _searchedProducts,
paginationData: _paginationData,
productsLoader: _productsLoader
}) as IsearchState;
case SearchActions.CLEAR_PRODUCTS:
return state.merge({
searchedProducts: [],
productsLoader: payload,
paginationData: {}
}) as IsearchState;
default:
return state;
}
}
|
5ba2c04cef738370a3500059ab8b89d83eccee5b
|
TypeScript
|
MrMarans/EIA2
|
/aufg4/aufg3b.ts
| 2.734375
| 3
|
//Aufgabe: Aufgabe 3
//Name: Metzger Ron
//Matrikel: 254878
//Datum: 07.04.2017
//Hiermit versichere ich, dass ich diesen Code selbst geschrieben habe. Er wurde nicht kopiert und auch nicht diktiert.
document.addEventListener('DOMContentLoaded', function() {
let Stapel: string[] = ["Karo 7", "Karo 8", "Karo 9", "Karo 10", "Karo Bube", "Karo Dame", "Karo König", "Karo As", "Baum 7", "Baum 8", "Baum 9", "Baum 10", "Baum Bube", "Baum Dame", "Baum König", "Baum As", "Herz 7", "Herz 8", "Herz 9", "Herz 10", "Herz Bube", "Herz Dame", "Herz König", "Herz As", "Blatt 7", "Blatt 8", "Blatt 9", "Blatt 10", "Blatt Bube", "Blatt Dame", "Blatt König", "Blatt As"];//Ich konnte mir die nie anders merken
let Hand: string[] = [];
let Friedhof: string[] = [];
let n: number = Stapel.length;
document.getElementById("Stapel").textContent = "Bitte Karten ziehen";
document.getElementById("Friedhof").textContent = "Friedhof";
document.getElementById("Stapel").addEventListener("click", function() {
if (Stapel.length > 0 && Hand.length < 5) {
n--;
var i: number = Math.floor((Math.random() * n) + 0);
let Ziehen: string = Stapel[i];
Stapel.splice(i, 1);
Hand.push(Ziehen);
document.getElementById("Stapel").textContent = "Es gibt noch " + Stapel.length + " Karten";
let div: HTMLDivElement = document.createElement("div");
document.getElementById("Hand").appendChild(div);
div.textContent = Ziehen;
div.addEventListener("click", function() {
for (let i: number = 0; i < Hand.length; i++) {
if (this.textContent == Hand[i]) {
Friedhof.push(Hand[i]);
Hand.splice(i, 1);
}
}
document.getElementById("Friedhof").textContent = "Verstorbene Karten" + "Karten: " + Friedhof.length;
this.parentNode.removeChild(this);
});
}
});
});
|
2306d885744f6f27d5f6e7fccccc6f2f727ffdb5
|
TypeScript
|
diorrego/api-rest-typescript-express
|
/src/utils/catch.ts
| 2.765625
| 3
|
import { Response } from 'express';
interface errors extends Error {
code: number;
message: string;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const sendError = (res: Response, e: errors | any): void => {
const statusCode: number = e.code || 500;
res.status(statusCode).send(e.message);
};
|
05d4e5b056c13ab1db59de97fed3a7d34e81051b
|
TypeScript
|
dbalatoni13/jikan-nodejs
|
/lib/functions/genre/animesByGenre.ts
| 2.625
| 3
|
import api from '../../api';
import AnimeByGenre from '../../interfaces/genre/AnimeByGenre';
export default async function animesByGenre(
id: number,
params?: { [Key: string]: number },
): Promise<AnimeByGenre> {
let url = `/search/anime?genre=${id}`;
for (const param in params) {
if (params[param]) {
url += `&${param}=${params[param]}`;
}
}
const { data } = await api.get<AnimeByGenre>(url);
return data;
}
|
dcabac2c5d630d22798207d68bbe356669107848
|
TypeScript
|
blockframes/bank-server
|
/src/firestore/firestore.ts
| 2.546875
| 3
|
import { initializeApp } from 'firebase-admin';
import { ExpectedPayment, Movement } from '../receipt/receipt';
import { PaymentParty } from '../payment/payment';
const app = initializeApp();
const db = app.firestore();
/** This interface come from the Draw.io data model */
interface InvoiceTitleDetails {
titleId: string;
price: number;
}
export interface MovieQuorumInfo {
amount: number;
ethContractAddress: string;
stakeholdersPrivateFor: string[];
}
/** Perform a read & write to firestore to check that the app can access the DB
* and to save the last time that the server has run
*/
export async function checkFirestoreConnection() {
// perform a write
const timestamp = Date.now();
await db.collection('_META').doc('_BANK').set({lastConnection: timestamp});
// assert the read correspond
const metaBankRef = await db.collection('_META').doc('_BANK').get();
if (!metaBankRef.exists) {
throw new Error('Something went wrong!');
} else {
const data = metaBankRef.data();
if (data!.lastConnection === timestamp) {
return true;
} else {
throw new Error('Something went wrong!');
}
}
}
/** Check all invoice object where `invoice.status === 'due'`
* and construct an ExpectedPayment object from every selected due invoices
*/
export async function retrieveExpectedPayments() {
const querySnapshot = await db.collection('invoices').where('status', '==', 'due').get();
const expectedPayments: ExpectedPayment[] = []
querySnapshot.forEach(invoice => {
const invoiceData = invoice.data();
expectedPayments.push({
invoiceId: invoice.id,
fromParty: invoiceData.account.name,
amount: invoiceData.price,
ref: invoiceData.paymentRef,
});
});
return expectedPayments;
}
/**
* Perform all the Firestore queries needed to get smart-contract addresses and privateFor lists for a given invoice
*/
export async function retrieveMoviesQuorumInfoFromInvoice(invoiceId: string) {
const invoiceSnapshot = await db.collection('invoices').doc(invoiceId).get();
const invoiceData = invoiceSnapshot.data();
if (!invoiceData) {
throw new Error(`Invoice Not Found : the invoice with id ${invoiceId} doesn't exist ! This is probably caused by incoherent data in the firestore.`);
}
const moviesQuorumInfoPromises = (invoiceData.titles as InvoiceTitleDetails[]).map(async title => {
const movieId = title.titleId;
const amount = title.price;
const movieSnapshot = await db.collection('movies').doc(movieId).get();
const movieData = movieSnapshot.data();
if (!movieData) {
throw new Error(`Movie Not Found : the movie with id ${movieId} doesn't exist ! This means that invoice #${invoiceId} contains incoherent 'titles' data.`);
}
const ethContractAddress = movieData.quorum.address;
const stakeholdersEthAddresses = movieData.quorum.stakeholderNodes as string[];
const stakeholdersPrivateForPromises = stakeholdersEthAddresses.map(async ethAddress => {
const nodeSnapshot = await db.collection('quorumNodes').doc(ethAddress).get();
const nodeData = nodeSnapshot.data();
if (!nodeData) {
throw new Error(`Quorum Node Not Found : the quorum node with address ${ethAddress} doesn't exist ! This means that the 'quorum.stakeholderNodes' key of the movie ${movieId} contains incoherent data.`);
}
return nodeData.privateFor as string;
});
const stakeholdersPrivateFor = await Promise.all(stakeholdersPrivateForPromises);
return {amount, ethContractAddress, stakeholdersPrivateFor} as MovieQuorumInfo;
});
return Promise.all(moviesQuorumInfoPromises);
}
/** set teh `status` field of a given invoice firestore document to 'paid' */
export async function setInvoiceStatusToPaid(invoiceId: string, txHashProofs: string[]) {
try {
await db.collection('invoices').doc(invoiceId).update({status: 'paid', txHashProofs});
} catch (error) {
console.error(`The update of the invoice ${invoiceId} has failed !`);
throw error;
}
}
/** save unmatched payment to firestore `unmatchedPayments` collection, so that they can be treated by an admin */
export async function persistUnmatchedPayment(payment: {account: string, movement: Movement}) {
try {
await db.collection('unmatchedPayments').add(payment);
} catch (error) {
// ! THIS IS A CRITICAL ERROR THAT SHOULD NEVER EVER HAPPEN
// ! IT MEANS THAT WE HAVE RECEIVE MONEY FOR AN UNKNOWN REASON
// ! AND WE HAVE FAIL TO SAVE THAT, SO THE MONEY WILL BE DIFFICULT TO RECOVER FOR THE SENDER
console.error(`The insertion of the following payment has failed !`);
console.error(payment);
throw error;
}
}
export async function retrieveBankAccountFromEthAddress(ethAddress: string): Promise<PaymentParty> {
const nodeSnapshot = await db.collection('quorumNodes').doc(ethAddress).get();
const nodeData = nodeSnapshot.data();
if (!nodeData) {
throw new Error(`Quorum Node Not Found : There is no node with address ${ethAddress}!`);
}
const orgId = nodeData.orgId;
const orgSnapshot = await db.collection('orgs').doc(orgId).get();
const orgData = orgSnapshot.data();
if (!orgData) {
throw new Error(`Organization Not Found : There is no org with id ${orgId}!`);
}
return { companyName: orgData.account.name, bic: orgData.account.BIC, iban: orgData.account.IBAN }
}
|
bbec990393302794ef88d1340ce1ccddfc5dae08
|
TypeScript
|
chigginsiii/tag_league
|
/client/src/components/style/colors.ts
| 2.828125
| 3
|
interface ToneProfile {
base: string,
bright: string,
brighter: string,
dark: string,
darker: string
}
interface ColorTones {
white: string,
black: string,
primary: ToneProfile,
secondary: ToneProfile,
tertiary: ToneProfile,
complent: ToneProfile,
}
const colors = {
white: "#ffffff",
black: "#000000",
primary: {
base: "#2b7e7e",
bright: "#71bebe",
brighter: "#dbefef",
dark: "#006969",
darker: "#004d4d"
},
secondary: {
base: "#d35f47",
bright: "#ffaa98",
brighter: "#ffedea",
dark: "#ae1e00",
darker: "#801600"
},
tertiary: {
base: "#339959",
bright: "#7ed29d",
brighter: "#e0f4e7",
dark: "#007f2f",
darker: "#005d23"
},
complement: {
base: "#d38647",
bright: "#ffc798",
brighter: "#fff3ea",
dark: "#ae4f00",
darker: "#803a00"
}
};
export default colors;
|
f2a9d3052b6457283897d803439129b42e0e8290
|
TypeScript
|
ShiningDan/intell-be
|
/app/service/loan.ts
| 2.546875
| 3
|
import { Service, Context } from 'egg'
import { LoanProductsModel, LoanUsersModel } from '../model'
export default class Loan extends Service {
constructor(ctx: Context) {
super(ctx)
}
// 这里实现搜素框查询功能
public async search({ name }: { name: string }): Promise<LoanProductsModel[]> {
const { app } = this
const loanProductRepository = app.typeorm.getRepository(LoanProductsModel)
const product = await loanProductRepository.find({name})
if (product.length) {
return product
}else {
throw new Error('Sorry, 没有搜索到相关产品')
}
}
// 这里实现贷款页面的贷款计算器
public async calculate({ job, monthlyIncome, houseType, housePrice, carPrice, phone }:
{ job: string, monthlyIncome: number, houseType: string, housePrice: number, carPrice: number, phone: string }): Promise<LoanUsersModel> {
const { app } = this
const loanUserRepository = app.typeorm.getRepository(LoanUsersModel)
const user = new LoanUsersModel()
user.job = job
user.monthlyIncome = monthlyIncome
user.houseType = houseType
user.housePrice = housePrice
user.carPrice = carPrice
user.phone = phone
if (user.phone.length !== 0) {
const result = await loanUserRepository.save(user)
return result
}else {
throw new Error('Sorry, 用户未输入手机号')
}
}
// 这里实现用户对想了解业务的申请功能
public async apply({ name, phone, amount}:
{ name: string, phone: string, amount: number}): Promise<LoanUsersModel> {
const { app } = this
const loanUserRepository = app.typeorm.getRepository(LoanUsersModel)
const user = new LoanUsersModel()
user.name = name
user.phone = phone
user.amount = amount
const result = await loanUserRepository.save(user)
return result
}
// 这里实现首页底部用户免费通话手机号存储
public async call({ phone}: { phone: string}): Promise<LoanUsersModel> {
const { app } = this
const loanUserRepository = app.typeorm.getRepository(LoanUsersModel)
const user = new LoanUsersModel()
user.phone = phone
if (user.phone.length) {
const result = await loanUserRepository.save(user)
return result
}else {
throw new Error('Sorry, 号码有误')
}
}
}
|
2dba7c038f2e192bec771f5b4c21a59c8b313082
|
TypeScript
|
Saervok/types
|
/definitions/utilities/math/Direction.d.ts
| 2.671875
| 3
|
/*!
* Copyright Unlok, Vaughn Royko 2011-2020
* http://www.unlok.ca
*
* Credits & Thanks:
* http://www.unlok.ca/credits-thanks/
*
* Wayward is a copyrighted and licensed work. Modification and/or distribution of any source files is prohibited. If you wish to modify the game in any way, please refer to the modding guide:
* https://github.com/WaywardGame/types/wiki
*/
import Vector2 from "utilities/math/Vector2";
import Vector3 from "utilities/math/Vector3";
export declare enum Direction {
None = -1,
East = 0,
North = 1,
West = 2,
South = 3
}
export declare module Direction {
const DIRECTIONS: Direction[];
const CARDINALS: Direction[];
const OPPOSITES: Record<Direction, Direction>;
function vector(direction: Direction): Vector2;
function vector(direction: Direction, z: number): Vector3;
const VECTORS: Record<Direction, Vector2>;
const HORIZONTAL: Record<Direction, boolean>;
const VERTICAL: Record<Direction, boolean>;
}
|
8a80cde000ce927fb9748074b4a2dcd56f469a60
|
TypeScript
|
digirati-co-uk/madoc-platform
|
/services/madoc-ts/src/frontend/shared/capture-models/types/to-be-removed.ts
| 2.765625
| 3
|
import { CaptureModel } from './capture-model';
import { NestedField } from './field-types';
import { BaseSelector } from './selector-types';
export type UseCaptureModel<Model extends CaptureModel = CaptureModel> = {
captureModel: Model;
};
export type CaptureModelContext<
Selector extends BaseSelector = BaseSelector,
Model extends CaptureModel = CaptureModel
> = UseCaptureModel<Model> & NavigationContext<Model> & UseCurrentForm<Model> & CurrentSelectorState<Selector>;
// How will the API for this work.
//
// The first step is setting the context of the content.
// <Content type="canvas-panel" state={{ thumbnail: '...', ... }}> ... </Content>
//
// This will let the hooks know which components to serve when you are displaying
// various selectors.
//
// => First the current active selector.
// The actions here will be for updating the selector, its state and preview.
// Also for removing it as the active selector.
//
// const = [ Component, actions ] = useContentSelector();
//
//
// => Display selectors next.
// These are optionally to be displayed on the content. They have some actions
// that can be applied.
// @todo new content-type display selector OR editing parameter passed to current.
//
// const [ Array<[Component, actions]> ] = useContentDisplaySelectors();
//
// The actions will also let you:
// - select/highlight attached field + select selector
// - show/hide individual selectors
//
//
// => Finally, the top level selector.
// This is the outermost and least specific selector on the current form. For example, a form
// may be a paragraph level box with fields for each line (and boxes for each
// line). This top level selector allows the content to focus in on a region
// where the work is being done (e.g. the paragraph in a viewer).
// @todo new prop for display OR editing to indicate top level selector.
// @todo what happens if the top level selector is edited?
// const [ Component, state, actions ] = useTopLevelSelector();
//
// NOTE: Instead of passing `content-type-id` we will have a static context.
export type UseCurrentForm<Model extends CaptureModel = CaptureModel> = {
currentFields: NestedField<Model['document']>;
updateFieldValue: (path: Array<[string, number]>, value: any) => void;
createUpdateFieldValue: (partialPath: Array<[string, number]>) => CaptureModelContext['updateFieldValue'];
};
export type CurrentSelectorState<Selector extends BaseSelector = BaseSelector> = {
// @todo at the moment, the selectors are global to the capture model context.
// This could be changed however, with a new context specifically for selectors.
// This would require the context around the form too, which could complicate things.
// It would not change the core functionality: updateCustomSelector and availableSelectors.
currentSelectorPath: Array<[string, number]> | null;
currentSelector: Selector['state'] | null;
currentSelectorOriginalState: Selector['state'] | null;
setCurrentSelector: (selectorPath: Array<[string, number]> | null) => void;
// @todo possibly reintroduce availableSelectors. Will contain available selectors for the
// content to display without being instantiated by the form to support UX cases. The information
// is still technically available, so not a huge issue. This will possibly used to show regions
// on an image or document that have existing selectors, supporting the UX experience where
// you can click on a selector and be taken to a field. This should really work in hand with
// the current form shown. Will get more complex with nested models.
// availableSelectors: Array<{
// path: Array<[string, number]>;
// selector: BaseSelector;
// }>;
updateCustomSelector: (path: Array<[string, number]>, state: BaseSelector['state']) => void;
};
export type UseCurrentSelector<Selector extends BaseSelector = BaseSelector> = CurrentSelectorState & {
updateSelector: (state: Selector['state'], confirm?: boolean) => void;
confirmSelector: () => void;
resetSelector: () => void;
};
export type NavigationContext<Model extends CaptureModel = CaptureModel> = {
currentView: Model['structure'];
replacePath: (path: number[]) => void;
currentPath: number[];
};
export type UseNavigation<Model extends CaptureModel = CaptureModel> = NavigationContext<Model> & {
pushPath: (index: number) => void;
popPath: () => void;
resetPath: () => void;
};
export type StoredCaptureModel = {
_id?: string;
_rev?: string;
} & CaptureModel;
|
fcc76cbe918e807b7f519c040163c8e1284d94a1
|
TypeScript
|
brTomaz/clonify
|
/src/reducers/player-reducer.ts
| 3.0625
| 3
|
import { Track } from '../entities/track';
import { PlayerContextState as PlayerState } from '../providers/player-context';
import { Action } from '../types/action.type';
export enum PlayerActionType {
CHANGE_QUEUE = 'CHANGE_QUEUE',
PLAY_TRACK = 'PLAY_TRACK',
}
export type PlayerAction = {
[PlayerActionType.CHANGE_QUEUE]: { queue: Track[] };
[PlayerActionType.PLAY_TRACK]: { trackIndex: number };
};
const changeQueue = (state: PlayerState, newQueue: Track[]): PlayerState => {
return {
...state,
queue: newQueue,
};
};
const playTrack = (state: PlayerState, trackIndex: number): PlayerState => {
const previous = state.currentPlayingAudio;
if (previous) previous.pause();
const track = state.queue[trackIndex];
const audio = new Audio(track.sourceUrl);
return {
...state,
currentPlayingIndex: trackIndex,
currentPlayingAudio: audio,
};
};
export const playerReducer = (
state: PlayerState,
action: Action<PlayerAction>
): PlayerState => {
switch (action.type) {
case PlayerActionType.CHANGE_QUEUE:
return changeQueue(state, action.payload.queue);
case PlayerActionType.PLAY_TRACK:
return playTrack(state, action.payload.trackIndex);
default:
return state;
}
};
|
0e03da02d679afb6e6df8c8abf74480595a2de35
|
TypeScript
|
ibuckner/collections
|
/src/slicer.ts
| 3.328125
| 3
|
export type TSlicerState = {
filtered: boolean,
selected: boolean
};
export enum SlicerModifier {
NO_KEY = 0,
CTRL_KEY = 1,
SHIFT_KEY = 2
}
export class Slicer<T> {
private _: Map<T, TSlicerState> = new Map<T, TSlicerState>();
private _selectionCount: number = 0;
public get members(): any {
const result: T[] = [];
this._.forEach((value: TSlicerState, key: T) => {
result.push(key);
});
return result;
}
public get selection(): T[] {
const result: T[] = [];
if (this._selectionCount > 0) {
this._.forEach((value: TSlicerState, key: T) => {
if (value.selected) {
result.push(key);
}
});
}
return result;
}
public lastSelection: T | undefined;
constructor(list?: T | T[] | undefined) {
if (list) {
if (Array.isArray(list)) {
list.forEach((item: T) => {
if (!this._.has(item)) {
this._.set(item, { filtered: false, selected: false });
}
});
} else if (!this._.has(list)) {
this._.set(list, { filtered: false, selected: false });
}
}
}
/**
* Add item to slicer
* @param key
*/
public add(key: T): Slicer<T> {
if (!this._.has(key)) {
let state: TSlicerState = { filtered: false, selected: false };
if (this._selectionCount > 0) {
state.filtered = true;
}
this._.set(key, state);
}
return this;
}
/**
* Removes all selections on the slicer
*/
public clear(): Slicer<T> {
this._.forEach((_: TSlicerState, key: T) => {
this._.set(key, { filtered: false, selected: false });
});
this._selectionCount = 0;
this.lastSelection = undefined;
return this;
}
/**
* Returns true if key already in data set
* @param key - item to search
*/
public has(key: T): boolean {
return this._.has(key);
}
/**
* Returns true if item is filtered
* @param key - item to search for
*/
public isFiltered(key: T): boolean {
const item: TSlicerState | undefined = this._.get(key);
return item ? item.filtered : false;
}
/**
* Returns true if item is selected
* @param key - item to search for
*/
public isSelected(key: T): boolean {
const item: TSlicerState | undefined = this._.get(key);
return item ? item.selected : false;
}
/**
* Remove item from slicer
* @param key - item to remove
*/
public remove(key: T): Slicer<T> {
const state: TSlicerState | undefined = this._.get(key);
if (state && state.selected) {
--this._selectionCount;
}
this._.delete(key);
if (this._selectionCount === 0) {
this.clear();
} else if (this.lastSelection === key) {
this.lastSelection = this.selection[0];
}
return this;
}
/**
* Updates the slicer state
* @param item - item selected by user
* @param modifier - was any modifying key pressed
*/
public toggle(item: T, modifier: SlicerModifier = SlicerModifier.NO_KEY): Slicer<T> {
if (modifier === SlicerModifier.SHIFT_KEY) {
return this.toggleRange(item);
} else if (modifier === SlicerModifier.CTRL_KEY) {
return this.toggleCumulative(item);
} else {
return this.toggleSingle(item);
}
}
/**
* Updates the slicer state using Ctrl key modifier
* @param key - item selected by user
*/
public toggleCumulative(key: T): Slicer<T> {
const state: TSlicerState | undefined = this._.get(key);
if (state) {
state.selected = !state.selected;
if (state.selected) {
++this._selectionCount;
} else {
--this._selectionCount;
}
this._.set(key, state);
}
if (this._selectionCount === 0 || this._selectionCount === this._.size) {
this.clear();
} else {
this._.forEach((value: TSlicerState, key: T) => {
value.filtered = !value.selected;
this._.set(key, value);
});
this.lastSelection = key;
}
return this;
}
/**
* Updates the slicer state using Shift key modifier
* @param item - item selected by user
*/
public toggleRange(item: T): Slicer<T> {
if (item === this.lastSelection) {
this.clear();
} else {
let state: number = 0;
this._selectionCount = 0;
this._.forEach((value: TSlicerState, key: T) => {
if (state === 1) { // in progress
if (item === key || this.lastSelection === key) { // signifies end of range choice
state = -1;
}
if (this.lastSelection === undefined) {
state = -1;
value = { filtered: true, selected: false };
} else {
value = { filtered: false, selected: true };
++this._selectionCount;
}
} else if (state === 0) { // pending
if (item === key || this.lastSelection === key) {
state = 1;
value = { filtered: false, selected: true };
++this._selectionCount;
} else {
value = { filtered: true, selected: false };
}
} else { // stopped
value = { filtered: true, selected: false };
}
this._.set(key, value);
});
this.lastSelection = item;
if (this._selectionCount === 0 || this._selectionCount === this._.size) {
this.clear();
}
}
return this;
}
/**
* Updates the slicer state without key modifier
* @param item - item selected by user
*/
public toggleSingle(item: T): Slicer<T> {
const state: TSlicerState | undefined = this._.get(item);
if (state) {
if (state.selected) {
this.clear();
} else {
this._.forEach((value: TSlicerState, key: T) => {
if (item === key) {
value.selected = !value.selected;
value.filtered = !value.selected;
} else {
value = { filtered: true, selected: false };
}
this._.set(key, value);
});
this._selectionCount = 1;
this.lastSelection = item;
}
}
return this;
}
}
|
2b7919fda842a8e18e35c0d68bba9ed70a2d0424
|
TypeScript
|
trevorhanus/dynaflo
|
/__test__/conditions/ContainsComparator.test.ts
| 2.65625
| 3
|
import ContainsComparator from '../../src/conditions/comparators/ContainsComparator';
describe('ContainsComparator', () => {
it('String', () => {
const comp = new ContainsComparator('test');
const str = comp.exprString('#test');
expect(str.includes('contains(#test, ')).toBe(true);
const valueMap = comp.valueMap();
Object.keys(valueMap).forEach(key => {
expect(valueMap[key]).toBe('test');
});
});
});
|
4064ecba222dea50763b15317474850813ba2473
|
TypeScript
|
pjlee11/speedcurve-cli
|
/src/command/update-url.ts
| 2.765625
| 3
|
import SpeedCurve from "../index"
import log from "../log"
interface UpdateUrlCommandOptions {
key: string
json: boolean
urlId: number
url: string
label?: string
}
export default async function updateUrlCommand(opts: UpdateUrlCommandOptions) {
const { key, json = false, urlId, url, label } = opts
try {
const response = await SpeedCurve.urls.update(key, urlId, {
url,
label
})
if (json) {
log.json(response)
} else {
log.ok(`URL ${response.url_id} was updated`)
}
} catch (e) {
log.error(`Couldn't update URL. ${e.error.message}`)
}
}
module.exports = updateUrlCommand
|