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
|
|---|---|---|---|---|---|---|
a41e25ef231b358d342219f525b7f46278981df0
|
TypeScript
|
rluvaton/bulk-npm-publish
|
/src/user-option/interactive/user-option-prompt-getter.ts
| 2.59375
| 3
|
import { IUserOptionGetter } from '../i-user-option-getter';
import { DEFAULT_USER_OPTIONS } from '../user-options';
import prompts from 'prompts';
import { logger } from '../../logger';
import { deepClone } from '../../utils';
import {
validateStorage,
validateDestPublishScriptFilePath,
validateNpmPublishOptionsIfSpecified,
validateOnlyNewOptionsIfSpecified,
} from '../validator';
const _questions = [
{
type: 'text',
name: 'storagePath',
message: `What's the storage path to publish?`,
validate: (path) => validateStorage(path).catch((err) => err.message),
},
{
type: 'text',
name: 'destPublishScriptFilePath',
message: `Where the publish script will be created`,
initial: DEFAULT_USER_OPTIONS.destPublishScriptFilePath,
validate: (path) => validateDestPublishScriptFilePath(path).catch((err) => err.message),
},
{
type: 'text',
name: 'npmPublishOptions.registry',
message: `What is the registry url you want to publish to`,
initial: DEFAULT_USER_OPTIONS?.npmPublishOptions?.registry,
validate: (registry) => !registry || validateNpmPublishOptionsIfSpecified({ registry }).catch((err) => err.message),
},
{
type: 'confirm',
name: 'createNewOnly',
message: `Should publish only new packages`,
initial: DEFAULT_USER_OPTIONS?.onlyNew?.enable,
},
{
type: (createNewOnlyRes) => (createNewOnlyRes ? 'text' : null),
name: 'onlyNew.registry',
message: `What's the registry to check for published packages`,
initial: DEFAULT_USER_OPTIONS?.onlyNew?.registry,
validate: (registry) =>
validateOnlyNewOptionsIfSpecified({
enable: true,
registry: registry,
}).catch((err) => err.message),
},
];
const getQuestions = () => {
// run clone on each variable request because the questions array is being modified and it's setting values
return deepClone(_questions);
};
export const userOptionPromptGetter: IUserOptionGetter = async () => {
let isCanceled = false;
const questions = getQuestions();
const response = await prompts(questions, {
onCancel: () => {
logger.debug('user cancelled');
isCanceled = true;
return false;
},
});
if (isCanceled) {
throw new Error('Cancelled');
}
logger.debug('user input in prompts', response);
if (!response) {
throw new Error('Error on trying to get input from console');
}
return {
storagePath: response.storagePath,
destPublishScriptFilePath: response.destPublishScriptFilePath,
npmPublishOptions: {
registry: response['npmPublishOptions.registry'],
},
onlyNew: {
enable: response.createNewOnly,
registry: response['onlyNew.registry'],
},
};
};
|
8d4a1f492e5e34e41b426e9d71fe9539e9383f6b
|
TypeScript
|
shawvyu/deviceone
|
/ui/do_TencentSVPlayerView.d.ts
| 2.671875
| 3
|
import { UiBasicInstance } from "../base/uiBase";
export interface DoTencentSVPlayerView extends UiBasicInstance {
/**
* 应用AppId
*
* 说明 : 和fileId配合使用(enableVod=false无效)
*/
appId: string;
/**
* 播放文件Id
*
* 说明 : 和appId配合使用(enableVod=false无效)
*/
fileId: string;
/**
* 是否使用vod点播
*
* 编辑方法: 仅设计器修改。
*
* 说明 : 默认为true,标明当前播放视图用于播放腾讯云点播视频,则会启用appId和fileId作为参数来初始化播放器
*/
enableVod: boolean;
/**
* 播放文件源路径
*
* 说明 : 单独使用;支持data://、source://(本地路径不能带有中文字符串)和网络地址(enableVod=true无效)
*/
path: string;
/**
* 视频封面图片
*
* 说明 : 支持data://、source://和网络地址.备注(如果enableVod=true,优先使用appId和fileId获取到的视频信息中的coverUrl来设置视频封面图片;如果vod视频中无法获取封面图片,则用当前值作为图片封面)
* @default true
*/
placeHolderImage: string;
/**
* 是否自动播放
*
* 编辑方法: 仅设计器修改。
*
* 说明 : 自动播放,默认不自动播放
* @default false
*/
autoPlay: boolean;
/**
* 是否开启视频缓存功能
*
* 编辑方法: 仅设计器修改。
*
* 说明 : 是否自动缓存播放的视频,默认自动缓存
* @default true
*/
enableCache: boolean;
/**
* 最大缓存视频个数
*
* 编辑方法: 仅设计器修改。
*
* 说明 : enableCache为true生效,设置最大缓存视频个数,建议不要设置过大,避免缓存太多数据,默认缓存数量为5
* @default 5
*/
maxCacheItems: number;
/**
* 是否循环播放
*
* 编辑方法: 仅设计器修改。
*
* 说明 :是否循环播放,默认不循环播放
* @default false
*/
loopPlay: boolean;
/**
* 视频缓存目录
*
* 编辑方法: 仅设计器修改。
*
* 说明 :enableCache时会以取cacheDirect为缓存目录,将视频缓存到此目录下。默认缓存目录为:data://do_TencentSVPlayerView
* @default false
*/
cacheDirect: boolean;
/**
* 暂停播放
*/
pause(): void;
/**
* 继续播放
*/
resume(): void;
/**
* 每次调用,会重新播放
* @param listen
*/
play(listen: () => void): void;
/**
* 播放进度回调
*
* 说明: 播放器右上角部分有个小相机按钮,点击后会截图当前视频的画面并给出预览图,预览图消失后,触发当前事件,返回预览图的本地路径
* @param eventName
* @param listen
* @returns {object} {currentTime:2.00,totalTime:10.00},currentTime为当前播放时长,totalTime为总时长,单位是秒
*/
on(eventName: "playProgress", listen: (data: object) => void): void;
}
|
5cad33c88c08f74b57fffa1dce90498b9e3e0c63
|
TypeScript
|
NingyuanXu/CPSC436_Project
|
/src/frontend/chat_room/Actions/index.ts
| 2.6875
| 3
|
import {Action, Dispatch} from "redux";
import {getCurrentUser, getUserInfo, user} from "../../shared/globleFunctions";
import {ISingleMessage, MessageStatus} from "../components/ChatRoomBubbles";
import { IChat } from "../../../shared/ModelInterfaces";
export enum ChatRoomActions{
RECEIVE_MESSAGE,
RECEIVE_INITIAL_MESSAGE,
SEND_MESSAGE,
SEND_MESSAGE_PENDING,
SEND_MESSAGE_ERROR
}
function sendMessageAPICall(user_id: string, receiver: string | null, text: string) {
return fetch('/api/v1/chats', {
method: 'POST',
body: JSON.stringify({
sender_username: user_id,
receiver_username: receiver ? receiver : user_id,
content: text
}),
headers: {
'Content-Type': 'application/json'
}
});
}
export const sendMessage = (text: string, receiver: string|null) => {
return function (dispatch: Dispatch<Action>) {
dispatch({
type: ChatRoomActions.SEND_MESSAGE_PENDING,
message: text,
sender: user
});
sendMessageAPICall(user.username, receiver, text).then((res) => {
if (res.status === 200) {
dispatch({
type: ChatRoomActions.SEND_MESSAGE,
message: text,
sender: user
})
} else {
throw new Error(JSON.stringify(res.body));
}
}).catch((err) => {
console.error(err);
dispatch({
type: ChatRoomActions.SEND_MESSAGE_ERROR,
message:text,
sender: user
})
})
}
};
async function getMessages<T>(user_id: any, recever: any) {
let res = await fetch(`/api/v1/chats?sender_id=${user_id}&receiver_id=${recever ? recever : user_id}`);
let data = await res.json();
return data.allMessages;
}
export const getInitialMessages = (receiver: string| null) => {
return async function(dispatch: Dispatch<Action>) {
if (!user){
await getCurrentUser();
}
if (!receiver){
return;
}
let user_id = user.username;
let receive_user = await getUserInfo(receiver);
let sent_messages = await getMessages(user_id, receiver);
sent_messages = sent_messages.map((m: IChat) => {
return {
message: m.content,
status:MessageStatus.SENT,
sender: user,
time: m.time
}
});
let receive_messages = await getMessages(receiver, user_id);
receive_messages = receive_messages.map((m: IChat) => {
return {
message: m.content,
status: MessageStatus.RECEIVED,
sender: receive_user,
time: m.time
}
});
receive_messages.push(...sent_messages);
console.log(receive_messages);
receive_messages.sort((a: any,b: any) => new Date(a.time).getTime() - new Date(b.time).getTime());
dispatch({
type: ChatRoomActions.RECEIVE_INITIAL_MESSAGE,
message: receive_messages
})
}
};
export const receiveNewMessage = (message: ISingleMessage) => {
return {
type: ChatRoomActions.RECEIVE_MESSAGE,
message: message
}
};
|
e7b1a6358b5c894cc87ab723e9d4233ec4a968c7
|
TypeScript
|
KostiaSA/KostiaSA_WmsAndroid
|
/src/core/speak.ts
| 2.609375
| 3
|
import {
View,
Text,
Navigator,
Route,
fetch as IFetch,
NativeModules,
AppRegistry,
Vibration,
BackAndroid
} from "react-native";
import * as tts_ from "react-native-android-speech"
let tts = tts_ as any;
function speak(text: string) {
console.log(tts);
tts.speak({
text: text, // Mandatory
pitch: 1.2, // Optional Parameter to set the pitch of Speech,
forceStop: false, // Optional Parameter if true , it will stop TTS if it is already in process
language: "ru" // Optional Paramenter Default is en you can provide any supported lang by TTS
}).then((isSpeaking: boolean)=> {
//Success Callback
console.log(isSpeaking);
}).catch((error: any)=> {
//Errror Callback
console.log(error)
});
}
let speaks: string[] = [];
tts.isSpeaking().then((x: any)=> {
console.log("tts.isSpeaking()");
console.log(x);
});
export function pushSpeak(text: string) {
// todo setOnUtteranceProgressListener - сделать перехват конца речи
speak(text);
//speaks.push(text);
}
// setInterval(() => {
// console.log("tts.isSpeaking()");
// console.log(tts.isSpeaking());
// if (speaks.length > 0 && tts.isSpeaking() !== true) {
// let text = speaks[0];
// speaks = speaks.slice(1);
// speak(text);
// }
// }, 500);
|
dcb626bdd193d8fdaee6a840af269dfcfd7e95fb
|
TypeScript
|
dwtcourses/kanban
|
/src/app/shared/column.model.ts
| 3.046875
| 3
|
export class Column{
title: string;
tasks: string[];
constructor(title: string, tasks: string[]){
this.title = title;
this.tasks = tasks;
}
}
|
53b661fc33f4e1fcf21eaeb32f6e374a7e9aeb12
|
TypeScript
|
qazirashid/abeamer
|
/client/lib/js/utilities.ts
| 2.703125
| 3
|
"use strict";
// uuid: 81ec129f-b642-498a-8b8b-f719c1d3bf21
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
/** @module end-user | The lines bellow convey information for the end-user */
/**
*
* ## Description
*
* This module provides utility functions, mostly to be used by plugin creators
* or developers.
*/
namespace ABeamer {
// The following section contains data for the end-user
// generated by `gulp build-definition-files`
// -------------------------------
// #export-section-start: release
export enum RoundFuncName {
none,
round,
ceil,
floor,
downRound,
}
export type RoundFunc = (v: number) => number;
export type RoundHandlerFunc = string | RoundFuncName | RoundFunc;
// #export-section-end: release
// -------------------------------
// ------------------------------------------------------------------------
// Implementation
// ------------------------------------------------------------------------
export function parseRoundFunc(handler: RoundHandlerFunc): RoundFunc {
if (handler === undefined) { return undefined; }
if (typeof handler === 'string') {
handler = RoundFuncName[handler];
} else if (typeof handler === 'function') {
return handler;
}
switch (handler) {
case RoundFuncName.round: return Math.round;
case RoundFuncName.downRound: return downRound;
case RoundFuncName.ceil: return Math.ceil;
case RoundFuncName.floor: return Math.floor;
}
return undefined;
}
export function _applyRoundFunc(values: number[], f: RoundFunc): number[] {
return f ? values.map(value => f(value)) : values;
}
export function parseHandler<T, TO>(handler: T, defaultHandler: T,
_mapper: any, args: ABeamerArgs): TO {
if (handler === undefined) {
if (!defaultHandler) { return undefined; }
handler = defaultHandler;
}
if (typeof handler === 'string') {
const exprValue = ifExprCalc(handler, args);
if (exprValue !== undefined) {
handler = exprValue as any;
}
}
if (typeof handler === 'function') {
return (handler as any)(args) as TO;
} else {
return handler as any;
}
}
export function parseEnum<T>(value: T | string, mapper: any,
defValue?: T | string | undefined): T {
// checks for undefined twice, since this way allows also to remap defValue
if (value === undefined) { value = defValue; }
return value === undefined ? defValue :
(typeof value === 'string' ? mapper[value] : value);
}
}
|
8bed49c27421b20cfde18432ab6e38d25140e3a8
|
TypeScript
|
GZJack/wensdk
|
/src/state/Abc.ts
| 2.984375
| 3
|
// 导出 User 整个对象
export default {
// 状态值的属性名称,必须时字符串,要求 大驼峰命名法,单词首字母大写,尽可能简写,数组尾数尽量使用 s 结尾
name:"User",
// 这里是 state 额外配置参数,这里的配置将决定着 mutations actions getters中的方法
config:{
// 当前 state 的类型,只有 Object 和 Array 这两种类型
type:Object, // 选项 ['Object','Array']
// 是否自动读取写入,当等于 true 的时候,就会自动 读取和写入到 localStorage 本地上
isAutoReadWrite:true, // 等于 false ,会执行本地删除,以前存在的也会被删除
// 当 上面设置本地 存储 后 expire , 过期会自动删除
expire:0, // 0: 表示长期有效, 单位:秒
// 读取和写入的时候 是否自动对数据进行加密
isAutoCrypto:false,
},
// 如果是 Object => {name:'lisi',age:18} , 如果是 Array => {data:[]}
state:{
isLogin:false,
// 员工的 appid, 自动生成, 这个 appid 是由客户端自动生成的 挂载到 system 下
// appid:"12321231312312",
// 员工的 id 登录后 返回并保存到本地
"userid":"",
// 是否官方员工
"isOfficial":false,
// 随机密钥串,每次登录成功都会产生一个,并且会保存到本地上
"appsecret":"",
// 员工头像
"headimgurl": "",
// 员工所在的城市
"city": "",
// 员工的所在国籍
"country": "",
// 员工的性别
"sex": 0,
// 员工的姓名
"name": "",
// 员工的昵称
"nickname": "",
// 员工的手机
"phone": "",
// 员工所在的省份
"province": "",
// 员工的角色id
"roleid": 'vip',
// 用户的 openid
"openid":"",
// 用户设置的语言
"language":"",
// 员工的固定电话
"tel": "",
// 用户的 token, 默认就是一个空的对象
token:{}
},
//
hooks:{
// 当状态已经生成,并已经从本地读取完成后,就会发生当前监听
created(vuevm:any){
console.log('vue',vuevm,this);
},
// 当状态发生变化后,会执行到该监听函数
change(newValue:any,oldValue:any){
}
},
// vuex 中 store.commit('my:(会自动增加当前的属性名(System))=>mySystem'),函数名尽量简写
mutations:{
},
// vuex 中 store.getters.doneTodos(+System 会自动添加这个属性名)(),函数名尽量简写
getters:{
},
// vuex 中 store.dispatch('check(+System 会自动添加这个属性名)'),函数名尽量简写
actions:{
// 定义一个用户注销登录
logout(context:any,options:any){
// 线上的数据也需要注销
context.state.User.set({
isLogin:false,
});
// 注销登录,第一会删除 User 属性
context.state.User.remove();
// 判断是否传入了this
if(options && options.hasThis){
// 拿到this
let that = options.that;
// 注销成功
that.$message("已注销成功,页面准备跳转");
// 路由重新跳转到 首页,如果没有登录,会自动去到登录页面
setTimeout(()=>{
window.location.href = '/';
},2000);
}
},
// // 定义一个用户登录的方法
// login(context,that){
// // 不需要写到这里,这里拿到不 http
// console.log('this $http',this,that);
// }
}
};
|
dcec486bd6158ce57e6d0284876e51047c294be2
|
TypeScript
|
angusm/toolbox-v2
|
/src/toolbox/utils/string/get-content-in-first-set-of-parentheses.ts
| 3.265625
| 3
|
import {ErrorService} from "../error/service";
function getContentInFirstSetOfParentheses(s: string): string {
if (s.indexOf('(') === -1 && s.indexOf(')') === -1) {
return '';
}
if (s.indexOf('(') === -1 && s.indexOf(')') !== -1) {
ErrorService.throw(
"Value passed to getContentInFirstSetOfParentheses() has no " +
"opening parenthesis");
return '';
}
const startIndex = s.indexOf('(') + 1;
let openParenthesesCount = 1;
let currentIndex = startIndex;
while (openParenthesesCount > 0 && currentIndex < s.length) {
const character = s[currentIndex];
if (character === ')') {
openParenthesesCount--;
} else if (character === '(') {
openParenthesesCount++
}
currentIndex++;
}
if (openParenthesesCount > 0) {
ErrorService.throw(
"Value passed to getContentInFirstSetOfParentheses() has uneven " +
"opening/closing parentheses");
return '';
} else {
const endIndex = currentIndex - 1;
return s.slice(startIndex, endIndex);
}
}
export {getContentInFirstSetOfParentheses};
|
232af80f563ae3ac7bd77c0f93cb0f5318435fc9
|
TypeScript
|
deadwin/algorithmByJS
|
/src/problems/KthLargest.ts
| 3.671875
| 4
|
class KthLargest {
private stack: Array<number> = null;
constructor(k: number, nums: number[]) {
this.stack = new Array(nums.length);
}
add(val: number): number {
}
}
class MinHeap {
private data: Array<number> = null;
private comparator: Function;
constructor(data = []) {
this.data = data;
this.comparator = (a, b) => a - b;
}
private heapify() {
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* var obj = new KthLargest(k, nums)
* var param_1 = obj.add(val)
*/
|
48b4b62c3daaef59b5827014b9e150c56ecf43a8
|
TypeScript
|
appnexus/anx-api
|
/src/concurrencyAdapter.ts
| 2.8125
| 3
|
import * as _ from 'lodash';
import { IRequestOptionsInternal } from './api';
import { IRequestQueueItem } from './request-queue';
export interface IConcurrencyQueueOptions {
limit: number;
request: (opts: any) => any;
}
export class ConcurrencyQueue {
private options: IConcurrencyQueueOptions;
private queue: IRequestQueueItem[];
private running: IRequestQueueItem[];
constructor(options: IConcurrencyQueueOptions) {
this.options = _.assign({}, options);
this.queue = [];
this.running = [];
}
public push(opts: IRequestOptionsInternal): Promise<any> {
return new Promise((resolve, reject) => {
const reqInfo: IRequestQueueItem = { opts, resolve, reject };
this.queue.push(reqInfo);
if (this.running.length < this.options.limit) {
this.makeRequest(this.queue.shift());
}
});
}
private finished(requestPromise: IRequestQueueItem): void {
_.remove(this.running, requestPromise);
if (this.queue.length > 0) {
this.makeRequest(this.queue.shift());
}
}
private makeRequest(reqInfo: IRequestQueueItem): void {
this.options
.request(reqInfo.opts)
.then((res) => {
this.finished(reqInfo);
reqInfo.resolve(res);
return null;
})
.catch((err) => {
this.finished(reqInfo);
reqInfo.reject(err);
});
this.running.push(reqInfo);
}
}
export const concurrencyAdapter = (options: IConcurrencyQueueOptions) => {
const concurrencyQueue = new ConcurrencyQueue(options);
return (opts: IRequestOptionsInternal): Promise<any> => {
return concurrencyQueue.push(opts);
};
};
|
e4d5a71f7c7eee0077e0f3e0a82f4aeda876dee4
|
TypeScript
|
sebasgamboa27/PathFinding-Visualizer-Angular
|
/PathFinder/src/app/grid/grid.component.ts
| 2.609375
| 3
|
import { Component, OnInit } from '@angular/core';
import { NodeComponent } from '../node/node.component';
@Component({
selector: 'app-grid',
templateUrl: './grid.component.html',
styleUrls: ['./grid.component.css']
})
export class GridComponent implements OnInit {
board: NodeComponent[][] = [];
startX: number = 5;
startY: number = 5;
endX: number = 20;
endY: number = 35;
mouseState: boolean = false;
dragAndDrop: boolean[] = [false,false];
openSet: NodeComponent[] = [];
closedSet: NodeComponent[] = [];
DFSPath: NodeComponent[] = [];
DFSEnded: boolean = false;
timeTaken: number = 0;
cellsVisited: number = 0;
pathLength: number = 0;
algortithmChosen: number = 0;
animation: boolean = true;
wallAnimation: boolean = false;
wallsToAnimate: NodeComponent[] = [];
constructor() {
for (let i = 0; i < 25; i++) {
let temp = []
for (let j = 0; j < 40; j++) {
const newNode = new NodeComponent();
newNode.i = i;
newNode.j = j;
temp.push(newNode);
}
this.board.push(temp);
}
}
ngOnInit(): void {
for (let i = 0; i < this.board.length; i++) {
for (let j = 0; j < this.board[i].length; j++) {
if(i === this.startX && j === this.startY){
this.board[i][j].isStart = true;
}
else if(i === this.endX && j === this.endY){
this.board[i][j].isFinish = true;
}
}
}
}
randomMaze(){
this.clearBoard();
this.wallAnimation = true;
for (let i = 0; i < this.board.length; i++) {
for (let j = 0; j < this.board[i].length; j++) {
let random = Math.floor(Math.random() * (100 - 0)) + 0;
if(random<30 && !this.board[i][j].isStart && !this.board[i][j].isFinish){
//this.board[i][j].isWall = true;
this.wallsToAnimate.push(this.board[i][j]);
}
}
}
this.animateWalls(this.wallsToAnimate);
}
recursiveDivisionHorizontal(){
this.clearBoard();
this.wallAnimation = true;
this.RDUtil(40,25,0,0,true,0);
this.animateWalls(this.wallsToAnimate);
}
recursiveDivisionVertical(){
this.clearBoard();
this.wallAnimation = true;
this.RDUtil(40,25,0,0,false,0);
this.animateWalls(this.wallsToAnimate);
}
RDUtil(width: number, height: number, startX: number,startY: number,isHorizontal:boolean,times:number){
if (times<7){
//let wix = Math.floor(Math.random() * (width - startX)) + startX;
//let wiy = Math.floor(Math.random() * (height - startY)) + startY;
let wix = Math.floor((width +startX) /2);
let wiy = Math.floor((height + startY) /2);
if(isHorizontal){
for (let i = startX; i < width; i++) {
if(i != wix&&i != wix+1 &&i != wix-1 && !this.board[wiy][i].isStart && !this.board[wiy][i].isFinish){
//this.board[wiy][i].isWall = true;
this.wallsToAnimate.push(this.board[wiy][i]);
}
}
}
else{
for (let i = startY; i < height; i++) {
if(i != wiy&&i != wiy+1 &&i != wiy-1 && !this.board[i][wix].isStart && !this.board[i][wix].isFinish){
//this.board[i][wix].isWall = true;
this.wallsToAnimate.push(this.board[i][wix]);
}
}
}
if(isHorizontal){
console.log(wiy);
this.RDUtil(width,wiy,startX,startY,!isHorizontal,times+1);
debugger;
this.RDUtil(width,height,startX,wiy,!isHorizontal,times+1);
}
else{
console.log(wix);
this.RDUtil(wix,height,startX,startY,!isHorizontal,times+1);
this.RDUtil(width,height,wix,startY,!isHorizontal,times+1);
}
}
}
clearBoard(){
this.board = [];
this.closedSet = [];
this.openSet = [];
this.DFSPath = [];
this.DFSEnded = false;
this.timeTaken = 0;
this.cellsVisited = 0;
this.pathLength = 0;
this.animation = true;
this.algortithmChosen = 0;
this.wallsToAnimate = [];
for (let i = 0; i < 25; i++) {
let temp = []
for (let j = 0; j < 40; j++) {
const newNode = new NodeComponent();
newNode.i = i;
newNode.j = j;
temp.push(newNode);
}
this.board.push(temp);
}
for (let i = 0; i < this.board.length; i++) {
for (let j = 0; j < this.board[i].length; j++) {
if(i === this.startX && j === this.startY){
this.board[i][j].isStart = true;
}
else if(i === this.endX && j === this.endY){
this.board[i][j].isFinish = true;
}
}
}
}
clearBoardWalls(){
let oldBoard = this.board;
this.board = [];
this.closedSet = [];
this.openSet = [];
this.DFSPath = [];
this.DFSEnded = false;
this.timeTaken = 0;
this.cellsVisited = 0;
this.pathLength = 0;
this.animation = true;
this.algortithmChosen = 0;
this.wallsToAnimate = [];
for (let i = 0; i < 25; i++) {
let temp = []
for (let j = 0; j < 40; j++) {
const newNode = new NodeComponent();
newNode.i = i;
newNode.j = j;
if(oldBoard[i][j].isWall){
newNode.isWall = true;
}
temp.push(newNode);
}
this.board.push(temp);
}
for (let i = 0; i < this.board.length; i++) {
for (let j = 0; j < this.board[i].length; j++) {
if(i === this.startX && j === this.startY){
this.board[i][j].isStart = true;
}
else if(i === this.endX && j === this.endY){
this.board[i][j].isFinish = true;
}
}
}
}
changeMouse(state: boolean[]){
this.mouseState = state[0];
this.dragAndDrop[0] = state[1];
this.dragAndDrop[1] = state[2];
}
showBoard(numbers: number[]){
if(numbers[2] === null || !this.dragAndDrop[0]){
if(this.board[numbers[0]][numbers[1]].isWall){
this.board[numbers[0]][numbers[1]].isWall = false;
}
else{
this.board[numbers[0]][numbers[1]].isWall = true;
}
}
else if(numbers[2] === 1 && this.dragAndDrop[0]){
this.board[this.startX][this.startY].isStart = false;
this.board[numbers[0]][numbers[1]].isStart = true;
this.startX = numbers[0];
this.startY = numbers[1];
}
else if(numbers[2] === 2){
this.board[this.endX][this.endY].isFinish = false;
this.board[numbers[0]][numbers[1]].isFinish = true;
this.endX = numbers[0];
this.endY = numbers[1];
}
console.log(this.board);
}
animateAgain(){
if(this.algortithmChosen === 1){
this.clearBoardWalls();
this.showDijkstra();
}
else if(this.algortithmChosen === 2){
this.clearBoardWalls();
this.showAStar();
}
else if(this.algortithmChosen === 3){
this.clearBoardWalls();
this.showBreadth();
}
else if(this.algortithmChosen === 4){
this.clearBoardWalls();
this.showDepth();
}
}
clearBoardPath(){
for (let i = 0; i < this.board.length; i++) {
for (let j = 0; j < this.board[i].length; j++) {
this.board[i][j].isPath = false;
this.board[i][j].animated = false;
this.board[i][j].visited = false;
}
}
}
showDijkstra(){
const start = performance.now();
const visitedNodesInOrder = this.dijkstra(this.board, this.board[this.startX][this.startY], this.board[this.endX][this.endY]);
const end = performance.now();
const time = end-start;
console.log(time);
this.timeTaken = time;
this.cellsVisited = visitedNodesInOrder.length;
const nodesInShortestPathOrder = this.getNodesInShortestPathOrder(this.board[this.endX][this.endY]);
this.pathLength = nodesInShortestPathOrder.length;
this.animateAll(visitedNodesInOrder, nodesInShortestPathOrder);
this.algortithmChosen = 1;
}
showAStar(){
const start = performance.now();
const end = this.aStar(this.board[this.startX][this.startY], this.board[this.endX][this.endY]);
const endTime = performance.now();
const time = endTime-start;
this.timeTaken = time;
this.cellsVisited = this.closedSet.length;
const nodesInShortestPathOrder = this.getNodesInShortestPathOrder(this.board[this.endX][this.endY]);
this.pathLength = nodesInShortestPathOrder.length;
this.animateAStar(nodesInShortestPathOrder);
this.algortithmChosen = 2;
}
showBreadth(){
const start = performance.now();
const visitedNodesInOrder = this.BFS(this.board[this.startX][this.startY], this.board[this.endX][this.endY]);
const end = performance.now();
const time = end-start;
this.timeTaken = time;
this.cellsVisited = visitedNodesInOrder.length;
const nodesInShortestPathOrder = this.getNodesInShortestPathOrder(this.board[this.endX][this.endY]);
this.pathLength = nodesInShortestPathOrder.length;
this.animateAll(visitedNodesInOrder, nodesInShortestPathOrder);
this.algortithmChosen = 3;
}
showDepth(){
const start = performance.now();
this.DFS(this.board[this.startX][this.startY], this.board[this.endX][this.endY]);
const end = performance.now();
const time = end-start;
this.timeTaken = time;
this.cellsVisited = this.DFSPath.length;
const nodesInShortestPathOrder = this.getNodesInShortestPathOrder(this.board[this.endX][this.endY]);
this.pathLength = nodesInShortestPathOrder.length;
this.animateAll(this.DFSPath, nodesInShortestPathOrder);
this.algortithmChosen = 4;
}
BFS(first: NodeComponent, end: NodeComponent){
for (var i = 0; i < 25; i++) {
for (var j = 0; j < 40; j++) {
this.board[i][j].addNeighbors(this.board);
}
}
let path = [];
let queue = [];
first.visited = true;
queue.push(first);
path.push(first);
while(queue.length>0){
let current = queue.shift();
path.push(current);
if(current === end){
return path;
}
current.neighbors.forEach(adjacent => {
if(adjacent.visited === false && !adjacent.isWall){
adjacent.visited = true;
adjacent.previousNode = current;
queue.push(adjacent);
}
});
}
return path;
}
DFS(first: NodeComponent, end: NodeComponent){
for (var i = 0; i < 25; i++) {
for (var j = 0; j < 40; j++) {
this.board[i][j].addNeighbors(this.board);
}
}
first.visited = true;
return this.DFSRecursive(end,first);
}
DFSRecursive(end: NodeComponent, current: NodeComponent){
if(!this.DFSEnded){
this.DFSPath.push(current);
console.log(current);
if(current === end){
this.DFSEnded = true;
return this.DFSPath;
}
else{
current.neighbors.forEach(adjacent => {
if(adjacent.visited === false && !adjacent.isWall){
adjacent.visited = true;
adjacent.previousNode = current;
this.DFSRecursive(end,adjacent);
}
});
}
}
}
showCorrectPath(visitedNodes: NodeComponent[],nodes:NodeComponent[]){
nodes.forEach(node => {
node.isPath = true;
});
visitedNodes.forEach(node => {
node.animated = true;
});
}
animateAll(visitedNodesInOrder:NodeComponent[], nodesInShortestPathOrder:NodeComponent[]) {
for (let i = 0; i <= visitedNodesInOrder.length; i++) {
if (i === visitedNodesInOrder.length) {
setTimeout(() => {
this.animateShortestPath(nodesInShortestPathOrder);
}, 10 * i);
return;
}
setTimeout(() => {
const node = visitedNodesInOrder[i];
node.animated = true;
}, 10 * i);
}
}
animateAStar( nodesInShortestPathOrder:NodeComponent[]) {
for (let i = 0; i <= this.closedSet.length; i++) {
if (i === this.closedSet.length) {
setTimeout(() => {
this.animateShortestPath(nodesInShortestPathOrder);
}, 10 * i);
return;
}
setTimeout(() => {
const node = this.closedSet[i];
node.animated = true;
}, 10 * i);
}
}
showAStarPath(){
for (var i = 0; i < this.openSet.length; i++) {
this.openSet[i].animated = true;
}
}
animateShortestPath(nodesInShortestPathOrder: NodeComponent[]) {
for (let i = 0; i < nodesInShortestPathOrder.length; i++) {
setTimeout(() => {
const node = nodesInShortestPathOrder[i];
node.isPath = true;
}, 40 * i);
}
}
animateWalls(walls: NodeComponent[]) {
for (let i = 0; i <= walls.length; i++) {
setTimeout(() => {
if(i!=walls.length){
const node = walls[i];
node.isWall = true;
}
else{
this.wallAnimation = false;
}
}, 30 * i);
}
}
dijkstra(grid: NodeComponent[][], startNode: NodeComponent, finishNode: NodeComponent) {
const visitedNodesInOrder = [];
startNode.distance = 0;
const unvisitedNodes = this.getAllNodes(grid);
while (!!unvisitedNodes.length) {
this.sortNodesByDistance(unvisitedNodes);
const closestNode = unvisitedNodes.shift();
// If we encounter a wall, we skip it.
if (closestNode.isWall) continue;
// If the closest node is at a distance of infinity,
// we must be trapped and should therefore stop.
if (closestNode.distance === Infinity) return visitedNodesInOrder;
closestNode.visited = true;
visitedNodesInOrder.push(closestNode);
if (closestNode === finishNode) return visitedNodesInOrder;
this.updateUnvisitedNeighbors(closestNode, grid);
}
}
sortNodesByDistance(unvisitedNodes) {
unvisitedNodes.sort((nodeA, nodeB) => nodeA.distance - nodeB.distance);
}
updateUnvisitedNeighbors(node, grid) {
const unvisitedNeighbors = this.getUnvisitedNeighbors(node, grid);
for (const neighbor of unvisitedNeighbors) {
neighbor.distance = node.distance + 1;
neighbor.previousNode = node;
}
}
getUnvisitedNeighbors(node: NodeComponent, grid: NodeComponent[][]) {
const neighbors = [];
const i = node.i;
const j = node.j;
if (j > 0) neighbors.push(grid[i][j - 1]);
if (j < grid[0].length - 1) neighbors.push(grid[i][j + 1]);
if (i > 0) neighbors.push(grid[i - 1][j]);
if (i < grid.length - 1) neighbors.push(grid[i + 1][j]);
return neighbors.filter(neighbor => !neighbor.visited);
}
getAllNodes(grid) {
const nodes = [];
for (const j of grid) {
for (const node of j) {
nodes.push(node);
}
}
return nodes;
}
// Backtracks from the finishNode to find the shortest path.
// Only works when called *after* the dijkstra method above.
getNodesInShortestPathOrder(finishNode: NodeComponent) {
const nodesInShortestPathOrder = [];
let currentNode = finishNode;
while (currentNode !== null) {
nodesInShortestPathOrder.unshift(currentNode);
currentNode = currentNode.previousNode;
}
return nodesInShortestPathOrder;
}
removeFromArray(arr, elt) {
// Could use iOf here instead to be more efficient
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i] == elt) {
arr.splice(i, 1);
}
}
}
aStar(start: NodeComponent, end:NodeComponent){
for (var i = 0; i < 25; i++) {
for (var j = 0; j < 40; j++) {
this.board[i][j].addNeighbors(this.board);
}
}
this.openSet.push(start);
//Starts algorithm
while (this.openSet.length > 0) {
// Best next option
var winner = 0;
for (var i = 0; i < this.openSet.length; i++) {
if (this.openSet[i].f < this.openSet[winner].f) {
winner = i;
}
}
var current = this.openSet[winner];
// Did I finish?
if (current === end) {
console.log("DONE!");
return current;
}
// Best option moves from openSet to closedSet
this.removeFromArray(this.openSet, current);
this.closedSet.push(current);
// Check all the neighbors
var neighbors = current.neighbors;
for (var i = 0; i < neighbors.length; i++) {
var neighbor = neighbors[i];
// Valid next spot?
if (!this.closedSet.includes(neighbor) && !neighbor.isWall) {
var tempG = current.g + this.heuristic(neighbor, current);
// Is this a better path than before?
var newPath = false;
if (this.openSet.includes(neighbor)) {
if (tempG < neighbor.g) {
neighbor.g = tempG;
newPath = true;
}
} else {
neighbor.g = tempG;
newPath = true;
this.openSet.push(neighbor);
}
// Yes, it's a better path
if (newPath) {
neighbor.h = this.heuristic(neighbor, end);
neighbor.f = neighbor.g + neighbor.h;
neighbor.previousNode = current;
}
}
}
}
return null;
}
heuristic(a, b) {
//var d = dist(a.i, a.j, b.i, b.j);
//var d = Math.abs(a.i - b.i) + Math.abs(a.j - b.j);
let d = Math.sqrt( Math.pow((a.i-b.i), 2) + Math.pow((a.j-b.j), 2) );
return d;
}
}
|
8c67cc75663f7469a71bbcd3320b04f42793414a
|
TypeScript
|
visgotti/Gotti.js
|
/lib/core/System/SharedSystem.d.ts
| 2.828125
| 3
|
import System from "./System";
/**
* Shared system is an isolated system from remote communications.
* If you need a system that runs independently from needed server functionality
* and is meant to be ran on both server and client, then this can accomplish that
* while also dispatching local messages.
*/
export declare abstract class SharedSystem extends System {
readonly name: string | number;
private dispatch;
constructor(name: string);
abstract onMessage(message: any): any;
onStateUpdate(path: any, change: any, value: any): void;
}
|
dd5f27e8c8c3d2ce5d52322b692bed00b6ef7c84
|
TypeScript
|
dpherod/angular-marvel-heroes
|
/client/src/app/state/heroes/reducers/heroes.ts
| 2.59375
| 3
|
import {createEntityAdapter, EntityAdapter, EntityState} from "@ngrx/entity";
import {Hero} from "../../../core/models/hero.model";
import {
ADD_HERO_DIALOG_CLOSE, ADD_HERO_DIALOG_OPEN, DELETE_HERO_SUCCESS, HeroesAction, LOAD_HERO_SUCCESS, LOAD_HEROES,
LOAD_HEROES_SUCCESS, SELECT_HERO, UPDATE_HERO_SUCCESS
} from "../actions/heroes";
export interface State extends EntityState<Hero> {
addDialogShow: boolean;
loading: boolean;
selectedHeroId: number;
}
export const adapter: EntityAdapter<Hero> = createEntityAdapter();
export const initialState: State = adapter.getInitialState({
addDialogShow: false,
loading: false,
selectedHeroId: null
});
export function reducer(state: State = initialState, action: HeroesAction) {
switch (action.type) {
case ADD_HERO_DIALOG_CLOSE:
return {...state, addDialogShow: false};
case ADD_HERO_DIALOG_OPEN:
return {...state, addDialogShow: true};
case DELETE_HERO_SUCCESS:
return adapter.removeOne(action.payload.id, state);
case LOAD_HERO_SUCCESS:
return adapter.addOne(action.payload, state);
case LOAD_HEROES:
return {...state, loading: true};
case LOAD_HEROES_SUCCESS:
state = {...state, loading: false};
return adapter.addAll(action.payload, state);
case SELECT_HERO:
return {...state, selectedHeroId: action.payload.id};
case UPDATE_HERO_SUCCESS:
return adapter.updateOne({
id: action.payload.id,
changes: action.payload
}, state);
default:
return state;
}
}
export const getSelectedHeroId = (state: State) => state.selectedHeroId;
export const isLoading = (state: State) => state.loading;
|
01217ec6dc09db2fb265fe6bae3e11579704d07b
|
TypeScript
|
InteractiveTimmy/js-abp
|
/src/middleware/connect/express-connector/express-connector.ts
| 2.546875
| 3
|
// external dependencies
import Express, {
Application,
json,
Request,
Response,
} from 'express';
import { Server } from 'http';
// internal dependencies
import { ConnectMiddleware, Structure, Payload } from '../../../models/index';
import { uuid } from '../../../utils/index';
export class ExpressConnector implements ConnectMiddleware<ExpressConnector> {
protected wsc: Application
protected wsi: Server
protected structures: Structure[] = []
protected responses: { [index: string]: Response } = {}
protected config: { [index: string]: string } = {}
protected ready: boolean;
protected active: boolean;
public receive: (payload: Payload) => void
public constructor(config: { [index: string]: string }) {
this.config = config;
this.wsc = Express();
}
public getExpressConfig(): Application {
return this.wsc;
}
public getHttpServer(): Server {
return this.wsi;
}
public load(...structures: Structure[]): ExpressConnector {
this.structures = [...structures];
const {
wsc,
ready,
active,
start,
stop,
receive,
} = this;
const wasActive = active;
if (wasActive) {
stop();
}
structures.forEach((structure) => {
wsc.all(`/api/v1/${structure.name}/:id?`, json(), (req: Request, res: Response) => {
let method: 'create' | 'read' | 'update' | 'remove';
switch (req.method) {
case 'POST':
method = 'create';
break;
case 'GET':
method = 'read';
break;
case 'PUT':
method = 'update';
break;
case 'DELETE':
method = 'remove';
break;
default:
}
const myUUID = uuid();
const payload = new Payload(
method,
structure.name,
req.params.id,
req.get('Authorization'),
myUUID,
);
const myInput: { [index: string]: string } = {};
Object.keys(req.query).forEach((queryKey) => {
myInput[queryKey] = req.query[queryKey];
});
Object.keys(req.body).forEach((bodyKey) => {
myInput[bodyKey] = req.body[bodyKey];
});
payload.setInput({ ...myInput });
if (method) {
if (this.receive) {
this.responses[myUUID] = res;
receive(payload);
}
}
});
});
if (wasActive) {
start();
}
if (!ready) {
this.ready = true;
}
return this;
}
public send(payload: Payload): void {
const res = this.responses[payload.id];
const responseObj = {
data: payload.output,
uuid: uuid(),
timestamp: new Date().toISOString(),
};
// eslint-disable-next-line no-console
console.log(
`
${responseObj.timestamp}
[${payload.type.toUpperCase()}/${payload.id}/${responseObj.uuid}] -
${JSON.stringify(responseObj.data)}
`,
);
res.send(responseObj);
delete this.responses[payload.id];
}
public start(): ExpressConnector {
if (this.ready && !this.active) {
const { port } = this.config;
this.wsi = this.wsc.listen(port);
}
return this;
}
public stop(): ExpressConnector {
if (this.active) {
this.wsi.close();
}
return this;
}
}
|
d3a9209a92d9a1879ca395570882db0c27951c0e
|
TypeScript
|
Kujikeo/cabelex
|
/src/services/mirage/index.ts
| 2.59375
| 3
|
import {
createServer,
Model,
Factory,
Response,
ActiveModelSerializer,
} from "miragejs";
import faker from "faker";
type Filial = {
nome: string;
total_funcionarios: number;
};
type User = {
email: string;
nome: string;
};
type Funcionario = {
nome: string;
nome_filial: string;
};
export function makeServer() {
const server = createServer({
serializers: {
aplication: ActiveModelSerializer,
},
models: {
filial: Model.extend<Partial<Filial>>({}),
user: Model.extend<Partial<User>>({}),
funcionario: Model.extend<Partial<Funcionario>>({}),
},
factories: {
user: Factory.extend({
nome(i: number) {
return `User ${i + 1}`;
},
email() {
return faker.internet.email().toLowerCase();
},
}),
filial: Factory.extend({
nome(i: number) {
return `Filial ${i + 1}`;
},
total_funcionarios() {
return faker.datatype.number();
},
}),
funcionario: Factory.extend({
nome(i: number) {
return `Raul ${i + 1}`;
},
nome_filial(i: number) {
return `Filial ${i + 1}`;
},
}),
},
seeds(server) {
server.createList("user", 10);
server.createList("filial", 5);
server.createList("funcionario", 6);
},
routes() {
this.namespace = "api";
this.timing = 750;
this.get("/filials", function (schema, request) {
const { page = 1, per_page = 10 } = request.queryParams;
const total = schema.all("filial").length;
const pageStart = (Number(page) - 1) * Number(per_page);
const pageEnd = pageStart + Number(per_page);
const filiais = this.serialize(schema.all("filial")).filials.slice(
pageStart,
pageEnd
);
return new Response(
200,
{ "x-total-count": String(total) },
{ filiais }
);
});
this.post("/filials", function (schema, request) {
let attrs = JSON.parse(request.requestBody).filial;
if (attrs.nome) {
return this.serialize(schema.create("filial", attrs));
} else {
return new Response(
400,
{ some: "header" },
{ errors: ["name cannot be blank"] }
);
}
});
this.put("/filials/:id", function (schema, request) {
let id = request.params.id;
let attrs = JSON.parse(request.requestBody).filial;
return this.serialize(schema.find("filial", id).update(attrs));
});
this.del("/filials/:id", function (schema, request) {
let id = request.params.id;
schema.find("filial", id).destroy();
return null;
});
this.get("/funcionarios");
this.get("/funcionarios", function (schema, request) {
const { page = 1, per_page = 10 } = request.queryParams;
const total = schema.all("funcionario").length;
const pageStart = (Number(page) - 1) * Number(per_page);
const pageEnd = pageStart + Number(per_page);
const funcionarios = this.serialize(
schema.all("funcionario")
).funcionarios.slice(pageStart, pageEnd);
return new Response(
200,
{ "x-total-count": String(total) },
{ funcionarios }
);
});
this.post("/funcionarios", function (schema, request) {
let attrs = JSON.parse(request.requestBody).funcionario;
if (attrs.nome) {
return this.serialize(schema.create("funcionario", attrs));
} else {
return new Response(
400,
{ some: "header" },
{ errors: ["name cannot be blank"] }
);
}
});
this.put("/funcionarios/:id", function (schema, request) {
let id = request.params.id;
let attrs = JSON.parse(request.requestBody).filial;
return this.serialize(schema.find("funcionario", id).update(attrs));
});
this.del("/funcionarios/:id", function (schema, request) {
let id = request.params.id;
schema.find("funcionario", id).destroy();
return null;
});
this.namespace = "";
this.passthrough();
},
});
return server;
}
|
4fda25ff188d2af47996dee75e0532aeeec77f85
|
TypeScript
|
thisisjacopo/Adidas-TC-SubscriptionService
|
/src/subscriptions/schemas/Subscriptions.schema.ts
| 2.59375
| 3
|
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
export type SubscriptionDocument = Subscription & Document;
@Schema()
export class Subscription{
@Prop()
id: string
@Prop({required: true})
email: string
@Prop()
firstName: string
@Prop()
gender: string
@Prop({required: true})
consent: boolean
@Prop({required: true})
dateOfBirth: Date
}
export const SubscriptionSchema = SchemaFactory.createForClass(Subscription);
|
2b494cd6a90c95166a54352c75942a99781bc4e6
|
TypeScript
|
Enitoni/gears
|
/website/src/modules/docs/helpers/getConstructorSignatureString.ts
| 2.921875
| 3
|
import { ConstructorSignature } from "../types/ClassDescriptor"
export const getConstructorSignatureString = (descriptor: ConstructorSignature) => {
const parameterString = descriptor.parameters
.map(descriptor => {
const { name, defaultValue } = descriptor
let str = name
if (defaultValue) {
str += ` = ${defaultValue}`
}
return str
})
.join(", ")
return `${descriptor.name}(${parameterString})`
}
|
12f32f1c401df1e9881dddc816730aa5693214d2
|
TypeScript
|
sirhypernova/forge
|
/src/data-providers/object-provider.ts
| 3.03125
| 3
|
import DataProvider from "./data-provider";
import {default as _} from "lodash";
/**
* @extends DataProvider
*/
export default class ObjectProvider extends DataProvider {
protected data: any;
/**
* @param {object} data
*/
constructor(data: any) {
super();
/**
* @type {object | null}
* @private
*/
this.data = data;
}
/**
* Retrieve guild data
* @param {string} path
* @return {object}
*/
public get(path: string): any {
return _.get(this.data, path);
}
/**
* Set guild data
* @param {string} path
* @param {*} value
*/
public set(path: string, value: any): void {
_.set(this.data, path, value);
}
/**
* @todo
* Merge guild data
* @param {string} path
* @param {*} value
*/
public merge(path: string, value: any): void {
throw new Error("[ObjectProvider.merge] Method not implemented.");
}
}
|
36a562f83b9daaee39149018f21273ea1e1a22dd
|
TypeScript
|
CamiloRozoP/UnitTestSample
|
/jasmine-karma/src/app/app.component.spec.ts
| 2.59375
| 3
|
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { By } from '@angular/platform-browser';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let n=0;
afterEach(()=>{
n++;
})
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('Se debe crear', () => {
expect(component).toBeTruthy(); //Comprueba si el valor actual se evalúa como "verdadero".
console.log("test",n);
});
it('crear titulo en etiqueta h1', () => {
const title = fixture.debugElement.query(By.css('h1')).nativeElement;
expect(title.innerHTML).toBe('jasmine-karma');
console.log("test",n);
});
//Encontrar un elemento usando la clase y verificando su contenido
it('debe haber contrenido en clase board ', () => {
const board = fixture.debugElement.query(By.css('.board')).nativeElement;
expect(board.innerHTML).not.toBeNull();
// console.log(board.innerHTML)
expect(board.innerHTML.length).toBeGreaterThan(0);
console.log("test",n);
});
//encontrar elemento usando id y verificando su contenido
it('Debe haber un yes en yes button"', () => {
const btn = fixture.debugElement.nativeElement.querySelector('#yes-btn');
expect(btn.innerHTML).toBe('Yes');
console.log("test",n);
});
//Recreate a “Click” event on a button
it('debe asignar un userresponse cuando el boton yes es clickeado ', () => {
expect(component.userResponse).toBeUndefined();
const btn = fixture.debugElement.nativeElement.querySelector('#yes-btn');
btn.click();
expect(component.userResponse).toBe('I am In');
console.log("test",n);
});
it('debe tener el boton no desactivado', () => {
const btn = fixture.debugElement.nativeElement.querySelector('#no-btn');
expect(btn.disabled).toBeTruthy();
console.log("test",n);
});
it('disablenobutton asignado por default', () => {
expect(component.disableNoButton).toBeTruthy();
console.log("test",n);
});
it('contiene boarding', () => {
const title = document.getElementById('titulo').innerHTML;
expect(title).toContain('Boarding'); //contiene una palabra
console.log("test",n);
});
});
|
221f735eabb19b8744328aaee4ec7a7e6c4545fa
|
TypeScript
|
hwanderlust/shiritori
|
/src/scripts/game/clock.ts
| 2.921875
| 3
|
import { get } from "../helpers"
const defaultTime = 10;
export default function Clock() {
window.sessionStorage.setItem("time", `${defaultTime}`);
const clockEl: HTMLElement = get("clock");
let currentTime = defaultTime;
let interval;
let callBuzzer: () => void;
return {
init: function (cb): void {
callBuzzer = cb;
},
countdown: function (): void {
interval = setInterval(() => {
currentTime--;
if (currentTime === 0) {
callBuzzer();
}
if (currentTime < 0) {
this.stop();
clockEl.innerText = `0:00`;
return;
}
if (currentTime < 10) {
clockEl.innerText = `0:0${currentTime}`;
return;
}
clockEl.innerText = `0:${currentTime}`;
}, 1000);
},
reset: function (): void {
const allowedTime = Number(window.sessionStorage.getItem("time"));
currentTime = allowedTime;
this.stop();
setTimeout(() => {
clockEl.innerText = `0:${currentTime}`;
this.countdown();
}, 200);
},
stop: function (): void {
clearInterval(interval);
}
}
}
|
20dc6922ab3f7d3824dc9144c3e6f8ea422a8abf
|
TypeScript
|
TarunShrivastva/angular-zomato-app
|
/src/app/gallery/gallery-thumbnail/gallery-thumbnail.model.ts
| 2.53125
| 3
|
export interface GalleryThumbnail {
id: number
name: string
image: string
street: string
country_id: number
state_id: number
city_id: number
created_at: Date
updated_at: Date
deleted_at: Date
foods: Food[]
}
export interface Food {
[index: number]: FoodData[]
}
export interface FoodData {
id: number
name: string
image: string
price: number
category_id: number
subcategory_id: number
restaurent_id: number
created_at: Date
updated_at: Date
deleted_at: Date
}
|
ff06b86828f34f681cb5cd544e7fc0498e717558
|
TypeScript
|
thinktecture/2d-3d-usergroup-2015
|
/2D/source/example9.ts
| 3.296875
| 3
|
/// <reference path="../typings/tsd.d.ts" />
/// <reference path="example9_arc.ts" />
/**
* Rotating Pie Chart with MouseHover and TouchMove
*/
class Example9 {
/**
* The canvas where the chart will be drawn to
*/
private _canvas: HTMLCanvasElement;
/**
* The 2D context of the canvas
*/
private _context: CanvasRenderingContext2D;
/**
* Width in pixel without devicePixelRatio scaling of the canvas
*/
private _width: number;
/**
* Height in pixel without devicePixelRatio scaling of the canvas
*/
private _height: number;
/**
* Array of all the pie parts
*/
private _pieParts: Array<Arc> = new Array<Arc>();
/**
* Will hold the current animation frame is the animation is running
*/
private _animationFrame: number;
constructor(canvas: HTMLCanvasElement, values: Array<number>) {
// Assign parameters of the constructor to the private variables
this._canvas = canvas;
this._context = <CanvasRenderingContext2D> canvas.getContext('2d');
this._width = canvas.width;
this._height = canvas.height;
this.adjustForRetina();
this.createPieParts(values);
this.assignEvents();
}
/**
* Returns the devicePixelRatio or 1
*/
private getDevicePixelRatio(): number {
return window.devicePixelRatio || 1;
}
/**
* Adjusts the canvas and the context for retina scaling (if devicePixelRatio > 1)
*/
private adjustForRetina(): void {
var factor: number;
if ((factor = this.getDevicePixelRatio()) > 1) {
this._canvas.width = this._width * factor;
this._canvas.height = this._height * factor;
this._canvas.style.width = this._width + 'px';
this._canvas.style.height = this._height + 'px';
this._context.scale(factor, factor);
}
}
/**
* Returns a random color
*/
private getRandomColor(): Array<number> {
return [Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255)];
}
/**
* Calculates radiants from degrees
*/
private degreesToRadiants(degrees: number): number {
return (degrees * Math.PI) / 180;
}
/**
* Creates the pie parts from the values
*/
private createPieParts(values: Array<number>): void {
var centerX: number = this._width / 2;
var centerY: number = this._height / 2;
var radius: number = this._width / 2 - 50;
var rotationDeg: number = 0;
values.forEach(value => {
var arc = new Arc(this._context);
arc.color = this.getRandomColor();
arc.centerX = centerX;
arc.centerY = centerY;
arc.radius = radius;
arc.startAngle = this.degreesToRadiants(rotationDeg);
arc.endAngle = arc.startAngle + this.degreesToRadiants(value * 3.6);
rotationDeg += value * 3.6;
this._pieParts.push(arc);
});
}
/**
* Assigns mouse and touch events to the canvas
*/
private assignEvents(): void {
var that = this;
that._canvas.addEventListener('mousemove', event => {
event.preventDefault();
that.handleMouseMove(event.layerX, event.layerY);
});
that._canvas.addEventListener('click', event => {
event.preventDefault();
that.toggleAnimation();
});
that._canvas.addEventListener('touchstart', event => {
event.preventDefault();
that.toggleAnimation();
});
that._canvas.addEventListener('touchmove', event => {
event.preventDefault();
console.log('touchmove');
that.handleTouchMoveEvent(<TouchEvent>event);
});
}
/**
* Toggles the animation
*/
private toggleAnimation(): void {
if (this._animationFrame) {
return this.stopAnimation();
}
this.startAnimation();
}
/**
* Returns the correct positions of an event (mouse/touch)
*
* See: http://stackoverflow.com/a/10816667/959687
*/
private getOffset(event: any): any {
var el = event.target,
x = 0,
y = 0;
while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
x += el.offsetLeft - el.scrollLeft;
y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
x = event.clientX - x;
y = event.clientY - y;
return { x: x, y: y };
}
/**
* Handles touch move. Will move the pie chart
*/
private handleTouchMoveEvent(e: TouchEvent): void {
var that = this;
// .touches is an array containing one or more touch points for multi-touch scenarios
var position = this.getOffset(e.touches[0]);
this._pieParts.forEach(part => {
part.centerX = position.x;
part.centerY = position.y;
});
window.requestAnimationFrame(() => {
that.draw();
});
}
/**
* Handles mouse move. Will simulate a "hover effect"
*/
private handleMouseMove(x: number, y: number): void {
var that = this;
var factor = this.getDevicePixelRatio();
var color = this._context.getImageData(x * factor, y * factor, 1, 1).data;
this._pieParts.forEach(part => {
if (part.color[0] === color[0] || part.color[0] === color[0] - 1 || part.color[0] === color[0] + 1) {
part.alpha = 0.5;
}
else {
part.alpha = 1;
}
});
window.requestAnimationFrame(() => {
that.draw();
});
}
/**
* Starts the animation sequence
*/
private startAnimation(): void {
var that = this;
var animationframeCallback = function() {
that._pieParts.forEach(part => {
part.rotation += that.degreesToRadiants(1);
});
that.draw();
that._animationFrame = window.requestAnimationFrame(animationframeCallback);
}
that._animationFrame = window.requestAnimationFrame(animationframeCallback);
}
/**
* Stops the animation sequence
*/
private stopAnimation(): void {
window.cancelAnimationFrame(this._animationFrame);
this._animationFrame = undefined;
}
/**
* Draws the chart :)
*/
public draw(): void {
var c: CanvasRenderingContext2D = this._context;
c.clearRect(0, 0, this._width, this._height);
this._pieParts.forEach(part => {
part.draw();
});
}
}
|
2311f77c8d6eeed54012823badeabfedae442028
|
TypeScript
|
chrisryanouellette/Airtable_Mapping_App
|
/frontend/types.ts
| 2.640625
| 3
|
export interface Mappings {
bases: {
[refName: string]: BaseMapping
}
tables: {
[refName: string]: TableMapping
}
views: {
[refName: string]: ViewMapping
}
}
export interface BaseMapping {
id: string
name: string
refName: string
tables: {
[id: string]: string
}
}
export interface TableMapping {
id: string
baseId: string
name: string
refName: string
views: {
[id: string]: string
}
}
export interface ViewMapping {
id: string
name: string
tableId: string
refName: string
fields: {
[refName: string]: FieldMapping
}
}
export interface FieldMapping {
id: string
tableId: string
viewId: string
name: string
type: string
refName: string
}
export type AllMappings = BaseMapping | TableMapping | ViewMapping
|
a37a5f68b2629a804a4786a375e448ebd9d96c99
|
TypeScript
|
nherault/renderer-system
|
/src/renderer/commons/entity/entity-factory.ts
| 2.796875
| 3
|
import { ShapeFactory } from '../shape/shape-factory';
import { Vector2DData } from '../vector-2d/vector-2d.types';
import { Entity2DData } from './entity.types';
export class Entity2DFactory {
public static create(
position?: Vector2DData, velocity?: Vector2DData,
size?: Vector2DData, acceleration?: Vector2DData): Entity2DData {
const entity2DData = ShapeFactory.createRectangleFromVector2DData(position, size) as Entity2DData;
entity2DData.velocity = velocity || {x: 0, y: 0};
entity2DData.acceleration = acceleration || {x: 0, y: 0};
return entity2DData;
}
}
|
4f3c8b07ff14c4a1326509be13f72fe5a12de9d5
|
TypeScript
|
bishrant/MapMyProperty
|
/src/app/shared/store/storage.metareducer.ts
| 2.578125
| 3
|
function setSavedState (state: any) {
localStorage.setItem(localStorageKey, JSON.stringify(state));
}
function clearLocalStorage () {
localStorage.removeItem(localStorageKey);
}
function getSavedState (): any {
return JSON.parse(localStorage.getItem(localStorageKey));
}
// the key for the local storage
const localStorageKey = '__mmp_storage__';
export { getSavedState, clearLocalStorage, setSavedState }
|
58dcad420804652395174f1e65f88e746db2e96d
|
TypeScript
|
mellet/csgonades-client
|
/src/utils/PairingUtils.ts
| 3.359375
| 3
|
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { NadeLight } from "../nade/models/NadeLight";
export function createPairings(nades: NadeLight[]): NadeLight[][] {
const updatedNades = [...nades];
// Remove a random nade if the count is odd
if (updatedNades.length % 2 !== 0) {
const randomIndex = Math.floor(Math.random() * updatedNades.length);
updatedNades.splice(randomIndex, 1);
}
// Separate the nades based on teamSide
const ctNades: NadeLight[] = updatedNades.filter(
(nade) => nade.teamSide === "counterTerrorist"
);
const tNades: NadeLight[] = updatedNades.filter(
(nade) => nade.teamSide === "terrorist"
);
const bothNades: NadeLight[] = updatedNades.filter(
(nade) => nade.teamSide === "both" || !nade.teamSide
);
// Shuffle the arrays to randomize the nades
shuffleArray(ctNades);
shuffleArray(tNades);
shuffleArray(bothNades);
// Create the pairings array
const randomizedPairings: NadeLight[][] = [];
while (ctNades.length > 0 || tNades.length > 0 || bothNades.length > 0) {
const pair: NadeLight[] = [];
if (ctNades.length > 0) {
const ctNade = ctNades.pop();
if (ctNade) {
pair.push(ctNade);
const companion = selectSameIfPossible(
ctNade,
ctNades,
tNades,
bothNades
);
pair.push(companion);
}
} else if (tNades.length > 0) {
const tNade = tNades.pop();
if (tNade) {
pair.push(tNade);
const companion = selectSameIfPossible(
tNade,
ctNades,
tNades,
bothNades
);
pair.push(companion);
}
} else if (bothNades.length > 0) {
const nade = bothNades.pop();
if (nade) {
pair.push(nade);
const companion = selectSameIfPossible(
nade,
ctNades,
tNades,
bothNades
);
pair.push(companion);
}
}
// Add the pair to the pairings array
randomizedPairings.push(pair);
}
shuffleArray(randomizedPairings);
return randomizedPairings;
}
function selectSameIfPossible(
selected: NadeLight,
ctNades: NadeLight[],
tNades: NadeLight[],
anyNades: NadeLight[]
) {
if (selected.teamSide === "counterTerrorist") {
if (ctNades.length) {
return ctNades.pop()!;
} else if (anyNades.length) {
return anyNades.pop()!;
} else {
return tNades.pop()!;
}
} else if (selected.teamSide === "terrorist") {
if (tNades.length) {
return tNades.pop()!;
} else if (anyNades.length) {
return anyNades.pop()!;
} else {
return ctNades.pop()!;
}
} else {
if (tNades.length) {
return tNades.pop()!;
} else if (anyNades.length) {
return anyNades.pop()!;
} else {
return ctNades.pop()!;
}
}
}
// Helper function to shuffle an array in place
export function shuffleArray<T>(array: T[]): void {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
// @ts-ignore
[array[i], array[j]] = [array[j], array[i]];
}
}
export function shuffleArrays<T>(arr: T[]): T[] {
const shuffled = [...arr];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
// @ts-ignore
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
export const cleanAndSortNadeClusters = (nadeCluster: NadeLight[][]) => {
const onlyClustersWithTwoNadesOrMore = [...nadeCluster].filter(
(nadeList) => nadeList.length >= 2
);
const onlyEven = makeEven(onlyClustersWithTwoNadesOrMore);
const shuffled = shuffleArrays(onlyEven);
return shuffled;
};
function makeEven(arr: NadeLight[][]): NadeLight[][] {
const result: NadeLight[][] = [];
for (const subarray of arr) {
if (subarray.length % 2 === 1) {
subarray.pop();
}
result.push(subarray);
}
return result;
}
export function selectElements(arr: any[][], count: number): any[][] {
const result: any[][] = [];
let totalCount = 0;
for (const subarray of arr) {
const subArrayCopy = [...subarray];
shuffleArray(subArrayCopy);
const remainingCount = Math.min(count - totalCount, 8);
const selectedElements = subArrayCopy.slice(0, remainingCount);
result.push(selectedElements);
totalCount += selectedElements.length;
if (totalCount >= count) {
break;
}
}
return result;
}
type ExtractedNadePair = {
newNadePairing: NadeLight[];
clusters: NadeLight[][];
};
export function extractNewNadePair(clusters: NadeLight[][]): ExtractedNadePair {
const clustersCopy = clusters.map((cluster) => [...cluster]);
shuffleArray(clustersCopy);
let newNadePairing: NadeLight[] = [];
let selectedClusterIndex = -1;
for (let i = 0; i < clustersCopy.length; i++) {
const cluster = clustersCopy[i];
if (!cluster) continue; // Skip if cluster is undefined
const newNades = cluster.filter((nade) => nade.isNew);
if (newNades.length > 0 && cluster.length >= 2) {
const randomNewNadeIndex = getRandomIndex(newNades.length);
const newNade = newNades[randomNewNadeIndex];
const remainingNades = cluster.filter((nade) => nade.id !== newNade?.id);
const randomNadeIndex = getRandomIndex(remainingNades.length);
const randomNade = remainingNades[randomNadeIndex];
if (newNade && randomNade) {
newNadePairing = [newNade, randomNade];
selectedClusterIndex = i;
break;
}
}
}
if (selectedClusterIndex === -1) {
return {
newNadePairing: [],
clusters: clustersCopy,
};
}
const clusterWithNewNade = clustersCopy[selectedClusterIndex];
const newNade = newNadePairing[0];
const randomNade = newNadePairing[1];
// Remove the selected nades from the clusters copy if it is defined
if (clusterWithNewNade && newNade && randomNade) {
clustersCopy[selectedClusterIndex] = clusterWithNewNade.filter(
(nade) => nade.id !== newNade.id && nade.id !== randomNade.id
);
}
return {
newNadePairing,
clusters: clustersCopy,
};
}
function getRandomIndex(length: number): number {
return Math.floor(Math.random() * length);
}
|
073d3b2657c527d30aff06758ba5308210921652
|
TypeScript
|
CodeguruEdison/leetcode-typescript-solutions
|
/problems/454.4Sum-II.ts
| 3.0625
| 3
|
function fourSumCount(
A: number[],
B: number[],
C: number[],
D: number[]
): number {
let res = 0;
const ABHash: { [key: string]: number } = {};
for (let i = 0; i < A.length; i++) {
for (let j = 0; j < B.length; j++) {
const AB = A[i] + B[j];
AB in ABHash ? ABHash[AB]++ : (ABHash[AB] = 1);
}
}
for (let i = 0; i < C.length; i++) {
for (let j = 0; j < D.length; j++) {
const CD = -(C[i] + D[j]);
if (CD in ABHash) {
res += ABHash[-CD];
}
}
}
return res;
}
|
7b65847a9b0ed1cbc6accc8a6c53d10661484c32
|
TypeScript
|
velizarvel/phonebook-angular-app
|
/src/app/contact.ts
| 2.71875
| 3
|
export class Contact {
contactId: number;
firstName: string;
lastName: string;
phone: string;
constructor(contactId: number, firstName: string, lastName: string, phone: string) {
this.contactId = contactId;
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
}
|
532e483695fec731eef7a3dc6f47f3f9a07f4941
|
TypeScript
|
MrRefactoring/jira.js
|
/src/version3/models/avatar.ts
| 3.078125
| 3
|
/** Details of an avatar. */
export interface Avatar {
/** The ID of the avatar. */
id: string;
/**
* The owner of the avatar. For a system avatar the owner is null (and nothing is returned). For non-system avatars
* this is the appropriate identifier, such as the ID for a project or the account ID for a user.
*/
owner?: string;
/** Whether the avatar is a system avatar. */
isSystemAvatar?: boolean;
/** Whether the avatar is used in Jira. For example, shown as a project's avatar. */
isSelected?: boolean;
/** Whether the avatar can be deleted. */
isDeletable?: boolean;
/** The file name of the avatar icon. Returned for system avatars. */
fileName?: string;
/** The list of avatar icon URLs. */
urls?: {};
}
|
cde59effd1fd6fed53919765407b42ec556ed3f4
|
TypeScript
|
adicomdotir/Just-Js
|
/TypeScript/transfer-system.ts
| 2.53125
| 3
|
export class Engine {
private teams: Array<Team> = [];
private players: Array<Player> = [];
private retiredPlayers: Array<Player> = [];
private sellList: Array<Player> = [];
public year: number;
constructor() {
this.year = 2000;
for (let i = 0; i < 8; i++) {
const tmpTm = new Team(IdGenerator.getId(), TeamNames[i]);
for (let j = 0; j < 11; j++) {
const age = Math.floor(Math.random() * 17) + 18;
const tmpPl = new Player(IdGenerator.getId(), NameGenerator.getFullName(), tmpTm.id, this.year - age, this.year);
this.players.push(tmpPl);
}
this.teams.push(tmpTm);
}
}
public aging() {
this.year += 1;
this.removeRetiredPlayer();
this.addHistory();
this.addPrize();
this.transfer();
}
private removeRetiredPlayer() {
const removeIndex = [];
this.players.forEach((x, index) => {
if (this.year - x.birth > 37) {
this.retiredPlayers.push(x);
removeIndex.push(index);
}
});
console.log(removeIndex.length, this.players.length);
let indexOffset = 0;
removeIndex.forEach(x => {
this.players.splice(x - indexOffset, 1);
indexOffset += 1;
});
console.log(removeIndex.length, this.players.length);
console.table(this.retiredPlayers);
}
private addPrize() {
this.teams.forEach(x => {
this.players.filter(y => y.teamId === x.id).forEach(z => {
x.price -= Math.floor(z.price / 20);
});
x.price += 50000;
});
}
private addHistory() {
this.players.forEach(x => {
x.histories.push(new PlayerHistory(this.year, x.teamId));
});
}
private transfer() {
const log = [];
// Add young player per team
for (let i = 0; i < this.teams.length; i++) {
const tmpId = (this.players.length + 1);
const newPlayer = new Player(IdGenerator.getId(), NameGenerator.getFullName(), '', this.year - 18, this.year);
this.players.push(newPlayer);
}
for (let i = 0; i < this.teams.length; i++) {
const tmpPlayers = this.players.filter(x => x.teamId === this.teams[i].id);
if (tmpPlayers.length > 0) {
const cntSellPlayerRnd = Math.floor(Math.random() * 3) + 1;
for (let j = 0; j < cntSellPlayerRnd; j++) {
const index = Math.floor(Math.random() * tmpPlayers.length);
if (this.sellList.findIndex(x => x.id === tmpPlayers[index].id) === -1) {
this.sellList.push(tmpPlayers[index]);
tmpPlayers[index].calculatePrice(this.year);
}
}
}
}
this.sellList.push(...this.players.filter(x => x.teamId === ''));
console.log('Transfer Market Size = ' + this.sellList.length);
let tryCounter = 0;
while (this.sellList.length > 0) {
const tmIndex = Math.floor(Math.random() * this.teams.length);
const plIndex = Math.floor(Math.random() * this.sellList.length);
const newTeam = this.teams[tmIndex];
const oldTeam = this.teams.filter(x => x.id === this.sellList[plIndex].teamId)[0];
if (newTeam.id !== this.sellList[plIndex].teamId && newTeam.price >= newTeam.transferManager * 50000) {
const oldTeamName = oldTeam != null ? oldTeam.name : 'Free';
log.push(`${this.sellList[plIndex].fullName} MOVE From ${oldTeamName} To ${newTeam.name}`);
newTeam.price -= this.sellList[plIndex].price;
if (oldTeam != null) {
oldTeam.price += this.sellList[plIndex].price;
}
this.sellList[plIndex].teamId = newTeam.id;
this.sellList[plIndex].histories[this.sellList[plIndex].histories.length - 1].teamId = newTeam.id;
this.sellList.splice(plIndex, 1);
tryCounter = 0;
}
tryCounter += 1;
if (tryCounter > 10) {
this.sellList = [];
}
}
console.table(log);
console.table(this.teams);
console.table(this.players);
}
}
export class Team {
id: string;
name: string;
price: number;
transferManager: number;
constructor(id: string, name: string) {
this.id = id;
this.name = name;
this.price = 0;
this.transferManager = Math.floor(Math.random() * 5);
}
}
export class Player {
id: string;
fullName: string;
birth: number;
attributesName: string[] = [
'dribbling',
'finishing',
'heading',
'passing',
'tackling',
'aggression',
'bravery',
'creativity',
'jumping',
'pace',
'stamina',
];
attributes: number[] = [];
overall: number;
teamId: string;
price: number;
histories: Array<PlayerHistory> = [];
constructor(id: string, name: string, teamId: string, birth: number, year: number) {
this.id = id;
this.fullName = name;
this.birth = birth;
this.teamId = teamId;
this.overall = 0;
this.attributesName.forEach(x => {
const value = Math.random() * 90;
this.overall += value;
this.attributes.push(value);
});
this.overall = Math.round(this.overall / this.attributesName.length);
this.calculatePrice(year);
this.histories.push(new PlayerHistory(year, teamId));
}
calculatePrice(year) {
this.price = Math.round((this.overall * 1000) * (29 / Math.abs(this.birth - year)));
}
}
export class PlayerHistory {
year: number;
teamId: string;
constructor(year: number, teamId: string) {
this.year = year;
this.teamId = teamId;
}
}
class NameGenerator {
static FIRSTNAME = [
'Abbas',
'Akbar',
'Ali',
'AliReza',
'Amin',
'AmirReza',
'Anooshirvan',
'Arash',
'Arman',
'Arsalan',
'Bagher',
'Bahram',
'Behnam',
'Behrad',
'Behrouz',
'Benyamin',
'Bijan',
'Ebrahim',
'Erfan',
'Esfandiyar',
'Esmaeel',
'Faramarz',
'Fariborz',
'Farid',
'Farrokh',
'Farzad',
'Fazel',
'Ferdous',
'Firooz',
'Habib',
'Hadi',
'Hamed',
'Hesam',
'Heydar',
'Homayoun',
'Hooman',
'Houshang',
'Jahangir',
'Kambiz',
'Kamran',
'Kannan',
'Kazem',
'Keyhan',
'Keykavous',
'Khashayar',
'Kioumars',
'Mahdi',
'Mahyar',
'Majid',
'Mamad',
'Mani',
'Manouchehr',
'Mehdi',
'Mehran',
'Moein',
'MohammadReza',
'Mojtaba',
'Morteza',
'Mostafa',
'Nima',
'Nouzar',
'Parsa',
'Payam',
'Pejman',
'Peyman',
'Pouya',
'Rasoul',
'Rostam',
'Sadeq',
'Saeed',
'Saman',
'Sasan',
'Sepand',
'Shadmehr',
'Siavash',
'Taghi',
'Vahid'
];
static LASTNAME = [
'Abbasi',
'Afshani',
'Afshar',
'Ahangar',
'Ahmadi',
'Almasi',
'Amini',
'Askari',
'Atlasi',
'Bahadori',
'Barbarz',
'Behdad',
'Bina',
'Blourian',
'Danesh',
'Dara',
'Dehghan',
'Entezami',
'Eskandari',
'Faghih',
'Foroutan',
'Freydooni',
'Ghaffari',
'Golzar',
'Haghighi',
'Haghjoo',
'Haghshenas',
'Hajar',
'Hashemi',
'Hedayati',
'Kashkouli',
'Kaviani',
'Keramati',
'Khaledi',
'Kianian',
'Layegh',
'Lorestani',
'Mahmoodi',
'Manesh',
'Mashayekhi',
'Mehrjoo',
'Miri',
'Mirzaii',
'Moghadam',
'Momeni',
'Moshiri',
'Mostofi',
'Mozafari',
'Najafi',
'Nassirian',
'Nassour',
'Nazeri',
'Nemati',
'Nouzari',
'Pahlevan',
'Pasdar',
'Poozesh',
'Qaderi',
'Qasemi',
'Radish',
'Raeisi',
'Razavian',
'Riahi',
'Rouhani',
'Sadiq',
'Saharkhiz',
'Salehi',
'Sayyadi',
'Shokoohi',
'Soleymani',
'Tabatabaii',
'Tajik',
'Tarokh',
'Tavakoli',
'Teymoori',
'Vossoughi',
'Zareii',
'Zarqan'
];
static getFullName() {
return this.getFirstName() + ' ' + this.getLastName();
}
static getFirstName() {
const rnd = Math.floor(Math.random() * this.FIRSTNAME.length);
return this.FIRSTNAME[rnd];
}
static getLastName() {
const rnd = Math.floor(Math.random() * this.LASTNAME.length);
return this.LASTNAME[rnd];
}
}
class IdGenerator {
private static lowerAlphabet = 'abcdefghijklmnopqrstuvwxyz';
private static upperAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
private static numbers = '0123456789';
static getId() {
const allLetters = this.lowerAlphabet + this.upperAlphabet + this.numbers;
let id = '';
for (let i = 0; i < 8; i++) {
const index = Math.floor(Math.random() * allLetters.length);
id += allLetters[index];
}
return id;
}
}
const TeamNames = [
'Esteghlal',
'Persepolis',
'Sepahan',
'Zob Ahan',
'Foolad',
'Saipa',
'Tractor',
'Saba Qom',
'Paykan',
'Malavan',
'Fajr Sepasi',
'Rah Ahan',
'Naft Tehran',
'Mes Kerman',
'Aboomoslem',
'Sanat Naft',
'Esteghlal Ahvaz',
'PAS Tehran',
'Bargh Shiraz',
'Damash',
'Shahr Khodro',
'Esteghlal Khuzestan',
'Gostaresh Foulad',
'PAS Hamedan',
'Shahin Bushehr',
'Pars Jonoubi Jam',
'Naft Masjed Soleyman',
'Steel Azin11',
'Machine Sazi',
'Nassaji Mazandaran',
'Shamoushak Noshahr',
'Siah Jamegan',
'Shahrdari Tabriz',
'Sepidrood',
'Aluminium Hormozgan',
'Payam',
'Gol Gohar Sirjan',
'Mes Sarcheshmeh',
'Rahian Kermanshah',
'Tarbiat Yazd',
'Gahar Zagros',
'Mes Rafsanjan',
'Aluminium Arak'
];
|
78c47e18bbfff2bde097936166c4d12d3a022dc3
|
TypeScript
|
knovoselic/qapass
|
/src/tests/unit/abstractions/Request.test.ts
| 2.609375
| 3
|
import loginRequest from '../../../requests/LoginRequest';
import { Request, Response, NextFunction } from 'express';
import { IncomingHttpHeaders } from 'http';
import Exception from '../../../errors/Exception';
describe('Request.validate', () => {
describe("collects rules with Request.rules, maps errors with Request.map and", () => {
it("calls Request.fail if there are validation errors", async () => {
const request = loginRequest as any;
const failSpy = jest.spyOn(request, 'fail');
failSpy.mockImplementation((...args) => {
return 'failed';
});
const req = {
body: {}
} as Request;
const res = {} as Response;
const next = jest.fn() as NextFunction;
await loginRequest.validate(req, res, next);
expect(next).not.toHaveBeenCalled();
expect(failSpy).toHaveBeenCalledTimes(1);
expect(failSpy).toHaveBeenCalledWith(expect.anything(), req, res, next);
});
it("calls next if there no validation errors", async () => {
const request = loginRequest as any;
const mapErrorsSpy = jest.spyOn(request, 'mapErrors');
mapErrorsSpy.mockImplementation((...args) => {
return {};
});
const req = {
body: {}
} as Request;
const res = {} as Response;
const next = jest.fn() as NextFunction;
await loginRequest.validate(req, res, next);
expect(next).toHaveBeenCalledTimes(1);
});
it("calls next if there is internal error", async () => {
const request = loginRequest as any;
const mapErrorsSpy = jest.spyOn(request, 'mapErrors');
mapErrorsSpy.mockImplementation((...args) => {
return {};
});
const req = {
} as Request;
const res = {} as Response;
const next = jest.fn() as NextFunction;
await loginRequest.validate(req, res, next);
expect(next).toHaveBeenCalledTimes(2);
expect(next).toHaveBeenCalledWith(expect.anything());
});
});
});
describe('Request.getMessages', () => {
describe("when called with identifier that exists in dictionary", () => {
it("returns the value in dictionary", () => {
const request = loginRequest as any;
expect(request.getMessage('required')).toBe('Value is required.');
});
});
describe("when called with identifier that does not exist in dictionary", () => {
it("returns with default message", () => {
const request = loginRequest as any;
expect(request.getMessage('any')).toBe('Invalid value.');
});
});
});
describe('Request.fail', () => {
describe("when xhr request and/or 'accept: application/json' header present", () => {
it("calls next function", () => {
const request = loginRequest as any;
const req = {
xhr: true,
headers: {
accept: 'application/json'
} as IncomingHttpHeaders
} as Request;
const res = {} as Response;
const next = jest.fn() as NextFunction;
const errors = {
email: [
'error'
]
};
request.fail(errors, req, res, next);
expect(next).toHaveBeenCalledTimes(1);
expect(next).toHaveBeenLastCalledWith(new Exception('Invalid request payload.', 422, errors));
});
});
describe("when not xhr request and 'accept: application/json' header is not present", () => {
it("sets errors to flash bag and redirect to referer or root site", () => {
const request = loginRequest as any;
const flash = jest.fn();
let header = jest.fn(() => '/login');
let req = {
flash: flash as Function,
header: header as Function,
xhr: false,
headers: {
} as IncomingHttpHeaders
} as Request;
const redirect = jest.fn();
const res = {
redirect: redirect as Function
} as Response;
const next = jest.fn() as NextFunction;
const errors = {
email: [
'error'
]
};
request.fail(errors, req, res, next);
expect(flash).toHaveBeenCalledTimes(1);
expect(flash).toHaveBeenLastCalledWith('validation-errors', errors);
expect(header).toHaveBeenCalledTimes(1);
expect(header).toHaveBeenLastCalledWith('Referer');
expect(redirect).toHaveBeenCalledTimes(1);
expect(redirect).toHaveBeenLastCalledWith('/login');
header = jest.fn(() => '');
req = {
flash: flash as Function,
header: header as Function,
xhr: false,
headers: {
} as IncomingHttpHeaders
} as Request;
request.fail(errors, req, res, next);
expect(flash).toHaveBeenCalledTimes(2);
expect(flash).toHaveBeenLastCalledWith('validation-errors', errors);
expect(header).toHaveBeenCalledTimes(1);
expect(header).toHaveBeenLastCalledWith('Referer');
expect(redirect).toHaveBeenCalledTimes(2);
expect(redirect).toHaveBeenLastCalledWith('/');
});
});
});
describe('Request.valueSet', () => {
describe("when value is undefined/null/false/''", () => {
it("returns false", () => {
const request = loginRequest as any;
expect(request.valueSet(undefined)).toBe(false);
expect(request.valueSet(null)).toBe(false);
expect(request.valueSet(false)).toBe(false);
expect(request.valueSet('')).toBe(false);
});
});
describe("when value is not undefined/null/false/''", () => {
it("returns true", () => {
const request = loginRequest as any;
expect(request.valueSet({})).toBe(true);
expect(request.valueSet(true)).toBe(true);
expect(request.valueSet([])).toBe(true);
expect(request.valueSet('asdsadsad')).toBe(true);
expect(request.valueSet(1)).toBe(true);
});
});
});
describe('Request.parseRule', () => {
describe("when rule string doesn't contain ':' characters", () => {
it("returns object without defined data property", () => {
const request = loginRequest as any;
expect(request.parseRule('test')).toMatchObject({
rule: 'test',
data: undefined
});
});
});
describe("when rule string contains ':' characters", () => {
it("returns object with defined data property", () => {
const request = loginRequest as any;
expect(request.parseRule('test:param')).toMatchObject({
rule: 'test',
data: 'param'
});
expect(request.parseRule('test:param:param')).toMatchObject({
rule: 'test',
data: 'param:param'
});
});
});
});
describe('Request.mapErrors', () => {
it("adds field errors to errors object", () => {
const request = loginRequest as any;
const errors = {
password: {
required: 'required',
string: 'string',
},
email: {}
};
const field_errors = {
email: {
required: 'required',
string: 'string',
}
}
request.mapErrors(errors, field_errors);
expect(errors).toMatchObject({
password: {
required: 'required',
string: 'string',
},
email: {
required: 'required',
string: 'string',
}
})
});
});
|
6a9344bf93c0a692e58f12c5347ceee9ba49e73a
|
TypeScript
|
winzter143/angularTraining
|
/src/app/user-form/user-form.component.ts
| 2.625
| 3
|
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.css']
})
export class UserFormComponent implements OnInit {
@Input() userDetails: any; // User Handle for user form
// Oser data hold to send form data to home
//@Output formValueEmitter = new EventEmitter();
postForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
console.log(this.userDetails);
// Assign the value to form
this.postForm.patchValue(this.userDetails);
}
initializeForm(){
this.postForm = this.formBuilder.group({
// Init the form data here
name: [""],
age: [99]
});
}
submit(){
console.log(this.postForm.value);
// get Specific value which "age"
console.log(this.postForm.controls['age'].value);
}
// Lister to form changes
listenToPostForm(){
this.postForm.valueChanges.subscribe((formValue) => {
console.log(formValue);
});
}
}
|
25573eab51676433371ff341fe212889ea45061a
|
TypeScript
|
ksxnodemodules/nodemonorepo
|
/packages/typescript/random-org-http/lib/types.ts
| 2.9375
| 3
|
// tslint:disable:variable-name
export interface QueryObject<Value> {
readonly [key: string]: Value
}
export enum Generator {
integers = 'integers',
sequences = 'sequences',
strings = 'strings'
}
export enum Base {
binary = 2,
octal = 8,
hexadecimal = 16,
decimal = 10
}
export enum Format {
html = 'html',
plain = 'plain'
}
export enum Activation {
on = 'on',
off = 'off'
}
enum NumBound {
min = 1,
max = 1000
}
enum EndBound {
min = -1e9,
max = 1e9
}
enum ColBound {
min = 1,
max = 1e9
}
enum LenBound {
min = 1,
max = 20
}
const __WORKAROUND__ = `
Don't mind this string,
this is to workaround typescript namespace import bug.
`
export namespace ranges {
export namespace integers {
export const num = NumBound
export const min = EndBound
export const max = EndBound
export const col = ColBound
export const base = Base
export const format = Format
export const __workaround = __WORKAROUND__
}
export namespace sequences {
export const min = EndBound
export const max = EndBound
export const col = ColBound
export const format = Format
export const __workaround = __WORKAROUND__
}
export namespace strings {
export const num = NumBound
export const len = LenBound
export const digits = Activation
export const upperalpha = Activation
export const loweralpha = Activation
export const unique = Activation
export const format = Format
export const __workaround = __WORKAROUND__
}
export const __workaround = __WORKAROUND__
}
export namespace structured {
export type Param =
Param.Integer |
Param.Sequence |
Param.String
export namespace Param {
export interface Integer {
readonly num: number
readonly min: number
readonly max: number
}
export interface Sequence {
readonly min: number
readonly max: number
}
export type String = utils.StringParam<true, false>
export const __workaround = __WORKAROUND__
}
export const __workaround = __WORKAROUND__
}
export namespace raw {
export type Param =
Param.Integer |
Param.Sequence |
Param.String
export namespace Param {
export type Integer = structured.Param.Integer & {
readonly col: number,
readonly base: Base,
readonly format: Format
}
export type Sequence = structured.Param.Sequence & {
readonly col: number,
readonly format: Format
}
export type String = utils.StringParam<Activation.on, Activation.off> & {
readonly format: Format
}
export const __workaround = __WORKAROUND__
}
export const __workaround = __WORKAROUND__
}
export namespace utils {
export type StringParam<On, Off> =
StringParam.DigitsRequired<On, Off> |
StringParam.LowerAlphaRequired<On, Off> |
StringParam.UpperAlphaRequired<On, Off>
export namespace StringParam {
export interface Common<Binary> {
readonly num: number
readonly len: number
readonly unique?: Binary
readonly digits?: Binary
readonly upperalpha?: Binary
readonly loweralpha?: Binary
}
export interface DigitsRequired<On, Off> extends Common<On | Off> {
digits: On
}
export interface UpperAlphaRequired<On, Off> extends Common<On | Off> {
upperalpha: On
}
export interface LowerAlphaRequired<On, Off> extends Common<On | Off> {
loweralpha: On
}
export const __workaround = __WORKAROUND__
}
export const __workaround = __WORKAROUND__
}
|
06dd605fbf16b82a431b1a4a9067f012b023ce86
|
TypeScript
|
anuragarwalkar/chat-buddy-backend
|
/src/middleware/logger.ts
| 2.90625
| 3
|
import { Request, Response, NextFunction } from 'express';
interface CustomError extends Error {
statusCode: number;
}
const logger = (err: CustomError, req: Request, res: Response, next: NextFunction) => {
const error = {...err};
error['message'] = err.message;
const statusCode = error.statusCode || 500;
const errorMessage = error.message || 'Server Error';
res.status(statusCode).json({
success:false,
error:errorMessage
})
}
export default logger;
|
91763ef7ea34e0a5356270c4ee4006475960cc5e
|
TypeScript
|
streamr-dev/streamr-client-protocol-js
|
/src/errors/UnsupportedVersionError.ts
| 2.734375
| 3
|
export default class UnsupportedVersionError extends Error {
version: number
constructor(version: number, message: string) {
super(`Unsupported version: ${version}, message: ${message}`)
this.version = version
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor)
}
}
}
|
b00040aa889302759e611bf2e88799ae70608517
|
TypeScript
|
qianyc1020/OneStroke-egret
|
/src/UI.ts
| 2.546875
| 3
|
class UI {
private static _instance: UI;
private _stageWidth: number;
private _stageHeight: number;
public createPanel(panelName: string): fairygui.GComponent {
const p: fairygui.GComponent = fairygui.UIPackage.createObject("Package1", panelName).asCom;
p.viewWidth = this._stageWidth;
p.viewHeight = this._stageHeight;
return p;
}
public set stageWidth(val: number) {
this._stageWidth = val;
}
public set stageHeight(val: number) {
this._stageHeight = val;
}
public static get instance() {
if (!UI._instance) {
UI._instance = new UI();
}
return UI._instance;
}
}
|
2331bba3ec065389dbeb48d4f227600d5c23e44f
|
TypeScript
|
cjr3/rdmgr
|
/src/tools/raffle/index.ts
| 2.8125
| 3
|
import { RaffleTicket, SMainController, SRaffle } from "tools/vars";
/**
* Add a raffle ticket
* @param state
* @param ticket
* @returns
*/
export const Add = (state:SMainController, ticket:RaffleTicket) : SMainController => {
const tickets = (state.Raffle.CurrentTickets || []).slice();
const records = (state.Raffle.Tickets || []).slice();
//keep it simple - we only need three tickets
if(tickets.length >= 3) {
tickets.shift();
}
tickets.push({...ticket});
records.push({...ticket});
if(records.length > 100) {
records.shift();
}
return {
...state,
Raffle:{
...state.Raffle,
CurrentTickets:tickets,
Tickets:records
},
UpdateTimeRaffle:Date.now()
}
};
/**
* Remove a raffle ticket
* @param state
* @param index
* @returns
*/
export const Remove = (state:SMainController, index:number = -1) : SMainController => {
if(index === -1)
index = (state.Raffle.CurrentTickets || []).length - 1;
if(index >= 0 && state.Raffle.CurrentTickets && state.Raffle.CurrentTickets[index]) {
const tickets = state.Raffle.CurrentTickets.slice();
tickets.splice(index, 1);
return {
...state,
Raffle:{
...state.Raffle,
CurrentTickets:tickets
},
UpdateTimeRaffle:Date.now()
};
}
return state;
}
/**
* Set all raffle ticket history records, and clear current tickets.
* @param state
* @param tickets
* @returns
*/
export const SetRecords = (state:SMainController, tickets:RaffleTicket[]) : SMainController => {
return {
...state,
Raffle:{
...state.Raffle,
Tickets:tickets,
CurrentTickets:[]
},
UpdateTimeRaffle:Date.now()
}
};
export const Update = (state:SMainController, values:SRaffle) : SMainController => {
return {
...state,
Raffle:{
...state.Raffle,
...values
},
UpdateTimeRaffle:Date.now()
};
}
|
94c1b5c4f46824327806a830f6a378203e17ac7f
|
TypeScript
|
tengyifei/forklift.js
|
/src/test/test-partition.ts
| 2.796875
| 3
|
/// <reference path="../../typings/globals/mocha/index.d.ts" />
/// <reference path="../../typings/globals/chai/index.d.ts" />
import { partitionDataset } from '../partition-dataset';
import * as rimraf from 'rimraf';
import * as mkdirp from 'mkdirp';
import * as Bluebird from 'bluebird';
import * as chai from 'chai';
import * as fs from 'fs';
import * as Stream from 'stream';
const streamToPromise: (x: Stream.Readable) => Promise<Buffer> = require('stream-to-promise');
const expect = chai.expect;
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var len = 3 + Math.random() * 20;
for (var i = 0; i < len; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
describe('Partition dataset', function () {
const testFolder = 'dist/test-partition';
this.timeout(10000000);
let allLines: string[] = [];
before(async () => {
// teardown test dataset
await Bluebird.promisify(rimraf)(testFolder);
await Bluebird.promisify(mkdirp)(testFolder);
// create some data
for (let i = 100; i < 150; i++) {
let words = [];
let line = [];
let allLinesFile = [];
for (let j = 0; j < 100000; j++) {
let randomWord = makeid();
words.push(randomWord);
line.push(randomWord);
if (Math.random() < 0.09) {
words.push('\n');
let joinLine = line.join(' ');
if (joinLine !== '') {
allLines.push(joinLine);
allLinesFile.push(joinLine);
}
line = [];
}
}
await (<(x: string, y: string) => Promise<void>> <any> Bluebird.promisify(fs.writeFile))
(`${testFolder}/${i}`, allLinesFile.join('\n'));
allLinesFile = [];
}
});
async function verifyPartition(streams: Stream.Readable[]) {
let allDataArr = await Bluebird.all(streams.map(streamToPromise));
let allData = Buffer.concat(allDataArr);
let myLines = allData.toString().split('\n').filter(x => x !== '');
expect(myLines.length).to.equal(allLines.length);
myLines.forEach((line, idx) => expect(line).to.equal(allLines[idx]));
}
it('partitions correctly (one)', function () {
return verifyPartition(partitionDataset(testFolder, 1));
});
it('partitions correctly (two)', function () {
return verifyPartition(partitionDataset(testFolder, 2));
});
it('partitions correctly (ten)', function () {
return verifyPartition(partitionDataset(testFolder, 10));
});
it('partitions correctly (many)', function () {
return verifyPartition(partitionDataset(testFolder, 300));
});
it('partitions correctly (too many)', function () {
return verifyPartition(partitionDataset(testFolder, 30000));
});
});
|
ae1ec5711ec896900bf498ff4fa666de7e074113
|
TypeScript
|
mlaursen/react-md
|
/packages/form/src/select/__tests__/utils.ts
| 3.015625
| 3
|
import { createElement } from "react";
import { getDisplayLabel, getOptionId, getOptionLabel } from "../utils";
describe("getOptionId", () => {
it("should return the correct id starting from 1 instead of 0", () => {
expect(getOptionId("base-id", 0)).toBe("base-id-option-1");
expect(getOptionId("base-id-1", 0)).toBe("base-id-1-option-1");
expect(getOptionId("base-id-2", 2)).toBe("base-id-2-option-3");
expect(getOptionId("listbox-1", 199)).toBe("listbox-1-option-200");
});
});
describe("getOptionLabel", () => {
it("should return the option itself if it is not an object", () => {
expect(getOptionLabel(null, "label")).toBe(null);
expect(getOptionLabel("", "label")).toBe("");
expect(getOptionLabel("Label", "label")).toBe("Label");
expect(getOptionLabel(0, "label")).toBe(0);
expect(getOptionLabel(100, "label")).toBe(100);
});
it("should return the labelKey if it exists and fallback to the children argument if it is an object", () => {
const option1 = { label: "Label", value: "A" };
const option2 = { label: 0, value: "0" };
expect(getOptionLabel(option1, "label")).toBe("Label");
expect(getOptionLabel(option2, "label")).toBe(0);
expect(getOptionLabel(option1, "value")).toBe("A");
expect(getOptionLabel(option2, "value")).toBe("0");
const children = createElement("span", null, "Hello");
expect(getOptionLabel({ children, value: "A" }, "label")).toBe(children);
expect(getOptionLabel({ value: "A" }, "label")).toBe(null);
});
});
describe("getDisplayLabel", () => {
it("should return null if there is no option", () => {
expect(getDisplayLabel(null, "label", true)).toBe(null);
expect(getDisplayLabel(null, "label", false)).toBe(null);
expect(getDisplayLabel("", "label", true)).toBe(null);
expect(getDisplayLabel("", "label", false)).toBe(null);
});
it("should return the label if the includeLeft option is false or the option is not an object", () => {
expect(getDisplayLabel(0, "label", true)).toBe(0);
expect(getDisplayLabel(0, "label", false)).toBe(0);
expect(getDisplayLabel("0", "label", true)).toBe("0");
expect(getDisplayLabel("0", "label", false)).toBe("0");
expect(getDisplayLabel("Hello", "label", true)).toBe("Hello");
expect(getDisplayLabel("Hello", "label", false)).toBe("Hello");
});
it("should return the TextIconSpacing component when includeLeft is enabled and the option is an prop object", () => {
const option = {
leftAddon: "Addon",
label: "Some Words",
};
const display1 = getDisplayLabel(option, "label", true);
expect(display1).toMatchInlineSnapshot(`
<TextIconSpacing
icon="Addon"
>
Some Words
</TextIconSpacing>
`);
const option2 = {
leftAddon: createElement("span"),
label: "Some Words",
};
const display2 = getDisplayLabel(option2, "label", true);
expect(display2).toMatchInlineSnapshot(
`
<TextIconSpacing
icon={<span />}
>
Some Words
</TextIconSpacing>
`
);
});
});
|
0e0c5fc498dea69d521a3c4f6266972732d512ed
|
TypeScript
|
avington/avitrackr-client
|
/src/app/feature-my-tasks/store/reducers/update-status-task.reducers.ts
| 2.859375
| 3
|
import { MyTask } from '../../models/my-tasks';
import * as fromActions from '../actions/update-status-task.actions';
export interface UpdateTaskStatusState {
entity: MyTask;
loading: boolean;
loaded: boolean;
error?: any;
}
const initialState: UpdateTaskStatusState = {
entity: null,
loading: false,
loaded: false
};
export function updateTaskStatusReducer(state = initialState, action: fromActions.UpdateTaskStatusActions): UpdateTaskStatusState {
switch (action.type) {
case fromActions.UpdateTaskStatusActionTypes.UpdateTaskStatus: {
return {
...state,
loading: true
};
}
case fromActions.UpdateTaskStatusActionTypes.UpdateTaskStatusSuccess: {
return {
...state,
loading: false,
loaded: true,
entity: action.payload
};
}
case fromActions.UpdateTaskStatusActionTypes.UpdateTaskStatusFailed: {
return {
...state,
loading: false,
loaded: false,
entity: action.payload
};
}
default: {
return state;
}
}
}
const getEntityStatusUpdated = (state: UpdateTaskStatusState) => state.entity;
const getEntityStatusUpdatedLoaded = (state: UpdateTaskStatusState) => state.loaded;
const getEntityStatusUpdatedLoading = (state: UpdateTaskStatusState) => state.loading;
const getEntityStatusUpdatedError = (state: UpdateTaskStatusState) => state.error;
|
56f6cecde307c2730e2195f9589cf1042e403394
|
TypeScript
|
pnp/sp-dev-fx-extensions
|
/samples/react-teamschatnotifications-functions/DataServices/AzureStorageTableService.ts
| 2.90625
| 3
|
import * as request from 'request-promise';
import { IReturnEntity } from './IReturnEntity';
import { IEntity } from './IEntity';
class DataService {
constructor(private table_name: string, private azure_storage_uri: string, private azure_storage_sas: string) {}
/**
* Create Table
*
* @returns {Promise<string>}
* @memberof DataService
*/
public async createTableIfNotExists(): Promise<string> {
try {
const tableExists: boolean = await this.checkIfTableExists();
if (tableExists) {
return this.table_name;
} else {
const URI: string = `${this.azure_storage_uri}/tables?${this.azure_storage_sas}`;
let options = {
method: 'POST',
uri: URI,
headers: {
'Content-Type': 'application/json;odata=nometadata'
},
body: {
TableName: this.table_name
},
json: true,
resolveWithFullResponse: true
};
const results = await request(options);
const tablesResult = JSON.parse(results);
return tablesResult.table_name;
}
} catch (error) {
throw new Error(error);
}
}
/**
* Check if Table Exists
*
* @returns {Promise<boolean>}
* @memberof DataService
*/
public async checkIfTableExists(): Promise<boolean> {
try {
const URI: string = `${this.azure_storage_uri}/tables?$filter=TableName eq '${this.table_name}'&${this.azure_storage_sas}`;
let options = {
method: 'GET',
uri: URI,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
}
};
const results = await request(options);
const tablesResult = JSON.parse(results);
return (tablesResult.value && tablesResult.value.length) > 0 ? true : false;
} catch (error) {
throw new Error(error);
}
}
/**
* Insert Entity
*
* @param {IEntity} entity
* @returns {Promise<IReturnEntity>}
* @memberof DataService
*/
public async insertEntity(entity: IEntity): Promise<IReturnEntity> {
try {
await this.createTableIfNotExists();
const URI: string = `${this.azure_storage_uri}/${this.table_name}?${this.azure_storage_sas}`;
let options = {
method: 'POST',
uri: URI,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: {
PartitionKey: entity.PartitionKey,
RowKey: entity.RowKey,
SubscriptionId: entity.SubscriptionId,
ExpirationDateTime: entity.ExpirationDateTime
},
json: true,
resolveWithFullResponse: true
};
const results = await request(options);
const entityAddedResult: IReturnEntity = JSON.parse(results);
return entityAddedResult;
} catch (error) {
throw new Error(error);
}
}
/**
* Insert or Upadate Entity
*
* @param {IEntity} entity
* @returns {Promise<void>}
* @memberof DataService
*/
public async insertOrUpdateEntity(entity: IEntity): Promise<void> {
try {
await this.createTableIfNotExists();
const URI: string = `${this.azure_storage_uri}/${this.table_name}(PartitionKey='${entity.PartitionKey}', RowKey='${entity.RowKey}')?${this.azure_storage_sas}`;
let options = {
method: 'PUT',
uri: URI,
headers: {
'Content-Type': 'Application/json',
Accept: 'Aplication/json'
},
body: {
PartitionKey: entity.PartitionKey,
RowKey: entity.RowKey,
SubscriptionId: entity.SubscriptionId,
ExpirationDateTime: entity.ExpirationDateTime
},
json: true,
resolveWithFullResponse: true
};
const results = await request(options);
} catch (error) {
throw new Error(error);
}
}
/**
* Update Entity
*
* @param {IEntity} entity
* @returns {Promise<void>}
* @memberof DataService
*/
public async updateEntity(entity: IEntity): Promise<void> {
try {
await this.createTableIfNotExists();
const URI: string = `${this.azure_storage_uri}/${this.table_name}(PartitionKey='${entity.PartitionKey}', RowKey='${entity.RowKey}')?${this.azure_storage_sas}`;
let options = {
method: 'PUT',
uri: URI,
headers: {
'Content-Type': 'Application/json',
Accept: 'Application/json',
'if-match': '*'
},
body: {
PartitionKey: entity.PartitionKey,
RowKey: entity.RowKey,
SubscriptionId: entity.SubscriptionId,
ExpirationDateTime: entity.ExpirationDateTime
},
json: true,
resolveWithFullResponse: true
};
const results = await request(options);
} catch (error) {
throw new Error(error);
}
}
/**
* Remove Entity
*
* @param {IEntity} entity
* @returns {Promise<void>}
* @memberof DataService
*/
public async removeEntity(entity: IEntity): Promise<void> {
try {
await this.createTableIfNotExists();
const URI: string = `${this.azure_storage_uri}/${this.table_name}(PartitionKey='${entity.PartitionKey}', RowKey='${entity.RowKey}')?${this.azure_storage_sas}`;
let options = {
method: 'DELETE',
uri: URI,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
}
};
const results = await request(options);
} catch (error) {
throw new Error(error);
}
}
/**
* Get Entity by Partition and rowKey
*
* @param {string} partitionKey
* @param {string} rowKey
* @returns {Promise<IReturnEntity>}
* @memberof DataService
*/
public async getEntity(partitionKey: string, rowKey: string): Promise<IReturnEntity> {
try {
await this.createTableIfNotExists();
const URI: string = `${this.azure_storage_uri}/${this.table_name}(PartitionKey='${partitionKey}', RowKey='${rowKey}')?${this.azure_storage_sas}`;
console.log('URI', URI);
let options = {
method: 'GET',
uri: URI,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
}
};
var results = await request(options);
var entityResult: IReturnEntity = JSON.parse(results);
return entityResult;
} catch (error) {
if (error.statusCode == 404){ // not found
return entityResult = undefined;
}
throw new Error(error);
}
}
/**
*
* Get Entities from Table base on Query
* accepts ODATA $filter and $select
* @param {string} query
* @returns {Promise<IReturnEntity[]>}
* @memberof DataService
*/
public async listEntities(query?: string): Promise<IReturnEntity[]> {
try {
let _query:string = '';
await this.createTableIfNotExists();
if (query){
_query=`&$filter=${query}`;
}
const URI: string = `${this.azure_storage_uri}/${this.table_name}()?${this.azure_storage_sas}${_query}`;
let options = {
method: 'GET',
uri: URI,
headers: {
'Content-Type': 'application/json;odata=nometadata',
Accept: 'application/json'
}
};
const results = JSON.parse(await request(options));
const entitiesListResults: IReturnEntity[] = results.value;
return entitiesListResults;
} catch (error) {
throw new Error(error);
}
}
}
export default DataService;
|
1ef60ab1a6225ddc1e7ac0293bec6fcbff4855ad
|
TypeScript
|
outbreak/webauthn-lib
|
/packages/server/test/utils/buffer-cake.test.ts
| 3.0625
| 3
|
import BufferCake from '../../src/utils/buffer-cake'
test('Must be class', () => {
const buffer = new BufferCake(Buffer.from('abcdef'))
expect(buffer).toBeInstanceOf(BufferCake)
})
test('Can be take and slice buffer', () => {
const buffer = new BufferCake(Buffer.from('abcde'))
expect(buffer.take(2)).toStrictEqual(Buffer.from('ab'))
expect(buffer.left()).toBe(3)
expect(buffer.get()).toStrictEqual(Buffer.from('cde'))
})
|
81daad2fff05d3d61a5e8ae67142291dcc15ce22
|
TypeScript
|
gforge/graphql-passport
|
/src/test/testServer/LaunchAPI.ts
| 2.96875
| 3
|
import { DataSource } from 'apollo-datasource';
export interface Launch {
id: number;
name: string;
}
export class LaunchAPI extends DataSource {
private launches: Launch[];
constructor() {
super();
this.launches = [
{ id: 1, name: 'rocket 1' },
{ id: 2, name: 'rocket 2' },
];
}
find(id: number) {
return this.launches.find((l) => l.id === id);
}
findName(name: string) {
return this.launches.find((l) => l.name === name);
}
add(name: string) {
const existingLaunch = this.findName(name);
if (existingLaunch) {
throw new Error(`The '${name}' already exists`);
}
const maxId = Math.max(...this.launches.map((l) => l.id));
const newLaunch: Launch = { id: maxId + 1, name };
this.launches.push(newLaunch);
return newLaunch;
}
}
|
64976b49c7ba896ea9faac940e95484cea5113ff
|
TypeScript
|
khattakdev/aqualink-app
|
/packages/website/src/helpers/numberUtils.ts
| 2.53125
| 3
|
import { isNumber } from "lodash";
export function formatNumber(n?: number | null, decimal = 0) {
return isNumber(n) ? n.toFixed(decimal) : "- -";
}
|
ecde31577f3f67d7d6d876b892425847be7bb673
|
TypeScript
|
abdelalielbahloul/gestin-association
|
/server/src/controllers/userController.ts
| 2.53125
| 3
|
import { Request, Response, NextFunction, response } from "express";
import mongoose from "mongoose";
import bcryptjs from "bcryptjs";
import { User } from '../models/User';
import JWT from "jsonwebtoken";
class UserController {
/**
* login an user users
*/
public async login(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const email = req.body.email;
await User.find({ email: email }).exec()
.then( user => {
if(user.length < 1){
res.json({
message: "Auth failed"
});
res.end();
return
}
bcryptjs.compare( req.body.password, user[0].password, (error, result) => {
if(error){
res.json({
message: "Auth failed"
});
res.end();
return
}
if(result){
const payLoad = {
email: user[0].email,
userId: user[0].password
}
const token = JWT.sign(payLoad, `${process.env.JWT_KEY}`, { expiresIn: "1H"});
return res.json({
message: "Auth success!",
token: token
})
}
})
})
.catch( er => {
console.log(er);
res.sendStatus(500);
res.end()
return
})
// res.json(userLoged);
} catch (e) {
console.log(e);
}
}
/**
* resgister of users
*/
public async register(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
await bcryptjs.hash(req.body.password, 10, (error, hash) => {
if (error){
console.log(error);
if(!req.body.password || !req.body.email || !req.body.firstName || !req.body.lastName){
res.json({
message: "An error has occured!"
});
res.end()
return
}
res.sendStatus(500);
res.end();
return
}
const user = new User({
_id: new mongoose.Types.ObjectId(),
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: hash,
created_at: new Date(),
updated_at: new Date()
});
user.save()
.then( result => {
// console.log(result);
res.json({
msg: "Register successful!"
})
// res.json({
// message: "Register successfully!"
// })
})
.catch( err => {
console.log(err);
res.json({
error: err
});
res.end()
return
})
})
} catch (e) {
console.log(e);
res.json(e);
res.end();
return
}
}
}
const userController = new UserController();
export default userController;
|
415f5908942785b7f9a8a4e10d15fc0c1ea64dac
|
TypeScript
|
superwower/wowgit
|
/server/domain/status.ts
| 3.234375
| 3
|
import File from "./file";
/**
* This class represents the status of a git repository
*/
export default class Status {
/**
* List of untracked files
*/
private _untracked: File[];
/**
* List of modified files
*/
private _modified: File[];
/**
* List of deleted files
*/
private _deleted: File[];
/**
* @param untracked Array of untracked file
* @param modified Array of modified file
* @param deleted Array of deleted file
*/
constructor(untracked: File[], modified: File[], deleted: File[]) {
this._untracked = untracked;
this._modified = modified;
this._deleted = deleted;
}
/**
* @return Array of untracked files
*/
get untracked(): File[] {
return this._untracked;
}
/**
* @return Array of modified files
*/
get modified(): File[] {
return this._modified;
}
/**
* @return Array of deleted files
*/
get deleted(): File[] {
return this._deleted;
}
}
|
2e79ff18d9f5f3aa2d86e9c25c87b955eecbbbe8
|
TypeScript
|
cure53/DefinitelyTyped
|
/types/inputmask/index.d.ts
| 2.84375
| 3
|
// Type definitions for inputmask 4.0
// Project: https://github.com/RobinHerbots/Inputmask
// Definitions by: Daniel Mester Pirttijarvi <https://github.com/dmester>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// The documentation is mainly copied from the source repo README.
declare namespace Inputmask {
type Range = { start: string, end: string } | [string, string];
type PositionCaretOnClick =
"none" | "lvp" | "radixFocus" | "select" | "ignore";
type InputMode =
"verbatim" | "none" | "text" | "decimal" | "numeric" | "tel" | "search" | "email" | "url";
type Casing = "upper" | "lower" | "title";
type DefinitionValidator = (chrs: string, buffer: string[], pos: number, strict: boolean, opts: Options) =>
boolean | { pos: number, c: string };
interface Options {
/**
* Change the mask placeholder. Instead of "_", you can change the unfilled characters mask as you like, simply
* by adding the placeholder option. For example, placeholder: " " will change the default autofill with empty
* values.
*
* @default "_"
*/
placeholder?: string;
/**
* Definition of the symbols used to indicate an optional part in the mask.
*
* @default { start: "[", end: "]" }
*/
optionalmarker?: Range;
/**
* Definition of the symbols used to indicate a quantifier in the mask.
*
* @default { start: "{", end: "}" }
*/
quantifiermarker?: Range;
/**
* Definition of the symbols used to indicate a group in the mask.
*
* @default { start: "(", end: ")" }
*/
groupmarker?: Range;
/**
* Definition of the symbols used to indicate an alternator part in the mask.
*
* @default "|"
*/
alternatormarker?: string;
/**
* Definition of the symbols used to escape a part in the mask.
*
* @default "\\"
*/
escapeChar?: string;
/**
* The mask to use.
*/
mask?: string | string[] | ((opts: Options) => string | string[]);
/**
* Use a regular expression as a mask. When using shorthands be aware that you need to double escape or use
* String.raw with a string literal.
*/
regex?: string;
/**
* Execute a function when the mask is completed.
*/
oncomplete?: () => void;
/**
* Execute a function when the mask is cleared.
*/
onincomplete?: () => void;
/**
* Execute a function when the mask is cleared.
*/
oncleared?: () => void;
/**
* Mask repeat function. Repeat the mask definition x-times.
* `*` ~ forever, otherwise specify an integer
*
* @default 0
*/
repeat?: number | string;
/**
* Toggle to allocate as much possible or the opposite. Non-greedy repeat function. With the non-greedy option
* set to `false`, you can specify `*` as repeat. This makes an endless repeat.
*
* @default false
*/
greedy?: boolean;
/**
* Automatically unmask the value when retrieved.
*
* When setting this option to true the plugin also expects the initial value from the server to be unmasked.
*
* @default false
*/
autoUnmask?: boolean;
/**
* Remove the mask before submitting the form.
*
* @default false
*/
removeMaskOnSubmit?: boolean;
/**
* Remove the empty mask on blur or when not empty removes the optional trailing part.
*
* @default true
*/
clearMaskOnLostFocus?: boolean;
/**
* Toggle to insert or overwrite input. This option can be altered by pressing the Insert key.
*
* @default true
*/
insertMode?: boolean;
/**
* Clear the incomplete input on blur.
*
* @default false
*/
clearIncomplete?: boolean;
/**
* The alias to use.
*
* @default null
*/
alias?: string;
/**
* Callback to implement autocomplete on certain keys for example.
*/
onKeyDown?: (event: KeyboardEvent, buffer: string[], caretPos: number, opts: Options) => void;
/**
* Executes before masking the initial value to allow preprocessing of the initial value.
*/
onBeforeMask?: (initialValue: string, opts: Options) => string;
/**
* This callback allows for preprocessing the pasted value before actually handling the value for masking.
* This can be useful for stripping away some characters before processing. You can also disable pasting
* a value by returning false in the `onBeforePaste` call.
*/
onBeforePaste?: (pastedValue: string, opts: Options) => string;
/**
* Executes before writing to the masked element Use this to do some extra processing of the input. This can
* be useful when implementing an alias, ex. decimal alias, autofill the digits when leaving the inputfield.
*/
onBeforeWrite?: (event: KeyboardEvent, buffer: string[], caretPos: number, opts: Options) => CommandObject;
/**
* Executes after unmasking to allow post-processing of the unmaskedvalue.
*
* @returns New unmasked value
*/
onUnMask?: (maskedValue: string, unmaskedValue: string) => string;
/**
* Shows the mask when the input gets focus.
*
* @default true
*/
showMaskOnFocus?: boolean;
/**
* Shows the mask when the input is hevered by the mouse cursor.
*
* @default true
*/
showMaskOnHover?: boolean;
/**
* Callback function is executed on every keyvalidation with the key & result as parameter.
*/
onKeyValidation?: (key: number, result: boolean) => void;
/**
* A character which can be used to skip an optional part of a mask.
*
* @default " "
*/
skipOptionalPartCharacter?: string;
/**
* Numeric input direction. Keeps the caret at the end.
*
* @default false
*/
numericInput?: boolean;
/**
* Align the input to the right
*
* By setting the rightAlign you can specify to right align an inputmask. This is only applied in combination of
* the `numericInput` option or the `dir-attribute`.
*
* @default true
*/
rightAlign?: boolean;
/**
* Make escape behave like undo. (ctrl-Z) Pressing escape reverts the value to the value before focus.
*
* @default true
*/
undoOnEscape?: boolean;
/**
* Define the radixpoint (decimal separator)
*
* @default ""
*/
radixPoint?: string;
/**
* Define the groupseparator.
*
* @default ""
*/
groupSeparator?: string;
/**
* Use in combination with the alternator syntax Try to keep the mask static while typing. Decisions to alter the
* mask will be postponed if possible.
*
* ex. $(selector).inputmask({ mask: ["+55-99-9999-9999", "+55-99-99999-9999", ], keepStatic: true });
*
* typing 1212345123 => should result in +55-12-1234-5123 type extra 4 => switch to +55-12-12345-1234
*
* When passing multiple masks (an array of masks) keepStatic is automatically set to true unless explicitly set
* through the options.
*
* @default null
*/
keepStatic?: boolean | null;
/**
* When enabled the caret position is set after the latest valid position on TAB.
*
* @default true
*/
positionCaretOnTab?: boolean;
/**
* Allows for tabbing through the different parts of the masked field.
*
* @default false
*/
tabThrough?: boolean;
/**
* List with the supported input types
*
* @default ["text", "tel", "url", "password", "search"]
*/
supportsInputType?: string[];
/**
* Specify keyCodes which should not be considered in the keypress event, otherwise the `preventDefault` will
* stop their default behavior especially in FF.
*/
ignorables?: number[];
/**
* With this call-in (hook) you can override the default implementation of the isComplete function.
*/
isComplete?: (buffer: string[], opts: Options) => boolean;
/**
* Hook to postValidate the result from isValid. Useful for validating the entry as a whole.
*/
postValidation?: (buffer: string[], pos: number, currentResult: CommandObject, opts: Options) =>
boolean | CommandObject;
/**
* Hook to preValidate the input. Useful for validating regardless the definition. When return true, the normal
* validation kicks in, otherwise it is skipped.
*/
preValidation?: (buffer: string[], pos: number, char: string, isSelection: boolean, opts: Options) =>
boolean | CommandObject;
/**
* The `staticDefinitionSymbol` option is used to indicate that the static entries in the mask can match a
* certain definition. Especially useful with alternators so that static element in the mask can match
* another alternation.
*
* @default undefined
*/
staticDefinitionSymbol?: string;
/**
* Just in time masking. With the `jitMasking` option you can enable jit masking. The mask will only be
* visible for the user entered characters.
*
* @default false
*/
jitMasking?: boolean;
/**
* Return nothing from the input `value` property when the user hasn't entered anything. If this is false,
* the mask might be returned.
*
* @default true
*/
nullable?: boolean;
/**
* Disable value property patching
*
* @default false
*/
noValuePatching?: boolean;
/**
* Positioning of the caret on click.
*
* Options:
*
* * `none`
* * `lvp` - based on the last valid position (default)
* * `radixFocus` - position caret to radixpoint on initial click
* * `select` - select the whole input
* * `ignore` - ignore the click and continue the mask
*
* @default "lvp"
*/
positionCaretOnClick?: PositionCaretOnClick;
/**
* Apply casing at the mask-level.
*
* @default undefined
*/
casing?: Casing;
/**
* Specify the inputmode - already in place for when browsers start to support them
* https://html.spec.whatwg.org/#input-modalities:-the-inputmode-attribute
*
* @default "verbatim"
*/
inputmode?: InputMode;
/**
* Create a css styleable mask.
*
* You need to include the inputmask.css in your page to use this option.
*
* See the inputmask.css for more info about the used styling. You can override the
* Inputmask.prototype.positionColorMask`if you need some custom positioning.
*
* @default false
*/
colorMask?: boolean;
/**
* Disables predictive text on mobile devices.
*
* What it does:
*
* * changes the input type to password => disables predictive text
* * enables the colorMask option which creates a div, which surrounds the input. So we type in the hidden
* password input and render the mask in the a created div.
*
* To use the colorMask, you need to include the inputmask.css. You might need to add some css-tweaks to make
* it all visually correct in your page.
*
* @default false
*/
disablePredictiveText?: boolean;
/**
* Specify to use the `data-inputmask` attributes or to ignore them.
*
* If you don't use data attributes you can disable the import by specifying `importDataAttributes: false`.
*
* @default true
*/
importDataAttributes?: boolean;
/**
* Shift position of the mask entries on entry and deletion. In some cases shift the mask enties isn't desired.
*
* Ex. date masks. Shifting month to day makes no sense
*
* @default true
*/
shiftPositions?: boolean;
/**
* Minimum value. This needs to be in the same format as the `inputFormat` when used with the datetime alias.
*/
min?: string;
/**
* Maximum value. This needs to be in the same format as the `inputFormat` when used with the datetime alias.
*/
max?: string;
/**
* Number of fractionalDigits.
*
* Possible values:
*
* * A number describing the number of fractional digits.
* * `*`
* * Quantifier syntax like `2,4`. When the quantifier syntax is used, the `digitsOptional` option is ignored
*
* @default "*"
*/
digits?: string;
/**
* Specify wheter the digits are optional.
*
* @default true
*/
digitsOptional?: boolean;
/**
* Enforces the decimal part when leaving the input field.
*
* @default false
*/
enforceDigitsOnBlur?: boolean;
/**
* Define the grouping of the integer part.
*
* @default 3
*/
groupSize?: number;
/**
* Enable grouping of the integer part.
*
* @default false
*/
autoGroup?: boolean;
/**
* Allow to enter -.
*
* @default true
*/
allowMinus?: boolean;
/**
* Define your negationSymbol.
*
* @default { front: "-", back: "" }
*/
negationSymbol?: { front: string, back: string };
/**
* Number of integerDigits
*
* @default "+"
*/
integerDigits?: string;
/**
* Specify wheter the integerdigits are optional.
*
* @default true
*/
integerOptional?: boolean;
/**
* Define a prefix.
*
* @default ""
*/
prefix?: string;
/**
* Define a suffix.
*
* @default ""
*/
suffix?: string;
/**
* Do not allow assumption of decimals input without entering the radixpoint.
*
* @default true
*/
decimalProtect?: boolean;
/**
* Define the step the ctrl-up & ctrl-down must take.
*
* @default 1
*/
step?: number;
/**
* Make unmasking returning a number instead of a string.
*
* Be warned that using the unmaskAsNumber option together with jQuery.serialize will fail as serialize expects a string. (See issue #1288)
*
* @default false
*/
unmaskAsNumber?: boolean;
/**
* Indicates whether the value passed for initialization is text or a number
*
* @default "text"
*/
inputType?: "text" | "number";
/**
* Format used to input a date. This option is only effective for the datetime alias.
*
* Supported symbols
*
* * `d` - Day of the month as digits; no leading zero for single-digit days.
* * `dd` - Day of the month as digits; leading zero for single-digit days.
* * `ddd` - Day of the week as a three-letter abbreviation.
* * `dddd` - Day of the week as its full name.
* * `m` - Month as digits; no leading zero for single-digit months.
* * `mm` - Month as digits; leading zero for single-digit months.
* * `mmm` - Month as a three-letter abbreviation.
* * `mmmm` - Month as its full name.
* * `yy` - Year as last two digits; leading zero for years less than 10.
* * `yyyy` - Year as 4 digits.
* * `h` - Hours; no leading zero for single-digit hours (12-hour clock).
* * `hh` - Hours; leading zero for single-digit hours (12-hour clock).
* * `hhh` - Hours; no limit
* * `H` - Hours; no leading zero for single-digit hours (24-hour clock).
* * `HH` - Hours; leading zero for single-digit hours (24-hour clock).
* * `HHH` - Hours; no limit
* * `M` - Minutes; no leading zero for single-digit minutes. Uppercase M unlike CF timeFormat's m to avoid
* conflict with months.
* * `MM` - Minutes; leading zero for single-digit minutes. Uppercase MM unlike CF timeFormat's mm to avoid
* conflict with months.
* * `s` - Seconds; no leading zero for single-digit seconds.
* * `ss` - Seconds; leading zero for single-digit seconds.
* * `l` - Milliseconds. 3 digits.
* * `L` - Milliseconds. 2 digits.
* * `t` - Lowercase, single-character time marker string: a or p.
* * `tt` - Two-character time marker string: am or pm.
* * `T` - Single-character time marker string: A or P.
* * `TT` - Two-character time marker string: AM or PM.
* * `Z` - US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the
* GMT/UTC offset is returned, e.g. GMT-0500
* * `o` - GMT/UTC timezone offset, e.g. -0500 or +0230.
* * `S` - The date's ordinal suffix (st, nd, rd, or th). Works well with d.
*
* @default "isoDateTime"
*/
inputFormat?: string;
/**
* Format of the unmasked value. This is only effective when used with the datetime alias.
*/
outputFormat?: string;
}
interface Instance {
/**
* Return the default (empty) mask value.
*/
getemptymask(): string;
/**
* The metadata of the actual mask provided in the mask definitions can be obtained by calling getmetadata. If
* only a mask is provided the mask definition will be returned by the getmetadata.
*/
getmetadata(): any;
/**
* Check whether the returned value is masked or not; currently only works reliably when using `jquery.val` fn
* to retrieve the value
*/
hasMaskedValue(): boolean;
/**
* Verify whether the current value is complete or not.
*/
isComplete(): boolean;
/**
* Validate a given value against the mask.
*/
isValid(): boolean;
/**
* Create a mask for the input.
*
* @param el Element selector, a single element or an array of elements.
*/
mask(selectorOrElement: string | HTMLElement | ArrayLike<HTMLElement>): Instance;
/**
* Get an option on an existing inputmask.
*
* @param key Name of option to retrieve.
*/
option(key: string): any;
/**
* Set an option on an existing inputmask. The option method is intented for adding extra options like
* callbacks, etc at a later time to the mask.
*
* When extra options are set the mask is automatically reapplied, unless you pas true for the `noremask`
* argument.
*/
option(opts: Options, noremask?: boolean): Instance;
/**
* Remove the inputmask.
*/
remove(): void;
/**
* The `setvalue` functionality is to set a value to the inputmask like you would do with `jQuery.val`, BUT it
* will trigger the internal event used by the inputmask always, whatever the case. This is particular useful
* when cloning an inputmask with jQuery.clone. Cloning an inputmask is not a fully functional clone. On the
* first event (`mouseenter`, `focus`, ...) the inputmask can detect if it where cloned and can reactivate the
* masking. However when setting the value with jQuery.val there is none of the events triggered in that case.
* The `setvalue` functionality does this for you.
*/
setValue(value: string): void;
/**
* Gets the unmasked value.
*/
unmaskedvalue(): string;
}
interface Definition {
validator: string | DefinitionValidator;
casing?: Casing;
cardinality?: number;
placeholder?: string;
definitionSymbol?: string;
}
interface InsertPosition {
/**
* Position to insert.
*/
pos: number;
/**
* Character to insert.
*/
c: string;
}
interface CommandObject {
/**
* Position to insert.
*/
pos?: number;
/**
* Character to insert.
*/
c?: string;
/**
* Position of the caret.
*/
caret?: number;
/**
* Position(s) to remove.
*/
remove?: number | number[];
/**
* Position(s) to add.
*/
insert?: InsertPosition | InsertPosition[];
/**
* * `true` => refresh validPositions from the complete buffer .
* * `{ start: , end: }` => refresh from start to end.
*/
refreshFromBuffer?: true | { start: number, end: number };
}
interface Static {
/**
* Creates a new Inputmask instance.
*
* @param maskOrAlias A mask pattern or a reference to a predefined alias.
* @param opts Mask options.
*/
(maskOrAlias: string, opts?: Options): Instance;
/**
* Creates a new Inputmask instance.
*
* @param opts Mask options.
*/
(opts?: Options): Instance;
/**
* Creates a new Inputmask instance.
*
* @param maskOrAlias A mask pattern or a reference to a predefined alias.
* @param opts Mask options.
*/
new (maskOrAlias: string, opts?: Options): Instance;
/**
* Creates a new Inputmask instance.
*
* @param opts Mask options.
*/
new (opts?: Options): Instance;
/**
* Extends the default inputmask options.
*/
extendDefaults(opts: Options): void;
/**
* Add new definitions to this inputmask.
*/
extendDefinitions(definitions: {
[key: string]: Definition,
}): void;
/**
* Extends the set of available mask aliases.
*/
extendAliases(aliases: {
[key: string]: Options,
}): void;
/**
* Instead of masking an input element it is also possible to use the inputmask for formatting given values.
* Think of formatting values to show in jqGrid or on other elements then inputs.
*
* @param value Value to format.
* @param opts Mask options.
*/
format(value: string, opts: Options): string;
/**
* Validate a given value against the mask.
*
* @param value Value to validate.
* @param opts Mask options.
*/
isValid(value: string, opts: Options): boolean;
/**
* Remove the inputmask.
*/
remove(selectorOrElement: string | HTMLElement | ArrayLike<HTMLElement>): void;
/**
* The setvalue functionality is to set a value to the inputmask like you would do with jQuery.val, BUT it will
* trigger the internal event used by the inputmask always, whatever the case. This is particular usefull when
* cloning an inputmask with jQuery.clone. Cloning an inputmask is not a fully functional clone. On the first
* event (mouseenter, focus, ...) the inputmask can detect if it where cloned and can reactivate the masking.
* However when setting the value with jQuery.val there is none of the events triggered in that case. The
* setvalue functionality does this for you.
*/
setValue(selectorOrElement: string | HTMLElement | ArrayLike<HTMLElement>, value: string): void;
/**
* Unmask a given value against the mask.
*
* @param value Value to be unmasked.
* @param opts Mask options.
*/
unmask(value: string, opts: Options): string;
}
}
declare global {
interface HTMLElement {
inputmask?: Inputmask.Instance;
}
interface JQuery {
/**
* Return the default (empty) mask value.
*/
inputmask(method: "getemptymask"): string; // tslint:disable-line:unified-signatures
/**
* The metadata of the actual mask provided in the mask definitions can be obtained by calling getmetadata. If
* only a mask is provided the mask definition will be returned by the getmetadata.
*/
inputmask(method: "getmetadata"): any;
/**
* Check whether the returned value is masked or not; currently only works reliably when using `jquery.val` fn
* to retrieve the value
*/
inputmask(method: "hasMaskedValue"): boolean; // tslint:disable-line:unified-signatures
/**
* Verify whether the current value is complete or not.
*/
inputmask(method: "isComplete"): boolean; // tslint:disable-line:unified-signatures
/**
* Validate a given value against the mask.
*/
inputmask(method: "isValid"): boolean; // tslint:disable-line:unified-signatures
/**
* Get an option on an existing inputmask.
*
* @param key Name of option to retrieve.
*/
inputmask(method: "option", key: string): any;
/**
* Set an option on an existing inputmask. The option method is intented for adding extra options like
* callbacks, etc at a later time to the mask.
*
* When extra options are set the mask is automatically reapplied, unless you pas true for the `noremask`
* argument.
*/
inputmask(method: "option", opts: Inputmask.Options, noremask?: boolean): Inputmask.Instance;
/**
* Remove the inputmask.
*/
inputmask(method: "remove"): void;
/**
* The `setvalue` functionality is to set a value to the inputmask like you would do with `jQuery.val`, BUT it
* will trigger the internal event used by the inputmask always, whatever the case. This is particular useful
* when cloning an inputmask with jQuery.clone. Cloning an inputmask is not a fully functional clone. On the
* first event (`mouseenter`, `focus`, ...) the inputmask can detect if it where cloned and can reactivate the
* masking. However when setting the value with jQuery.val there is none of the events triggered in that case.
* The `setvalue` functionality does this for you.
*/
inputmask(method: "setValue", value: string): void;
/**
* Gets the unmasked value.
*/
inputmask(method: "unmaskedvalue"): string; // tslint:disable-line:unified-signatures
/**
* Creates a new Inputmask instance.
*
* @param maskOrAlias A mask pattern or a reference to a predefined alias.
* @param opts Mask options.
*/
inputmask(maskOrAlias: string, opts?: Inputmask.Options): Inputmask.Instance;
/**
* Creates a new Inputmask instance.
*
* @param opts Mask options.
*/
inputmask(opts?: Inputmask.Options): Inputmask.Instance;
}
}
declare const Inputmask: Inputmask.Static;
export = Inputmask;
export as namespace Inputmask;
|
6b69929e594bb866e550013e82e31136ae9fbaf5
|
TypeScript
|
jnoodle0503/typescript_api_practice
|
/src/test/app.ts
| 3.25
| 3
|
/* 일반 변수에 타입 선언 */
const personName: string = "inyong";
const personAge: number = 27;
/* 배열 변수에 타입 선언 */
const TempNumberArray: number[] = [10, 20, 30];
export const TempArray: [boolean, number] = [true, 10];
|
c554a5f61b3e85f579d60598b2523810b29e573c
|
TypeScript
|
Zero-to-Heroes/firestone
|
/libs/legacy/feature-shell/src/lib/js/services/battlegrounds/store/real-time-stats/event-parsers/rtstats-turn-start-parser.ts
| 2.671875
| 3
|
import { GameEvent } from '../../../../../models/game-event';
import { RealTimeStatsState } from '../real-time-stats';
import { EventParser } from './_event-parser';
export class RTStatTurnStartParser implements EventParser {
applies(gameEvent: GameEvent, currentState: RealTimeStatsState): boolean {
return gameEvent.type === GameEvent.TURN_START;
}
parse(
gameEvent: GameEvent,
currentState: RealTimeStatsState,
): RealTimeStatsState | PromiseLike<RealTimeStatsState> {
const newCurrentTurn = Math.ceil(gameEvent.additionalData.turnNumber / 2);
return currentState.update({
currentTurn: newCurrentTurn,
} as RealTimeStatsState);
}
name(): string {
return 'RTStatTurnStartParser';
}
}
|
5badbdd74d7d3e5bcc6fcde5854395a350363b30
|
TypeScript
|
0xGG/vscode-isomorphic-git
|
/src/errors.ts
| 2.75
| 3
|
function Err(name: string) {
return class extends Error {
private code: string;
constructor(...args: any[]) {
super(...args);
this.code = name;
if (this.message) {
this.message = name + ": " + this.message;
} else {
this.message = name;
}
}
};
}
export const EEXIST = Err("EEXIST");
export const ENOENT = Err("ENOENT");
export const ENOTDIR = Err("ENOTDIR");
export const ENOTEMPTY = Err("ENOTEMPTY");
export const ETIMEDOUT = Err("ETIMEDOUT");
|
66419b611d58e98016c2b6b01f0fe423a0ea7973
|
TypeScript
|
elauffenburger/playbliss
|
/src/renderer/services/playlist.ts
| 2.953125
| 3
|
import { Playlist, Track, CreatePlaylistArgs, PlaylistTrack } from "../models";
import { Store } from "vuex";
import { AppState } from "../store";
import { v4 as uuid } from "uuid";
export interface PlaylistService {
getPlaylists(includeAll?: boolean): Playlist[];
getPlaylistById(id: string): Playlist | null;
createPlaylist(args: CreatePlaylistArgs): Promise<Playlist>;
setPlaylistTracks(playlistId: string, tracks: Track[]): Promise<void>;
removePlaylist(id: string): Promise<any>;
removeTrack(track: PlaylistTrack): Promise<void>;
addTrackToPlaylist(playlistId: string, track: Track): Promise<any>;
}
export class DefaultPlaylistService implements PlaylistService {
constructor(private store: Store<AppState>) {}
getPlaylists(includeAll?: boolean) {
const playlists = this.store.state.playlists.playlists;
if (includeAll) {
return playlists;
}
return playlists.filter(p => !p.isVirtual);
}
async createPlaylist(args: CreatePlaylistArgs) {
// If the caller wants a virtual playlist and is fine reusing
// an existing one, find the first available and use that.
// Otherwise, hook into the regular flow
if (args.isVirtual && !args.createNew) {
const playlist = this.getPlaylists().find(p => p.isVirtual);
if (!playlist) {
return await this.createNewPlaylist(args);
}
await this.setPlaylistTracks(playlist.id, args.tracks);
return playlist;
}
return await this.createNewPlaylist(args);
}
async createNewPlaylist(args: CreatePlaylistArgs): Promise<Playlist> {
const id = uuid();
const playlist: Playlist = {
id,
name: args.isVirtual ? "virtual" : args.name,
isVirtual: args.isVirtual || false,
tracks: this.toPlaylistTracks(id, args.tracks)
};
await this.store.dispatch("playlists/createPlaylist", playlist);
return playlist;
}
async removePlaylist(id: string) {
return this.store.dispatch("playlists/removePlaylist", id);
}
async removeTrack(track: PlaylistTrack) {
if (!track.playlistId) {
return;
}
const playlist = await this.getPlaylistById(track.playlistId);
if (!playlist) {
return;
}
// Create a copy of the playlist tracks to modify
const tracks = [...playlist.tracks];
const trackIndex = tracks.findIndex(
t => !!t.position && !!track.position && t.position == track.position
);
tracks.splice(trackIndex, 1);
this.setPlaylistTracks(playlist.id, tracks.map(t => t.track));
}
async addTrackToPlaylist(playlistId: string, track: Track) {
return this.store.dispatch("playlists/addTrackToPlaylist", {
playlistId,
track
});
}
getPlaylistById(id: string) {
return this.store.state.playlists.playlists.find(p => p.id == id) || null;
}
setPlaylistTracks(playlistId: string, tracks: Track[]) {
return this.store.dispatch("playlists/setTracks", {
playlistId: playlistId,
tracks: tracks
});
}
private toPlaylistTracks(
playlistId: string,
tracks: Track[]
): PlaylistTrack[] {
return tracks.map<PlaylistTrack>((t, i) => {
return {
track: t,
position: i,
playlistId: playlistId
};
});
}
}
|
5106337a868033e785c412ec4bcb6c43630131f8
|
TypeScript
|
eyeamkd/jsds
|
/StackOfStacks.ts
| 3.203125
| 3
|
import Stack from './Stack';
import {LinkedList} from './LinkedList';
class StackOfStacks{
private thresholdValue:number;
private stackOfStacks:LinkedList<Stack>;
private stack : Stack;
constructor(thresholdValue:number,firstElement:number){
this.thresholdValue = thresholdValue;
this.stack = new Stack(firstElement);
this.stackOfStacks = new LinkedList<Stack>(this.stack);
// this.stackOfStacks = new StackOfStacks(thresholdValue,firstElement);
}
public changeThreshold(newValue:number){
if(newValue>this.thresholdValue){
this.thresholdValue = newValue;
}
}
private addStack(stack:Stack){
this.stackOfStacks.append(stack);
}
public pop(){
return this.stack.pop()
}
public push(element:number){
if(this.stack.size() == this.thresholdValue || this.stack==null){
this.stack = new Stack(element);
this.addStack(this.stack);
}else
this.stack.push(element);
}
}
export default StackOfStacks;
|
303390c3ac403d6d56e1d4448b496c846314a923
|
TypeScript
|
kaushi/codecharta
|
/visualization/app/codeCharta/state/store/dynamicSettings/recentFiles/recentFiles.actions.ts
| 2.609375
| 3
|
import { Action } from "redux"
import { CCAction } from "../../../../codeCharta.model"
export enum RecentFilesActions {
SET_RECENT_FILES = "SET_RECENT_FILES",
REMOVE_RECENT_FILE = "REMOVE_RECENT_FILE"
}
export interface SetRecentFilesAction extends Action {
type: RecentFilesActions.SET_RECENT_FILES
payload: string[]
}
export interface RemoveRecentFileAction extends CCAction {
type: RecentFilesActions.REMOVE_RECENT_FILE
payload: string
}
export type RecentFilesAction = SetRecentFilesAction | RemoveRecentFileAction
export function setRecentFiles(recentFiles: string[] = defaultRecentFiles): SetRecentFilesAction {
return {
type: RecentFilesActions.SET_RECENT_FILES,
payload: recentFiles
}
}
export function removeRecentFile(fileName: string): RemoveRecentFileAction {
return {
type: RecentFilesActions.REMOVE_RECENT_FILE,
payload: fileName
}
}
export const defaultRecentFiles: string[] = []
|
7c6c55211e8231f0b5085918d511fc039ed6f3eb
|
TypeScript
|
dabbott/javascript-playgrounds
|
/src/utils/Object.ts
| 3.4375
| 3
|
export function hasOwnProperty<O extends object, K extends PropertyKey>(
obj: O,
key: K
): obj is O & { [key in K]: unknown } {
return Object.prototype.hasOwnProperty.call(obj, key)
}
function isEnumerable(obj: object, key: PropertyKey) {
return Object.prototype.propertyIsEnumerable.call(obj, key)
}
export function fromEntries<T = any>(
entries: Iterable<readonly [PropertyKey, T]>
): { [k: string]: T } {
return [...entries].reduce((obj: Record<PropertyKey, T>, [key, val]) => {
obj[key as any] = val
return obj
}, {})
}
export function entries<T>(
obj: { [s: string]: T } | ArrayLike<T>
): [string, T][] {
if (obj == null) {
throw new TypeError('Cannot convert undefined or null to object')
}
const pairs: [string, T][] = []
for (let key in obj) {
if (hasOwnProperty(obj, key) && isEnumerable(obj, key)) {
pairs.push([key, obj[key]])
}
}
return pairs
}
|
b1616ca5775242ee281d6eb2e655ff042fe50884
|
TypeScript
|
aaronosher/discord-login
|
/website/src/store/verify/reducer.ts
| 2.6875
| 3
|
import { createReducer } from "@reduxjs/toolkit";
import { startVerify, verifyWithCode } from "./actions";
export interface VerifyState {
loading: boolean;
error: string | null;
}
const initialState: VerifyState = {
loading: false,
error: null,
};
const reducer = createReducer<VerifyState>(initialState, (builder) =>
builder
.addCase(startVerify.pending, (state) => ({
...state,
loading: true,
error: null,
}))
.addCase(startVerify.rejected, (state, { error }) => ({
...state,
loading: false,
error: error.message as string,
}))
.addCase(startVerify.fulfilled, (state) => ({
...state,
loading: false,
}))
.addCase(verifyWithCode.pending, (state) => ({
...state,
loading: true,
error: null,
}))
.addCase(verifyWithCode.fulfilled, (state) => ({
...state,
loading: false,
error: null,
}))
.addCase(verifyWithCode.rejected, (state, { error }) => ({
...state,
loading: false,
error: error.message as string,
}))
);
export default reducer;
|
1aa0bdd2010682d4e5ea061400d16ea94d7c13c6
|
TypeScript
|
W402593/sp-dev-build-extensions
|
/samples/azure-devops-ci-cd-spfx/src/webparts/devOps/tests/DevOpsWebPart.spec.ts
| 2.734375
| 3
|
/// <reference types="mocha" />
import {assert, expect} from 'chai';
import { DevOpsWebPartService } from "../DevOpsWebPart.service";
import { BusinessService } from "../businesslogic";
import { MockSPListCollectionService } from "../dataservice/mockSPListCollectionService";
describe("DevOpsWebPart", () => {
let service: DevOpsWebPartService = new DevOpsWebPartService();
it("should do something", () => {
assert.ok(true, 'should be true');
});
it("should add numbers Sync fluent", () => {
const result:number = service.add(1, 3);
expect(result).to.eq(4); // fluent API
});
it("should add numbers sync assert", () => {
const result:number = service.add(1, 3);
assert.equal(result, 4, "result equals 4"); // assert/imperative API
});
it("should add numbers async", async () => { // async test
const result: number = await service.addAsync(1, 3);
expect(result).to.eq(4);
});
it("get a business value of 3", async () => {
const businessService:BusinessService = new BusinessService(new MockSPListCollectionService());
const result = await businessService.GetBusinessLogic();
expect(result).to.eq(3);
});
});
|
1cd1247fdc6d4fe1aef78ff907657c2f0d5b6f2d
|
TypeScript
|
bbarry/store
|
/packages/store/src/internal/state-operators.ts
| 2.8125
| 3
|
import {
throwPatchingArrayError,
throwPatchingPrimitiveError
} from '../configs/messages.config';
import { StateOperator } from '../symbols';
export function simplePatch<T>(val: Partial<T>): StateOperator<T> {
return (existingState: Readonly<T>) => {
if (Array.isArray(val)) {
throwPatchingArrayError();
} else if (typeof val !== 'object') {
throwPatchingPrimitiveError();
}
const newState: any = { ...(existingState as any) };
for (const key in val) {
// deep clone for patch compatibility
// noinspection JSUnfilteredForInLoop (IDE)
newState[key] = (val as any)[key];
}
return newState as T;
};
}
|
88ed4797aa4d168df2e2dcbdd787aac4e54872d6
|
TypeScript
|
voorjaar/fluire
|
/src/interfaces.ts
| 2.59375
| 3
|
export interface Todo {
id: string
title: string
date: string
duration: number
color: 'red' | 'dark-orange' | 'orange' | 'yellow' | 'green' | 'teal' | 'light-blue' | 'blue' | 'dark-blue' | 'dark-purple' | 'purple' | 'pink' | 'dark-gray' | 'gray' | 'brown'
finished: boolean
}
export interface NavItem {
id?: string
name: string
icon: string
}
export interface Nav {
title: string
children: NavItem[]
}
export interface Option {
label: string
value: string
}
|
7362408ee4912e758aa54afff7cf3da7b37d1ae1
|
TypeScript
|
user-dob/academy
|
/src/logic/part_13.ts
| 2.796875
| 3
|
import { printBF } from './util';
const printBF3 = printBF(3);
// дистрибутивность
// (p ∧ (q ∨ r)) ↔ ((p ∧ q) ∨ (p ∧ r))
printBF3(
(p, q, r) => p && (q || r),
(p, q, r) => (p && q) || (p && r),
);
// дистрибутивность
// (p ∨ (q ∧ r)) ↔ ((p ∨ q) ∧ (p ∨ r))
printBF3(
(p, q, r) => p || (q && r),
(p, q, r) => (p || q) && (p || r),
);
|
efe6afc04db920c87c9fc4c82a7f9225b1a0729c
|
TypeScript
|
brandcoded/HelloFriendPlayer
|
/src/db.ts
| 2.734375
| 3
|
import * as MRE from '@microsoft/mixed-reality-extension-sdk'
import { Pool } from 'pg'
import AudioFileInfo, { SessionData, SessionState } from './types'
export default class DBConnect{
pool = new Pool({
user: process.env.PG_USER,
host: process.env.PG_HOST,
database: process.env.PG_DATABASE,
password: process.env.PG_PASSWORD,
port: parseInt( process.env.PG_PORT)
})
/**
* creates a db connection
*/
constructor(){
//action to be take on pool connection
this.pool.on('connect', (client)=>{ })
//db error action
this.pool.on('error', (err, client) => {
MRE.log.error('app', 'db error on idle client', err)
process.exit(-1)
})
//test the connection to the db on startup
this.pool.connect().then(client => {
return client
.query('SELECT * FROM sessiondata WHERE id = $1', [1])
.then(res => {
client.release()
MRE.log.info('app', "db connection test returned: ", res.rows[0])
})
.catch(err => {
client.release()
MRE.log.info('app', "db error:", err.stack)
})
})
}
/**
* pull the current playlist for a given sessionid from the db
* @param sessionId
*/
async getSessionData(sessionId:string):Promise<SessionData> {
const text = 'SELECT * FROM sessiondata WHERE sessionId=$1'
const values = [sessionId]
const res = await this.pool.query(text, values)
//if nothing was found in the db return undefined
let sessionData = new SessionData()
sessionData.playlist = res.rows[0] ? JSON.parse(res.rows[0].playlistjson) as AudioFileInfo[] : undefined
sessionData.state = res.rows[0] ? JSON.parse(res.rows[0].state) as SessionState : undefined
return sessionData
}
/**
* save a new playlist to the db
* @param sessionId
* @param musicFileList
*/ //INSERT INTO users(name, email) VALUES($1, $2)
async saveNewSessionList(sessionId:string, musicFileList: AudioFileInfo[]){
//first we check to see if an entry exists
let text = 'select * from sessiondata WHERE sessionid = $1'
let values = [sessionId]
const res = await this.pool.query(text, values)
//set the values for the insert or update
values = [sessionId, JSON.stringify(musicFileList) ]
//if the select didn't find anything then we do an insert
if (!res.rows[0]) {
let text = 'INSERT INTO sessiondata (sessionid, playlistjson) VALUES ($1, $2)'
const res = await this.pool.query(text, values)
MRE.log.info('app', `saving playlist for ${sessionId} with ${musicFileList.length} tracks`)
//else update the existing row
}else{
let text = 'UPDATE sessiondata SET playlistjson = $2 WHERE sessionid = $1'
const res = await this.pool.query(text, values)
MRE.log.info('app', `updating playlist for ${sessionId} to new list with ${musicFileList.length} tracks`)
}
}
/**
* clear playlist for session
* @param sessionId
*/
async clearSessionPlaylist(sessionId:string){
//first we check to see if an entry exists
let text = 'select * from sessiondata WHERE sessionid = $1'
let values = [sessionId]
const res = await this.pool.query(text, values)
//set the values for the insert or update
values = [sessionId, JSON.stringify([]) ]
//if the select didn't find anything then we do an insert
if (!res.rows[0]) {
let text = 'INSERT INTO sessiondata (sessionid, playlistjson) VALUES ($1, $2)'
const res = await this.pool.query(text, values)
MRE.log.info('app', `clearing playlist for ${sessionId}`)
//else update the existing row
}else{
let text = 'UPDATE sessiondata SET playlistjson = $2 WHERE sessionid = $1'
const res = await this.pool.query(text, values)
MRE.log.info('app', `clearing playlist for ${sessionId} t`)
}
}
/**
* save session settings to the db
* to receive session settings just load a playlist
* @param state
*/
async saveSessionState(sessionId:string, state:SessionState){
MRE.log.info('app', `saving session state for ${sessionId}: `, state)
//first we check to see if an entry exists
let text = 'select * from sessiondata WHERE sessionid = $1'
let values = [sessionId]
const res = await this.pool.query(text, values)
//set the values for the insert or update
values = [sessionId, JSON.stringify(state) ]
//if the select didn't find anything then we do an insert
if (!res.rows[0]) {
let text = 'INSERT INTO sessiondata (sessionid, state) VALUES ($1, $2)'
const res = await this.pool.query(text, values)
//else update the existing row
}else{
let text = 'UPDATE sessiondata SET state = $2 WHERE sessionid = $1'
const res = await this.pool.query(text, values)
}
}
}
|
a9fb0ff8a44c614fe59b782dcaf2585d27b99792
|
TypeScript
|
phanhien9218/ng2SexyBong
|
/app/sexybong/sexybong.list.ts
| 2.5625
| 3
|
//java, ...
import { Component } from '@angular/core';
//model
import { SexyBong } from '../model/SexyBong';
//service
import { SexyBongService } from '../service/sexybong.service';
//decorator
@Component({
templateUrl: 'app/sexybong/sexybong.list.html',
//templateUrl: 'test.html',
})
/**
* public class
*/
export class SexyBongList {
pageTitle: string = 'Product List';
widthImage: number = 50;
showInfo: boolean = true;
filterBy: string = "Trang Phi";
public errorMessage: string;
sexybongs: SexyBong[]; //access modifier (public, private, default)
//aggregration
//DI
constructor(private _service: SexyBongService) {
}
//hook life cycle
ngOnInit(): void {
this._service.getSexyBong()
//observable
//arrow function
.subscribe(sexybongs => {
this.sexybongs = sexybongs;
this._service.sexybongs = sexybongs;
console.log(this.sexybongs);
},
error => this.errorMessage = <any>error,
() => {
console.log("Complete ok bebi");
});
}
fiveHundredInfo(): void {
this.showInfo = !this.showInfo;
}
}
|
8d391e83d3362de1838e107497f360461faf535e
|
TypeScript
|
DanielPopOut/project-2
|
/src/app/card-element.ts
| 2.515625
| 3
|
import { Voter } from './voter';
export class CardElement {
public _id: string;
public title: string;
public type: number;
public event_id: string;
public card_id: string;
public voters: Voter[];
public added_by: string;
public voterLimit: number;
constructor(id: string, title: string, type: number, event_id: string, card_id: string, added_by: string, voterLimit: number = -1) {
this._id = id;
this.title = title;
this.type = type;
this.event_id = event_id;
this.card_id = card_id;
this.added_by = added_by;
this.voterLimit = voterLimit;
this.voters = [];
}
public vote() {
}
}
|
2cef833aa243b6ffb7407b166e91ff0268d8580c
|
TypeScript
|
noce2/design-factory-monitor
|
/src/app/insight360/app/shared/i360-design.service.ts
| 2.9375
| 3
|
import { Injectable } from '@angular/core';
import { Design } from '../../../../../app_server/models/design';
@Injectable()
export class DesignService {
// this service will handle retrieving designs from the backend
// creating new designs and validating data going into a design
dummyData: Design[] = [
new Design('1','Design 1', 'Joseph Akingbusi', 'A glorious work of engineering'),
new Design('2','Design 2', 'Joseph Akingbusi', 'A glorious work of engineering'),
new Design('3','Design 3', 'Joseph Akingbusi', 'A glorious work of engineering'),
new Design('4','Design 4', 'Joseph Akingbusi', 'A glorious work of engineering'),
new Design('5','Design 5', 'Joseph Akingbusi', 'A glorious work of engineering'),
new Design('6','Design 6', 'Joseph Akingbusi', 'A glorious work of engineering'),
new Design('7','Design 7', 'Joseph Akingbusi', 'A glorious work of engineering'),
new Design('8','Design 8', 'Joseph Akingbusi', 'A glorious work of engineering'),
];
getDesignData(): Design[] {
return (this.dummyData);
}
createBlankDesign() {
// this has been created here rather than on the design class
// because the design class will not be instantiated
// the service, however will be.
return new Design('','','','');
}
addNewDesign(input:Design) {
// this will need some sort of error checking
// so that you can send a message to user when it succeeds
this.dummyData.push(input);
}
editExistingDesign(input:Design) {
// this will need some serious error checking etc
// this will also need some sort of error checking
// so that you can send a message to user when it succeeds
const itemToReplace = this.dummyData.findIndex((each) => {
return each.id === input.id;
});
this.dummyData[itemToReplace] = input;
}
}
|
e3961f0af4359ef42978cbb78ed719185bd772f2
|
TypeScript
|
yandeu/phaser3-multiplayer-with-physics
|
/src/client/components/fullscreenEvent.ts
| 2.5625
| 3
|
// listen for fullscreen change event
const FullScreenEvent = (callback: Function) => {
const fullScreenChange = () => {
let times = [50, 100, 200, 500, 1000, 2000, 5000]
times.forEach(time => {
window.setTimeout(() => {
callback()
}, time)
})
}
var vendors = ['webkit', 'moz', 'ms', '']
vendors.forEach(prefix => {
document.addEventListener(prefix + 'fullscreenchange', fullScreenChange, false)
})
document.addEventListener('MSFullscreenChange', fullScreenChange, false)
}
export default FullScreenEvent
|
d4a5a5cf331e82d7238b271485acdeedc2e62b63
|
TypeScript
|
martycabj1999/front-angular
|
/src/app/components/home/home.component.ts
| 2.640625
| 3
|
import { Component } from '@angular/core';
import { ProductsService } from '../../services/products.service'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styles: [
]
})
export class HomeComponent {
newProducts: any[] = []
categories: any[] = []
loading: boolean[];
validate: string;
empty: boolean = false;
constructor(private products: ProductsService) {
this.loading = true;
/*this.newProducts = this.products.getProducts();
let cat = []
this.newProducts.map(product => {
cat.push(product.category)
});
this.categories = cat.filter(this.onlyUnique);*/
this.products.getProducts().subscribe((data: any) => {
this.newProducts = data;
let cat = []
this.newProducts.map(product => {
cat.push(product.category)
});
this.categories = cat.filter(this.onlyUnique);
this.loading = false;
});
}
onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
search(product: String) {
let currentProducts = []
let productsSearch = []
if (product !== '') {
this.products.getProducts().subscribe((data: any) => {
currentProducts = data;
productsSearch = currentProducts.filter(p => p.name.toLowerCase().indexOf(product) !== -1)
if (productsSearch.length == 0) {
return this.empty = true
}
return this.newProducts = productsSearch;
});
} else {
this.products.getProducts().subscribe((data: any) => {
console.log(data)
this.empty = false
return this.newProducts = data;
});
}
}
filter(min: Number, max: Number) {
if (!min) {
this.validate = "Debe Ingresar un valor"
return setTimeout(() => {
this.validate = ""
}, 1000);
}
if (!max) {
this.validate = "Debe Ingresar un valor"
return setTimeout(() => {
this.validate = ""
}, 1000);
}
if (parseFloat(min) > parseFloat(max)) {
this.validate = "El max debe ser mayor que min"
return setTimeout(() => {
this.validate = ""
}, 1000);
}
this.products.getProducts().subscribe((data: any) => {
let products = data
let filterProducts = []
products.map(product => {
if (product.price > parseFloat(min) && product.price < parseFloat(max)) {
filterProducts.push(product)
}
})
if (filterProducts.length == 0) {
return this.empty = true
}
return this.newProducts = filterProducts;
});
}
categoryFilter(category: String) {
this.products.getProducts().subscribe((data: any) => {
let products = data;
if (!category) {
return this.newProducts = products
}
return this.newProducts = products.filter(p => p.category.indexOf(category) !== -1)
});
}
}
|
35ab207824955cd0e5c6a8e866e4f704a20778d3
|
TypeScript
|
Coffeekraken/coffeekraken
|
/packages/builders/s-images-builder/src/node/SImagesBuilder.ts
| 2.53125
| 3
|
import type { ISBuilderSettings } from '@coffeekraken/s-builder';
import __SBuilder from '@coffeekraken/s-builder';
import __SDuration from '@coffeekraken/s-duration';
import __SFile from '@coffeekraken/s-file';
import type { IResolveGlobSettings } from '@coffeekraken/s-glob';
import __SGlob from '@coffeekraken/s-glob';
import __SLog from '@coffeekraken/s-log';
import {
__copySync,
__ensureDirSync,
__folderPath,
__removeSync,
} from '@coffeekraken/sugar/fs';
import { __deepMerge } from '@coffeekraken/sugar/object';
import { __packageRootDir } from '@coffeekraken/sugar/path';
import __fs from 'fs';
import __imageSize from 'image-size';
import __minimatch from 'minimatch';
import __path from 'path';
import __sharp from 'sharp';
import __SImagesBuilderBuildParamsInterface from './interface/SImagesBuilderBuildParamsInterface.js';
import __SImagesBuilderSettingsInterface from './interface/SImagesBuilderSettingsInterface.js';
/**
* @name SImagesBuilder
* @namespace node
* @type Class
* @interface ./interface/SImagesBuilderBuildParamsInterface
* @extends SBuilder
* @platform node
* @status beta
*
* This class allows you to compress the more popular images formats like
* "png", "jpg", "svg", "gif", etc... using the WONDERFULL sharp library.
*
* @param {ISImagesBuilderSettings} [settings={}] Some settings to configure your image compression process
*
* @snippet __SImagesBuilder($1)
* const imagesBuilder = new __SImagesBuilder();
* const imagesBuilderResult = await imagesBuilder.build({
* glob: $1,
* inDir: $2,
* outDir: $3,
* quality: 80,
* webp: true,
* width: 1280,
* height: 1280,
* resolution: [1,2],
* clear: false,
* specificParams: {}
* });
*
* @example js
* import __SImagesBuilder from '@coffeekraken/s-image-builder';
* const imagesBuilder = new __SImagesBuilder({
* // some settings...
* });
* const imagesBuilderResult = await imagesBuilder.build({
* glob: '** /*.jpg',
* inDir: 'src/img',
* outDir: 'dist/img',
* quality: 80,
* webp: true,
* width: 1280,
* height: 1280,
* resolution: [1,2],
* clear: false,
* specificParams: {}
* });
*
* @see https://www.npmjs.com/package/sharp
* @since 2.0.0
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
export interface ISImagesBuilderSettings extends ISBuilderSettings {
resolveGlob: Partial<IResolveGlobSettings>;
}
export interface ISImagesBuilderBuildParams {
glob: string;
compressExts: string[];
inDir: string;
outDir: string;
quality: number;
webp: boolean;
width: number;
height: number;
resolution: number[];
clear: boolean;
specificParams: Record<string, ISImagesBuilderBuildParams>;
}
export interface ISImagesBuilderImageResult {
source: __SFile;
builded: __SFile[];
webp: __SFile[];
}
export interface ISImagesBuilderResultItem extends ISImagesBuilderStats {
fromSourceGain?: ISImagesBuilderStats;
fromBuildedGain?: ISImagesBuilderStats;
}
export interface ISImagesBuilderStats {
percentage?: number;
bytes: number | string;
kbytes: number | string;
mbytes: number | string;
gbytes: number | string;
}
export interface ISImagesBuilderResult {
source: ISImagesBuilderResultItem;
builded: ISImagesBuilderResultItem;
webp: ISImagesBuilderResultItem;
files: Record<string, ISImagesBuilderImageResult>;
}
export default class SImagesBuilder extends __SBuilder {
/**
* @name constructor
* @type Function
* @constructor
*
* Constructor
*
* @since 2.0.0
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
constructor(settings?: Partial<ISImagesBuilderSettings>) {
super(
__deepMerge(
// @ts-ignore
__SImagesBuilderSettingsInterface.defaults(),
settings ?? {},
),
);
}
/**
* @name _build
* @type Function
* @private
* @async
*
* This method allows you to compress some images by passing one or more globs
* as parameters and if needed some ISImagesBuilderSettings settings to override
* these passed in the constructor
*
* @param {ISImagesBuilderBuildParams} params The parameters to build the images correctly. These parameters are passed by the SBuilder class
* @param {Partial<ISImagesBuilderSettings>} [settings={}] Some settings to override the ones passed in the constructor if needed
* @return {SPromise<ISImagesBuilderResult>} A promise resolved with the ISImagesBuilderResult object that store all the builded files stats, etc...
*
* @since 2.0.0
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
_build(
params: ISImagesBuilderBuildParams,
settings?: Partial<ISImagesBuilderSettings>,
): Promise<ISImagesBuilderResult | void> {
return new Promise(async (resolve) => {
const finalSettings = <ISImagesBuilderSettings>(
__deepMerge(this.settings, settings ?? {})
);
// @ts-ignore
params = __SImagesBuilderBuildParamsInterface.apply(params ?? {});
// clear if needed
if (params.clear) {
__removeSync(params.outDir);
__ensureDirSync(params.outDir);
}
// preparing files stack that store source AND output SFile instances
const filesStack = {};
// init stats variables
const sourceStats = {
bytes: 0,
};
const buildedStats = {
bytes: 0,
};
const webpStats = {
bytes: 0,
};
console.log(`<yellow>[build]</yellow> Starting images Build`);
function printParams(paramsObj) {
if (paramsObj.glob) {
console.log(
`<yellow>○</yellow> Glob : <yellow>${paramsObj.glob}</yellow>`,
);
}
if (paramsObj.inDir) {
console.log(
`<yellow>○</yellow> Input : <cyan>${__path.relative(
process.cwd(),
paramsObj.inDir,
)}</cyan>`,
);
}
if (paramsObj.outDir) {
console.log(
`<yellow>○</yellow> Output : <cyan>${__path.relative(
process.cwd(),
paramsObj.outDir,
)}</cyan>`,
);
}
if (paramsObj.quality) {
console.log(
`<yellow>○</yellow> Quality : <green>${paramsObj.quality}</green>`,
);
}
if (paramsObj.webp !== undefined) {
console.log(
`<yellow>○</yellow> Webp : ${
paramsObj.webp
? '<green>true</green>'
: '<red>false</red>'
}`,
);
}
if (paramsObj.width || paramsObj.height) {
console.log(
`<yellow>○</yellow> Size : <yellow>${
paramsObj.width ? paramsObj.width : '...'
}/${
paramsObj.height ? paramsObj.height : '...'
}</yellow>`,
);
}
if (paramsObj.resolution) {
console.log(
`<yellow>○</yellow> Resolution${
paramsObj.resolution.length > 1 ? 's' : ' '
} : ${paramsObj.resolution
.map((res) => {
return `<magenta>${res}x</magenta>`;
})
.join(', ')}`,
);
}
}
printParams(params);
if (params.specificParams) {
Object.keys(params.specificParams).forEach((glob) => {
const customParamsObj = params.specificParams[glob];
console.log(`<cyan>[${glob}]</cyan> Specific params`);
printParams(customParamsObj);
});
}
// resolving globs
await __SGlob
.resolveSync(`${params.inDir}/${params.glob}`, {
...(finalSettings.resolveGlob ?? {}),
cwd: params.inDir,
})
.forEach((file) => {
sourceStats.bytes += file.stats.bytes;
filesStack[file.path] = {
source: file,
builded: [],
};
});
for (let i = 0; i < Object.keys(filesStack).length; i++) {
const path = Object.keys(filesStack)[i];
let imgParams = Object.assign({}, params);
const file = filesStack[path].source;
const outPath = `${imgParams.outDir}/${file.relPath}`;
// check if is a file to compress
if (!params.compressExts.includes(file.extension)) {
console.log({
clear: __SLog.isTypeEnabled(__SLog.TYPE_VERBOSE)
? false
: true,
type: __SLog.TYPE_INFO,
value: `<cyan>[copy]</cyan> Copying file "<cyan>${__path.relative(
__packageRootDir(),
file.path,
)}</cyan>" under "<magenta>${__path.relative(
__packageRootDir(),
outPath,
)}</magenta>"`,
});
const duration = new __SDuration();
// track the builded stats
buildedStats.bytes += __fs.statSync(file.path).size;
webpStats.bytes += __fs.statSync(file.path).size;
// copy file
__copySync(file.path, outPath);
console.log({
clear: __SLog.isTypeEnabled(__SLog.TYPE_VERBOSE)
? false
: true,
type: __SLog.TYPE_INFO,
value: `<green>[copy]</green> File "<cyan>${__path.relative(
__packageRootDir(),
file.path,
)}</cyan>" copied <green>successfully</green> under "<magenta>${__path.relative(
__packageRootDir(),
outPath,
)}</magenta>" in <yellow>${
duration.end().formatedDuration
}</yellow>`,
});
// pass to next file
continue;
} else {
if (params.specificParams) {
for (
let l = 0;
l < Object.keys(params.specificParams).length;
l++
) {
const glob = Object.keys(params.specificParams)[l];
const specificParams = params.specificParams[glob];
if (__minimatch(file.relPath, glob)) {
imgParams = <ISImagesBuilderBuildParams>(
__deepMerge(params, specificParams)
);
// @ts-ignore
imgParams.specific = true;
}
}
}
// remove file
__removeSync(outPath);
// ensure directory
__ensureDirSync(__folderPath(outPath));
// shared manipulations
const imageSize = __imageSize(file.path);
const idealSize = imageSize;
if (imgParams.width && idealSize.width > imgParams.width) {
const percent =
(100 / idealSize.width) * imgParams.width;
idealSize.width = imgParams.width;
idealSize.height = Math.round(
(idealSize.height / 100) * percent,
);
}
if (
imgParams.height &&
idealSize.height > imgParams.height
) {
const percent =
(100 / idealSize.height) * imgParams.height;
idealSize.height = imgParams.height;
idealSize.width = Math.round(
(idealSize.width / 100) * percent,
);
}
const imgsArray = [
{
size: idealSize,
resolution: 1,
outPath,
},
];
for (let k = 0; k < imgParams.resolution.length; k++) {
const resolution = imgParams.resolution[k];
if (resolution === 1) continue;
if (file.extension === 'svg') continue;
imgsArray.push({
size: {
width: idealSize.width * resolution,
height: idealSize.height * resolution,
},
resolution,
outPath: outPath.replace(
/\.([a-zA-Z]+)$/,
`@${resolution}x.$1`,
),
});
}
for (let j = 0; j < imgsArray.length; j++) {
const imgObj = imgsArray[j];
const outputFn =
file.extension === 'jpg' ? 'jpeg' : file.extension;
console.log({
clear: __SLog.isTypeEnabled(__SLog.TYPE_VERBOSE)
? false
: true,
type: __SLog.TYPE_INFO,
// @ts-ignore
value: `<yellow>[compress]</yellow> Compressing file "<cyan>${__path.relative(
__packageRootDir(),
file.path,
)}</cyan>" under "<magenta>${__path.relative(
__packageRootDir(),
imgObj.outPath,
)}</magenta>" ${
imgParams.specific
? ` with <red>specific parameters</red>`
: ''
}`,
});
const duration = new __SDuration();
const img = __sharp(path);
if (!img[outputFn]) {
await img
.resize(imgObj.size)
.toFile(imgObj.outPath);
continue;
}
await img
.resize(imgObj.size)
[outputFn]({
quality: params.quality,
})
.toFile(imgObj.outPath);
const buildedFile = __SFile.new(imgObj.outPath);
buildedStats.bytes += buildedFile.stats.bytes;
filesStack[path].builded.push(buildedFile);
console.log({
clear: __SLog.isTypeEnabled(__SLog.TYPE_VERBOSE)
? false
: true,
type: __SLog.TYPE_INFO,
value: `<green>[compress]</green> File "<cyan>${__path.relative(
__packageRootDir(),
file.path,
)}</cyan>" compressed <green>successfully</green> under "<magenta>${__path.relative(
__packageRootDir(),
imgObj.outPath,
)}</magenta>" in <yellow>${
duration.end().formatedDuration
}</yellow>`,
});
if (params.webp) {
const webpDuration = new __SDuration();
const webpOutPath = imgObj.outPath.replace(
/\.[a-zA-Z0-9]+/,
'.webp',
);
console.log(
`<yellow>[webp]</yellow> Generating webp version of file "<cyan>${__path.relative(
__packageRootDir(),
imgObj.outPath,
)}</cyan>"`,
);
await __sharp(path)
.resize(imgObj.size)
.webp({
quality: params.quality,
})
.toFile(webpOutPath);
const webpFile = __SFile.new(webpOutPath);
webpStats.bytes += webpFile.stats.bytes;
filesStack[path].builded.push(webpFile);
console.log(
`<green>[webp]</green> Webp generation of file "<cyan>${__path.relative(
__packageRootDir(),
imgObj.outPath,
)}</cyan>" finished <green>successfully</green> in <yellow>${
webpDuration.end().formatedDuration
}</yellow>`,
);
}
}
}
}
const buildedGainedBytes = sourceStats.bytes - buildedStats.bytes,
webpFromSourceGainedBytes = sourceStats.bytes - webpStats.bytes,
webpFromBuildedGainedBytes =
buildedStats.bytes - webpStats.bytes;
const result: ISImagesBuilderResult = {
source: {
bytes: sourceStats.bytes.toFixed(2),
kbytes: (sourceStats.bytes * 0.001).toFixed(2),
mbytes: (sourceStats.bytes * 0.000001).toFixed(2),
gbytes: (sourceStats.bytes * 0.00000001).toFixed(2),
},
builded: {
fromSourceGain: {
percentage:
100 -
Math.round(
(100 / sourceStats.bytes) * buildedStats.bytes,
),
bytes: buildedGainedBytes.toFixed(2),
kbytes: (buildedGainedBytes * 0.001).toFixed(2),
mbytes: (buildedGainedBytes * 0.000001).toFixed(2),
gbytes: (buildedGainedBytes * 0.00000001).toFixed(2),
},
bytes: buildedStats.bytes.toFixed(2),
kbytes: (buildedStats.bytes * 0.001).toFixed(2),
mbytes: (buildedStats.bytes * 0.000001).toFixed(2),
gbytes: (buildedStats.bytes * 0.00000001).toFixed(2),
},
webp: {
fromSourceGain: {
percentage:
100 -
Math.round(
(100 / sourceStats.bytes) * webpStats.bytes,
),
bytes: webpFromSourceGainedBytes.toFixed(2),
kbytes: (webpFromSourceGainedBytes * 0.001).toFixed(2),
mbytes: (webpFromSourceGainedBytes * 0.000001).toFixed(
2,
),
gbytes: (
webpFromSourceGainedBytes * 0.00000001
).toFixed(2),
},
fromBuildedGain: {
percentage:
100 -
Math.round(
(100 / buildedStats.bytes) * webpStats.bytes,
),
bytes: webpFromBuildedGainedBytes.toFixed(2),
kbytes: (webpFromBuildedGainedBytes * 0.001).toFixed(2),
mbytes: (webpFromBuildedGainedBytes * 0.000001).toFixed(
2,
),
gbytes: (
webpFromBuildedGainedBytes * 0.00000001
).toFixed(2),
},
bytes: webpStats.bytes.toFixed(2),
kbytes: (webpStats.bytes * 0.001).toFixed(2),
mbytes: (webpStats.bytes * 0.000001).toFixed(2),
gbytes: (webpStats.bytes * 0.00000001).toFixed(2),
},
files: filesStack,
};
console.log(`<green>[success]</green> Images build success!`);
console.log(
`<yellow>[source]</yellow> Sources files : <yellow>${result.source.mbytes}mb</yellow>`,
);
console.log(
`<yellow>[builded]</yellow> Builded files : <yellow>${result.builded.mbytes}mb</yellow>`,
);
console.log(
`<white> </white> : <cyan>-${result.builded.fromSourceGain.percentage}%</cyan> from source`,
);
if (params.webp) {
console.log(
`<yellow>[webp]</yellow> Webp files : <yellow>${result.webp.mbytes}mb</yellow>`,
);
console.log(
`<white> </white> : <cyan>-${result.webp.fromSourceGain.percentage}%</cyan> from source`,
);
console.log(
`<white> </white> : <cyan>-${result.webp.fromBuildedGain.percentage}%</cyan> from builded`,
);
}
console.log(
`<cyan>[info]</cyan> Note that only images at resolution <magenta>1x</magenta> are used for stats...`,
);
resolve(result);
});
}
}
|
8c872ed11489092e3754bd522487c9db05d27596
|
TypeScript
|
pankona/learning-graphql
|
/src/index.ts
| 2.8125
| 3
|
import { ApolloServer } from 'apollo-server'
const typeDefs = `
type Query {
totalPhotos: Int!
}
type Mutation {
postPhoto(name: String! description: String): Boolean!
}
`
type photo = {
name: string
description: string
}
let photos: photo[] = []
const resolvers = {
Query: {
totalPhotos: () => photos.length,
},
Mutation: {
postPhoto(_: any, args: photo) {
photos.push(args)
return true
},
},
}
const server = new ApolloServer({
typeDefs,
resolvers,
})
server
.listen()
.then(({ url }) => console.log(`GraphQL Service running on ${url}`))
|
ca6859ca11824bda85ed834d222fcc83e12db830
|
TypeScript
|
GitRaymond/FinancialDashboard
|
/src/main/webapp/app/shared/model/budget.model.ts
| 2.75
| 3
|
export interface IBudget {
id?: number;
year?: number;
month?: number;
amount?: number;
reportingCategoryId?: number;
}
export class Budget implements IBudget {
constructor(
public id?: number,
public year?: number,
public month?: number,
public amount?: number,
public reportingCategoryId?: number
) {}
}
|
8a5e9e90743d003cf159e5250a1205b253e1a993
|
TypeScript
|
hlpd-pham/meal-prep-tracking
|
/test/fixtures/connection.fixture.ts
| 2.734375
| 3
|
import Knex from 'knex';
import { Tables } from '../../src/database/tables.constants';
import * as knexConfigs from '../../src/database/knexfile';
import { seed as usersSeed } from '../../src/database/seeds/test_data/user.seed';
/** Create a new knex instance for testing */
export const getTestConnection = async () => {
const kn = knexFatory();
return await seedDb(await setupSchema(kn));
};
/** Factory for creating knex connection instance */
export const knexFatory = () => {
return Knex(knexConfigs['test']);
};
/** Close the given Knex connection */
export const closeConnection = async (kn: Knex) => {
kn.destroy();
};
/** Migrates the db to latest migration */
export const setupSchema = async (kn: Knex): Promise<Knex> => {
await kn.migrate.latest();
await truncateDb(kn);
return kn;
};
/** Truncates all test tables for given connection, including
* incrementing ids
*/
export const truncateDb = async (kn: Knex): Promise<Knex> => {
await Promise.all(
Object.values(Tables).map(async table => {
await kn(table).truncate();
await kn.raw(`UPDATE SQLLITE_SEQUENCE SET SEQ=0 WHERE NAME='${table}'`);
}),
);
return kn;
};
/** Executes the given seed functions aginast the given knex connection. */
export const seedDb = async (
kn: Knex,
seeds: ((kn: Knex) => Promise<void>)[] = [usersSeed],
): Promise<Knex> => {
// Ensure usersSeed isn't added twice
const index = seeds.indexOf(usersSeed);
if (index < 0) {
seeds = [...seeds, usersSeed];
}
await Promise.all(
seeds.map(seed => {
return seed(kn);
}),
);
return kn;
};
/** Truncates and reseeds the db for the given connection */
export const refreshDb = async (
kn: Knex,
seeds: ((kn: Knex) => Promise<void>)[] = [],
) => {
await truncateDb(kn);
await seedDb(kn, seeds);
return kn;
};
|
e555c4321f5305301de17f284c1db884e9d3c56e
|
TypeScript
|
alex1278/redux-saga-auth
|
/src/client/constants.ts
| 2.984375
| 3
|
export enum ClientActionType {
CLIENT_SET = 'CLIENT_SET',
CLIENT_UNSET = 'CLIENT_UNSET'
}
export interface ClientSetPayload {
token: Token;
}
export type ClientSetAction = ActionWithPayload<ClientActionType.CLIENT_SET, ClientSetPayload>;
export type ClientUnsetAction = Action<ClientActionType.CLIENT_UNSET>;
export type ClientAction = ClientSetAction | ClientUnsetAction;
export interface ClientState {
id: string | null;
token: Token | null;
}
|
b33afb050bfcea0b3359d7ee048100b5626c4fc5
|
TypeScript
|
packmule/packmule
|
/packages/pack-raw/src/common/pack.ts
| 2.5625
| 3
|
import webpack from 'webpack';
import { merge } from 'webpack-merge';
import { Hints, Options, Pack } from '@packmule/core';
type GenerateArgument = (options: Options, hints: Hints) => webpack.Configuration;
type ProcessArgument = (
configuration: webpack.Configuration,
options?: Options,
hints?: Hints,
) => webpack.Configuration;
interface PackOptions {
generate?: GenerateArgument;
process?: ProcessArgument;
}
export default class RawPack implements Pack {
private options: PackOptions = {};
private configuration: webpack.Configuration = {
plugins: [],
};
public constructor(generate?: GenerateArgument, process?: ProcessArgument) {
this.options.generate = generate;
this.options.process = process;
}
public plugin(plugin: webpack.WebpackPluginInstance): this {
this.configuration.plugins!.push(plugin);
return this;
}
public generate(options: Options, hints: Hints): webpack.Configuration {
const configuration = this.options.generate ? this.options.generate!(options, hints) : {};
return merge(configuration, this.configuration);
}
public process(configuration: webpack.Configuration, options?: Options, hints?: Hints): webpack.Configuration {
return this.options.process ? this.options.process(configuration, options, hints) : configuration;
}
}
|
4b4466445bdd8e5a4350105bc0750a647321aeeb
|
TypeScript
|
HunterGalloway-dev/BuntLang
|
/src/app/Components/game-window/game-window.component.ts
| 2.734375
| 3
|
import { Direction } from './../../BuntLangCompiler/Models/direction';
import { CardinalDirection } from './../../BuntLangCompiler/Enums/cardinal-direction.enum';
import { Player } from './../../BuntLangCompiler/Models/player';
import { createOfflineCompileUrlResolver } from '@angular/compiler';
import { Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import { Cell } from 'src/app/BuntLangCompiler/Enums/cell.enum';
import { GameModel, numCols, numRows } from 'src/app/BuntLangCompiler/Models/game-model';
@Component({
selector: 'app-game-window',
templateUrl: './game-window.component.html',
styleUrls: ['./game-window.component.scss']
})
export class GameWindowComponent implements OnInit {
private gameModel: GameModel = new GameModel();
private cellSize: number = 40;
public width = this.cellSize*numCols;
public height = this.cellSize*numRows;
@ViewChild('canvas', { static: true })
canvas: ElementRef<HTMLCanvasElement>;
private ctx: CanvasRenderingContext2D | null;
constructor() {
}
ngAfterViewInit() {
this.ctx = this.canvas.nativeElement.getContext('2d');
this.canvas.nativeElement.width = this.width;
this.canvas.nativeElement.height = this.height;
this.draw();
}
draw() {
if(this.ctx != null) {
this.ctx.lineWidth = 2;
this.ctx.clearRect(0,0,this.width,this.height);
for(let r = 0; r < numRows; r++) {
for(let c = 0; c < numCols; c++) {
let cell: Cell = this.gameModel.getCellAtLoc([r,c]);
switch(cell) {
case Cell.PLAYER: {
this.ctx.fillStyle = 'red';
break;
} default: {
this.ctx.fillStyle = 'white';
break;
}
}
let x = c*this.cellSize;
let y = r*this.cellSize;
this.drawTriangle(x,y,this.gameModel.getPlayerDirection());
this.ctx.fill
this.ctx.strokeRect(x,y,this.cellSize,this.cellSize);
}
}
this.ctx?.strokeRect(1,1,this.width-2,this.height-2);
}
}
drawTriangle(x: number, y: number, direction: CardinalDirection) {
switch(direction) {
case CardinalDirection.North: {
this.ctx?.beginPath();
this.ctx?.moveTo(x,y+this.cellSize);
this.ctx?.lineTo(x+this.cellSize/2,y);
this.ctx?.lineTo(x+this.cellSize,y+this.cellSize);
this.ctx?.fill();
break;
}
case CardinalDirection.East: {
this.ctx?.beginPath();
this.ctx?.moveTo(x,y+this.cellSize);
this.ctx?.lineTo(x+this.cellSize,y+this.cellSize/2);
this.ctx?.lineTo(x,y);
this.ctx?.fill();
break;
}
case CardinalDirection.West: {
this.ctx?.beginPath();
this.ctx?.moveTo(x+this.cellSize,y);
this.ctx?.lineTo(x,y+this.cellSize/2);
this.ctx?.lineTo(x+this.cellSize,y+this.cellSize);
this.ctx?.fill();
break;
}
case CardinalDirection.South: {
this.ctx?.beginPath();
this.ctx?.moveTo(x+this.cellSize,y);
this.ctx?.lineTo(x+this.cellSize/2,y+this.cellSize);
this.ctx?.lineTo(x,y);
this.ctx?.fill();
break;
}
}
}
turnLeft() {
this.gameModel.turnLeft();
this.update();
}
turnRight() {
this.gameModel.turnRight();
this.update();
}
turn180() {
this.gameModel.turn180();
this.update();
}
move() {
this.gameModel.movePlayer();
this.update();
}
update() {
this.draw();
}
ngOnInit(): void {
}
}
|
f2eee46c83ca95ea4b4baebd9a105cfb4294fc79
|
TypeScript
|
politie/sherlock
|
/src/utils/plain-object-detection.ts
| 3.921875
| 4
|
/**
* Function to test if an object is a plain object, i.e. is constructed
* by the built-in Object constructor or inherits directly from Object.prototype
* or null. Some built-in objects pass the test, e.g. Math which is a plain object
* and some host or exotic objects may pass also.
*
* @param obj the object to test
*/
export function isPlainObject(obj: any): obj is object {
// Basic check for type 'object' that's not null
if (typeof obj !== 'object' || obj == null) {
return false;
}
const proto = Object.getPrototypeOf(obj);
return proto === Object.prototype || proto === null || obj.constructor === Object;
}
|
b68fe1c65298d93a42d15e67394f3814d306459d
|
TypeScript
|
yafeya/ng-platform-app
|
/ng-system-common-app/projects/ng-system-common/src/lib/action/ActionRepository.ts
| 2.953125
| 3
|
import { Action } from './Action';
import * as Collections from '../collections/index';
import { IAction } from './IAction';
export interface IActionRepository {
readonly Actions: Collections.List<IAction>;
Register(action: IAction): IActionRepository;
Find(expression: (action: IAction) => boolean): Collections.IEnumerable<IAction>;
FindOne(name: string): IAction;
}
export class ActionRepository implements IActionRepository {
readonly Actions = new Collections.List<IAction>();
Register(action: IAction): ActionRepository {
if (action) {
this.Actions.Add(action);
}
return this;
}
Find(expression: (action: IAction) => boolean): Collections.IEnumerable<IAction> {
return this.Actions.FindAll(expression);
}
FindOne(name: string): IAction {
return this.Actions.FirstOrDefault(x => x.Name === name);
}
}
|
dd6844bea6297dabf91ea625c75201d3447835fb
|
TypeScript
|
swimos/swim
|
/swim-js/swim-runtime/swim-core/swim-structure/src/main/form/Form.ts
| 3
| 3
|
// Copyright 2015-2023 Swim.inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Lazy} from "@swim/util";
import {AnyItem, Item} from "../Item";
import {AnyValue, Value} from "../Value";
import {TagForm} from "../"; // forward import
import {UnitForm} from "../"; // forward import
import {StringForm} from "../"; // forward import
import {NumberForm} from "../"; // forward import
import {BooleanForm} from "../"; // forward import
import {AnyForm} from "../"; // forward import
import {ItemForm} from "../"; // forward import
import {ValueForm} from "../"; // forward import
/**
* Transformation between a structurally typed [Item] and a nominally typed
* JavaScript object.
* @public
*/
export abstract class Form<T, U = T> {
/**
* Returns the key of the tag attribute that distinguishes structures of this
* `Form`; returns `undefined` if this `Form` has no distinguishing tag
* attribute. Used to accelerate distrcrimination of polymorphic structural
* types with nominal type hints.
*/
declare readonly tag: string | undefined; // getter defined below to work around useDefineForClassFields lunacy
/**
* Returns a version of this `Form` that requires a head [Attr] with the
* given `tag` name.
*/
withTag(tag: string | undefined): Form<T, U> {
if (tag !== void 0 && tag !== this.tag) {
return new TagForm(this, tag);
} else {
return this;
}
}
/**
* Returns a default–possibly `undefined`–value of type `T`. Used as the
* fallback return value when [Item.coerce coercing] an invalid structural
* value.
*/
declare readonly unit: T | undefined; // getter defined below to work around useDefineForClassFields lunacy
/**
* Returns a version of this `Form` with the given `unit` value.
*/
withUnit(unit: T | undefined): Form<T, U> {
if (unit !== this.unit) {
return new UnitForm(this, unit);
} else {
return this;
}
}
/**
* Converts a nominally typed JavaScript `object` into its structurally typed
* equivalent, optionally based on the provided prototype `item`.
*/
abstract mold(object: T | U, item?: Item): Item;
/**
* Converts a structurally typed `item` into a nominally typed JavaScript
* object, optionally based on the provided prototype `object`.
*/
abstract cast(item: Item, object?: T): T | undefined;
@Lazy
static forString(): Form<string> {
return new StringForm("");
}
@Lazy
static forNumber(): Form<number> {
return new NumberForm(0);
}
@Lazy
static forBoolean(): Form<boolean> {
return new BooleanForm(false);
}
@Lazy
static forAny(): Form<AnyItem> {
return new AnyForm(void 0);
}
@Lazy
static forItem(): Form<Item, AnyItem> {
return new ItemForm(Item.absent());
}
@Lazy
static forValue(): Form<Value, AnyValue> {
return new ValueForm(Value.absent());
}
}
Object.defineProperty(Form.prototype, "tag", {
get<T, U>(this: Form<T, U>): string | undefined {
return void 0;
},
configurable: true,
});
Object.defineProperty(Form.prototype, "unit", {
get<T, U>(this: Form<T, U>): T | undefined {
return void 0;
},
configurable: true,
});
|
a949d19d570d7bb89dbe759e1826679df92adc79
|
TypeScript
|
juli-albertengo/entregaPF
|
/src/models/model/user.model.ts
| 2.96875
| 3
|
import { IsInt, IsString, IsEmail, IsNotEmpty } from 'class-validator';
export class User {
@IsNotEmpty()
public fullName: string
@IsNotEmpty()
@IsInt()
public phone: number
@IsNotEmpty()
@IsEmail()
public email: string
public admin: boolean
@IsNotEmpty()
public username: string
@IsNotEmpty()
@IsString()
public password: string
@IsNotEmpty()
@IsString()
public duplicatedPassword: string
constructor(fullName: string, phone: number, email: string, admin: boolean, username: string, password: string, duplicatedPassword: string){
this.fullName = fullName;
this.phone = phone;
this.email = email;
this.admin = admin || false;
this.username = username;
this.password = password;
this.duplicatedPassword = duplicatedPassword;
}
}
//MONGOOSE MODEL
var mongoose = require('mongoose');
const userModel = mongoose.model('Users',{
fullName: {type: String, required: true},
phone: {type: Number, required: true},
email: {type: String, required: true, unique: true},
admin: {type: Boolean, required: true},
username: {type: String, required: true, unique: true},
password: {type: String, required: true}
});
export default userModel;
|
c1437d2e57cb6b6efedd371875f2c6d157da721f
|
TypeScript
|
joelmut/torrent-manager
|
/packages/torrent/src/series/filter.ts
| 2.78125
| 3
|
import { SeriesTorrentMetadata } from "../interfaces";
export function filter(torrents: SeriesTorrentMetadata[]): SeriesTorrentMetadata[] {
return torrents.reduce((acc, val) => {
const inc = acc.some(
(e) => e.episode === val.episode && e.season === val.season
);
if (!inc) {
acc.push(val);
}
return acc;
}, [] as SeriesTorrentMetadata[]);
}
|
5b131769f89a208036eee088eb8354516ad92f03
|
TypeScript
|
alistairvu/reanswers
|
/backend/modules/question/question.model.ts
| 2.53125
| 3
|
import mongoose from "mongoose"
import Answer from "../answer/answer.model"
import Bookmark, { BookmarkSchemaInterface } from "../bookmark/bookmark.model"
import Like from "../like/like.model"
import Tag from "../tag/tag.model"
export interface QuestionSchemaInterface extends mongoose.Document {
title: string
body: string
updates: string
imageUrl: string
tags: mongoose.Types.ObjectId[]
author: mongoose.Types.ObjectId
bookmarks: BookmarkSchemaInterface[]
}
const QuestionSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
body: {
type: String,
},
updates: {
type: String,
default: "",
},
imageUrl: {
type: String,
default: "",
},
tags: {
type: [
{
type: mongoose.Types.ObjectId,
ref: "tag",
},
],
default: [],
},
author: {
type: mongoose.Types.ObjectId,
ref: "user",
required: true,
},
},
{ timestamps: true, toJSON: { virtuals: true }, toObject: { virtuals: true } }
)
QuestionSchema.virtual("answers", {
ref: "answer",
localField: "_id",
foreignField: "question",
})
QuestionSchema.virtual("likes", {
ref: "like",
localField: "_id",
foreignField: "questionId",
justOne: false,
})
QuestionSchema.virtual("bookmarks", {
ref: "bookmark",
localField: "_id",
foreignField: "questionId",
justOne: false,
})
QuestionSchema.virtual("likeCount", {
ref: "like",
localField: "_id",
foreignField: "questionId",
count: true,
})
QuestionSchema.index({ title: "text", body: "text", updates: "text" })
QuestionSchema.pre(
"remove",
async function (this: QuestionSchemaInterface, next: any) {
await Answer.remove({ question: this._id })
await Bookmark.remove({ questionId: this._id })
await Like.remove({ questionId: this._id })
const updateTags = async (id: mongoose.Types.ObjectId) => {
await Tag.findOneAndUpdate({ _id: id }, { $inc: { count: -1 } })
}
const updateTagPromises = []
for (let tag of this.tags) {
updateTagPromises.push(updateTags(tag))
}
await Promise.all(updateTagPromises)
next()
}
)
export default mongoose.model<QuestionSchemaInterface>(
"question",
QuestionSchema
)
|
35a1d51fcf4d4a1c021abdcb710c8435092b2334
|
TypeScript
|
fnpack/fnpack
|
/fnpack/callChain.ts
| 2.921875
| 3
|
import { nameHash } from '../util/hashing'
export interface Callable {
type: string;
}
export interface CodeCallable {
runtime: string;
isMiddleware: boolean;
}
export interface FileDeclarationInformation {
ext: string;
}
export class StaticFile implements Callable {
type = 'staticFile';
public declarationInformation: FileDeclarationInformation;
constructor(private path: string) {}
}
export class Constant implements Callable {
type = 'constant';
public declarationInformation: FileDeclarationInformation;
constructor (public value: any) {
this.declarationInformation = {
ext: '.txt'
}
}
}
export class Lambda implements Callable, CodeCallable {
type = 'lambda';
runtime: string = 'js';
constructor (public lambda: Function, public isMiddleware: boolean = false) {}
}
export class CallableFile implements Callable, CodeCallable {
type = 'callableFile';
name: string;
constructor (
public path: string,
public runtime: string,
public exportName: string = 'default',
public isMiddleware: boolean = false) {
this.name = nameHash(path);
}
}
export class CallChain {
public offset: number = 0;
constructor(public links: Callable[], public name: string = undefined) {}
as (name: string): CallChain {
this.name = name;
return this;
}
concat (chain: CallChain): CallChain {
this.links = this.links.concat(chain.links);
if (chain.name !== undefined) {
this.name = chain.name;
}
return this;
}
}
|
a908444469d1c763494bede9a4a6f0a1df06db76
|
TypeScript
|
mitchellolsthoorn/ASE-Technical-2021-api-linkage-replication
|
/EvoMaster/client-js/evomaster-client-js/src/controller/api/dto/AuthenticationDto.ts
| 3
| 3
|
/**
* To authenticate a user, would need specific settings, like
* specific values in the HTTP headers (eg, cookies)
*/
import HeaderDto from "./HeaderDto";
export default class AuthenticationDto {
/**
* The name given to this authentication info.
* Just needed for display/debugging reasons
*/
public name: string;
/**
* The headers needed for authentication
*/
public headers = new Array<HeaderDto>();
/**
* If the login is based on cookies, need to provide info on
* how to get such a cookie
*/
public cookieLogin: CookieLoginDto;
}
|
67b8abb936c4cb2577722187b4fa1f16d5a01a6f
|
TypeScript
|
artsy/metaphysics
|
/src/lib/hasFieldSelection.ts
| 2.53125
| 3
|
/* eslint-disable require-yield */
import {
FieldNode,
visit,
FragmentDefinitionNode,
BREAK,
GraphQLResolveInfo,
} from "graphql"
import { CursorPageable } from "relay-cursor-paging"
const SELECTION_DEPTH_THRESHOLD = 3
export const hasFieldSelection = (
resolveInfo: GraphQLResolveInfo,
match: (fieldName: string) => boolean
): boolean => {
if (!resolveInfo.fieldNodes) return true
return resolveInfo.fieldNodes.some((rootNode) => {
let matched = false
const visitor = (
fieldNode: FieldNode | FragmentDefinitionNode,
fragments?: { [key: string]: FragmentDefinitionNode }
): void => {
visit(fieldNode, {
Field(node, _key, _parent, path, _ancestors) {
// Stop recursion for nodes deeper than our threshold
if (path.length > SELECTION_DEPTH_THRESHOLD) {
return false
}
if (
path.length === SELECTION_DEPTH_THRESHOLD &&
match(node.name.value)
) {
matched = true
return BREAK
}
},
FragmentSpread(node) {
const fragmentDef = resolveInfo.fragments[node.name.value]
visitor(fragmentDef, fragments)
},
})
}
visitor(rootNode)
return matched
})
}
export const hasIntersectionWithSelectionSet = (
resolveInfo: GraphQLResolveInfo,
fieldNames: string[]
): boolean => {
return hasFieldSelection(resolveInfo, (nodeName) =>
fieldNames.includes(nodeName)
)
}
export const includesFieldsOtherThanSelectionSet = (
resolveInfo: GraphQLResolveInfo,
fieldNames: string[]
): boolean => {
return hasFieldSelection(
resolveInfo,
(nodeName) => !fieldNames.includes(nodeName)
)
}
export const isSkipped = ({ directives, info }) => {
if (!directives || !directives.length) return false
let skipped = false
directives.forEach((directive) => {
if (directive.name.value === "skip") {
directive.arguments &&
directive.arguments.forEach((arg) => {
if (arg.name.value === "if") {
if (arg.value.kind === "Variable") {
const variableName = arg.value.name.value
skipped = info.variableValues[variableName]
} else if (arg.value.kind === "BooleanValue") {
skipped = arg.value.value
}
return
}
})
}
})
return skipped
}
// If there's a nested collection being queried, this will return
// the pagination params. This might be useful in order to de-dupe
// or better batch requests. For instance, two queries only differing
// in pagination params could be consolidated.
// Currently used by `filter_artworks`.
export const parseConnectionArgsFromConnection = (
info: GraphQLResolveInfo,
connectionName: string
) => {
const connectionArgs: CursorPageable = {}
info.fieldNodes &&
info.fieldNodes.forEach((rootNode) => {
const visitor = (
fieldNode: FieldNode | FragmentDefinitionNode,
fragments?: { [key: string]: FragmentDefinitionNode }
): void => {
visit(fieldNode, {
Field(node, _key, _parent, path, _ancestors) {
// Stop recursion for nodes deeper than our threshold
if (path.length > SELECTION_DEPTH_THRESHOLD) {
return
}
if (
path.length === SELECTION_DEPTH_THRESHOLD &&
node.name.value === connectionName
) {
if (isSkipped({ directives: node.directives, info })) return BREAK
node.arguments &&
node.arguments.forEach((arg) => {
if (
["first", "last", "before", "after"].includes(
arg.name.value
)
) {
let val: string
if (arg.value.kind === "Variable") {
const variableName = arg.value.name.value
val = info.variableValues[variableName]
} else if (
arg.value.kind === "IntValue" ||
arg.value.kind === "StringValue"
) {
val = arg.value.value
} else {
val = "0"
}
connectionArgs[arg.name.value] = parseInt(val, 10) || val
}
})
return BREAK
}
},
FragmentSpread(node) {
const fragmentDef = info.fragments[node.name.value]
visitor(fragmentDef, fragments)
},
})
}
visitor(rootNode)
})
return connectionArgs
}
|
c7c4f7886c9512f4c56f5e12de971297b7d2f6d8
|
TypeScript
|
Drumrodri/appimagenmio
|
/backend/src/controllers/usuariosController.ts
| 2.53125
| 3
|
import {Request, Response} from 'express';
import pool from '../database';
class UsuariosController{
index(req:Request, res:Response){
res.json({'message': 'estas en usuarios'});
}
public async create(req:Request, res:Response){
await pool.query('INSERT INTO usuarios SET ?', [req.body]);
res.json({'message': 'se ha insertado correctamente'}); //mensaje que sale por consola cuando se inserta un user
}
public async read(req:Request, res:Response){
const usuarios = await pool.query('SELECT * FROM usuarios', [req.body]);
res.json(usuarios); // metemos en un objeto json lo que nos devuelve la consulta
}
public async update(req:Request, res:Response){
await pool.query('UPDATE usuarios SET ? WHERE id=?', [req.params.id]);
}
public async delete(req:Request, res:Response){
await pool.query('SELECT * FROM usuarios WHERE id=?', [req.params.id]);
}
public async readone(req:Request, res:Response){
const usuarios= await pool.query('SELECT * FROM usuarios WHERE id=?', [req.params.id]);
res.json(usuarios);
}
}
export const usuariosController= new UsuariosController;
|
f0e6fbfbf0c7f4dc560059389dc5921918bbc97b
|
TypeScript
|
Sten-H/report-maker
|
/src/lib/report/createReport.ts
| 2.765625
| 3
|
import { ContractManager, ReportType } from "./ContractManager";
import { ContractMonthMetric, getEventMonth } from "./contract";
import { ContractEvent, MonthMetric } from "./types";
// Draw first of every month on given year
const getDrawDates = (year: string) =>
Array.from(Array(12))
.map((_, i) => i + 1)
.map((i) => new Date(`${year}-${i}-01`).getTime());
const getMonthlyMetrics = (
events: ContractEvent[],
reportType: ReportType
): ContractMonthMetric[] => {
// this is a little hacky, I should look into the events to know the year
const drawDates = getDrawDates("2020");
const manager = new ContractManager(reportType);
const monthlyMetrics = [];
let eventCursor = 0;
for (let i = 0; i < 12; i++) {
let currentEvent = events[eventCursor];
if (currentEvent) {
while (getEventMonth(currentEvent) === i) {
manager.addEvent(currentEvent);
eventCursor += 1;
currentEvent = events[eventCursor];
if (!currentEvent) break;
}
}
const metrics = manager.getMonthlyMetrics(drawDates[i]);
monthlyMetrics.push(metrics);
}
return monthlyMetrics;
};
const aggregateMetrics = (metrics: ContractMonthMetric[]): MonthMetric[] => {
let aggregateActualGross = 0;
const aggregateMetrics: MonthMetric[] = [];
for (let metric of metrics) {
// calculation order is impportant here (due to mutation of aggregateActualGross)
const expectedGross = aggregateActualGross + metric.expectedGross;
aggregateActualGross += metric.monthlyGross;
const monthActualGross = aggregateActualGross;
aggregateMetrics.push({
actualGross: monthActualGross,
expectedGross,
activeContracts: metric.activeContracts,
});
}
return aggregateMetrics;
};
const createReport = (
events: ContractEvent[],
reportType: ReportType
): MonthMetric[] => {
const metrics = getMonthlyMetrics(events, reportType);
return aggregateMetrics(metrics);
};
export default createReport;
|
f9af8eb3743064a7aa14c7a4f6afbeb7b86a6f22
|
TypeScript
|
naren-singamsetti/franks-car-sale
|
/src/app/components/filters/filters.component.ts
| 2.703125
| 3
|
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.scss']
})
export class FiltersComponent {
searchText: string;
modelYearsSelected: number[];
@Output() searchFilters = new EventEmitter();
constructor() {
this.searchText = '';
this.modelYearsSelected = [];
}
/**
* Takes a string and emits an event to parent component
* @param keyword search text
* @returns an object with search text and model years selected
*/
searchCarsWithKeyword(keyword: string): void {
this.searchText = keyword ? keyword.toLowerCase() : '';
this.searchFilters.emit({ searchText: this.searchText, modelYearsSelected: this.modelYearsSelected });
}
/**
* Takes a model years and emits an event to parent component
* @param modelYearFrom Model year from value
* @param modelYearTo search text
* @returns an object with search text and model years selected
*/
searchCarsWithModelYear(modelYearFrom, modelYearTo): void {
this.modelYearsSelected = [modelYearFrom, modelYearTo];
this.searchFilters.emit({ searchText: this.searchText, modelYearsSelected: this.modelYearsSelected });
}
}
|
2b6c66a48d3bae1c439b0dbe77d439fcbf8f3a0d
|
TypeScript
|
Maxximl/express_interior
|
/src/reducers/elements/elements.slice.ts
| 2.75
| 3
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { IAddElement, IDeleteElement, IElementState, ISetPosition, ISetScale, ISetSelectedId } from './elements.types'
const initialState: IElementState = {
elements: {}
};
const elementsSlice = createSlice({
name: 'elements',
initialState,
reducers: {
addElement(state, action: PayloadAction<IAddElement>) {
const { id, name, path, data, selected, position, scale } = action.payload;
state.elements[id] = { id, name, path, selected, position, scale, data };
},
setSelectedId(state, action: PayloadAction<ISetSelectedId>) {
const { id } = action.payload;
if (state.selectedId === id) {
state.selectedId = ""
} else {
state.selectedId = id;
}
},
setPosition(state, action: PayloadAction<ISetPosition>) {
const { id, position } = action.payload;
state.elements[id] = { ...state.elements[id], position };
},
setScale(state, action: PayloadAction<ISetScale>) {
const { id, scale } = action.payload;
state.elements[id] = { ...state.elements[id], scale }
},
deleteElement(state, action: PayloadAction<IDeleteElement>) {
const { id } = action.payload;
for (const elementId in state.elements) {
if (elementId === id) {
delete state.elements[id]
}
}
}
}
})
export const elementsSliceActions = elementsSlice.actions;
export const elementsReducer = elementsSlice.reducer;
|
7f18768aff876974a444fe47b8804f449cfc51ca
|
TypeScript
|
Soluto/tweek-clients
|
/js/tweek-client/src/utils.ts
| 2.515625
| 3
|
import { fetch as globalFetch, Response } from 'cross-fetch';
import qs from 'query-string';
import { FetchClientConfig } from './types';
import { FetchError } from './FetchError';
const createFetchWithTimeout =
(timeoutInMillis: number, fetchFn: typeof fetch): typeof fetch =>
(input: RequestInfo, init?: RequestInit) => {
let timeout: any;
return Promise.race([
fetchFn(input, init),
new Promise<Response>((res) => {
timeout = setTimeout(() => res(new Response(null, { status: 408 })), timeoutInMillis);
}),
])
.then((response) => {
if (timeout) {
clearTimeout(timeout);
}
return response;
})
.catch((error) => {
if (timeout) {
clearTimeout(timeout);
}
throw error;
});
};
export const createFetchClient = ({
fetch = globalFetch,
getAuthenticationToken,
clientId,
clientSecret,
requestTimeoutInMillis = 8000,
onError,
}: FetchClientConfig): ((input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>) => {
const fetchClient = async (input: RequestInfo, init: RequestInit = {}) => {
let authHeaders: Record<string, string> | undefined;
if (getAuthenticationToken) {
const token = await getAuthenticationToken();
authHeaders = { Authorization: `Bearer ${token}` };
} else if (clientId && clientSecret) {
authHeaders = { 'X-Client-Id': clientId, 'X-Client-Secret': clientSecret };
}
try {
const response = await fetch(input, {
...init,
headers: {
...init.headers,
...authHeaders,
},
});
if (onError && !response.ok) {
setImmediate(() => {
try {
onError(new FetchError(response, 'tweek server responded with an error'));
} catch (err) {
onError(err);
}
});
}
return response;
} catch (err) {
onError && onError(err);
throw err;
}
};
if (!requestTimeoutInMillis) {
return fetchClient;
}
return createFetchWithTimeout(requestTimeoutInMillis, fetchClient);
};
export function delay(timeout: number) {
return new Promise((resolve) => setTimeout(resolve, timeout));
}
export const isScanKey = (key: string) => key === '_' || key.endsWith('/_');
export const optimizeInclude = (keys: string[]): string[] => {
let count = 0,
i = 0;
const keysLength = keys.length;
const result = new Array<string>(keysLength);
keys = keys.map(normalizeKeyPath).sort();
const handleKey = (key: string) => {
result[count] = key;
count++;
if (!isScanKey(key)) {
return;
}
const prefixLength = key.length - 1;
const prefix = key.substring(0, prefixLength);
while (i < keysLength) {
const nextKey = keys[i];
if (!nextKey.startsWith(prefix)) {
break;
}
i++;
if (nextKey.includes('/@', prefixLength)) {
handleKey(nextKey);
}
}
};
while (i < keysLength) {
const key = keys[i];
i++;
handleKey(key);
}
result.splice(count);
return result;
};
export const normalizeBaseUrl = (url: string) => {
return url.endsWith('/') ? url.substr(0, url.length - 1) : url;
};
export const normalizeKeyPath = (keyPath: string) => {
return keyPath.startsWith('/') ? keyPath.substr(1) : keyPath;
};
export type InputParams = Record<string, unknown>;
export const toQueryString = (query: InputParams) => {
const queryString = qs.stringify(query);
return queryString ? `?${queryString}` : '';
};
|
3e2d600907d1bf853e2c17bfea5d242bd2515499
|
TypeScript
|
amzinino/engie
|
/back/routes/api/index.ts
| 2.515625
| 3
|
import express, { Request, Response } from 'express';
const router= express.Router()
const getAgencies = (_req: Request,res: Response) => res.json({
data: [
{
type: 'agencies',
id: 1,
attributes: {
name: 'agency1',
desc: 'first agency',
},
links: {
self: `http://localhost:3000/api/agency/1`,
},
},
{
type: 'agencies',
id: 2,
attributes: {
name: 'agency2',
desc: 'second agency',
},
links: {
self: `http://localhost:3000/api/agency/2`,
},
},
{
type: 'agencies',
id: 3,
attributes: {
name: 'agency3',
desc: 'third agency',
},
links: {
self: `http://localhost:3000/api/agency/3`,
},
},
],
links: {
self: "http://example.com/agencies?page[number]=1&page[size]=1",
first: "http://example.com/agencies?page[number]=1&page[size]=1",
prev: "http://example.com/agencies?page[number]=1&page[size]=1",
next: "http://example.com/agencies?page[number]=1&page[size]=1",
last: "http://example.com/agencies?page[number]=13&page[size]=1"
}
});
router.route('/agencies').get(getAgencies)
export default router;
|
e027ff847a1dbec7a318539eec7e9930fa210972
|
TypeScript
|
Sergey-Shamov/mcalc
|
/src/models/input-data.ts
| 2.546875
| 3
|
import { CommonHelper } from './../helpers/сommon-helper';
export class InputData {
public currMoney: number = 1000000; // сейчас в наличии денег
public canPayM: { [month: number]: number } = { 0: 70000 }; // могу платить, в мес
public mortRateY: number = 3; // ставка по ипотеке, % в год
public investRateY: number = 3; // ставка по вкладу, % в год
public propInflationY: number = 2; // удорожание квартиры, % в год
public rentInflationY: number = 2; // удорожание аренды, % в год
public comFeesInflationY: number = 3; // удорожание коммуналки, % в год
public payInflationY: number = 0; // увеличение платежа, % в год
public flatPrice = 7_000_000 //цена квартиры
public get propPriceIn10Years(): number { return CommonHelper.inflateYearly(this.flatPrice, this.propInflationY, 120); }
public get canPayIn10Years(): number { return CommonHelper.inflateYearly(this.canPayM[0], this.payInflationY, 120); }
}
|
004b92a1a0fc72fb8e29c00f8b929d06c6b295b4
|
TypeScript
|
kmerkulov94/engine
|
/src/app/Controllers/KeyboardController.ts
| 2.546875
| 3
|
import {IUserController} from "../interfaces/IUserController";
import {ICanvasData} from "../interfaces/IAssets";
import {Camera} from "../general/Camera";
export class KeyboardController implements IUserController{
setControllerPosition(e: KeyboardEvent, canvas: ICanvasData) {
switch (e.key) {
case 'ArrowDown': {
Camera.moveDown();
break;
}
case 'ArrowUp': {
Camera.moveUp();
break;
}
case 'ArrowLeft': {
Camera.moveLeft();
break;
}
case 'ArrowRight': {
Camera.moveRight();
break;
}
}
}
}
|
b342de399711653c6e0943a4ae82f6a0116d4a2f
|
TypeScript
|
matheusrdelima/gerenciamento-pomar
|
/src/modules/trees/repositories/fakes/FakeGroupTreesRepository.ts
| 2.671875
| 3
|
import IGroupTreesRepository from '@modules/trees/repositories/IGroupTreesRepository';
import IGroupTreeDTO from '@modules/trees/dtos/IGroupTreeDTO';
import GroupTrees from '../../infra/typeorm/entities/GroupTrees';
class FakeGroupTreesRepository implements IGroupTreesRepository {
private groupTrees: GroupTrees[] = [];
public async findAllGroupTrees(): Promise<GroupTrees[]> {
return this.groupTrees;
}
public async findById({
group_id,
tree_id }:
IGroupTreeDTO): Promise<GroupTrees | undefined> {
const groupTree = this.groupTrees.find(groupTree =>
groupTree.group_id === group_id &&
groupTree.tree_id === tree_id);
return groupTree;
}
public async create({ group_id, tree_id }: IGroupTreeDTO): Promise<GroupTrees> {
const groupTree = new GroupTrees();
Object.assign(groupTree, { group_id, tree_id });
this.groupTrees.push(groupTree);
return groupTree;
}
}
export default FakeGroupTreesRepository;
|
2d31330a3e782602ae5fa3884dce2e27aa7f4418
|
TypeScript
|
huaweicloud/huaweicloud-sdk-nodejs-v3
|
/services/oms/v2/model/SourceCdnReq.ts
| 2.671875
| 3
|
export class SourceCdnReq {
private 'authentication_key'?: string;
private 'authentication_type'?: SourceCdnReqAuthenticationTypeEnum | string;
public domain?: string;
public protocol?: SourceCdnReqProtocolEnum | string;
public constructor(authenticationType?: string, domain?: string, protocol?: string) {
this['authentication_type'] = authenticationType;
this['domain'] = domain;
this['protocol'] = protocol;
}
public withAuthenticationKey(authenticationKey: string): SourceCdnReq {
this['authentication_key'] = authenticationKey;
return this;
}
public set authenticationKey(authenticationKey: string | undefined) {
this['authentication_key'] = authenticationKey;
}
public get authenticationKey(): string | undefined {
return this['authentication_key'];
}
public withAuthenticationType(authenticationType: SourceCdnReqAuthenticationTypeEnum | string): SourceCdnReq {
this['authentication_type'] = authenticationType;
return this;
}
public set authenticationType(authenticationType: SourceCdnReqAuthenticationTypeEnum | string | undefined) {
this['authentication_type'] = authenticationType;
}
public get authenticationType(): SourceCdnReqAuthenticationTypeEnum | string | undefined {
return this['authentication_type'];
}
public withDomain(domain: string): SourceCdnReq {
this['domain'] = domain;
return this;
}
public withProtocol(protocol: SourceCdnReqProtocolEnum | string): SourceCdnReq {
this['protocol'] = protocol;
return this;
}
}
/**
* @export
* @enum {string}
*/
export enum SourceCdnReqAuthenticationTypeEnum {
NONE = 'NONE',
QINIU_PRIVATE_AUTHENTICATION = 'QINIU_PRIVATE_AUTHENTICATION',
ALIYUN_OSS_A = 'ALIYUN_OSS_A',
ALIYUN_OSS_B = 'ALIYUN_OSS_B',
ALIYUN_OSS_C = 'ALIYUN_OSS_C',
KSYUN_PRIVATE_AUTHENTICATION = 'KSYUN_PRIVATE_AUTHENTICATION'
}
/**
* @export
* @enum {string}
*/
export enum SourceCdnReqProtocolEnum {
HTTP = 'http',
HTTPS = 'https'
}
|
f030338d6a714de7f276657a33ee21b50808455a
|
TypeScript
|
fredsmit/hello-world
|
/t61.ts
| 2.84375
| 3
|
import { getRequiredNamedForm, getRequiredNamedFormControl, queryRequiredElement } from "./pageUtils.js";
let abortController = new AbortController();
const htmlForm = getRequiredNamedForm("publish");
PublishForm(htmlForm, "http://localhost:8080/publish");
// random url parameter to avoid any caching issues
const subscribeEl = queryRequiredElement(document.body, "div", "subscribe");
SubscribePane(subscribeEl, 'http://localhost:8080/subscribe?random=' + Math.random());
// Sending messages, a simple POST
function PublishForm(form: HTMLFormElement, url: string) {
const messageField = getRequiredNamedFormControl(form, "message", (c): c is HTMLInputElement => c instanceof HTMLInputElement)
function sendMessage(message: string) {
fetch(url, {
method: 'POST',
body: message
});
}
form.onsubmit = function () {
const message = messageField.value;
if (message) {
messageField.value = "";
if (message === "stop") {
abortController.abort();
abortController = new AbortController();
}
else
sendMessage(message);
}
return false;
};
}
// Receiving messages with long polling
function SubscribePane(messagesEl: HTMLElement, url: string) {
function showMessage(message: string) {
const div = document.createElement('div');
div.textContent = message;
messagesEl.append(div);
}
async function subscribe(): Promise<void> {
try {
const response = await fetch(url, { signal: abortController.signal });
if (response.status == 502) {
// Connection timeout
// happens when the connection was pending for too long
// let's reconnect
//await subscribe();
} else if (response.status != 200) {
// Show Error
showMessage(response.statusText);
// Reconnect in one second
await new Promise(resolve => setTimeout(resolve, 1000));
//await subscribe();
} else {
// Got message
const message = await response.text();
showMessage(message);
//await subscribe();
}
} catch (error) {
showMessage("Error:" + String(error));
}
await new Promise(resolve => setTimeout(resolve, 1000));
await subscribe();
}
subscribe();
}
export { };
|
0b5d16d03488ea21a451184c41653eec24ba4f6a
|
TypeScript
|
vcheeze/mammon-manager
|
/pages/api/category/[id].ts
| 2.609375
| 3
|
import { NextApiHandler } from 'next';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
const handler: NextApiHandler = async (req, res) => {
const {
method,
body: { name, color },
query: { id },
} = req;
switch (method) {
case 'PUT': {
if (!name && !color) {
return res
.status(400)
.json({ message: 'No fields to update', success: false });
}
const updatedCategory = await prisma.category.update({
where: { id: +id },
data: { name, color },
});
return res.status(200).json({ data: updatedCategory, success: true });
}
case 'GET': {
try {
const category = await prisma.category.findUnique({
where: { id: +id },
});
return res.status(200).json({ data: category, success: true });
} catch (e) {
return res.status(500).json({ message: e.message });
}
}
case 'DELETE': {
const deletedCategory = await prisma.category.delete({
where: { id: +id },
});
return res.status(200).json({ data: deletedCategory, success: true });
}
default:
res.setHeader('Allow', ['PUT', 'GET', 'DELETE']);
return res
.status(405)
.json({ message: `Method ${method} Not Allowed`, success: false });
}
};
export default handler;
|
d34e1da5e352519fa16569500cd0c00da65eb86c
|
TypeScript
|
jlenoble/tenth
|
/src/sandbox/App3/packages/data-structures/tree/binary-search-tree/binary-search-tree.ts
| 3.171875
| 3
|
import {
Comparator,
defaultCompare,
ComparatorFunction,
} from "../../../comparator";
import { BinarySearchTreeNode } from "./binary-search-tree-node";
import { EmptyBinarySearchTreeNode } from "./empty-binary-search-tree-node";
import {
BinarySearchTreeNode as BinarySearchTreeNodeInterface,
BinarySearchTreeNodeConstructor,
BinarySearchTree as BinarySearchTreeInterface,
} from "./types";
export class BinarySearchTree<T> implements BinarySearchTreeInterface<T> {
#emptyRoot: BinarySearchTreeNodeInterface<T>;
#root: BinarySearchTreeNodeInterface<T>;
#comparator: Comparator<T>;
#size: number;
protected get root(): BinarySearchTreeNodeInterface<T> {
return this.#root;
}
protected set root(node: BinarySearchTreeNodeInterface<T>) {
this.#root = node;
}
get comparator(): Comparator<T> {
return this.#comparator;
}
get size(): number {
return this.#size;
}
*[Symbol.iterator](): IterableIterator<T> {
yield* this.#root;
}
constructor(
values?: Iterable<T>,
compare: ComparatorFunction<T> = defaultCompare,
Node: BinarySearchTreeNodeConstructor<T> = BinarySearchTreeNode
) {
this.#comparator = new Comparator(compare);
this.#size = 0;
this.#emptyRoot = new EmptyBinarySearchTreeNode<T>((value: T) => {
this.#root = new Node(value, this.#comparator);
return this.#root;
}, this.#comparator);
this.#root = this.#emptyRoot;
if (values !== undefined) {
for (const value of values) {
this.insert(value);
}
}
}
isEmpty(): boolean {
return this.#size === 0;
}
insert(value: T): boolean {
return Boolean(this._insert(value));
}
remove(value: T): boolean {
return Boolean(this._remove(value));
}
has(value: T): boolean {
return this.#root.has(value);
}
*dftNodeIterate(): IterableIterator<BinarySearchTreeNodeInterface<T>> {
yield* this.#root.dftNodeIterate() as IterableIterator<
BinarySearchTreeNodeInterface<T>
>;
}
*rdftNodeIterate(): IterableIterator<BinarySearchTreeNodeInterface<T>> {
yield* this.#root.rdftNodeIterate() as IterableIterator<
BinarySearchTreeNodeInterface<T>
>;
}
*bftNodeIterate(): IterableIterator<BinarySearchTreeNodeInterface<T>> {
yield* this.#root.bftNodeIterate() as IterableIterator<
BinarySearchTreeNodeInterface<T>
>;
}
*rbftNodeIterate(): IterableIterator<BinarySearchTreeNodeInterface<T>> {
yield* this.#root.rbftNodeIterate() as IterableIterator<
BinarySearchTreeNodeInterface<T>
>;
}
*dftNodeIterateWithDepth(
depth?: number
): IterableIterator<{
node: BinarySearchTreeNodeInterface<T>;
depth: number;
}> {
yield* this.#root.dftNodeIterateWithDepth(depth) as IterableIterator<{
node: BinarySearchTreeNodeInterface<T>;
depth: number;
}>;
}
*bftNodeIterateWithDepth(
depth?: number
): IterableIterator<{
node: BinarySearchTreeNodeInterface<T>;
depth: number;
}> {
yield* this.#root.bftNodeIterateWithDepth(depth) as IterableIterator<{
node: BinarySearchTreeNodeInterface<T>;
depth: number;
}>;
}
_insert(value: T): BinarySearchTreeNodeInterface<T> | null {
const node = this.#root._insert(value);
if (node !== null) {
this.#size++;
}
return node;
}
_remove(value: T): BinarySearchTreeNodeInterface<T> | null {
if (this.#size > 0) {
const node = this.#root._remove(value);
if (node === this.#root && this.#size === 1) {
this.#root = this.#emptyRoot;
}
if (node !== null) {
this.#size--;
}
return node;
}
return null;
}
toString<N extends BinarySearchTreeNodeInterface<T>, V>(
fn?: (node: N) => V
): string {
return this.#root.toString(fn);
}
}
|
23b6e8efe08f28c6d89bf2ffe9ce593d02d6e4a9
|
TypeScript
|
almeidawarley/Plano-Departamental
|
/View/src/app/perfil/perfil.component.ts
| 2.625
| 3
|
import { Component, OnInit } from '@angular/core';
import { Perfil } from '../perfil';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-perfil',
templateUrl: './perfil.component.html',
styleUrls: ['./perfil.component.css']
})
export class PerfilComponent implements OnInit {
atual : Perfil; // armazena objeto que aparece para o usuário
data : any; // recebe os registros que são retornados da base de dados pela API
modo : string; // Inicial, Cadastrar, Editar, Remover
mensagem : string; // mensagem exibida para o usuário
erro: string;
alerta: string;
constructor(private http: HttpClient) { }
ngOnInit() {
this.mensagem = 'Olá, bem-vindo ao cadastro de perfis!';
this.alerta = 'alert-info';
this.erro = '';
this.atual = new Perfil(0,'','');
this.atualizar();
}
validar(){
/*if (this.atual.codigo.length != 6){
this.erro += "<br> > O campo código deve possuir seis dígitos ";
}
if (this.atual.nome.length < 5){
this.erro += "<br> > O campo nome deve possuir mais que cinco dígitos ";
}
let retorno = this.atual.codigo.length == 6 && this.atual.nome.length >= 5;
return retorno;*/
return true;
}
cancelar(){
this.mensagem = 'Ação de ' + this.modo + ' cancelada';
this.modo = 'Inicial';
this.alerta = 'alert-info';
}
submeter(){
if(this.validar()){
if (this.modo == 'Cadastrar'){
let header = new HttpHeaders();
let self = this;
header.append('Content-Type', 'application/json');
this.http.post<string>('http://127.0.0.1:5000/perfil/0', JSON.stringify(this.atual), {headers: header})
.subscribe(data => {self.atualizar();});
this.mensagem = 'Perfil cadastrado com sucesso!';
this.alerta = 'alert-success';
}
if (this.modo == 'Editar'){
let header = new HttpHeaders();
let self = this;
header.append('Content-Type', 'application/json');
this.http.put<string>('http://127.0.0.1:5000/perfil/0', JSON.stringify(this.atual), {headers: header})
.subscribe(data => {self.atualizar();});
this.mensagem = 'Perfil editado com sucesso!';
this.alerta = 'alert-success';
}
if (this.modo == 'Remover'){
let header = new HttpHeaders();
let self = this;
header.append('Content-Type', 'application/json');
this.http.delete<string>('http://127.0.0.1:5000/perfil' + '/' + this.atual.codigo, {headers: header})
.subscribe(data => {self.atualizar();});
this.mensagem = 'Perfil removido com sucesso!';
this.alerta = 'alert-success';
}
}else{
this.erro = "Erro na validação dos dados! Por favor, corrija os seguintes campos:" + this.erro;
}
}
atualizar(){
this.modo = 'Inicial';
this.http.get('http://127.0.0.1:5000/perfil')
.subscribe(data => {this.data = data['mensagem'];});
}
cadastrar(){
this.modo = 'Cadastrar';
this.mensagem = 'Cadastro em processo';
this.alerta = 'alert-warning';
this.atual.atualizar(0,'','');
}
editar(registro){
this.modo = 'Editar';
this.mensagem = 'Edição em processo';
this.alerta = 'alert-warning';
this.atual.atualizar(registro['codigo'], registro['perfilNome'], registro['abreviacao']);
}
remover(registro){
this.modo = 'Remover';
this.mensagem = 'Remoção em processo';
this.alerta = 'alert-warning';
this.atual.atualizar(registro['codigo'], registro['perfilNome'], registro['abreviacao']);
}
conferir(palavra){
if(palavra == 'exibirCodigo'){
return (this.modo == 'Editar');
}
if(palavra == 'mostrarFormulario'){
return (this.modo == 'Cadastrar' || this.modo == 'Editar' || this.modo == 'Remover');
}
if(palavra == 'editarCodigo'){
return (this.modo == 'Cadastrar');
}
if(palavra == 'editarFormulario'){
return (this.modo == 'Cadastrar' || this.modo == 'Editar');
}
if(palavra == 'mostrarAviso'){
return this.data == undefined;
}
}
}
|
1a8f1fa7070d232be1dc97ae850dcea804bf525c
|
TypeScript
|
zimberzimber/game-project
|
/src/main/Components/Hitboxes/HitboxCircle.ts
| 2.5625
| 3
|
import { HitboxBase } from "./HitboxBase";
import { TriggerState, HitboxType } from "../../Models/CollisionModels";
import { EntityBase } from "../../Entities/EntityBase";
import { Vec2Utils } from "../../Utility/Vec2";
import { ScalarUtil } from "../../Utility/Scalar";
import { DebugDrawColors } from "../../Models/GenericInterfaces";
export class HitboxCircle extends HitboxBase {
readonly HitboxType: HitboxType = HitboxType.Circular;
private _radius: number;
constructor(parent: EntityBase, radius: number) {
super(parent);
this._radius = radius;
this.CalculateBoundingRadius();
}
protected CalculateBoundingRadius(): void {
this._boundingRadius = this._radius;
}
get Radius(): number { return this._radius; }
set Radius(radius: number) {
this._radius = radius;
this.CalculateBoundingRadius();
}
get DebugDrawData(): number[] | null {
const absTransform = this._parent.WorldRelativeTransform;
const radius = (absTransform.Scale[0] + absTransform.Scale[1]) / 2 * this._radius;
const color = this.TriggerState == TriggerState.NotTrigger ? DebugDrawColors.Hitbox : DebugDrawColors.HitboxTrigger;
const vertexes: number[] = [];
for (let i = 0; i < 360 / 4; i++) {
const pos = Vec2Utils.Sum(absTransform.Position, Vec2Utils.RotatePoint([radius, 0], ScalarUtil.ToRadian(i * 4)));
vertexes.push(...pos, ...color);
}
return vertexes;
}
}
|
97fdb1095af07f4bbcc3b9dc2791727407587635
|
TypeScript
|
ULL-ESIT-INF-DSI-2021/ull-esit-inf-dsi-20-21-prct09-async-fs-process-alu0101021768
|
/tests/ejercicio-04.spec.ts
| 2.890625
| 3
|
import 'mocha';
import {expect} from 'chai';
import {execSync} from 'child_process';
const test = (args: string): string => {
return execSync(`node dist/ejercicio-04.js ${args}`)
.toString();
};
const openError = 'Error opening the file/directory: Unexisting path\n';
const removeError = 'Error removing the file/directory: Unexisting path\n';
describe('Ejercicio 4 - Tests', () => {
describe('Identify command', () => {
it(`test('identify --path=notapath') should return ${openError}`, () => {
expect(test('identify --path=notapath')).to.equal(openError);
});
it(`test('identify --path=src') should return 'src is a directory'`,
() => {
expect(test('identify --path=src')).to.equal('src is a directory\n');
});
it(`test('identify --path=file') should return 'file is a file'`,
() => {
execSync('touch file');
expect(test('identify --path=file')).to.equal('file is a file\n');
execSync('rm file');
});
});
describe('Create command', () => {
it(`test('create --path=newPath') should return 'Directory newPath` +
` created succesfully\n' `, () => {
expect(test('create --path=newPath')).to
.equal('Directory newPath created succesfully\n');
});
it(`test('create --path=newPath') should return 'Cannot create the ` +
`directory newPath: Already exists\n `, () => {
expect(test('create --path=newPath')).to
.equal('Cannot create the directory newPath: Already exists\n');
execSync('rmdir newPath');
});
});
describe('List command', () => {
it(`test('list --path=notapath') should return 'Error opening the ` +
`directory: Unexisting path\n'`, () => {
expect(test('list --path=notapath')).to
.equal('Error opening the directory: Unexisting path\n');
});
it(`test('list --path=./src/teacher') should return ` +
`'Nestor note\nNew Nestor note\n'`, () => {
expect(test('list --path=./src/teacher')).to
.equal('Nestor note\nNew Nestor note\n');
});
});
describe('Show command', () => {
it(`test('show --path=hello') should return 'Error opening the ` +
`file: Unexisting path\n'`, () => {
expect(test('show --path=hello')).to
.equal('Error opening the file: Unexisting path\n');
});
it(`test('show --path=helloworld.txt') should return ` +
` 'Hola, \nmundo.\n¿Que tal?\n'`, () => {
expect(test('show --path=helloworld.txt')).to
.equal('Hola, \nmundo.\n¿Que tal?\n');
});
});
describe('Remove command', () => {
it(`test('remove --path=hello') should return ${removeError}`, () => {
expect(test('remove --path=hello')).to.equal(removeError);
});
it(`test('remove --path=hello') should return ` +
`'File hello deleted succesfully.\n'`, () => {
execSync('touch hello');
expect(test('remove --path=hello')).to
.equal('File hello deleted succesfully.\n');
});
it(`test('remove --path=hello') should return ` +
`'File hello deleted succesfully.\n'`, () => {
execSync('mkdir hello');
expect(test('remove --path=hello')).to
.equal('Directory hello deleted succesfully.\n');
});
});
describe('Move command', () => {
it(`test('move --origin=hello --destiny=halo') should return ` +
`'Error moving/copying the file/directory: Unexisting path\n'`,
() => {
expect(test('move --origin=hello --destiny=halo')).to
.equal('Error moving/copying the file/directory: Unexisting path\n');
});
it(`test('move --origin=content --destiny=sameContent') should return ` +
`'Content copied succesfully!\n'`,
() => {
execSync('mkdir content');
execSync('touch content/file1 content/file2');
expect(test('move --origin=content --destiny=sameContent')).to
.equal('Content copied succesfully!\n');
execSync('rm -r content');
execSync('rm -r sameContent');
});
it(`test('move --origin=file.txt --destiny=samefile.txt') should return ` +
`'File moved succesfully!\n'`,
() => {
execSync('touch file.txt');
expect(test('move --origin=file.txt --destiny=samefile.txt')).to
.equal('File moved succesfully!\n');
execSync('rm samefile.txt');
});
});
});
|
14b651bb47e6fe63197417c0c09ad49d6a01ecba
|
TypeScript
|
imldresden/vistiles
|
/server/utility/math.ts
| 3.171875
| 3
|
// Source: code from http://stackoverflow.com/questions/27205018/multiply-2-matrices-in-javascript
export function multiplyMatrices(m1, m2) {
var result = [];
for (var i = 0; i < m1.length; i++) {
result[i] = [];
for (var j = 0; j < m2[0].length; j++) {
var sum = 0;
for (var k = 0; k < m1[0].length; k++) {
sum += m1[i][k] * m2[k][j];
}
result[i][j] = sum;
}
}
return result;
}
//exports.multiplyMatrices = multiplyMatrices;
export function quaternionToEuler(quaternion) {
var w = quaternion[3];
var x = quaternion[0];
var y = quaternion[1];
var z = quaternion[2];
var sqx = x * x;
var sqy = y * y;
var sqz = z * z;
var rotX = Math.atan2(2 * (y * w - x * z), 1 - 2 * (sqy + sqz));
var rotY = Math.asin(2 * ( x * y + z * w));
var rotZ = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * (sqx + sqz));
return [rotX, rotY, rotZ];
}
//exports.quaternionToEuler = quaternionToEuler;
export function degreeToRadian (degree) {
return degree * (Math.PI / 180);
}
//exports.degreeToRadian = degreeToRadian;
export function radianToDegree (radian) {
return radian * (180/Math.PI);
}
//exports.radianToDegree = radianToDegree;
|
de5e26d618d5a96623759da85ca81fb0dd07bf79
|
TypeScript
|
warrenxxx/comping
|
/src/app/app.component.ts
| 2.921875
| 3
|
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
texto2="";
texto: String = 'for int';
salida = [];
act(x){
this.salida=[]
console.log(this.texto)
this.goatr()
};
goatr() {
this.texto=this.texto2;
let i = 1, j = 1;
while (i < this.texto.length) {
j = this.getMaxVariable(this.texto);
if (j > 1) {
let palabra = this.texto.substr(0, j);
if (this.palabrasr.indexOf(palabra) != -1)
this.salida.push({tok: palabra, typo: 'recervada'});
else
this.salida.push({tok: palabra, typo: 'variable'});
this.texto = this.texto.substr(j, this.texto.length);
continue;
}
if (this.getMaxNumer(this.texto) >= 1) {
j = this.getMaxNumer(this.texto);
this.salida.push({tok: this.texto.substr(0, j), typo: 'numero'});
this.texto = this.texto.substr(j, this.texto.length);
continue;
} else if (this.operadores.indexOf(this.texto[0]) != -1) {
this.salida.push({tok: this.texto[0], typo: 'operador'});
} else if (this.delimitadores.indexOf(this.texto[0]) != -1) {
this.salida.push({tok: this.texto[0], typo: 'delimitador'});
}
console.log(j);
this.texto = this.texto.substr(1, this.texto.length);
console.log(this.texto);
}
console.log(this.texto);
console.log(this.salida);
}
getMaxVariable(x) {
let k = 2 ;
let res = '';
while (k < x.length && this.isVariable(x.substr(0, k))) {
k++;
}
if (k == 2) return 0;
if (k == x.length)
return k;
return k - 1;
}
getMaxNumer(x) {
let k = 1;
let res = '';
console.log("waaaaa" ,this.isNumber("4564"))
while (k < x.length && this.isNumber(x.substr(0, k))) {
k++;
}
if (k == 2) return 0;
if (k == x.length)
return k;
return k - 1;
}
getMaxPalabraRecervada(x) {
for (let i of this.palabrasr) {
if (i == x.substr(0, i.length))
return i.length;
}
return 0;
}
isletra(x) {
if ((x[0] >= 'a' && x[0] <= 'z') || (x[0] >= 'A' && x[0] <= 'Z'))
return true;
else return false;
}
isNumber(x) {
for (let i of x)
if ((i < '0' || i > '9'))
return false;
return true;
}
isVariable(x) {
console.log('---', x);
if (x.length < 2) return false;
if (!this.isletra(x[0])) return false;
if (x.slice(-1)[0] == '.' || x.slice(-1)[0] == '_') return false;
for (let i of x) {
if (!this.isletra(i) && !this.isNumber(i) && i != '.' && i != '_')
return false;
}
return true;
}
operadores = ['*', '/', '-', '+'];
delimitadores = ['{', '}', '[', ']', '(', ')'];
palabrasr = [
'abstract',
'assert',
'boolean',
'break',
'byte',
'case',
'catch',
'char',
'class',
'const',
'continue',
'default',
'do',
'double',
'else',
'enum',
'extends',
'final',
'finally',
'float',
'for',
'goto',
'if',
'implements',
'import',
'instanceof',
'int',
'interface',
'long',
'native',
'new',
'package',
'private',
'protected',
'public',
'return',
'short',
'static',
'strictfp',
'super',
'switch',
'synchronized',
'this',
'throw',
'throws',
'transient',
'try',
'void',
'volatile',
'while'
];
}
interface Interface {
token;
tipo;
}
|
6692818ed3c04c6d66dc38fc425a1652551ff735
|
TypeScript
|
ritvik122/FIT2095-S2-2019
|
/Week 10/Lab Task/src/app/actor/actor.component.ts
| 2.71875
| 3
|
import {
Component,
OnInit
} from '@angular/core';
import {
DatabaseService
} from "../database.service";
import {
stringify
} from 'querystring';
@Component({
selector: 'app-actor',
templateUrl: './actor.component.html',
styleUrls: ['./actor.component.css']
})
export class ActorComponent implements OnInit {
section = 1;
actorsDB: any[] = [];
moviesDB: any[] = [];
movieFullName: string = "";
productionYear: number = 0;
fullName: string = "";
bYear: number = 0;
actorId;
movieId;
deleteYear: number = 0;
nameOfTheMovie: string = "";
nameOfTheActor: string = "";
constructor(private dbService: DatabaseService) {}
ngOnInit() {}
// Function to change the value of the section variable
changeSection(sectionId) {
this.section = sectionId;
}
////////////////////////////////////// Functions for the actors ////////////////////////////////////
// Function to save all the actors in a database
// Since the output of the getActors() happens to be an observable so we have to subscribe to it
onGetActors() {
this.dbService.getActors().subscribe((data: any[]) => {
this.actorsDB = data;
});
}
// Function to save the actor
// On saving the current actor, we are calling the onGetActors function to display all the actors in the table format
onSaveActor() {
let obj = {
name: this.fullName,
bYear: this.bYear
};
this.dbService.createActor(obj).subscribe(result => {
this.onGetActors();
});
}
// Function to get all the details of the selected actor and assign those details to the global variable
onSelectUpdate(item) {
this.fullName = item.name;
this.bYear = item.bYear;
this.actorId = item._id;
}
// Function to update the details of the selected actor
onUpdateActor() {
let obj = {
name: this.fullName,
bYear: this.bYear
};
this.dbService.updateActor(this.actorId, obj).subscribe(result => {
this.onGetActors();
});
}
// Function to delete an actor
onDeleteActor(item) {
this.dbService.deleteActor(item._id).subscribe(result => {
this.onGetActors();
});
}
// Function to reset the values of all the variables
resetValues() {
this.fullName = "";
this.bYear = 0;
this.actorId = "";
}
////////////////////////////////////// Functions for the Movies ////////////////////////////////////
// Function to save all the actors in a database
// Since the output of the getActors() happens to be an observable so we have to subscribe to it
onGetMovies() {
this.dbService.getMovies().subscribe((data: any[]) => {
this.moviesDB = data;
});
}
// Function to save the actor
// On saving the current actor, we are calling the onGetActors function to display all the actors in the table format
onSaveMovie() {
let obj = {
title: this.movieFullName,
year: this.productionYear
};
this.dbService.createMovie(obj).subscribe(result => {
this.onGetMovies();
});
}
// Function to delete an actor
onDeleteMovie(item) {
this.dbService.deleteMovie(item._id).subscribe(result => {
this.onGetMovies();
});
}
// Function to delete a year produced before the specified year
deleteAsPerSpecificYear() {
let idCollection = [];
// Getting the ids of all those movies which are to be deleted
for (let i = 0; i < this.moviesDB.length; i++) {
if (this.moviesDB[i].year < this.deleteYear) {
idCollection.push(this.moviesDB[i].year);
}
}
// Deleting all those movies produced before the speicified year
let totalLength = idCollection.length;
for (let j = 0; j < totalLength; j++) {
let currentMovieYear = idCollection[j];
for (let k = 0; k < this.moviesDB.length; k++) {
if (this.moviesDB[k].year === currentMovieYear) {
this.onDeleteMovie(this.moviesDB[k]);
break;
}
}
}
}
// Function to add Actor to Movie
addActorToMovie() {
let firstFlag = false;
let movieIndex = 0;
let actorIndex = 0;
// Checking whether the given movie exist or not
for (let j = 0; j < this.moviesDB.length; j++) {
if (this.nameOfTheMovie === this.moviesDB[j].title) {
movieIndex = j;
for (let i = 0; i < this.actorsDB.length; i++) {
if (this.nameOfTheActor === this.actorsDB[i].name) {
actorIndex = i;
firstFlag = true;
break;
}
}
}
}
if (firstFlag === true) {
this.moviesDB[movieIndex].actors.push(this.actorsDB[actorIndex]._id);
this.dbService.updateMovie(this.moviesDB[movieIndex]._id, this.moviesDB[movieIndex]).subscribe(result => {
this.onGetMovies();
});
} else {
alert("Invalid Actor/Movie entered !");
}
}
// Function to add Actor to Movie
addMovieToActor() {
let firstFlag = false;
let actorIndex = 0;
let movieIndex = 0;
// Checking whether the given movie exist or not
for (let j = 0; j < this.actorsDB.length; j++) {
if (this.nameOfTheActor === this.actorsDB[j].name) {
actorIndex = j;
for (let i = 0; i < this.moviesDB.length; i++) {
if (this.nameOfTheMovie === this.moviesDB[i].title) {
movieIndex = i;
firstFlag = true;
break;
}
}
}
}
if (firstFlag === true) {
this.actorsDB[actorIndex].movies.push(this.moviesDB[movieIndex]._id);
this.dbService.updateActor(this.actorsDB[actorIndex]._id, this.actorsDB[actorIndex]).subscribe(result => {
this.onGetActors();
});
} else {
alert("Invalid Actor/Movie entered !");
}
}
}
|