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
|
|---|---|---|---|---|---|---|
cf3c5375454703eef311a5e16e75c05afd07abf4
|
TypeScript
|
nmalyschkin/machine-map-demo
|
/src/eventSource.ts
| 2.921875
| 3
|
/**
* @param handleNewEvent
* @returns {function} cleanup function, to close the event source
*/
export default (handleNewEvent: (event) => {}) => {
const ws = new WebSocket("ws://machinestream.herokuapp.com/api/v1/events/websocket?vsn=2.0.0");
ws.onopen = () => ws.send('["1", "1", "events", "phx_join", {}]');
const clearInt = (() => {
let counter = 2;
const interval = setInterval(() => {
ws.send(`[null, "${counter++}", "phoenix", "heartbeat", {}]`);
}, 25_000);
return () => clearInterval(interval);
})();
ws.onmessage = (msg) => {
let data;
try {
data = JSON.parse(msg.data);
} catch (error) {
// unexpected msg data
return;
}
if (data[2] === "events" && data[3] === "new") handleNewEvent(data[4]);
};
return () => {
clearInt();
ws.close();
};
};
|
ca9033e7bfa0cc1264319182d38d31b5a694d1d5
|
TypeScript
|
cxwithyxy/tjb
|
/inject_js_lib/touch_emulator.ts
| 2.625
| 3
|
export = {
"touch_emulator_init": () =>
{
// 从别人的库中偷回来的代码
// https://github.com/hammerjs/touchemulator
// 能用就行了不是吗
// 还要我搞一堆any包裹起来
// 真的烦为啥别人不用typescript写
var isMultiTouch = false;
var multiTouchStartPos: any;
var eventTarget: any;
var touchElements = {};
// polyfills
if(!(<any>document).createTouch) {
(<any>document).createTouch = function(view: any, target: any, identifier: any, pageX: any, pageY: any, screenX: any, screenY: any, clientX: any, clientY: any) {
// auto set
if(clientX == undefined || clientY == undefined) {
clientX = pageX - window.pageXOffset;
clientY = pageY - window.pageYOffset;
}
return new (<any>Touch)(target, identifier, {
pageX: pageX,
pageY: pageY,
screenX: screenX,
screenY: screenY,
clientX: clientX,
clientY: clientY
});
};
}
if(!(<any>document).createTouchList) {
(<any>document).createTouchList = function() {
var touchList = new (<any>TouchList)();
for (var i = 0; i < arguments.length; i++) {
touchList[i] = arguments[i];
}
touchList.length = arguments.length;
return touchList;
};
}
/**
* create an touch point
* @constructor
* @param target
* @param identifier
* @param pos
* @param deltaX
* @param deltaY
* @returns {Object} touchPoint
*/
class Touch
{
identifier: any
target: any
clientX: any
clientY: any
screenX: any
screenY: any
pageX: any
pageY: any
constructor(target: any, identifier: any, pos: any, deltaX: any, deltaY: any)
{
deltaX = deltaX || 0;
deltaY = deltaY || 0;
this.identifier = identifier;
this.target = target;
this.clientX = pos.clientX + deltaX;
this.clientY = pos.clientY + deltaY;
this.screenX = pos.screenX + deltaX;
this.screenY = pos.screenY + deltaY;
this.pageX = pos.pageX + deltaX;
this.pageY = pos.pageY + deltaY;
}
}
/**
* create empty touchlist with the methods
* @constructor
* @returns touchList
*/
class TouchList extends Array
{
item(index: any)
{
return this[index] || null;
}
identifiedTouch(id: any)
{
return this[id + 1] || null;
}
}
/**
* Simple trick to fake touch event support
* this is enough for most libraries like Modernizr and Hammer
*/
function fakeTouchSupport() {
var objs = [<any>window, document.documentElement];
var props = ['ontouchstart', 'ontouchmove', 'ontouchcancel', 'ontouchend'];
for(var o=0; o<objs.length; o++) {
for(var p=0; p<props.length; p++) {
if(objs[o] && objs[o][props[p]] == undefined) {
objs[o][props[p]] = null;
}
}
}
}
/**
* we don't have to emulate on a touch device
* @returns {boolean}
*/
function hasTouchSupport() {
return false
}
/**
* disable mouseevents on the page
* @param ev
*/
function preventMouseEvents(ev: any) {
ev.preventDefault();
ev.stopPropagation();
}
/**
* only trigger touches when the left mousebutton has been pressed
* @param touchType
* @returns {Function}
*/
function onMouse(touchType: any) {
return function(ev: any) {
// prevent mouse events
preventMouseEvents(ev);
if (ev.which !== 1) {
return;
}
// The EventTarget on which the touch point started when it was first placed on the surface,
// even if the touch point has since moved outside the interactive area of that element.
// also, when the target doesnt exist anymore, we update it
if (ev.type == 'mousedown' || !eventTarget || (eventTarget && !eventTarget.dispatchEvent)) {
eventTarget = ev.target;
}
// shiftKey has been lost, so trigger a touchend
if (isMultiTouch && !ev.shiftKey) {
triggerTouch('touchend', ev);
isMultiTouch = false;
}
triggerTouch(touchType, ev);
// we're entering the multi-touch mode!
if (!isMultiTouch && ev.shiftKey) {
isMultiTouch = true;
multiTouchStartPos = {
pageX: ev.pageX,
pageY: ev.pageY,
clientX: ev.clientX,
clientY: ev.clientY,
screenX: ev.screenX,
screenY: ev.screenY
};
triggerTouch('touchstart', ev);
}
// reset
if (ev.type == 'mouseup') {
multiTouchStartPos = null;
isMultiTouch = false;
eventTarget = null;
}
}
}
/**
* trigger a touch event
* @param eventName
* @param mouseEv
*/
function triggerTouch(eventName: any, mouseEv: any) {
var touchEvent = <any>document.createEvent('Event');
touchEvent.initEvent(eventName, true, true);
touchEvent.altKey = mouseEv.altKey;
touchEvent.ctrlKey = mouseEv.ctrlKey;
touchEvent.metaKey = mouseEv.metaKey;
touchEvent.shiftKey = mouseEv.shiftKey;
touchEvent.touches = getActiveTouches(mouseEv, eventName);
touchEvent.targetTouches = getActiveTouches(mouseEv, eventName);
touchEvent.changedTouches = getChangedTouches(mouseEv, eventName);
eventTarget.dispatchEvent(touchEvent);
}
/**
* create a touchList based on the mouse event
* @param mouseEv
* @returns {TouchList}
*/
function createTouchList(mouseEv: any) {
var touchList = new TouchList();
if (isMultiTouch) {
var f = TouchEmulator.multiTouchOffset;
var deltaX = multiTouchStartPos.pageX - mouseEv.pageX;
var deltaY = multiTouchStartPos.pageY - mouseEv.pageY;
touchList.push(new Touch(eventTarget, 1, multiTouchStartPos, (deltaX*-1) - f, (deltaY*-1) + f));
touchList.push(new Touch(eventTarget, 2, multiTouchStartPos, deltaX+f, deltaY-f));
} else {
touchList.push(new Touch(eventTarget, 1, mouseEv, 0, 0));
}
return touchList;
}
/**
* receive all active touches
* @param mouseEv
* @returns {TouchList}
*/
function getActiveTouches(mouseEv: any, eventName: any) {
// empty list
if (mouseEv.type == 'mouseup') {
return new TouchList();
}
var touchList = createTouchList(mouseEv);
if(isMultiTouch && mouseEv.type != 'mouseup' && eventName == 'touchend') {
touchList.splice(1, 1);
}
return touchList;
}
/**
* receive a filtered set of touches with only the changed pointers
* @param mouseEv
* @param eventName
* @returns {TouchList}
*/
function getChangedTouches(mouseEv: any, eventName: any) {
var touchList = createTouchList(mouseEv);
// we only want to return the added/removed item on multitouch
// which is the second pointer, so remove the first pointer from the touchList
//
// but when the mouseEv.type is mouseup, we want to send all touches because then
// no new input will be possible
if(isMultiTouch && mouseEv.type != 'mouseup' &&
(eventName == 'touchstart' || eventName == 'touchend')) {
touchList.splice(0, 1);
}
return touchList;
}
/**
* show the touchpoints on the screen
*/
function showTouches(ev: any) {
var touch, i, el, styles;
// first all visible touches
for(i = 0; i < ev.touches.length; i++) {
touch = ev.touches[i];
el = (<any>touchElements)[touch.identifier];
if(!el) {
el = (<any>touchElements)[touch.identifier] = document.createElement("div");
document.body.appendChild(el);
}
styles = TouchEmulator.template(touch);
for(var prop in styles) {
el.style[prop] = (<any>styles)[prop];
}
}
// remove all ended touches
if(ev.type == 'touchend' || ev.type == 'touchcancel') {
for(i = 0; i < ev.changedTouches.length; i++) {
touch = ev.changedTouches[i];
el = (<any>touchElements)[touch.identifier];
if(el) {
el.parentNode.removeChild(el);
delete (<any>touchElements)[touch.identifier];
}
}
}
}
/**
* TouchEmulator initializer
*/
function TouchEmulator() {
if (hasTouchSupport()) {
return;
}
fakeTouchSupport();
window.addEventListener("mousedown", onMouse('touchstart'), true);
window.addEventListener("mousemove", onMouse('touchmove'), true);
window.addEventListener("mouseup", onMouse('touchend'), true);
window.addEventListener("mouseenter", preventMouseEvents, true);
window.addEventListener("mouseleave", preventMouseEvents, true);
window.addEventListener("mouseout", preventMouseEvents, true);
window.addEventListener("mouseover", preventMouseEvents, true);
// it uses itself!
window.addEventListener("touchstart", showTouches, true);
window.addEventListener("touchmove", showTouches, true);
window.addEventListener("touchend", showTouches, true);
window.addEventListener("touchcancel", showTouches, true);
}
// start distance when entering the multitouch mode
TouchEmulator.multiTouchOffset = 75;
/**
* css template for the touch rendering
* @param touch
* @returns object
*/
TouchEmulator.template = function(touch: any) {
var size = 30;
var transform = 'translate('+ (touch.clientX-(size/2)) +'px, '+ (touch.clientY-(size/2)) +'px)';
return {
position: 'fixed',
left: 0,
top: 0,
background: '#fff',
border: 'solid 1px #999',
opacity: .6,
borderRadius: '100%',
height: size + 'px',
width: size + 'px',
padding: 0,
margin: 0,
display: 'block',
overflow: 'hidden',
pointerEvents: 'none',
webkitUserSelect: 'none',
mozUserSelect: 'none',
userSelect: 'none',
webkitTransform: transform,
mozTransform: transform,
transform: transform,
zIndex: 100
}
};
TouchEmulator();
}
}
|
f3280a8fb65f6bbfc377c9a847b73e5c17ac996b
|
TypeScript
|
dapriett/media-viewer
|
/projects/media-viewer/src/lib/annotations/services/tags/tags.services.ts
| 2.75
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { TagItemModel } from '../../models/tag-item.model';
@Injectable()
export class TagsServices {
public tagItems: {[id: string]: TagItemModel[]};
constructor(private http: HttpClient) {}
public getAllTags(createdBy): Observable<TagItemModel[]> {
const url = `/em-anno/tags/${createdBy}`;
return this.http.get<TagItemModel[]>(url);
}
getTagItems(annoid): TagItemModel[] {
return this.tagItems ? this.tagItems[annoid] : [];
}
updateTagItems(items, annoId) {
const snakeCased = items.map(item => {
return {
...item,
name: this.snakeCase(item.name)
};
});
this.tagItems = {
...this.tagItems,
[annoId]: snakeCased
};
}
private snakeCase = string => {
// transform string_to_snake_case
return string.replace(/\W+/g, " ") // find space
.split(/ |\B(?=[A-Z])/) // split it into array
.map(word => word.toLowerCase()) // transform to lover case
.join('_'); // trun array into sting using _
};
}
|
313a83a25fc7f0dd08ef0c03dc62d8622611368a
|
TypeScript
|
leipzig/fcs_upbrowse
|
/reactive/src/scripts/modules/todos/store.ts
| 3.140625
| 3
|
'use strict';
/*!
* @version: 1.1.1
* @name: store
*
* @author: https://themeforest.net/user/flexlayers
*/
import {Item} from './item';
export default class Store {
/**
* @type {ItemList}
*/
private liveItems: Array<Item>;
/**
* @type {Storage}
*/
private localStorage: Storage;
/**
* @param {!string} name Database name
* @param {function()} [callback] Called when the Store is ready
*/
constructor(private name: string, callback?: any) {
this.localStorage = window.localStorage;
if (callback) {
callback();
}
}
/**
* Read the local ItemList from localStorage.
*
* @returns {ItemList} Current array of todos
*/
public getStorage() {
return this.liveItems || JSON.parse(this.localStorage.getItem(this.name) || '[]');
}
/**
* Write the local ItemList to localStorage.
*
* @param {ItemList} todos Array of todos to write
*/
public setStorage(items: Array<Item>) {
this.localStorage.setItem(this.name, JSON.stringify(this.liveItems = items));
}
/**
* Update an item in the Store.
*
* @param {ItemUpdate} update Record with an id and a property to update
* @param {function()} [callback] Called when partialRecord is applied
*/
public update(update: Item, callback: any) {
const id = update.id;
const todos = this.getStorage();
let i = todos.length;
while (i--) {
if (todos[i].id === id) {
for (let k in update) {
todos[i][k] = (<any>update)[k];
}
break;
}
}
this.setStorage(todos);
if (callback) {
callback();
}
}
/**
* Insert an item into the Store.
*
* @param {Item} item Item to insert
* @param {function()} [callback] Called when item is inserted
*/
public insert(item: Item, callback: any) {
const todos = this.getStorage();
todos.push(item);
this.setStorage(todos);
if (callback) {
callback();
}
}
/**
* Remove items from the Store based on a query.
*
* @param {Item} query Query matching the items to remove
* @param {function(ItemList)|function()} [callback] Called when records matching query are removed
*/
public remove(query: Item, callback: any) {
const todos = this.getStorage().filter((todo: Item) => {
for (let k in query) {
if ((<any>query)[k] !== (<any>todo)[k]) {
return true;
}
}
return false;
});
this.setStorage(todos);
if (callback) {
callback(todos);
}
}
/**
* Count total, active, and completed todos.
*
* @param {function(number, number, number)} callback Called when the count is completed
*/
public count(callback: any) {// todo
this.find(null, (items: Array<Item>) => {
const total = items.length;
let i = total;
let completed = 0;
while (i--) {
completed += items[i].completed ? 1 : 0;
}
callback(total, total - completed, completed);
});
}
/**
* Find items with properties matching those on query.
*
* @param {Item} query Query to match
* @param {function(ItemList)} callback Called when the query is done
*
* @example
* db.find({completed: true}, data => {
* // data shall contain items whose completed properties are true
* })
*/
public find(query: Item, callback: any) {
const todos = this.getStorage();
callback(todos.filter((todo: Item) => {
for (let k in query) {
if ((<any>query)[k] !== (<any>todo)[k]) {
return false;
}
}
return true;
}));
}
}
|
592664c73f15c7017f0737e20d82397966a2b718
|
TypeScript
|
ynse01/cpu6510
|
/src/cpu/operations/noop/kil.ts
| 2.640625
| 3
|
import { AddressingMode } from "../../addressing-mode";
import { Processor } from "../../processor";
import { IOperationImplicit } from "../i-operation-implicit";
import { IOperationWithAddress } from "../i-operation-with-address";
import { IOperationWithValue } from "../i-operation-with-value";
/* eslint-disable @typescript-eslint/no-unused-vars */
export class KIL implements IOperationImplicit, IOperationWithAddress, IOperationWithValue {
constructor(cpu: Processor) {
// Nothing to do here.
}
public executeWithValue(_value: number): number {
throw new Error("Invalid instruction.");
}
public executeWithAddress(_address: number): number {
throw new Error("Invalid instruction.");
}
public execute(): number {
throw new Error("Invalid instruction.");
}
public delay(_mode: AddressingMode): number {
return 0;
}
}
|
7e1ebce782cf3c109ab2a691443fec2d1c62d280
|
TypeScript
|
famo-lsd/pda
|
/client/src/Scripts/utils/number.ts
| 2.71875
| 3
|
import numeral from 'numeral';
// locales
import 'numeral/locales/pt-pt';
import 'numeral/locales/de';
import 'numeral/locales/es-es';
import 'numeral/locales/fr';
window['numeral'] = numeral;
export function convertNumeralToJS(number: any) {
return !number ? number : number.toString().replace(new RegExp('\\' + numeral.localeData().delimiters.thousands, 'g'), '').replace(new RegExp('\\' + numeral.localeData().delimiters.decimal, 'g'), '.');
}
export function isInteger(number: any) {
return Number.isInteger(parseFloat(number));
}
export async function setDecimalDelimiter(event: any, input: React.RefObject<any>) {
const cursorPos = input.current.selectionStart,
inputVal = input.current.value;
if (event.keyCode === 110) {
event.preventDefault();
input.current.value = inputVal.substr(0, cursorPos) + numeral.localeData().delimiters.decimal + inputVal.substr(cursorPos, inputVal.length - 1);
}
}
export function setNumeralLocale(code: string) {
switch (code) {
case 'POR':
numeral.locale('pt-pt');
break;
case 'DEU':
numeral.locale('de');
break;
case 'ENG':
numeral.locale('en');
break;
case 'ESP':
numeral.locale('es-es');
break;
case 'FRA':
numeral.locale('fr');
break;
}
}
|
06dda67f5cde5fd5be315df72a3b15e76914dacf
|
TypeScript
|
hienkhieu/async
|
/src/main.ts
| 3.0625
| 3
|
import async from 'async';
// async.eachLimit([1, 2, 3, 4, 5], 2, (itemId, callback) => {
// setTimeout(() => {
// console.log("in with item Id: ", itemId);
// }, 10000);
// callback();
// }, function (err) {
// if (err) {
// console.log("err : ", err);
// throw err;
// }
// });
function upload_file(id: number, callback: Function) {
// Do funky stuff with file
console.log(id);
callback();
}
const errorCallBack = (error: any) => console.log(error);
var queue = async.queue((id: number, callback: Function) => {
console.log(id);
callback();
}, 2); // Run ten simultaneous uploads
// Queue your files for upload
queue.push([1, 2, 3, 4, 5]);
|
f676c2b1d30df977e876d5abf2a2128bd2527067
|
TypeScript
|
openmusicgame/omgc-core
|
/src/types/animatable/notes/Wipe.ts
| 2.609375
| 3
|
import { Location, TimeValue } from "@/types/base/typeutil";
import { INote, Note } from "./Note";
export interface Wipe extends INote<"wipe"> {
}
export class WipeNote extends Note<"wipe"> implements Wipe {
kind: "wipe" = "wipe";
constructor(public name: string, public location: Location, public beginTime: TimeValue){
super(name, location, beginTime);
}
}
|
0f71a9de184adfc3055e66d67e8fd869e3b1e452
|
TypeScript
|
parsehex/hit-scraper
|
/src/Settings/html/to/sort-type.ts
| 2.9375
| 3
|
import { sectionTitle, label, input, descriptionTitle } from '../_dom';
export default function () {
return `
<div class="row">
<div class="column opts">
${sectionTitle('Sort Type')}
<p>
${label('Simple', 'stSim')}
${input('radio', { id: 'stSim', name: 'sortType', value: 'sim', checked: this.sortType === 'sim' })}
</p>
<p>
${label('Adjusted', 'stAdj')}
${input('radio', { id: 'stAdj', name: 'sortType', value: 'adj', checked: this.sortType === 'adj' })}
</p>
</div>
<div class="column opts-dsc">
<section>
${descriptionTitle('Simple')}
HIT Scraper will sort results based simply on value regardless of the number of reviews.
</section>
<section>
${descriptionTitle('Adjusted')}
HIT Scraper will use a Bayesian adjusted rating based on reliability
(i.e. confidence) of the data.
It factors in the number of reviews such that, for example,
a requester with 100 reviews rated at 4.6 will rightfully be ranked higher
than a requester with 3 reviews rated at 5.
This gives a more accurate representation of the data.
</section>
</div>
</div>
`;
}
|
ceb020af30a8d08d6f6342483bdabb28a8b4fcba
|
TypeScript
|
Manjunath3003/mernStack
|
/mernStack/strLi.ts
| 2.890625
| 3
|
function strLi(sList:string[]):void{
for(let i:number=0; i<sList.length;i++){
if(sList[i].toUpperCase()=='P'){
console.log(sList[i],i)
}
}
}
let sL:string[]=['a','p','c','d','m']
strLi(sL)
|
1a234b6628619a802bf56504eba68ed8a0516009
|
TypeScript
|
edrlab/thorium-reader
|
/src/utils/tryCatch.ts
| 2.53125
| 3
|
// ==LICENSE-BEGIN==
// Copyright 2017 European Digital Reading Lab. All rights reserved.
// Licensed to the Readium Foundation under one or more contributor license agreements.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file exposed on Github (readium) in the project repository.
// ==LICENSE-END=
import * as debug_ from "debug";
export function tryCatchSync<R>(fn: () => (R), errorPath: string, errMessage = ""): R {
// Logger
const debug = debug_(errorPath);
try {
const res = fn();
return res;
} catch (e) {
if (e instanceof Error) {
debug(errMessage, e.message, e.stack);
} else {
debug(errMessage, e);
}
}
return undefined;
}
export async function tryCatch<R>(fn: () => (R | Promise<R>), errorPath: string, errMessage = ""): Promise<R> {
// Logger
const debug = debug_(errorPath);
try {
const res = fn();
return await Promise.resolve(res);
} catch (e) {
if (e instanceof Error) {
debug(errMessage, e.message, e.stack);
} else {
debug(errMessage, e);
}
}
return undefined;
}
|
cc228e135fb881fea6c5f810fba9b646edc011ec
|
TypeScript
|
suzukalight/study-styled-components-mixin-csstype-expo
|
/src/logics/reducers/types.ts
| 2.765625
| 3
|
export interface SerializedError {
name?: string;
message?: string;
code?: string;
stack?: string;
}
export interface PendingAction<ThunkArg> {
type: string;
payload: undefined;
meta: {
requestId: string;
arg: ThunkArg;
};
}
export interface FulfilledAction<ThunkArg, PromiseResult> {
type: string;
payload: PromiseResult;
meta: {
requestId: string;
arg: ThunkArg;
};
}
export interface RejectedAction<ThunkArg> {
type: string;
payload: any;
error: SerializedError | any;
meta: {
requestId: string;
arg: ThunkArg;
aborted: boolean;
condition: boolean;
};
}
export interface RejectedWithValueAction<ThunkArg, RejectedValue> {
type: string;
payload: RejectedValue | any;
error: { message: 'Rejected' } | any;
meta: {
requestId: string;
arg: ThunkArg;
aborted: boolean;
};
}
export type Pending = <ThunkArg>(requestId: string, arg: ThunkArg) => PendingAction<ThunkArg>;
export type Fulfilled = <ThunkArg, PromiseResult>(
payload: PromiseResult,
requestId: string,
arg: ThunkArg,
) => FulfilledAction<ThunkArg, PromiseResult>;
export type Rejected = <ThunkArg>(requestId: string, arg: ThunkArg) => RejectedAction<ThunkArg>;
export type RejectedWithValue = <ThunkArg, RejectedValue>(
requestId: string,
arg: ThunkArg,
) => RejectedWithValueAction<ThunkArg, RejectedValue>;
export type AsyncThunkConfig<T = unknown> = {
rejectValue: T;
};
|
52bc941c4c7341aa3c102a809a1c5da2f43e5d9b
|
TypeScript
|
SystemDevelopTraining/oic-sns
|
/server/front/src/utils/AsyncOnce.ts
| 3.53125
| 4
|
// 同時に一度しか非同期の処理が行われないように保証される
// 処理中にもう一つ実行しようとした場合はキャンセルされる
export class AsyncOnce {
private onceFlags = false;
//同時に一度しか実行したくない処理を実行
public async Do<R>(f: () => R) :Promise<R|undefined>{
try { if (this.onceFlags)return;
this.onceFlags = true;
const result = await f();
this.onceFlags = false;
return result;
}catch (e){
this.onceFlags = false;
throw e;
}
}
}
|
0d002696ae60a9f9564df7072c2b835eeef001da
|
TypeScript
|
fangsmile/page-test-webpack
|
/src/drawing/Core/Global.ts
| 2.84375
| 3
|
export class MouseInfo {
curX: number;
curY: number;
lastX: number;
lastY: number;
isCanvas: boolean;
constructor(curX: number, curY: number, lastX: number, lastY: number, isCanvas: boolean = false) {
this.curX = curX;
this.curY = curY;
this.lastX = lastX;
this.lastY = lastY;
this.isCanvas = isCanvas;
}
}
export class XYRange {
startX: number;
startY: number;
endX: number;
endY: number;
constructor() {
}
set(startX: number,
startY: number,
endX: number,
endY: number) {
this.startX = startX;
this.startY = startY;
this.endX = endX;
this.endY = endY
}
}
|
eeb285f2dc9dfc4786b1df252020059939b46448
|
TypeScript
|
fahmi-idris/pokedex
|
/src/utils/__test__/formatter.test.ts
| 2.734375
| 3
|
import {
renderPokemonImage,
renderPokemonId,
capitalize,
formatHeight,
formatWeight,
getAllPokemon,
toFeet,
} from '../formatter';
import { pokemonDummy } from '../__fixtures__/dummyData';
describe('utils/formatter', () => {
describe('renderPokemonImage', () => {
test('should render pokemon image URL', () => {
const testString = '1';
expect(renderPokemonImage(testString)).toEqual(
'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/1.svg',
);
});
test('should render pokemon id from URL', () => {
expect(renderPokemonId(pokemonDummy)).toEqual('1');
});
test('should capitalize text', () => {
const testString = 'lorem';
expect(capitalize(testString)).toEqual('Lorem');
});
test('should format height to formatter height', () => {
const height = 4;
expect(formatHeight(height)).toEqual(`1 feet 4" (0.4m)`);
});
test('should format weight to formatter weight', () => {
const weight = 200;
expect(formatWeight(weight)).toEqual(`44.09 lbs (20kg)`);
});
test('should render all pokement endpoint height', () => {
const page = '2';
expect(getAllPokemon(page)).toEqual('/pokemon/?limit=40&offset=0');
});
test('should format height feet', () => {
const height = 4 * 10;
expect(toFeet(height)).toEqual(`1 feet 4"`);
});
});
});
|
74c7462625147919a3fdf569d9baf6d6f0846d89
|
TypeScript
|
riggs/binary-structures
|
/typings/transcode.d.ts
| 3.015625
| 3
|
import 'improved-map';
import { Size } from './serialization';
export declare type Primitive = number | string | ArrayBuffer;
export declare type Mapped<T> = Map<string, T>;
export declare type Encoded_Map = Mapped<any>;
export declare type Encoded_Array = Array<any>;
export declare type Encoded = Primitive | Encoded_Map | Encoded_Array;
export declare type Map_Context = Encoded_Map;
export declare type Array_Context = Encoded_Array;
export declare type Context = Encoded;
export declare const Parent: unique symbol;
export interface Contextualized<P> {
[Parent]?: P;
}
export declare type Context_Type<E extends Encoded, C> = E & Contextualized<C>;
export declare type Context_Map<Encoded, Context> = Context_Type<Mapped<Encoded>, Context>;
export declare type Context_Array<Encoded, Context> = Context_Type<Array<Encoded>, Context>;
export declare type Context_Iterable<Encoded, Context> = Context_Map<Encoded, Context> | Context_Array<Encoded, Context>;
export declare type Encoder<Decoded, E extends Encoded, Context> = (decoded: Decoded, context?: Context) => E;
export declare type Decoder<E extends Encoded, Decoded, Context> = (encoded: E, context?: Context) => Decoded;
export interface Transcoders<E extends Encoded, Decoded, Context> {
encode?: Encoder<Decoded, E, Context>;
decode?: Decoder<E, Decoded, Context>;
little_endian?: boolean;
}
export declare const inspect_transcoder: <T>(data: T, context?: any) => T;
export declare const inspect: {
encode: <T>(data: T, context?: any) => T;
decode: <T>(data: T, context?: any) => T;
};
/** A function to fetch the data to be packed.
* It is provided by the code handling the input data and called by the packer function to fetch the data to pack.
*/
export interface Fetcher<Decoded> {
(): Decoded;
}
/** A function to deliver the parsed result to the correct place.
* It is provided by the code managing the results container and called by the parser function with the parsed data.
*/
export interface Deliver<Decoded> {
(data: Decoded): void;
}
export interface Parse_Options<Context> {
byte_offset?: number;
little_endian?: boolean;
context?: Context;
}
export interface Pack_Options<C> extends Parse_Options<C> {
data_view?: DataView;
}
export interface Packed {
buffer: ArrayBuffer;
size: Size;
}
export interface Parsed<Decoded> {
data: Decoded;
size: Size;
}
export interface Packer<Decoded, Context> {
(source: Decoded | Fetcher<Decoded>, options?: Pack_Options<Context>): Packed;
}
export interface Parser<Decoded, Context> {
(data_view: DataView, options?: Parse_Options<Context>, deliver?: Deliver<Decoded>): Parsed<Decoded>;
}
export interface Struct<Decoded, Context> {
pack: Packer<Decoded, Context>;
parse: Parser<Decoded, Context>;
}
export declare const Bits: <D, C>(bits: number, transcoders?: Transcoders<string | number, D, C>) => Struct<D, C>;
export declare const Uint: <D, C>(bits: number, transcoders?: Transcoders<string | number, D, C>) => Struct<D, C>;
export declare const Int: <D, C>(bits: number, transcoders?: Transcoders<string | number, D, C>) => Struct<D, C>;
export declare const Float: <D, C>(bits: number, transcoders?: Transcoders<string | number, D, C>) => Struct<D, C>;
export declare const Utf8: <D, C>(bits: number, transcoders?: Transcoders<string, D, C>) => Struct<D, C>;
export declare type Numeric<C> = number | {
bits?: number;
bytes?: number;
} | ((context?: C) => number);
/** Byte_Buffer doesn't do any serialization, but just copies bytes to/from an ArrayBuffer that's a subset of the
* serialized buffer. Byte_Buffer only works on byte-aligned data.
*
* @param {Numeric} length
* @param {Transcoders<ArrayBuffer, any>} transcoders
*/
export declare const Byte_Buffer: <D, C>(length: Numeric<C>, transcoders?: Transcoders<ArrayBuffer, D, C>) => {
pack: (source: D | Fetcher<D>, options?: Pack_Options<C>) => Packed;
parse: (data_view: DataView, options?: Parse_Options<C>, deliver?: Deliver<D> | undefined) => {
data: D;
size: number;
};
};
export declare const Padding: <C>(bits: Numeric<C>, transcoders?: Transcoders<number, any, C>) => Struct<any, C>;
export declare type Chooser<C> = (context?: C) => number | string;
export interface Choices<D, C> {
[choice: number]: Struct<D, C>;
[choice: string]: Struct<D, C>;
}
export interface Branch<D, C> {
chooser: Chooser<C>;
choices: Choices<D, C>;
default_choice?: Struct<D, C>;
}
export declare const Branch: <D, C>({ chooser, choices, default_choice }: Branch<D, C>) => Struct<D, C>;
export declare const Embed: <D, C extends Context_Iterable<D, S>, S>(embedded: Struct<Context_Iterable<D, S>, S> | Struct<D, C>) => Struct<D | Context_Type<Map<string, D>, S> | Context_Type<D[], S>, C>;
export declare type Map_Item<I> = Struct<I, Mapped<I>>;
export declare type Map_Iterable<I> = Array<[string, Map_Item<I>]>;
export declare type Map_Transcoders<I, D, C> = Transcoders<Mapped<I>, D, C>;
export interface Binary_Map<I, D, C> extends Mapped<Map_Item<I>>, Struct<D, C> {
pack: (source: D | Fetcher<D>, options?: Pack_Options<C>, encoded?: Context_Map<I, C>) => Packed;
parse: (data_view: DataView, options?: Parse_Options<C>, deliver?: Deliver<D>, results?: Context_Map<I, C>) => Parsed<D>;
}
export declare function Binary_Map<I, D, C>(transcoders?: Map_Transcoders<I, D, C> | Map_Iterable<I>, iterable?: Map_Iterable<I> | Map_Transcoders<I, D, C>): Binary_Map<I, D, C>;
export declare namespace Binary_Map {
let object_encoder: (obj: any) => Map<any, any>;
let object_decoder: (map: Map<any, any>) => any;
let object_transcoders: {
encode: (obj: any) => Map<any, any>;
decode: (map: Map<any, any>) => any;
};
}
export declare type Array_Item<I> = Struct<I, Array<I>>;
export declare type Array_Transcoders<I, D, C> = Transcoders<Array<I>, D, C>;
export interface Binary_Array<I, D, C> extends Array<Array_Item<I>>, Struct<D, C> {
pack: (source: D | Fetcher<D>, options?: Pack_Options<C>, fetcher?: Fetcher<I>) => Packed;
__pack_loop: (fetcher: Fetcher<I>, options: Pack_Options<Array<I>>, store: (result: Packed) => void, parent?: C) => number;
parse: (data_view: DataView, options?: Parse_Options<C>, deliver?: Deliver<D>, results?: Context_Array<I, C>) => Parsed<D>;
__parse_loop: (data_view: DataView, options: Parse_Options<Context_Array<I, C>>, deliver: Deliver<I>, parent?: C) => number;
}
export declare const Binary_Array: <I, D, C>(...elements: (Transcoders<I[], D, C> | Struct<I, I[]>)[]) => Binary_Array<I, D, C>;
export interface Repeat_Options<I, D, C> extends Array_Transcoders<I, D, C> {
count?: Numeric<C>;
bytes?: Numeric<C>;
}
export declare const Repeat: <I, D, C>(...elements: (Repeat_Options<I, D, C> | Struct<I, I[]>)[]) => Binary_Array<I, D, C>;
|
410240515e9483df5cb0cc19cb3cbf2741a73d04
|
TypeScript
|
cowwoc/requirements.js
|
/src/internal/VariableType.mts
| 3.84375
| 4
|
/**
* Describes the type of a variable.
*/
class VariableType
{
public static readonly NULL = new VariableType("null");
public static readonly BOOLEAN = new VariableType("boolean");
public static readonly NUMBER = new VariableType("number");
public static readonly BIGINT = new VariableType("bigint");
public static readonly ARRAY = new VariableType("array");
public static readonly STRING = new VariableType("string");
public static readonly SYMBOL = new VariableType("symbol");
public readonly type: "undefined" | "null" | "boolean" | "number" | "bigint" | "array" | "string" |
"symbol" | "function" | "class" | "object";
public readonly name: null | string;
/**
* Creates a new VariableType.
*
* @param type - the name of the type
* @param name - the name of the function or class (Default: <code>null</code>)
* @throws RangeError if neither <code>type</code> or <code>name</code> are set.
* If <code>type</code> does not have a name (e.g. "number" or "array") but <code>name</code> is set.
*/
constructor(type: "undefined" | "null" | "boolean" | "number" | "bigint" | "array" | "string" | "symbol" |
"function" | "class" | "object", name: null | string = null)
{
switch (type)
{
case "undefined":
case "null":
case "boolean" :
case "number" :
case "bigint":
case "array":
case "string":
case "symbol":
if (name !== null)
throw new RangeError(type + " may not have a name");
}
this.type = type;
this.name = name;
}
/**
* @returns the string representation of this object
*/
toString()
{
let result;
switch (this.type)
{
case "function":
case "class":
{
result = "a ";
break;
}
case "object":
{
result = "an ";
break;
}
default:
return this.type;
}
result += this.type;
if (this.name !== null)
result += " named " + this.name;
return result;
}
}
export {VariableType};
|
480a8dda19a87863d363539a6f7ef798ee56733c
|
TypeScript
|
danigb/smplr
|
/src/sampler/midi.ts
| 2.890625
| 3
|
function noteNameToMidi(note: string): number | undefined {
const REGEX = /^([a-gA-G]?)(#{1,}|b{1,}|)(-?\d+)$/;
const m = REGEX.exec(note);
if (!m) return;
const letter = m[1].toUpperCase();
if (!letter) return;
const acc = m[2];
const alt = acc[0] === "b" ? -acc.length : acc.length;
const oct = m[3] ? +m[3] : 4;
const step = (letter.charCodeAt(0) + 3) % 7;
return [0, 2, 4, 5, 7, 9, 11][step] + alt + 12 * (oct + 1);
}
export function toMidi(note: string | number | undefined): number | undefined {
return note === undefined
? undefined
: typeof note === "number"
? note
: noteNameToMidi(note);
}
/// This is how the MIDI association converts midi velocity [0..127] into gain [0..1]
/// @see https://www.midi.org/specifications/file-format-specifications/dls-downloadable-sounds/dls-level-1
export function midiVelToGain(vel: number) {
return (vel * vel) / 16129; // 16129 = 127 * 127
}
export function findNearestMidi(
midi: number,
isAvailable: Record<string | number, unknown>
): [number, number] {
let i = 0;
while (isAvailable[midi + i] === undefined && i < 128) {
if (i > 0) i = -i;
else i = -i + 1;
}
return i === 127 ? [midi, 0] : [midi + i, -i * 100];
}
|
9befe2a086a9c0b1afd2d8a5b87ed68e0719eb83
|
TypeScript
|
xiaosasori/discord-clone-vite
|
/src/stores/channel.ts
| 2.8125
| 3
|
import { defineStore } from 'pinia'
type ChannelState = {
typingUsers: string[]
}
export const useChannel = defineStore('channel', {
state: () => {
return {
typingUsers: [],
} as ChannelState
},
actions: {
addTyping(username: string) {
this.typingUsers.push(username)
},
removeTyping(username: string) {
this.typingUsers = this.typingUsers.filter((u) => u !== username)
},
},
})
|
39d6abeca2d83161fa3d21c394088720604234a8
|
TypeScript
|
jmw5598/grow-system
|
/_modules/@grow/common/src/lib/utilities/logger.service.ts
| 3.046875
| 3
|
import { LogType } from './log-type.enum';
export class Logger {
constructor(public _class: string) {}
public debug(message: string): void {
this._log(LogType.DEBUG, message);
}
public warn(message: string): void {
this._log(LogType.WARN, message);
}
public error(message: string): void {
this._log(LogType.ERROR, message);
}
public danger(message: string): void {
this._log(LogType.DANGER, message);
}
public trace(message: string): void {
this._log(LogType.TRACE, message);
}
private _log(type: LogType, message: string): void {
const timestamp: Date = new Date();
// tslint:disable-next-line:no-console
console.log(`[${type}][${timestamp.toISOString()}][${this._class}] ${message}`);
}
}
|
4620b40efd77799a964e71fd42f6519f1420bfe1
|
TypeScript
|
Sylvenas/color-transfer
|
/src/HSL/HSLToRGB.ts
| 3.1875
| 3
|
import { formatHSLAToNum } from '../utils'
import { HSL_REG, HSLA_REG } from '../utils/reg'
import { isNumeric } from '../utils/type-check'
/**
* HSL to RGB
* @example
* (h,s%,l%) => rgb(r,g,b)
* (h,s%,l%,a) => rgb(r,g,b,a)
* hsl(h,s%,l%) => rgb(r,g,b)
* hsla(h,s%,l%,a) => rgb(r,g,b,a)
* hsl(h s% l%) => rgb(r,g,b)
* hsla(h s% l% a) => rgb(r,g,b,a)
* hsl(hdeg,s%,l%) => rgb(r,g,b)
* hsl(hrad,s%,l%) => rgb(r,g,b)
* hsl(hturn,s%,l%) => rgb(r,g,b)
*
* @param h hue number or hsl[a] string
* @param s saturation number
* @param l lightness number
* @param a alpha number
*
* @returns 'rgb[a]' string
*/
function HSLToRGB(h: number | string, s?: number, l?: number, a?: number): Array<number> {
let hue: number,
saturation: number,
lightness: number,
alpha: number;
if (typeof h === 'number') {
if (!isNumeric(h, s, l, a ? a : 1))
throw new Error("Invalid input HSL[A] color")
// Must be fractions of 1
hue = h as number;
saturation = s / 100;
lightness = l / 100;
if (a && typeof a === 'number')
alpha = a
} else if (typeof h === 'string') {
if (!(HSL_REG.test(h) || HSLA_REG.test(h)))
throw new Error("Invalid input HSL[A] color")
const hsla = formatHSLAToNum(h)
hue = hsla.hue
saturation = hsla.saturation
lightness = hsla.lightness
if (hsla.alpha != null) {
alpha = hsla.alpha
}
}
let primary: number = (1 - Math.abs(2 * lightness - 1)) * saturation,
secondary: number = primary * (1 - Math.abs((hue / 60) % 2 - 1)),
middle: number = lightness - primary / 2,
red: number = 0,
green: number = 0,
blue: number = 0;
if (0 <= hue && hue < 60) {
red = primary; green = secondary; blue = 0;
} else if (60 <= hue && hue < 120) {
red = secondary; green = primary; blue = 0;
} else if (120 <= hue && hue < 180) {
red = 0; green = primary; blue = secondary;
} else if (180 <= hue && hue < 240) {
red = 0; green = secondary; blue = primary;
} else if (240 <= hue && hue < 300) {
red = secondary; green = 0; blue = primary;
} else if (300 <= hue && hue < 360) {
red = primary; green = 0; blue = secondary;
}
red = Math.round((red + middle) * 255);
green = Math.round((green + middle) * 255);
blue = Math.round((blue + middle) * 255);
if (alpha) {
return [red, green, blue, alpha]
}
return [red, green, blue]
}
export default HSLToRGB
|
b7809fa288e634cf5173f0a7546f85e11d431b1d
|
TypeScript
|
hookedjs/hookedjs
|
/src/lib/polyfills/iso/Map.ts
| 3.546875
| 4
|
/**
* Extensions for String
*
* Note: Extending primitive's can be problematic without care. For more info, see
* https://stackoverflow.com/questions/8859828/javascript-what-dangers-are-in-extending-array-prototype
*
* Tips:
* 1. for...in will break if you naively extend via Set.propotype.foo = ...
* Instead, use Object.defineProperty({value: fnc, enumerable: false})
* 2. Drop support for older Internet Explorer
*/
// You must export something or TS gets confused.
export {}
declare global {
interface Map<K, V> {
copy(): Map<K, V>
toObj(): Record<string, V>
/**
* Like set but the value is a callback that accepts the prior
* value and returns the next value, kinda like react's useState
* updater
**/
update(key: K, valueCb: (previous: V) => V): Map<K, V>
}
}
Object.defineProperties(Map.prototype, {
copy: {
value: function () {
return Object.copy(this)
},
enumerable: false,
},
toObj: {
value: function () {
return Object.fromEntries(this)
},
enumerable: false,
},
update: {
value: function (key: any, valueCb: (previous: any) => any) {
return this.set(key, valueCb(this.get(key)))
},
enumerable: false,
},
})
|
c4c5ba3b5d95503d8cc56cf188344cd71a85cb10
|
TypeScript
|
aaf1974/AngularLerningSolution
|
/ClientApp/src/app/samples/timer/timer.component.ts
| 2.625
| 3
|
import { Component } from "@angular/core";
import { timer } from "rxjs";
@Component({
selector: 'app-samples-timer',
templateUrl: './timer.component.html'
})
export class TimerSampleComponent {
//let dateTime = new Date();
startTime: Date = new Date();
endTime: Date = null;//new Date();
/**Пример использования setTimeOut */
public sampleDelay() {
this.startTime = new Date();
console.log("timer");
this.delay(10000);
}
delay(ms: number) {
return new Promise(resolve => setTimeout(this.setEndTime, ms));
}
setEndTime() {
this.endTime = new Date();
console.log(this.endTime);
}
public sampleObservible() {
this.startTime = new Date();
this.oberserableTimer();
}
oberserableTimer() {
const source = timer(1000, 2000);
let abc = source.subscribe(val => {
if (val < 10) {
console.log(val, '-');
}
else {
this.endTime = new Date();
console.log("End observible");
abc.unsubscribe();
}
});
}
public sampleWait() {
this.endTime = null;
this.startTime = new Date();
this.wait(5000);
this.endTime = new Date();
}
wait(ms) {
var start = new Date().getTime();
var end = start;
while (end < start + ms) {
end = new Date().getTime();
}
}
}
|
fad5ee22848737ba0e9391772f58f27b171f1ad8
|
TypeScript
|
greenn-lab/egovframe-msa-edu
|
/frontend/portal/src/service/Login.ts
| 2.59375
| 3
|
import { ACCESS_TOKEN, AUTH_USER_ID, CLAIM_NAME } from '@constants/env'
import axios from 'axios'
const JWT_EXPIRED_TIME = 1800000
const LOGIN_SERVICE_URL = `/api/login/user-service`
const LOGIN_URL = `/login`
const CLIENT_REFRESH_URL = '/api/login/user-service/api/v1/users/token/refresh'
export interface ILogin {
email?: string
password?: string
isRemember?: boolean
provider: 'email' | 'google' | 'naver' | 'kakao'
token?: string
name?: string
}
const onSuccessLogin = (result: any) => {
axios.defaults.headers.common[CLAIM_NAME] = result[ACCESS_TOKEN]
axios.defaults.headers.common[AUTH_USER_ID] = result[AUTH_USER_ID]
// access-token 만료 1분 전에 로그인 연장
setTimeout(loginSerivce.silentRefresh, JWT_EXPIRED_TIME - 60000)
}
export const loginSerivce = {
login: (data: ILogin) => {
return new Promise<string>(async (resolve, reject) => {
try {
const result = await fetch(LOGIN_SERVICE_URL + LOGIN_URL, {
method: 'POST',
body: JSON.stringify(data),
})
if (result.status === 200) {
onSuccessLogin(await result.json())
resolve('success')
} if (result.status === 412) {
reject('join')
} else {
reject('noAuth')
}
} catch (error) {
reject(error)
}
})
},
silentRefresh: async () => {
try {
const result = await fetch(CLIENT_REFRESH_URL, {
method: 'PUT',
})
if (result) {
onSuccessLogin(await result.json())
}
} catch (error) {
console.warn('refresh token 만료로 인한 로그아웃!!!!')
fetch('/api/v1/token')
.then(res => {
console.warn('fetch', res)
})
.catch(error => {
console.warn('fetch error', error)
})
}
},
}
|
969cf5c418fe92e2cfe9adc85718d0931ae670c3
|
TypeScript
|
wankhede04/basic-math
|
/src/app/add-numbers/add-numbers.component.ts
| 2.609375
| 3
|
import { Component, OnDestroy } from '@angular/core';
import { BehaviorSubject, Subscription } from 'rxjs';
import { IAdditionValues, ITimeStamps } from '../models/addition';
import { take, tap } from 'rxjs/operators';
@Component({
selector: 'app-add-numbers',
templateUrl: './add-numbers.component.html',
styleUrls: ['./add-numbers.component.scss']
})
export class AddNumbersComponent implements OnDestroy {
public inputValue: number;
public isCorrectValue: boolean;
public averageSolutionTime: ITimeStamps;
public correctAnswers: number = 0;
public calculationValues$: BehaviorSubject<IAdditionValues>;
public subscription: Subscription;
constructor() {
this.calculationValues$ = new BehaviorSubject({
firstDigit: this.generateAdditionValues(),
secondDigit: this.generateAdditionValues()
});
this.averageSolutionTime = {
start: Date.now(),
end: null,
average: null
};
}
public getInputValue(inputValue: number) {
this.subscription = this.calculationValues$.pipe(
take(1),
tap((calValues) => {
if (inputValue === calValues.firstDigit + calValues.secondDigit) {
this.averageSolutionTime.end = Date.now();
this.calculationValues$.next({
firstDigit: this.generateAdditionValues(),
secondDigit: this.generateAdditionValues()
});
this.inputValue = null;
this.isCorrectValue = true;
this.correctAnswers++;
this.getAverageTime();
} else {
this.isCorrectValue = false;
}
})
).subscribe();
}
public generateAdditionValues(): number {
return Math.floor(Math.random() * 10)
}
public getAverageTime() {
this.averageSolutionTime.average = (this.averageSolutionTime.end - this.averageSolutionTime.start) / this.correctAnswers;
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
|
f3120852615aac80ac9e3a1eb46f7ae22630d8e2
|
TypeScript
|
youri333/code-morce
|
/main.ts
| 2.828125
| 3
|
input.onButtonPressed(Button.A, function () {
code_morse = "" + code_morse + "1"
})
input.onButtonPressed(Button.B, function () {
code_morse = "" + code_morse + "2"
})
input.onGesture(Gesture.Shake, function () {
basic.showString("" + (morce[CODE.indexOf(code_morse)]))
})
let CODE: string[] = []
let morce: string[] = []
let code_morse = ""
code_morse = ""
morce = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
CODE = ["12", "2111", "2121", "211", "1", "1121", "221", "1111", "11", "1222", "212", "1211", "22", "21", "222", "1221", "2212", "121", "111", "2", "112", "1112", "122", "2112", "2122", "2211"]
|
e55c1fdc9bfa225e1cc87fc5bf3d908de9b70658
|
TypeScript
|
MrBrax/ProjectorRays
|
/src/DataStream.ts
| 3.171875
| 3
|
/* DataStream */
export class DataStream {
static BIG_ENDIAN = false;
static LITTLE_ENDIAN = true;
position: number;
constructor(public buffer: Buffer, public endianness:boolean = DataStream.BIG_ENDIAN) {
this.position = 0;
}
seek(pos: number) {
this.position = pos;
}
skip(n: number) {
this.position = this.position + n;
}
endOfFile() {
return this.position >= this.buffer.length;
}
readBytes(length: number) {
let result = this.buffer.slice(this.position, this.position + length);
this.position += length;
return result;
}
readInt8() {
let result = this.buffer.readInt8(this.position);
this.position += 1;
return result;
}
readUint8() {
let result = this.buffer.readUInt8(this.position);
this.position += 1;
return result;
}
readInt16() {
let result = this.endianness ? this.buffer.readInt16LE(this.position) : this.buffer.readInt16BE(this.position);
this.position += 2;
return result;
}
readUint16() {
let result = this.endianness ? this.buffer.readUInt16LE(this.position) : this.buffer.readUInt16BE(this.position);
this.position += 2;
return result;
}
readUint24() {
let result = this.endianness
? (this.buffer.readUInt8(this.position) | (this.buffer.readUInt8(this.position + 1) << 8) | (this.buffer.readUInt8(this.position + 2) << 16))
: ((this.buffer.readUInt8(this.position) << 16) | (this.buffer.readUInt8(this.position + 1) << 8) | this.buffer.readUInt8(this.position + 2));
this.position += 3;
return result;
}
readInt32() {
let result = this.endianness ? this.buffer.readInt32LE(this.position) : this.buffer.readInt32BE(this.position);
this.position += 4;
return result;
}
readUint32() {
let result = this.endianness ? this.buffer.readUInt32LE(this.position) : this.buffer.readUInt32BE(this.position);
this.position += 4;
return result;
}
readFloat() {
let result = this.endianness ? this.buffer.readFloatLE(this.position) : this.buffer.readFloatBE(this.position);
this.position += 4;
return result;
}
readDouble() {
let result = this.endianness ? this.buffer.readDoubleLE(this.position) : this.buffer.readDoubleBE(this.position);
this.position += 8;
return result;
}
readString(length: number) {
let result = this.buffer.toString("utf8", this.position, this.position + length);
this.position += length;
return result;
}
readFourCC() {
let result = this.buffer.toString("utf8", this.position, this.position + 4);
if (this.endianness) {
result = result.split("").reverse().join("");
}
this.position += 4;
return result;
}
}
|
2b1fc79a595dc196c047f14d82a37ad1674a6b34
|
TypeScript
|
NicoFerrero/Laboratorio3-Programacion3
|
/Laboratorio/Guia Typescript/Ejer03.ts
| 3.015625
| 3
|
function Test(numero: number, cadena?: String): void{
if (cadena) {
for (let i = 0; i < numero; i++){
console.log(`${cadena}\n`);
}
}
else {
console.log(`${ numero - (numero * 2)}`);
}
}
Test(2, "Como te va");
|
e6c3dde654c5883e39d1033749b6730145b51707
|
TypeScript
|
PBKcore/LayaTS
|
/src/sear/struct/HashList.ts
| 3.40625
| 3
|
module sear.struct {
/**
*
*
* @author pbk
*/
export class HashList<T> {
private _hash: Object = null;
private _values: T[] = null;
constructor() {
this.clear();
}
clear(): void {
this._hash = {};
this._values = [];
}
add(key: string | number, value: T): T {
if (key == null) {
error("[HashList Add] Cannot put a value with undefined or null key!");
return undefined;
}
else if (value == undefined) {
return this.del(key);
}
else {
let ret: T = this._hash[key];
if (ret != undefined) {
this._values[this._values.indexOf(ret)] = value;
} else {
this._values.push(value);
}
this._hash[key] = value;
return ret;
}
}
del(key: string | number): T {
let ret: T = this._hash[key];
if (ret != undefined) {
delete this._hash[key];
this._values.splice(this._values.indexOf(ret), 1);
}
return ret;
}
get(key: string | number): T {
return this._hash[key];
}
contains(key: string | number): boolean {
return this._hash[key] != undefined;
}
clone(): HashList<T> {
let ret: HashList<T> = new HashList<T>();
for (let key in this._hash) {
ret._hash[key] = this._hash[key];
}
ret._values = this._values.concat();
return ret;
}
get values(): T[] {
return this._values;
}
get length(): number {
return this._values.length;
}
}
}
|
abd7da591c47719aaf58d4bd2fe73777ce065691
|
TypeScript
|
yanuas123/shopy
|
/src/ts/plug-modules/load-more.ts
| 2.578125
| 3
|
/* module Load More ---------------- */
export function loadMore(operation: string): void {
const loader: HTMLElement = document.getElementById("loader");
const body: HTMLElement = document.body;
const style_open: string = "open";
const style_blocked_body: string = "noscroll";
const act_open: string = "open";
const act_close: string = "close";
if(operation == act_open) {
loader.classList.add(style_open);
body.classList.add(style_blocked_body);
} else if(operation == act_close) {
loader.classList.remove(style_open);
body.classList.remove(style_blocked_body);
}
}
|
49891d32d7c5d18464f57859053acd23b169ffe5
|
TypeScript
|
GustavoOM/IFYouNeed
|
/server/src/controllers/ReinforcementsController.ts
| 2.59375
| 3
|
import {Request, Response} from "express"
import db from "../database/connection"
import convertHourToMinutes from "../utils/convertHourToMinutes"
export default class ReinforcementController{
// async index(request:Request, response:Response){
// const filters = request.query
//
// const subject = filters.subject as string
// const week_day = filters.week_day as string
// const time = filters.time as string
//
// const periods = [[360,780],[780,1080],[1080,1320]]
//
// let classes = []
//
// if(!!week_day && !!subject && !!time){
// classes = await db.from("classes")
// .whereExists(function(){
// this.select("class_schedule.*")
// .from("class_schedule")
// .whereRaw("`class_schedule`.`class_id` = `classes`.`id`")
// .whereRaw("`class_schedule`.`week_day` = ??", [Number(week_day)])
// .whereRaw("`class_schedule`.`from` <= ??", periods[Number(time)][1])
// .whereRaw("`class_schedule`.`to` > ??", periods[Number(time)][0])
// })
// .where("classes.subject", "=", subject)
// .join("users", "classes.user_id", "=", "users.id")
// .select(["classes.*","users.*"])
// }else
//
// if(!!week_day && !!subject){
// classes = await db.from("classes")
// .whereExists(function(){
// this.select("class_schedule.*")
// .from("class_schedule")
// .whereRaw("`class_schedule`.`class_id` = `classes`.`id`")
// .whereRaw("`class_schedule`.`week_day` = ??", [Number(week_day)])
// })
// .where("classes.subject", "=", subject)
// .join("users", "classes.user_id", "=", "users.id")
// .select(["classes.*","users.*"])
//
// }else
//
// if(!!subject && !!time){
// classes = await db.from("classes")
// .whereExists(function(){
// this.select("class_schedule.*")
// .from("class_schedule")
// .whereRaw("`class_schedule`.`class_id` = `classes`.`id`")
// .whereRaw("`class_schedule`.`from` <= ??", periods[Number(time)][1])
// .whereRaw("`class_schedule`.`to` > ??", periods[Number(time)][0])
// })
// .where("classes.subject", "=", subject)
// .join("users", "classes.user_id", "=", "users.id")
// .select(["classes.*","users.*"])
//
// }else
//
// if(!!time && !!week_day){
// classes = await db.from("classes")
// .whereExists(function(){
// this.select("class_schedule.*")
// .from("class_schedule")
// .whereRaw("`class_schedule`.`class_id` = `classes`.`id`")
// .whereRaw("`class_schedule`.`week_day` = ??", [Number(week_day)])
// .whereRaw("`class_schedule`.`from` <= ??", periods[Number(time)][1])
// .whereRaw("`class_schedule`.`to` > ??", periods[Number(time)][0])
// })
// .join("users", "classes.user_id", "=", "users.id")
// .select(["classes.*","users.*"])
// }else
//
// if(!!subject){
// classes = await db.from("classes")
// .whereExists(function(){
// this.select("class_schedule.*")
// .from("class_schedule")
// .whereRaw("`class_schedule`.`class_id` = `classes`.`id`")
// })
// .where("classes.subject", "=", subject)
// .join("users", "classes.user_id", "=", "users.id")
// .select(["classes.*","users.*"])
//
// }else
//
// if(!!time){
// classes = await db.from("classes")
// .whereExists(function(){
// this.select("class_schedule.*")
// .from("class_schedule")
// .whereRaw("`class_schedule`.`class_id` = `classes`.`id`")
// .whereRaw("`class_schedule`.`from` <= ??", periods[Number(time)][1])
// .whereRaw("`class_schedule`.`to` > ??", periods[Number(time)][0])
// })
// .join("users", "classes.user_id", "=", "users.id")
// .select(["classes.*","users.*"])
//
// }else
//
// if(!!week_day){
// classes = await db.from("classes")
// .whereExists(function(){
// this.select("class_schedule.*")
// .from("class_schedule")
// .whereRaw("`class_schedule`.`class_id` = `classes`.`id`")
// .whereRaw("`class_schedule`.`week_day` = ??", [Number(week_day)])
// })
// .join("users", "classes.user_id", "=", "users.id")
// .select(["classes.*","users.*"])
//
// }
//
// else{
// classes = await db.from("classes")
// .select()
// .join("users", "classes.user_id", "=", "users.id")
// .select(["classes.*","users.*"])
// }
//
// return response.json(classes)
// }
async index(request:Request, response:Response){
const reinforcements = await db.from("reinforcements").select().join("users", "reinforcements.user_id", "=", "users.id")
return response.json(reinforcements)
}
async create(request: Request, response:Response){
const {
subject,
principal_year,
course,
week_day,
to,
from,
place,
reinforcement_bio,
user_id
} = request.body
const trx = await db.transaction()
try{
const insertedReinforcementData = await trx("reinforcements").insert({
subject,
principal_year,
course,
week_day,
from: convertHourToMinutes(from),
to: convertHourToMinutes(to),
place,
reinforcement_bio,
user_id
})
await trx.commit()
return response.status(201).send()
}catch (err){
await trx.rollback()
return response.status(400).json({
error: "Unexpected error while creating new reinforcement"
})
}
}
}
|
39355537a03e0565772d807619c4de5877408636
|
TypeScript
|
dioskuroi/koa2-ts-weibo
|
/src/services/user-relation.ts
| 2.546875
| 3
|
/**
* @description 用户关系 service
* @author 徐俊
*/
import { UserRelation, User } from '../db/models'
import { UserList } from '../types'
import { formatUserInfo } from './helpers/_format'
import { Op } from 'sequelize'
/**
* 根据被关注用户id获取粉丝列表
* @param followerId 被关注用户id
*/
export async function listUserByFollowerId(followerId: number): Promise<UserList> {
const { rows, count } = await User.findAndCountAll({
attributes: ['id', 'userName', 'nickName', 'picture'],
order: [
['id', 'desc']
],
include: [
{
model: UserRelation,
as: 'userRelations',
where: {
followerId,
userId: {
[Op.ne]: followerId
}
}
}
]
})
const list = rows.map(row => formatUserInfo({
id: row.id,
userName: row.userName,
nickName: row.nickName,
picture: row.picture
}))
return {
list,
count
}
}
/**
* 根据当前用户id获取关注人列表
* @param userId 当前用户id
*/
export async function listFollowerByUserId(userId: number): Promise<UserList> {
const { rows, count } = await UserRelation.findAndCountAll({
order: [
['id', 'desc']
],
include: [
{
model: User,
as: 'user',
attributes: ['id', 'userName', 'nickName', 'picture']
}
],
where: {
userId,
followerId: {
[Op.ne]: userId
}
}
})
const list = rows.map(row => formatUserInfo({
id: row.user.id,
userName: row.user.userName,
nickName: row.user.nickName,
picture: row.user.picture
}))
return {
list,
count
}
}
/**
* 添加关注
* @param userId 当前用户id
* @param followerId 被关注用户id
*/
export async function addFollow(userId: number, followerId: number): Promise<UserRelation> {
const result = UserRelation.create({
userId,
followerId
})
return result
}
/**
* 删除关注
* @param userId 当前用户id
* @param followerId 被关注用户id
*/
export async function deleteFollow(userId: number, followerId: number): Promise<boolean> {
const result = await UserRelation.destroy({
where: {
userId,
followerId
}
})
return result > 0
}
|
6311411b28646df172fa34390402cceadf2b8c6e
|
TypeScript
|
v8187/rs-mock
|
/src/phone-no.ts
| 2.953125
| 3
|
import { xToNum, deepMergeObject, randomItem, randomNum } from '@v8187/rs-utils';
import { ICountry, CONUTRIES_LIST } from './geographic';
export enum EPhoneLength {
MIN = 8, MAX = 13
};
export enum EPhoneFormats {
PLAIN, GROUP_OF_2 = 2, GROUP_OF_3 = 3, GROUP_OF_4 = 4, GROUP_OF_5 = 5
};
export enum EPhoneSeparator {
HYPHEN = '-', FULLSTOP = '.', SPACE = ' ', NON = ''
};
export enum EPhoneStartsWith {
PLUS = '+', ZEROS = '00', ISD = ''
};
export interface IPhoneOptions {
countries?: ICountry[];
format?: EPhoneFormats;
isdInBraces?: boolean;
separateISD?: boolean;
withISD?: boolean;
separator?: EPhoneSeparator;
startsWith?: EPhoneStartsWith;
};
export const phoneNoDefaults = (): TRequired<IPhoneOptions> => ({
countries: CONUTRIES_LIST.filter((con: ICountry) => con.code3 === 'IND'),
format: EPhoneFormats.PLAIN,
isdInBraces: false,
separateISD: true,
withISD: true,
separator: EPhoneSeparator.SPACE,
startsWith: EPhoneStartsWith.PLUS
});
/**
* Generates the random Phone number based on given parameters
*
* @param options { IPhoneOptions }
* @returns { string }
*/
export const phoneNo = (options: IPhoneOptions = phoneNoDefaults()): string => {
const {
countries, format, isdInBraces, separateISD,
withISD, separator, startsWith
} = deepMergeObject(phoneNoDefaults(), options);
let isd = withISD ? randomItem(countries).isdCode : '';
// Get random Local number
let local = xToNum(new Array(randomNum(EPhoneLength.MIN - isd.length, EPhoneLength.MAX - isd.length) + 1).join('x'));
// Group and Fill Spaces as per Options provided
if (format !== EPhoneFormats.PLAIN && separator !== EPhoneSeparator.NON) {
local = local.replace(new RegExp(`(\\d{${format}})`, 'g'), `$1${separator}`).replace(/[^\d]$/, '');
}
if (isd) {
// Wrap in Braces, if asked
isd = `${isdInBraces ? '(' : ''}${startsWith}${isd}${isdInBraces ? ')' : ''}`;
// Add Separator as per configuration
isd += !separateISD && separator === EPhoneSeparator.NON && format !== EPhoneFormats.PLAIN ? '' : separator;
}
return isd + local;
};
|
a85156ae562aa4b9b1bc992193c56d05d1a2d2ec
|
TypeScript
|
anantmittal/math-json
|
/src/compute-engine/dictionary/arithmetic.ts
| 2.6875
| 3
|
import type { Dictionary } from '../public';
export const ARITHMETIC_DICTIONARY: Dictionary = {
//
// Constants
//
Pi: {
domain: 'IrrationalNumber',
constant: true,
wikidata: 'Q167',
value: Math.PI,
},
ImaginaryI: {
domain: 'ImaginaryNumber',
constant: true,
wikidata: 'Q193796',
},
ExponentialE: {
domain: 'IrrationalNumber',
wikidata: 'Q82435',
constant: true,
value: { num: '2.7182818284590452354' },
},
//
// Functions
//
Abs: {
domain: 'Function',
wikidata: 'Q3317982', //magnitude 'Q120812 (for reals)
threadable: true,
idempotent: true,
signatures: [{ args: ['RealNumber'], result: 'RealNumber' }],
},
Add: {
domain: 'Function',
wikidata: 'Q32043',
associative: true,
commutative: true,
threadable: true,
idempotent: true,
signatures: [{ rest: ['RealNumber'], result: 'RealNumber' }],
},
Chop: {
domain: 'Function',
associative: true,
threadable: true,
idempotent: true,
signatures: [{ args: ['RealNumber'], result: 'RealNumber' }],
},
Ceil: {
domain: 'Function',
/** rounds a number up to the next largest integer */
},
Exp: {
domain: ['ContinuousFunction', 'MonotonicFunction'],
wikidata: 'Q168698',
threadable: true,
signatures: [{ args: ['RealNumber'], result: 'RealNumber' }],
},
Erf: {
// Error function
domain: ['ContinuousFunction', 'MonotonicFunction'],
signatures: [{ args: ['RealNumber'], result: 'RealNumber' }],
},
Erfc: {
// Complementary Error Function
domain: ['ContinuousFunction', 'MonotonicFunction'],
signatures: [{ args: ['RealNumber'], result: 'RealNumber' }],
},
Factorial: {
wikidata: 'Q120976',
domain: 'MonotonicFunction',
signatures: [{ args: ['NaturalNumber'], result: 'NaturalNumber' }],
},
Floor: { domain: 'Function', wikidata: 'Q56860783' },
Gamma: { domain: 'Function', wikidata: 'Q190573' },
LogGamma: { domain: 'Function' },
Log: {
domain: 'Function',
wikidata: 'Q11197',
signatures: [
{ args: ['RealNumber'], result: 'RealNumber' },
{ args: ['RealNumber', ['base', 'NaturalNumber']], result: 'RealNumber' },
],
},
Log2: {
domain: 'Function',
wikidata: 'Q581168',
signatures: [{ args: ['RealNumber'], result: 'RealNumber' }],
},
Log10: {
domain: 'Function',
wikidata: 'Q966582',
signatures: [{ args: ['RealNumber'], result: 'RealNumber' }],
},
// LogOnePlus: { domain: 'Function' },
MachineEpsilon: {
/*
The difference between 1 and the next larger floating point number
2^{−52}
See https://en.wikipedia.org/wiki/Machine_epsilon
*/
domain: 'RealNumber',
constant: true,
value: { num: '2.220446049250313e-16' },
},
Multiply: {
domain: 'Function',
wikidata: 'Q40276',
associative: true,
commutative: true,
idempotent: true,
signatures: [{ rest: ['RealNumber'], result: 'RealNumber' }],
},
Negate: {
domain: 'Function',
wikidata: 'Q715358',
signatures: [{ args: ['RealNumber'], result: 'RealNumber' }],
},
Power: {
domain: 'Function',
wikidata: 'Q33456',
commutative: false,
signatures: [{ args: ['RealNumber', 'RealNumber'], result: 'RealNumber' }],
},
Round: {
domain: 'Function',
signatures: [{ args: ['RealNumber', 'RealNumber'], result: 'RealNumber' }],
},
SignGamma: {
domain: 'Function',
/** The sign of the gamma function: -1 or +1 */
},
Sqrt: {
domain: 'Function',
wikidata: 'Q134237',
signatures: [
// @todo: arg should be positive number to map to a RealNumber
{ args: ['RealNumber'], result: 'RealNumber' },
{ args: ['Number'], result: 'Number' },
],
},
Root: {
domain: 'Function',
commutative: false,
signatures: [{ args: ['NaturalNumber'], result: 'RealNumber' }],
},
Subtract: {
domain: 'Function',
wikidata: 'Q32043',
commutative: false,
signatures: [
{ args: ['RealNumber', 'RealNumber'], result: 'RealNumber' },
{ args: ['Number', 'Number'], result: 'Number' },
],
},
// mod (modulo). See https://numerics.diploid.ca/floating-point-part-4.html,
// regardin 'remainder' and 'truncatingRemainder'
// lcm
// gcd
// root
// sum
// product
};
|
38a82c1e0596f37edd8e0f8fb988a9d502751a53
|
TypeScript
|
AudiusProject/audius-client
|
/packages/common/src/store/confirmer/reducer.ts
| 2.5625
| 3
|
import { noop } from 'lodash'
import { createReducer, ActionType } from 'typesafe-actions'
import {
ADD_CONFIRMATION_CALL,
SET_CONFIRMATION_RESULT,
ADD_COMPLETION_CALL,
CLEAR_COMPLETE,
CLEAR_CONFIRM,
INCREMENT_CONFIRM_GROUP_INDEX,
SET_OPERATION_SUCCESS_CALL
} from './actions'
import * as actions from './actions'
import { ConfirmerState } from './types'
export const initialState = {
confirm: {},
complete: {},
operationSuccessCallIdx: {}
} as ConfirmerState
type ConfirmerActions = ActionType<typeof actions>
const reducer = createReducer<ConfirmerState, ConfirmerActions>(initialState, {
[ADD_CONFIRMATION_CALL](state, action) {
const { operationId, squashable, parallelizable } =
action.confirmationOptions
const newCall = {
call: action.confirmationCall,
result: null,
squashable,
operationId,
parallelizable
}
const newConfirm = { ...state.confirm }
if (action.uid in state.confirm) {
newConfirm[action.uid] = {
...state.confirm[action.uid],
calls: [...state.confirm[action.uid].calls, newCall]
}
} else {
newConfirm[action.uid] = {
index: 0,
calls: [newCall]
}
}
return {
...state,
confirm: newConfirm
}
},
[actions.CANCEL_CONFIRMATION_CALL](state, action) {
const newConfirm = { ...state.confirm }
if (action.uid in state.confirm) {
const newCalls = [...state.confirm[action.uid].calls]
newCalls[action.callIndex] = {
...newCalls[action.callIndex],
cancelled: true
}
newConfirm[action.uid] = {
...state.confirm[action.uid],
calls: newCalls
}
newConfirm[action.uid].index = state.confirm[action.uid].index + 1
} else {
console.warn(
'Programming error - cancel confirmation call action called with an invalid uid.'
)
}
return {
...state,
confirm: newConfirm
}
},
[SET_CONFIRMATION_RESULT](state, action) {
const newConfirm = { ...state.confirm }
const newCalls = state.confirm[action.uid].calls
newCalls[action.resultIndex ?? state.confirm[action.uid].index].result =
action.result
if (action.shouldIncrementConfirmGroupIndex) {
newConfirm[action.uid].index = state.confirm[action.uid].index + 1
}
return {
...state,
confirm: newConfirm
}
},
[INCREMENT_CONFIRM_GROUP_INDEX](state, action) {
const newConfirm = { ...state.confirm }
newConfirm[action.uid].index = state.confirm[action.uid].index + 1
return {
...state,
confirm: newConfirm
}
},
[ADD_COMPLETION_CALL](state, action) {
const newComplete = { ...state.complete }
if (action.uid in newComplete) {
newComplete[action.uid].push(action.completionCall)
} else {
newComplete[action.uid] = [action.completionCall]
}
return {
...state,
complete: newComplete
}
},
[SET_OPERATION_SUCCESS_CALL](state, action) {
const newComplete = { ...state.complete }
const newOperationSuccessCallIdx = { ...state.operationSuccessCallIdx }
if (
action.uid in newOperationSuccessCallIdx &&
action.operationId in newOperationSuccessCallIdx[action.uid]
) {
const index = newOperationSuccessCallIdx[action.uid][action.operationId]
// Cancel the previous success call in the `complete` queue
newComplete[action.uid][index] = noop
const newLength = newComplete[action.uid].push(action.completionCall)
// Update the tracker with new index of the operation's success call
newOperationSuccessCallIdx[action.uid][action.operationId] = newLength - 1
} else {
let newLength: number
if (action.uid in newComplete) {
newLength = newComplete[action.uid].push(action.completionCall)
} else {
newComplete[action.uid] = [action.completionCall]
newLength = 1
}
if (!(action.uid in newOperationSuccessCallIdx)) {
newOperationSuccessCallIdx[action.uid] = {}
}
newOperationSuccessCallIdx[action.uid][action.operationId] = newLength - 1
}
return {
...state,
operationSuccessCallIdx: newOperationSuccessCallIdx,
complete: newComplete
}
},
[CLEAR_CONFIRM](state, action) {
const newConfirm = { ...state.confirm }
delete newConfirm[action.uid]
return {
...state,
confirm: newConfirm
}
},
[CLEAR_COMPLETE](state, action) {
const newComplete = { ...state.complete }
const newOperationSuccessCallIdx = { ...state.operationSuccessCallIdx }
delete newOperationSuccessCallIdx[action.uid]
if (
action.index == null ||
action.index + 1 > newComplete[action.uid].length - 1
) {
delete newComplete[action.uid]
} else {
const newCompleteCalls = newComplete[action.uid].slice(action.index + 1)
newComplete[action.uid] = newCompleteCalls
}
return {
...state,
complete: newComplete,
operationSuccessCallIdx: newOperationSuccessCallIdx
}
}
})
export default reducer
|
19b1f903a475343446d0b11a5007556aba6d564c
|
TypeScript
|
antoniojr0007/desafio_ignite_node07
|
/src/modules/statements/useCases/transferFunds/TransferFundsController.spec.ts
| 2.640625
| 3
|
import { hash } from 'bcryptjs';
import request from 'supertest';
import { Connection, createConnection } from 'typeorm';
import { v4 as uuidV4 } from 'uuid';
import { app } from '../../../../app';
import { JWTInvalidTokenError } from '../../../../shared/errors/JWTInvalidTokenError';
import { JWTTokenMissingError } from '../../../../shared/errors/JWTTokenMissingError';
import { OperationType } from '../../entities/Statement';
import { TransferFundsError } from '../../errors/TransferFundsError';
let connection: Connection;
const SENDER_NAME = 'User Sender';
const SENDER_EMAIL = 'sender@fin.com';
const SENDER_PASSWORD = 'any';
const idSender = uuidV4();
let tokenSender: string;
const RECEIVER_NAME = 'User Receiver';
const RECEIVER_EMAIL = 'receiver@fin.com';
const RECEIVER_PASSWORD = 'any';
const idReceiver = uuidV4();
describe('Transfer Funds Controller', () => {
beforeAll(async () => {
// Conecta com o BD
connection = await createConnection();
// Cria a estrutura do BD através das migrations
await connection.runMigrations();
// Cria os usuários
const passwordSender = await hash(SENDER_PASSWORD, 8);
await connection.query(
`INSERT INTO users(id, name, email, password, created_at, updated_at)
VALUES('${idSender}', '${SENDER_NAME}', '${SENDER_EMAIL}', '${passwordSender}', 'NOW()', 'NOW()')
`
);
const passwordReceiver = await hash(RECEIVER_PASSWORD, 8);
await connection.query(
`INSERT INTO users(id, name, email, password, created_at, updated_at)
VALUES('${idReceiver}', '${RECEIVER_NAME}', '${RECEIVER_EMAIL}', '${passwordReceiver}', 'NOW()', 'NOW()')
`
);
// Faz login para obter o token do usuário emissor
const responseToken = await request(app)
.post('/api/v1/sessions')
.send({
email: SENDER_EMAIL,
password: SENDER_PASSWORD,
});
tokenSender = responseToken.body.token;
// Cria um novo depósito para o usuário emissor
await request(app)
.post('/api/v1/statements/deposit')
.send({
amount: 100.00,
description: 'Bank transfer',
})
.set({
Authorization: `Bearer ${tokenSender}`,
});
});
afterAll(async () => {
// Exclui dados e tabelas do BD
await connection.dropDatabase();
// Fecha a conexão com o BD
await connection.close();
});
it('should be able to transfer funds from one user to another', async () => {
const response = await request(app)
.post(`/api/v1/statements/transfers/${idReceiver}`)
.send({
amount: 100.00,
description: 'Bank transfer'
})
.set({
Authorization: `Bearer ${tokenSender}`,
});
expect(response.statusCode).toBe(201);
expect(response.body).toHaveProperty('id');
expect(response.body).toHaveProperty('sender_id');
expect(response.body.user_id).toBe(idReceiver);
expect(response.body.sender_id).toBe(idSender);
expect(response.body.type).toBe(OperationType.TRANSFER);
expect(Number(response.body.amount)).toBe(100.00);
});
it('should not be able to transfer funds from a non existing user', async () => {
// Token não cadastrado
const nonExistentToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiMjJlMzU3YzQtZWY3YS00NDU3LWI0OGMtZDZhYzBjZTkwNDQ5IiwibmFtZSI6IlVzdcOhcmlvIERvaXMiLCJlbWFpbCI6ImRvaXNAZmluLWFwaS5jb20iLCJwYXNzd29yZCI6IiQyYSQwOCRkdXFiQ2FTTlRjNUxmbnZSY0lCOGJPS3AuTmtwQlNQTUU0NnltaFVxSFlEbGgzWGhKTEhteSIsImNyZWF0ZWRfYXQiOiIyMDIxLTA2LTAxVDE4OjAxOjA0LjI0MVoiLCJ1cGRhdGVkX2F0IjoiMjAyMS0wNi0wMVQxODowMTowNC4yNDFaIn0sImlhdCI6MTYyMjU1OTcxMCwiZXhwIjoxNjIyNjQ2MTEwLCJzdWIiOiIyMmUzNTdjNC1lZjdhLTQ0NTctYjQ4Yy1kNmFjMGNlOTA0NDkifQ.Ylobyp0dZO8fWxPsvrJ1FlFjR_mtaImcY5RuD_osiwk';
// Tenta transferir com um token não cadastrado
const response = await request(app)
.post(`/api/v1/statements/transfers/${idReceiver}`)
.send({
amount: 100.00,
description: 'Bank transfer'
})
.set({
Authorization: `Bearer ${nonExistentToken}`,
});
expect(response.statusCode).toBe(404);
expect(response.body.message).toBe(new TransferFundsError.SendingUserNotFound().getMessage());
});
it('should not be able to transfer funds to a non existing user', async () => {
// Tenta transferir para um uuid não cadastrado
const nonExistentUuid = 'af2c9f76-afbc-4f59-b570-7b4b20d0b330';
const response = await request(app)
.post(`/api/v1/statements/transfers/${nonExistentUuid}`)
.send({
amount: 100.00,
description: 'Bank transfer'
})
.set({
Authorization: `Bearer ${tokenSender}`,
});
expect(response.statusCode).toBe(404);
expect(response.body.message).toBe(new TransferFundsError.ReceivingUserNotFound().getMessage());
});
it('should not be able to transfer funds if the token is missing', async () => {
// Tenta obter a movimentação, sem informar o token
const response = await request(app)
.post(`/api/v1/statements/transfers/${idReceiver}`)
.send({
amount: 100.00,
description: 'Bank transfer'
});
expect(response.statusCode).toBe(401);
expect(response.body.message).toBe(new JWTTokenMissingError().getMessage());
});
it('should not be able to transfer funds if the token is invalid', async () => {
// Token inválido
const invalidToken = 'invalid-token';
// Tenta transferir com um token inválido
const response = await request(app)
.post(`/api/v1/statements/transfers/${idReceiver}`)
.send({
amount: 100.00,
description: 'Bank transfer'
})
.set({
Authorization: `Bearer ${invalidToken}`,
});
expect(response.statusCode).toBe(401);
expect(response.body.message).toBe(new JWTInvalidTokenError().getMessage());
});
it('should not be able to transfer funds if there are no sufficient funds', async () => {
// Tenta obter a movimentação, sem informar o token
const response = await request(app)
.post(`/api/v1/statements/transfers/${idReceiver}`)
.send({
amount: 111.00,
description: 'Bank transfer'
})
.set({
Authorization: `Bearer ${tokenSender}`,
});
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe(new TransferFundsError.InsufficientFunds().getMessage());
});
});
|
16ac787f1cc69cc112dc7a3c11f89ced20b22b50
|
TypeScript
|
dakom/pure3d-typescript
|
/src/lib/internal/gltf/gltf-parse/Gltf-Parse-File.ts
| 2.8125
| 3
|
import { GLTF_ORIGINAL } from "../../../Types";
import {getJsonFromArrayBuffer} from "../../common/Json";
const getHeader = (aBuffer:ArrayBuffer) => {
const dv = new DataView(aBuffer, 0, 12);
return {
magic: dv.getUint32(0, true),
version: dv.getUint32(4, true),
length: dv.getUint32(8, true)
}
}
const getChunk = (offset:number) => (aBuffer:ArrayBuffer): [GLTF_ORIGINAL | ArrayBuffer, number] => {
const dv = new DataView(aBuffer, offset, 8);
const chunkLength = dv.getUint32(0, true);
const chunkType = dv.getUint32(4, true);
const chunkStart = offset + 8;
const chunkEnd = chunkStart + chunkLength;
const chunkData = aBuffer.slice(chunkStart, chunkEnd);
const result = [
(chunkType === 0x4E4F534A)
? getJsonFromArrayBuffer(chunkData)
: (chunkType === 0x004E4942)
? chunkData
: null,
chunkEnd
] as [GLTF_ORIGINAL | ArrayBuffer, number];
if(result[0] === null) {
console.log(`unknown chunk type: ${chunkType}`);
}
return result;
}
const asGlb = (aBuffer:ArrayBuffer) => {
const [gltf, gltfEndOffset] = getChunk(12) (aBuffer) as [GLTF_ORIGINAL, number];
const buffers = new Array<ArrayBuffer>();
let offset = gltfEndOffset;
while(offset < aBuffer.byteLength) {
const [bin, endOffset] = getChunk(offset) (aBuffer) as [ArrayBuffer, number];
if(bin !== null) {
buffers.push(bin);
}
offset += endOffset;
}
return {gltf, glbBuffers: buffers};
}
const GLTF_PARSE_isBinaryFile = (aBuffer:ArrayBuffer):boolean =>
getHeader(aBuffer).magic === 0x46546C67;
export const GLTF_PARSE_getOriginalFromArrayBuffer = (aBuffer:ArrayBuffer) =>
GLTF_PARSE_isBinaryFile (aBuffer)
? asGlb(aBuffer)
: {gltf: getJsonFromArrayBuffer(aBuffer), glbBuffers: []};
|
4f458c5e71e81d63567fbd0cc170ef4a49a63317
|
TypeScript
|
matt-ramotar/dropbox-reads-api
|
/src/api/actions/models/Action.ts
| 2.53125
| 3
|
import { DocumentType, prop } from "@typegoose/typegoose";
import { Field, ID, ObjectType } from "type-graphql";
import ActionReaction from "../../actionreactions/models/ActionReaction";
import Book from "../../books/models/Book";
import BookshelfBook from "../../bookshelfbooks/models/BookshelfBook";
import Bookshelf from "../../bookshelves/models/Bookshelf";
import BookTag from "../../booktags/models/BookTag";
import CommentReaction from "../../commentreactions/models/CommentReaction";
import Comment from "../../comments/models/Comment";
import ReviewReaction from "../../reviewreactions/models/ReviewReaction";
import Review from "../../reviews/models/Review";
import Tag from "../../tags/models/Tag";
import User from "../../users/models/User";
import { GodAction, RealGodAction } from "./GodAction";
/**
* @tsoaModel
*/
@ObjectType({ description: "Action model" })
export default class Action {
@Field(() => ID)
@prop()
id!: string;
@Field()
@prop()
type!: string;
@Field()
@prop()
datetime!: Date;
@Field(() => ID)
@prop({ ref: () => User })
userId!: string;
@Field(() => ID)
@prop({ ref: () => User })
otherUserId?: string;
@Field(() => ID)
@prop({ ref: () => Book })
bookId?: string;
@Field(() => ID)
@prop({ ref: () => BookshelfBook })
bookshelfBookId?: string;
@Field(() => ID)
@prop({ ref: () => Bookshelf })
bookshelfId?: string;
@Field(() => ID)
@prop({ ref: () => BookTag })
bookTagId?: string;
@Field(() => ID)
@prop({ ref: () => Tag })
tagId?: string;
@Field(() => ID)
@prop({ ref: () => Review })
reviewId?: string;
@Field(() => ID)
@prop({ ref: () => Comment })
commentId?: string;
@Field(() => ID)
@prop({ ref: () => Comment })
otherCommentId?: string;
@Field(() => ID)
@prop({ ref: () => ReviewReaction })
reviewReactionId?: string;
@Field(() => ID)
@prop({ ref: () => CommentReaction })
commentReactionId?: string;
@Field(() => ID)
@prop({ ref: () => ActionReaction })
actionReactionId?: string;
@Field(() => [ID])
@prop({ ref: () => ActionReaction })
actionReactionIds?: string[];
public async toGodAction(this: DocumentType<Action>): Promise<GodAction> {
const godAction = new RealGodAction(this._id, this.type, this.datetime);
await godAction.populate({
userId: this.userId,
otherUserId: this.otherUserId,
bookId: this.bookId,
bookshelfBookId: this.bookshelfBookId,
bookshelfId: this.bookshelfId,
bookTagId: this.bookTagId,
tagId: this.tagId,
reviewId: this.reviewId,
commentId: this.commentId,
otherCommentId: this.otherCommentId,
reviewReactionId: this.reviewReactionId,
commentReactionId: this.commentReactionId,
actionReactionId: this.actionReactionId,
actionReactionIds: this.actionReactionIds
});
return godAction;
}
public toPojo(this: DocumentType<Action>): Action {
const pojo = this.toObject();
pojo.id = pojo._id;
delete pojo._id;
return pojo;
}
}
|
ff261b67e677e98078b7d71e512f192cb3a89cc6
|
TypeScript
|
Zhouyuj/recycling
|
/src/app/shared/services/map/driving.model.ts
| 2.875
| 3
|
import { Map } from './map.model';
export class Driving {
policy: DrivingPolicy; // 驾车路线规划策略
extensions: string; // 默认值:base,返回基本地址信息, 当取值为:all,返回DriveStep基本信息+DriveStep详细信息
ferry: number; // 默认为0,表示可以使用轮渡,为1的时候表示不可以使用轮渡
map: Map; // AMap.Map对象, 展现结果的地图实例。当指定此参数后,搜索结果的标注、线路等均会自动添加到此地图上。可选
panel: string | HTMLElement; // 结果列表的HTML容器id或容器元素,提供此参数后,结果列表将在此容器中进行展示。可选
hideMarkers: boolean; // 设置隐藏路径规划的起始点图标,设置为true:隐藏图标;设置false:显示图标, 默认值为:false
showTraffic: boolean; // 设置是否显示实时路况信息,默认设置为true。显示绿色代表畅通,黄色代表轻微拥堵,红色代表比较拥堵,灰色表示无路况信息。
province: string; // 车牌省份的汉字缩写,用于判断是否限行,与number属性组合使用,可选。例如:京
number: string; // 除省份之外车牌的字母和数字,用于判断限行相关,与province属性组合使用,可选。例如:NH1N11
isOutline: boolean; // 使用map属性时,绘制的规划线路是否显示描边。缺省为true
outlineColor: string; // 使用map属性时,绘制的规划线路的描边颜色。缺省为'white'
autoFitView: boolean; // 用于控制在路径规划结束后,是否自动调整地图视野使绘制的路线处于视口的可见范围
constructor(obj?: {
policy?: DrivingPolicy,
extensions?: string,
ferry?: number,
map?: Map,
panel?: string | HTMLElement,
hideMarkers?: boolean,
showTraffic?: boolean,
province?: string,
number?: string,
isOutline?: boolean,
outlineColor?: string,
autoFitView?: boolean
}) {
/* tslint:disable-next-line */
for (let k in obj) {
this[k] = obj[k];
}
}
search(start: any, end: any, opts: { waypoints: number[] }) {}
clear() {}
}
export enum DrivingPolicy {
LEAST_TIME = 'LEAST_TIME', // 最快捷模式
LEAST_FEE = 'LEAST_FEE', // 最经济模式
LEAST_DISTANCE = 'LEAST_DISTANCE', // 最短距离模式
REAL_TRAFFIC = 'REAL_TRAFFIC' // 考虑实时路况
}
|
7ee0f471f7589f92ffa7291c25a9fb5fc5bfe2ed
|
TypeScript
|
joonhocho/ts-jutil
|
/src/func/memoize.ts
| 3.21875
| 3
|
export const memoize = <A extends any[], R>(
fn: (...args: A) => R
): ((...args: A) => R) => {
let prevArgs: A | null = null;
let prevReturn: any = null;
return function memoizedFn(this: any, ...args: A): R {
let changed = false;
if (prevArgs) {
const len = args.length;
for (let i = 0; i < len; i += 1) {
if (args[i] !== prevArgs[i]) {
changed = true;
break;
}
}
} else {
// first call
changed = true;
}
if (changed) {
prevArgs = args;
prevReturn = fn.apply(this, args);
return prevReturn;
}
return prevReturn;
};
};
|
2554b987d7eac89ac3473d5659323ee83a933a26
|
TypeScript
|
rogreyroom/caesar-rot-react
|
/src/app/features/alphabet/alphabetSlice.ts
| 2.546875
| 3
|
import { createSlice } from '@reduxjs/toolkit';
import { RootState } from '../../store';
import { generateAlphabet } from '../util/generateAlphabet'
interface AlphabetState {
alphabet: string[]
}
const initialState: AlphabetState = {
alphabet: generateAlphabet()
};
export const alphabetSlice = createSlice({
name: 'alphabet',
initialState,
reducers: {}
})
export const selectAlphabet = (state: RootState) => state.alphabet.alphabet
export default alphabetSlice.reducer
|
1bb8d1973ec46151ddf6a981cdfee237bbd22b32
|
TypeScript
|
i78s/frontend-utils
|
/src/ts/tab/index.ts
| 3.203125
| 3
|
interface TabOption {
index?: number;
activeClass?: string;
onChange?(content: HTMLDivElement): void;
}
export default class Tab {
private tabs: NodeListOf<HTMLAnchorElement>;
private contents: NodeListOf<HTMLDivElement>;
option: TabOption;
private onSelectHandler: (e: Event) => void;
constructor(tabs: NodeListOf<HTMLAnchorElement>, contents: NodeListOf<HTMLDivElement>, option?: TabOption) {
this.tabs = tabs;
this.contents = contents;
this.option = {
index: 0,
activeClass: 'is-active',
onChange: () => {},
...option
};
this.onSelectHandler = (e: Event) => {
e.preventDefault();
this.select(parseInt((<HTMLAnchorElement>e.target).getAttribute('data-index')));
};
this.init();
}
init() {
Array.prototype.forEach.call(this.tabs, (tab: HTMLAnchorElement) => {
tab.addEventListener('click', this.onSelectHandler);
});
this.select(this.option.index);
}
select(index: number) {
Array.prototype.forEach.call(this.tabs, (tab: HTMLAnchorElement) => {
tab.classList.remove(this.option.activeClass);
});
Array.prototype.forEach.call(this.contents, (content: HTMLDivElement) => {
content.classList.remove(this.option.activeClass);
});
this.tabs[index].classList.add(this.option.activeClass);
this.contents[index].classList.add(this.option.activeClass);
this.option.onChange(this.contents[index]);
}
destroy() {
Array.prototype.forEach.call(this.tabs, (tab: HTMLAnchorElement) => {
tab.removeEventListener('click', this.onSelectHandler);
});
}
}
|
5fbf228b6223b4fa58553f90969577d2d5b75ccd
|
TypeScript
|
lgy87/algo
|
/tree/TreeNode.ts
| 3.34375
| 3
|
import * as r from "ramda"
import * as ra from "ramda-adjunct"
const LEFT_PARENTHESIS_WIDTH = 1
const RIGHT_PARENTHESIS_WIDTH = 1
const PARENTHESIS_WIDTH = LEFT_PARENTHESIS_WIDTH + RIGHT_PARENTHESIS_WIDTH
export default class TreeNode<T> {
constructor(private readonly value?: T) {}
static empty = new TreeNode()
static of<T>(value?: T): TreeNode<T> {
return new TreeNode(value)
}
width() {
const realWidth = ra.isUndefined(this.value) ? 0 : String(this.value).length
return realWidth + PARENTHESIS_WIDTH
}
isEmpty() {
return ra.isUndefined(this.value) || this === TreeNode.empty
}
toString() {
return r.isNil(this.value) ? "()" : `(${this.value})`
}
}
|
21797c9731b239ae393fab4648715cc267c7b336
|
TypeScript
|
aravindanve/ts-experiments
|
/complex-inference-2/json-entity.ts
| 3.1875
| 3
|
namespace Entity {
export type Descriptor =
PrimitiveDescriptor |
ArrayDescriptor<UnkeyedContainerDescriptor> |
ObjectDescriptor<KeyedContainerDescriptor>
export type KeyedContainerDescriptor = { [key: string]: Descriptor }
export type UnkeyedContainerDescriptor = { items: Descriptor }
export type PrimitiveDescriptor =
BooleanDescriptor |
NumberDescriptor |
StringDescriptor
export type BooleanDescriptor = { booleanType: true }
export type NumberDescriptor = { numberType: true }
export type StringDescriptor = { stringType: true }
export type ObjectDescriptor<T extends KeyedContainerDescriptor> = { objectType: true, properties: T }
export type ArrayDescriptor<T extends UnkeyedContainerDescriptor> = { arrayType: true } & T
export type Optional<T> = T & { optional: true }
export type Nullable<T> = T & { nullable: true }
export type MetaDescriptor = {
optional?: boolean
nullable?: boolean
}
export type TypeFromDescriptor<T> =
T extends Optional<Nullable<infer T1>> ? ComplexTypeFromDescriptor<T1> | undefined | null :
T extends Optional<infer T2> ? ComplexTypeFromDescriptor<T2> | undefined :
T extends Nullable<infer T3> ? ComplexTypeFromDescriptor<T3> | null :
ComplexTypeFromDescriptor<T>
export type PrimitiveTypeFromDescriptor<T> =
T extends BooleanDescriptor ? boolean :
T extends NumberDescriptor ? number :
T extends StringDescriptor ? string :
unknown
export type ComplexTypeFromDescriptor<T> =
T extends ArrayDescriptor<infer T1> ? ComplexTypeFromDescriptorMap<T1>['items'][] :
T extends ObjectDescriptor<infer T2> ? ComplexTypeFromDescriptorMap<T2> :
PrimitiveTypeFromDescriptor<T>
export type ComplexTypeFromDescriptorMap<T> =
T extends object ? { [K in keyof T]: TypeFromDescriptor<T[K]> } : unknown
export type DescriptorWithMeta<M extends MetaDescriptor, T> =
M extends { optional: true, nullable: true } ? Optional<Nullable<T>> :
M extends { optional: true } ? Optional<T> :
M extends { nullable: true } ? Nullable<T> :
T
export type Factory<T> = { (): T }
export type MetaFactoryReturnType<M extends MetaDescriptor, T> =
DescriptorWithMeta<M, T> &
Factory<TypeFromDescriptor<DescriptorWithMeta<M, T>>>
export function Boolean<M extends MetaDescriptor>(meta?: M): MetaFactoryReturnType<M, BooleanDescriptor> {
throw new Error('Not implemented')
}
export function Number<M extends MetaDescriptor>(meta?: M): MetaFactoryReturnType<M, NumberDescriptor> {
throw new Error('Not implemented')
}
export function String<M extends MetaDescriptor>(meta?: M): MetaFactoryReturnType<M, StringDescriptor> {
throw new Error('Not implemented')
}
export function Object<T extends KeyedContainerDescriptor, M extends MetaDescriptor>(
descriptors: T, meta?: M): MetaFactoryReturnType<M, ObjectDescriptor<T>> {
throw new Error('Not implemented')
}
export function Array<T extends Descriptor, M extends MetaDescriptor>(
descriptor: T, meta?: M): MetaFactoryReturnType<M, ArrayDescriptor<{ items: T }>> {
throw new Error('Not implemented')
}
}
const someBoolean /* :boolean */ = Entity.Boolean()()
const someOptionalBoolean /* :boolean | undefined */ = Entity.Boolean({ optional: true })()
const someNullableBoolean /* :boolean | null */ = Entity.Boolean({ nullable: true })()
const someOptionalNullableBoolean /* :boolean | null | undefined */ = Entity.Boolean({ optional: true, nullable: true })()
const someNumber /* :number */ = Entity.Number()()
const someOptionalNumber /* :number | undefined */ = Entity.Number({ optional: true })()
const someNullableNumber /* :number | null */ = Entity.Number({ nullable: true })()
const someOptionalNullableNumber /* :number | null | undefined */ = Entity.Number({ optional: true, nullable: true })()
const someString /* :string */ = Entity.String()()
const someOptionalString /* :string | undefined */ = Entity.String({ optional: true })()
const someNullableString /* :string | null */ = Entity.String({ nullable: true })()
const someOptionalNullableString /* :string | null | undefined */ = Entity.String({ optional: true, nullable: true })()
const someObject /* :{ name: string } */ = Entity.Object({ name: Entity.String() })()
const someObjectWithOptionalProperty /* :{ name: string | undefined } */ = Entity.Object({ name: Entity.String({ optional: true }) })()
const someObjectWithNullableProperty /* :{ name: string | null } */ = Entity.Object({ name: Entity.String({ nullable: true }) })()
const someObjectWithOptionalNullableProperty /* :{ name: string | undefined | null } */ = Entity.Object({ name: Entity.String({ optional: true, nullable: true }) })()
const someOptionalObject /* :{ name: string } | undefined */ = Entity.Object({ name: Entity.String() }, { optional: true })()
const someNullableObject /* :{ name: string } | null */ = Entity.Object({ name: Entity.String() }, { nullable: true })()
const someOptionalNullableObject /* :{ name: string } | undefined | null */ = Entity.Object({ name: Entity.String() }, { optional: true, nullable: true })()
const someStringArray /* :string[] */ = Entity.Array(Entity.String())()
const someOptionalStringArray /* :string[] | undefined */ = Entity.Array(Entity.String(), { optional: true })()
const someNullableStringArray /* :string[] | null */ = Entity.Array(Entity.String(), { nullable: true })()
const someOptionalNullableStringArray /* :string[] | null | undefined */ = Entity.Array(Entity.String(), { optional: true, nullable: true })()
const someObjectArray /* :{ name: string }[] */ = Entity.Array(Entity.Object({ name: Entity.String() }))()
const someOptionalObjectArray /* :{ name: string }[] | undefined */ = Entity.Array(Entity.Object({ name: Entity.String() }), { optional: true })()
const someNullableObjectArray /* :{ name: string }[] | null */ = Entity.Array(Entity.Object({ name: Entity.String() }), { nullable: true })()
const someOptionalNullableObjectArray /* :{ name: string }[] | undefined | null */ = Entity.Array(Entity.Object({ name: Entity.String() }), { optional: true, nullable: true })()
const SomeEntity = Entity.Object({
id: Entity.Number(),
displayName: Entity.String(),
isDefault: Entity.Boolean(),
isPrivate: Entity.Boolean({ optional: true, nullable: true }),
info: Entity.Object({
phone: Entity.String()
}),
roles: Entity.Array(Entity.Object({
id: Entity.Number(),
displayName: Entity.String(),
isPrivate: Entity.Boolean({ optional: true, nullable: true })
}))
})
const someEntity /* :{
id: number;
displayName: string;
isDefault: boolean;
isPrivate: boolean | null | undefined;
info: {
phone: string;
};
roles: {
id: number;
displayName: string;
isPrivate: boolean | null | undefined;
}[];
} */ = SomeEntity()
|
c7c2ddf8dcd1eedc84e40bd6ca62f79df4f59871
|
TypeScript
|
bazo/itera_test
|
/src/types.d.ts
| 2.796875
| 3
|
declare interface Department {
id: number;
departmentName: string;
}
declare interface Employee {
id: number;
name: string;
age: number;
departmentId: number;
startDate: string;
endDate: string | null;
}
declare interface DepartmentsByID {
[id: number]: Department;
}
|
b8a55f7ac979b3f52be97b4977edca5442b8c315
|
TypeScript
|
djwhatle/mig-ui
|
/src/app/storage/duck/reducers.ts
| 2.53125
| 3
|
import { Types } from './actions';
import { createReducer } from 'reduxsauce';
import ConnectionState from '../../common/connection_state';
export const INITIAL_STATE = {
isFetching: false,
isError: false,
migStorageList: [],
searchTerm: '',
connectionState: ConnectionState.Pending,
};
export const migStorageFetchRequest = (state = INITIAL_STATE, action) => {
return { ...state, isFetching: true };
};
export const migStorageFetchSuccess = (state = INITIAL_STATE, action) => {
return {
...state,
migStorageList: action.migStorageList,
isFetching: false,
};
};
export const migStorageFetchFailure = (state = INITIAL_STATE, action) => {
return {
...state,
isError: true,
isFetching: false,
};
};
export const setConnectionState = (state = INITIAL_STATE, action) => {
return { ...state, connectionState: action.connectionState };
};
export const addStorageSuccess = (state = INITIAL_STATE, action) => {
return {
...state,
migStorageList: [...state.migStorageList, action.newStorage],
};
};
export const removeStorageSuccess = (state = INITIAL_STATE, action) => {
return {
...state,
migStorageList: state.migStorageList.filter(
item => item.MigStorage.metadata.name !== action.name
),
};
};
export const updateSearchTerm = (state = INITIAL_STATE, action) => {
return { ...state, searchTerm: action.searchTerm };
};
export const updateStorageSuccess = (state = INITIAL_STATE, action) => {
return {
...state,
migStorageList: [
...state.migStorageList.filter(
s => s.MigStorage.metadata.name !== action.updatedStorage.MigStorage.metadata.name
),
{ ...action.updatedStorage },
],
};
};
export const updateStorages = (state = INITIAL_STATE, action) => {
return {
...state,
migStorageList: action.updatedStorages,
};
};
export const HANDLERS = {
[Types.MIG_STORAGE_FETCH_REQUEST]: migStorageFetchRequest,
[Types.MIG_STORAGE_FETCH_SUCCESS]: migStorageFetchSuccess,
[Types.MIG_STORAGE_FETCH_FAILURE]: migStorageFetchFailure,
[Types.ADD_STORAGE_SUCCESS]: addStorageSuccess,
[Types.UPDATE_STORAGES]: updateStorages,
[Types.UPDATE_STORAGE_SUCCESS]: updateStorageSuccess,
[Types.REMOVE_STORAGE_SUCCESS]: removeStorageSuccess,
[Types.UPDATE_SEARCH_TERM]: updateSearchTerm,
[Types.SET_CONNECTION_STATE]: setConnectionState,
};
export default createReducer(INITIAL_STATE, HANDLERS);
|
2bcd253c743bf4afeecc89fb4e584842af164faa
|
TypeScript
|
WangWenJuan666/hmr-ng6
|
/src/app/shared/directive/forbidden-name.directive.ts
| 3.078125
| 3
|
import { Directive,HostBinding, } from '@angular/core';
import { AbstractControl, FormGroup, NG_VALIDATORS, ValidationErrors, Validator, ValidatorFn } from '@angular/forms';
// export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
// return (control: AbstractControl): {[key: string]: any} | null => {
// const forbidden = nameRe.test(control.value);
// return forbidden ? {'forbiddenName': {value: control.value}} : null;
// };
// }
/** A hero's name can't match the hero's alter ego */
export const identityRevealedValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
const name = control.get('name');
const alterEgo = control.get('alterEgo');
return name && alterEgo && name.value === alterEgo.value ? { 'identityRevealed': true } : null;
};
@Directive ({
selector: '[appIdentityRevealed]',
providers: [{ provide: NG_VALIDATORS, useExisting: IdentityRevealedValidatorDirective, multi: true }]
})
export class IdentityRevealedValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors {
return identityRevealedValidator(control)
}
}
// 这个函数实际上是一个工厂,它接受一个用来检测指定名字是否已被禁用的正则表达式,并返回一个验证器函数。
// 在本例中,禁止的名字是“bob”; 验证器会拒绝任何带有“bob”的英雄名字。 在其他地方,只要配置的正则表达式可以匹配上,它可能拒绝“alice”或者任何其他名字。
// forbiddenNameValidator 工厂函数返回配置好的验证器函数。 该函数接受一个 Angular 控制器对象,并在控制器值有效时返回 null,或无效时返回验证错误对象。 验证错误对象通常有一个名为验证秘钥(forbiddenName)的属性。其值为一个任意词典,你可以用来插入错误信息({name})。
// 自定义异步验证器和同步验证器很像,只是它们必须返回一个稍后会输出 null 或“验证错误对象”的承诺(Promise)或可观察对象,如果是可观察对象,那么它必须在某个时间点被完成(complete),那时候这个表单就会使用它输出的最后一个值作为验证结果。(译注:HTTP 服务是自动完成的,但是某些自定义的可观察对象可能需要手动调用 complete 方法)
|
2349f84ecb4ccd40add8f758c00b002ae35efabb
|
TypeScript
|
mwjaworski/rise
|
/test/service_query_spec.ts
| 2.984375
| 3
|
import 'mocha';
import { assert } from 'chai';
import { ServiceQuery } from '../lib/engine/service_query';
import { IService } from '../lib/components/service';
import { Component, IComponent } from '../lib/engine/component';
import { IMessage } from '../lib/core/types';
import { head, has, includes } from 'lodash';
class Service1 extends Component implements IService {
// VALUE
identity(): IMessage {
return {
type: 1
};
}
}
class Service2 extends Component implements IService {
// TYPE
identity(): IMessage {
return {
type: Number
};
}
}
class Service3 extends Component implements IService {
// ANY
identity(): IMessage {
return {
type: null
};
}
}
describe('RISE: ServiceQuery', () => {
const service1 = new Service1();
const service2 = new Service2();
const service3 = new Service3();
it('ServiceQuery will track matches against values, types, or *', () => {
const serviceQuery = new ServiceQuery();
serviceQuery.registerService(service1);
serviceQuery.registerService(service2);
serviceQuery.registerService(service3);
const database = serviceQuery.database;
assert(head(database['type']['number::1']) === service1, 'Service 1 matches a value');
assert(head(database['type']['number']) === service2, 'Service 1 matches a type');
assert(head(database['type']['*']) === service3, 'Service 1 matches a anything');
});
it('ServiceQuery will match (lookup) against values, types, or *', () => {
const serviceQuery = new ServiceQuery();
serviceQuery.registerService(service1);
serviceQuery.registerService(service2);
serviceQuery.registerService(service3);
const serviceLookup1 = serviceQuery.discoverServices({
type: 1
});
const serviceLookup2 = serviceQuery.discoverServices({
type: 2
});
const serviceLookup3 = serviceQuery.discoverServices({
type: '-'
});
assert(includes(serviceLookup1 as any, service3), `service(*) matches 1`);
assert(includes(serviceLookup1 as any, service2), `service(number) matches 1`);
assert(includes(serviceLookup1 as any, service1), `service(1) matches 1`);
assert(includes(serviceLookup2 as any, service3), `service(*) matches 2`);
assert(includes(serviceLookup2 as any, service2), `service(number) matches 2`);
assert(includes(serviceLookup3 as any, service3), `service(3) matches '-'`);
});
});
|
b8bfd15eb8c225b8a84b35b4026abec0d30b36d9
|
TypeScript
|
leonardoquevedox/kombi
|
/legacy/src/services/file-uploader.service.ts
| 2.53125
| 3
|
/**
* @license MIT
* @version 1.1.0
* @author M.A.R.S. Labs
* @description File upload management service.
*/
import { Injectable } from "@angular/core";
import { Uploader } from "angular2-http-file-upload";
import { UploadItem } from "angular2-http-file-upload";
@Injectable()
export class MarsFileUploaderService {
constructor(private uploaderService: Uploader) { }
upload(url: string, file: File, params: any, headers: any, callback: Function) {
let uploadItem = new UploadItem();
uploadItem.file = file;
uploadItem.url = url;
uploadItem.headers = headers;
uploadItem.formData = params;
this.uploaderService.upload(uploadItem);
this.uploaderService.onCompleteUpload = (item, response, status, headers) => {
if (callback) callback(undefined, response);
};
this.uploaderService.onErrorUpload = (item, response, status, headers) => {
if (callback) callback({ status: status, message: "Whoops! There was an error uploading the file :(" });
};
}
}
|
8dd7d64ea9f05b7e8a92a1907771892c62c2967c
|
TypeScript
|
IMRZ/tw-db
|
/src/generated/threekingdoms/collections/Mens.ts
| 2.609375
| 3
|
import { CollectionCache, CollectionKey } from "../../../common";
import { BattleEntities } from "./BattleEntities";
import { BattleAnimationsTable } from "./BattleAnimationsTable";
export namespace Mens {
export const KEY = new CollectionKey("mens");
export class Entry {
private readonly collectionCache: CollectionCache;
readonly key: string;
readonly _battleEntity: string;
readonly _animation: string;
readonly _additionalAnimation: string;
constructor(collectionCache: CollectionCache, values: any) {
this.collectionCache = collectionCache;
this.key = values["key"];
this._battleEntity = values["battle_entity"];
this._animation = values["animation"];
this._additionalAnimation = values["additional_animation"];
}
get battleEntity(): BattleEntities.Entry | undefined {
const collection = <BattleEntities.Entry[]>this.collectionCache.getCollection(BattleEntities.KEY, BattleEntities.Entry);
return collection.find(entry => entry.key === this._battleEntity);
}
get animation(): BattleAnimationsTable.Entry | undefined {
const collection = <BattleAnimationsTable.Entry[]>this.collectionCache.getCollection(BattleAnimationsTable.KEY, BattleAnimationsTable.Entry);
return collection.find(entry => entry.key === this._animation);
}
get additionalAnimation(): BattleAnimationsTable.Entry | undefined {
const collection = <BattleAnimationsTable.Entry[]>this.collectionCache.getCollection(BattleAnimationsTable.KEY, BattleAnimationsTable.Entry);
return collection.find(entry => entry.key === this._additionalAnimation);
}
}
}
export default Mens;
|
7962053d74a74eeb1f87a7a1e42565f967229147
|
TypeScript
|
yuhenabc/sketchpad
|
/src/libs/CanvasStatus.ts
| 2.9375
| 3
|
import {Point} from '../d/types'
/**
* Class CanvasStatus
*/
export default class CanvasStatus {
last: number
backup: number
current: number
startPoint: Point
endPoint: Point
points: Array<Point>
static FLAG_PENCEL: number = 1
static FLAG_ERASER: number = 2
static FLAG_S_LINE: number = 3
static FLAG_RECTANGLE: number = 4
static FLAG_CIRCLE: number = 5
static FLAG_S_RECTANGLE: number = 6
static FLAG_ROUND: number = 7
constructor() {
this.last = CanvasStatus.FLAG_PENCEL
this.backup = CanvasStatus.FLAG_PENCEL
this.current = 0
this.startPoint = {x: 0, y: 0}
this.endPoint = {x: 0, y: 0}
this.points = []
}
startWorking() {
if (this.current === 0) this.current = this.backup
}
endWorking() {
this.backup = this.current
this.current = 0
}
isWorking(): boolean {
return this.current > 0
}
setTool(value) {
if (value !== CanvasStatus.FLAG_ERASER) this.last = value
this.backup = value
this.current = 0
}
restoreTool() {
this.backup = this.last
this.current = 0
}
setStartPoint(point: Point) {
const {x, y} = point
this.startPoint.x = x
this.startPoint.y = y
}
getStartPoint(): Point {
const {x, y} = this.startPoint
return {x, y}
}
setEndPoint(point: Point) {
const {x, y} = point
this.endPoint.x = x
this.endPoint.y = y
}
getEndPoint(): Point {
const {x, y} = this.endPoint
return {x, y}
}
appendPoints(value) {
this.points.push(value)
}
clearPoints() {
this.points = []
}
}
|
a88c1a20a1f8fab389f1572ee024917d99db2857
|
TypeScript
|
plumthedev/cutter
|
/src/core/tabs/contracts/repository.ts
| 2.71875
| 3
|
import Tab = chrome.tabs.Tab;
import QueryInfo = chrome.tabs.QueryInfo;
/**
* Tabs repository interface.
*
* @author Kacper Pruszyński (plumthedev) <kacper.pruszynski99@gmail.com>
* @package Cutter/Core
*/
interface Repository {
/**
* Get all tabs.
*
* @param query {chrome.tabs.QueryInfo}
*
* @return {Promise<chrome.tabs.Tab[]>}
*/
find(query: QueryInfo): Promise<Tab[]>;
/**
* Get active tab.
*
* @return {Promise<chrome.tabs.Tab[]>}
*/
findActive(): Promise<Tab>;
}
export default Repository;
|
27209f2cf1aae9200d6e894db9f424a3cdb23d0b
|
TypeScript
|
MarioLegenda/voca-builder
|
/src/app/http/ErrorFactory.ts
| 2.75
| 3
|
import { ApiError, AppError, ErrorType, FailedRequest, NetworkError } from './Errors';
import { getHeaders } from './httpHelpers';
import { AxiosResponse, AxiosError } from 'axios';
export default class ErrorFactory {
static isNetworkError(e: AxiosError) {
if (!e.response) {
const re = new RegExp('timeout');
return !re.test(e.message);
}
return false;
}
static isTimoutError(e: AxiosError) {
const message = e.message;
const re = new RegExp('timeout');
return re.test(message);
}
static isServerError(err: AxiosError) {
const status = err.response?.status as number;
return status > 500 && status < 599;
}
static isHttpError(response: AxiosResponse) {
const status = response.status;
return status < 200 || status > 299;
}
static isApiError(response: AxiosResponse) {
const status = response.status;
return status === 400;
}
static createTimeoutError(): AppError {
return new AppError('', ErrorType.TimeoutError);
}
static createServerError(): AppError {
return new AppError('', ErrorType.ServerError);
}
static createApiError(data: any): ApiError {
return new ApiError('', ErrorType.ApiError, data);
}
static createNetworkError(e: AxiosError): NetworkError {
const tmp = { realMessage: '', message: '' };
if (e) {
tmp.realMessage = e.message;
tmp.message = e.message;
}
return new NetworkError(tmp.message, ErrorType.NetworkError, tmp.realMessage);
}
static createUnknownError(e: AxiosError): AppError {
const tmp = { message: '' };
if (e) {
tmp.message = e.message;
}
return new AppError(tmp.message, ErrorType.UnknownError);
}
static createFailedRequest(response: AxiosResponse, e: AppError, message: string) {
const tmp = { realMessage: '' };
if (e) {
tmp.realMessage = e.message;
}
return new FailedRequest(message, ErrorType.FailedRequestError, response.status, response.request.url, getHeaders(response));
}
static createUnsuccessfulRequestError(response: AxiosResponse) {
return new FailedRequest('Unsuccessful request', ErrorType.HttpError, response.status, response.request.url, response.headers);
}
}
|
f461222f8132c430a1491d9801ed4c1f30d0c6d1
|
TypeScript
|
mremolt/stundenzettel-webcomponents
|
/src/app/store/counter/counter.reducer.ts
| 2.984375
| 3
|
import { ActionType, getType } from 'typesafe-actions';
import { DeepReadonly } from 'utility-types';
import * as actions from './counter.actions';
export type CounterAction = ActionType<typeof actions>;
export const initialState = { value: 0 };
export type CounterState = DeepReadonly<typeof initialState>;
export const counterReducer = (state: CounterState = initialState, action: CounterAction): CounterState => {
switch (action.type) {
case getType(actions.increment):
return { ...state, value: state.value + 1 };
case getType(actions.decrement):
return { ...state, value: state.value - 1 };
case getType(actions.add):
return { ...state, value: state.value + action.payload };
default:
return state;
}
};
|
2750db121a126b1bafb91bb4c4a5a2ec4e315ca3
|
TypeScript
|
heikaimu/phaser3-game-one
|
/src/state-machine/StateMachine.ts
| 3.171875
| 3
|
/*
* @Description: 状态机器
* @Version: 2.0
* @Autor: Yaowen Liu
* @Date: 2021-01-11 22:26:28
* @LastEditors: Yaowen Liu
* @LastEditTime: 2021-01-12 12:41:25
*/
class StateMachine {
private initialState: string;
private possibleStates: Object;
private stateArgs:Array<any>;
private state?: string;
constructor(initialState: string, possibleStates: Object, stateArgs = []) {
this.initialState = initialState;
this.possibleStates = possibleStates;
this.stateArgs = stateArgs;
Object.keys(this.possibleStates).forEach((key: string) => {
this.possibleStates[key].stateMachine = this;
})
}
step() {
// 如果没有状态则设置为初始状态
if (!this.state) {
this.state = this.initialState;
this.possibleStates[this.state].enter(...this.stateArgs);
}
this.possibleStates[this.state].execute(...this.stateArgs);
}
transition(newState, ...enterArgs) {
this.state = newState;
if (this.state) {
this.possibleStates[this.state].enter(...this.stateArgs, ...enterArgs);
}
}
}
class State {
stateMachine: any;
enter(...args) {
}
execute(...args) {
}
}
export {
StateMachine,
State
}
|
c4c34832beea7bf25cc2f8cf8be10cf78d7b1789
|
TypeScript
|
da-peng/common-manager
|
/crewler-ws/src/repositpry/AnchorRepository.ts
| 2.796875
| 3
|
import { EntityRepository, Repository } from "typeorm";
import { Anchor } from "../entity/Anchor";
@EntityRepository(Anchor)
export class AnchorRepository extends Repository<Anchor> {
/**唯一 */
async createAndSave(nickName: string, anchorLink: string, sex: string = 'male' || 'female' || '', ageGroup: string = '70后' || '80后' || '90后' || '00后' || '10后' || '') {
const anchor = new Anchor();
anchor.nickName = nickName
anchor.sex = sex
anchor.ageGroup = ageGroup
anchor.anchorLink = anchorLink
const isExist = await this.getByanchorLink(anchorLink)
if (isExist!!) {
if (isExist.nickName !== nickName) {
isExist.nickName = nickName
return this.manager.save(isExist);/**更新 */
} else {
return isExist
}
} else {
return this.manager.save(anchor);/**插入新的 */
}
}
getByNickNameAndAnchorLink(nickName: string, anchorLink: string): Promise<Anchor> {
return this.createQueryBuilder('anchor')
.where(`anchor.nickName = :nickName OR anchor.anchorLink= :anchorLink`, { 'nickName': nickName, 'anchorLink': anchorLink })
.getOne();
}
getByanchorLink(anchorLink: string): Promise<Anchor> {
return this.createQueryBuilder('anchor')
.where(`anchor.anchorLink= :anchorLink`, { 'anchorLink': anchorLink })
.getOne();
}
getByanchorId(anchorId: number) {
return this.createQueryBuilder('anchor')
.where(`anchor.id = :anchorId`, { 'anchorId': anchorId })
.getOne();
}
/**
* 查询出所有anchorLinks
* @param pageSize
* @param pageIndex
*/
getByanchorLinks(pageSize: number, pageIndex: number) {
return this.createQueryBuilder('anchor')
.select('anchor.id,anchor.anchorLink')
.limit(pageSize)
.offset(pageIndex * pageSize)
.getRawMany()
}
/**
* 查询表的记录数
*/
getRows() {
return this.createQueryBuilder('anchor').getCount()
}
}
|
aea7e9083a6493b38eb6d79c60df121e3434b8d2
|
TypeScript
|
Hawkbat/ToDoQuestBootstrap
|
/src/app/store.service.ts
| 2.859375
| 3
|
import { Injectable } from '@angular/core'
export enum Status {
Editing = 1,
InProgress = 2,
Completed = 4
}
export namespace Status {
export function print(status: Status) {
if (status == Status.InProgress) return "In Progress"
else return Status[status]
}
}
export interface ITask {
name: string
info: string
}
export interface IQuest extends ITask {
status: Status
steps: IStep[]
exp: number
}
export interface IStep extends ITask {
complete: boolean
}
export interface State {
quests: IQuest[]
level: number
exp: number
selectedQuest: number
editing: boolean
tempQuest: IQuest
filter: number
}
@Injectable()
export class StoreService {
state: State
constructor() {
this.loadState()
}
addNewQuest() {
this.state.quests.push({ name: "New Quest", info: "", status: Status.Editing, exp: 20, steps: [{ name: "Step 1", info: "", complete: false }] })
this.state.selectedQuest = this.state.quests.length - 1
this.setEditing(true)
this.refresh()
}
selectQuest(questId: number) {
this.state.selectedQuest = questId
if (this.state.editing) {
this.setEditing(false)
}
this.refresh()
}
removeCurrentQuest() {
this.state.quests.splice(this.state.selectedQuest, 1)
this.state.selectedQuest = -1
this.refresh()
}
setCurrentQuestStatus(status: Status) {
var quest = this.state.quests[this.state.selectedQuest]
if (quest.status == Status.Completed && status != Status.Completed) {
this.state.exp -= quest.exp
while (this.state.exp < 0) {
this.state.exp += 100
this.state.level--
}
}
quest.status = status
if (status == Status.Completed) {
this.state.exp += quest.exp
while (this.state.exp >= 100) {
this.state.exp -= 100
this.state.level++
}
} else {
for (let i = 0; i < quest.steps.length; i++) {
quest.steps[i].complete = false
}
}
this.refresh()
}
addNewStep() {
this.state.tempQuest.steps.push({ name: "Step " + (this.state.tempQuest.steps.length + 1), info: "", complete: false })
this.refresh()
}
removeStep(id: number) {
this.state.tempQuest.steps.splice(id, 1)
this.refresh()
}
setStepCompletion(stepId: number, complete: boolean) {
this.state.quests[this.state.selectedQuest].steps[stepId].complete = complete
this.refresh()
}
applyEdit() {
this.state.quests.splice(this.state.selectedQuest, 1, this.state.tempQuest)
this.setEditing(false)
this.refresh()
}
setEditing(editing: boolean) {
this.state.editing = editing
if (editing) {
this.state.tempQuest = JSON.parse(JSON.stringify(this.state.quests[this.state.selectedQuest]))
} else {
this.state.tempQuest = null
}
this.refresh()
}
toggleFilter(status: Status) {
if ((this.state.filter & status) == status) {
this.state.filter -= status
} else {
this.state.filter += status
}
this.refresh()
}
refresh() {
this.saveState()
}
saveState() {
localStorage.setItem("state", JSON.stringify(this.state))
}
loadState() {
if (localStorage.getItem("state")) {
this.state = JSON.parse(localStorage.getItem("state"))
} else {
this.state = {
quests: [],
level: 1,
exp: 0,
selectedQuest: -1,
editing: false,
tempQuest: null,
filter: Status.Editing | Status.InProgress
}
}
}
}
|
90d3305e7309cd84c47f217b42e087a958ba52d5
|
TypeScript
|
manuncorrea/backend-sistema-de-cadastro
|
/src/services/DeleteUserService.ts
| 2.703125
| 3
|
import { isValidObjectId } from 'mongoose';
import User from '../models/User';
interface Request {
id: string
}
class DeleteUserService {
public async execute({ id }: Request) {
if(!isValidObjectId(id)) throw new Error('Invalid id argument type')
const userExists = await User.findById(id)
if(!userExists) throw new Error('User not found' )
const user = await User.findByIdAndDelete(id)
return user
}
}
export default DeleteUserService
|
81a9b38c83784c3654cbb4c9820faa327d2dcd5b
|
TypeScript
|
fnortes/commons-utils
|
/tests/text/validations/text.test.ts
| 2.921875
| 3
|
import { isNull, isNotNull, isEmpty, isNotEmpty, isEmptyString, isNotEmptyString, isBlankString, isNotBlankString, isBlank, isNotBlank, isBase64Encoded } from "../../../src/text/validations/text";
describe("it should exist a isNull function", () => {
test("should return true", () => {
expect(isNull(undefined)).toBeTruthy();
expect(isNull(null)).toBeTruthy();
});
test("should return false", () => {
expect(isNull("")).toBeFalsy();
expect(isNull("a")).toBeFalsy();
expect(isNull(new Date())).toBeFalsy();
expect(isNull(2)).toBeFalsy();
expect(isNull(-2)).toBeFalsy();
expect(isNull({ test: 1 })).toBeFalsy();
});
});
describe("it should exist a isNotNull function", () => {
test("should return false", () => {
expect(isNotNull(undefined)).toBeFalsy();
expect(isNotNull(null)).toBeFalsy();
});
test("should return true", () => {
expect(isNotNull("")).toBeTruthy();
expect(isNotNull("a")).toBeTruthy();
expect(isNotNull(new Date())).toBeTruthy();
expect(isNotNull(2)).toBeTruthy();
expect(isNotNull(-2)).toBeTruthy();
expect(isNotNull({ test: 1 })).toBeTruthy();
});
});
describe("it should exist a isEmpty function", () => {
test("should return true", () => {
expect(isEmpty(undefined)).toBeTruthy();
expect(isEmpty(null)).toBeTruthy();
expect(isEmpty("")).toBeTruthy();
});
test("should return false", () => {
expect(isEmpty("a")).toBeFalsy();
expect(isEmpty(new Date())).toBeFalsy();
expect(isEmpty(2)).toBeFalsy();
expect(isEmpty(-2)).toBeFalsy();
expect(isEmpty({ test: 1 })).toBeFalsy();
});
});
describe("it should exist a isNotEmpty function", () => {
test("should return false", () => {
expect(isNotEmpty(undefined)).toBeFalsy();
expect(isNotEmpty(null)).toBeFalsy();
expect(isNotEmpty("")).toBeFalsy();
});
test("should return true", () => {
expect(isNotEmpty("a")).toBeTruthy();
expect(isNotEmpty(new Date())).toBeTruthy();
expect(isNotEmpty(2)).toBeTruthy();
expect(isNotEmpty(-2)).toBeTruthy();
expect(isNotEmpty({ test: 1 })).toBeTruthy();
});
});
describe("it should exist a isEmptyString function", () => {
test("should return true", () => {
expect(isEmptyString("")).toBeTruthy();
});
test("should return false", () => {
expect(isEmptyString(undefined)).toBeFalsy();
expect(isEmptyString(null)).toBeFalsy();
expect(isEmptyString(" ")).toBeFalsy();
expect(isEmptyString("a")).toBeFalsy();
expect(isEmptyString(new Date())).toBeFalsy();
expect(isEmptyString(2)).toBeFalsy();
expect(isEmptyString(-2)).toBeFalsy();
expect(isEmptyString({ test: 1 })).toBeFalsy();
});
});
describe("it should exist a isNotEmptyString function", () => {
test("should return false", () => {
expect(isNotEmptyString("")).toBeFalsy();
expect(isNotEmptyString(undefined)).toBeFalsy();
expect(isNotEmptyString(null)).toBeFalsy();
expect(isNotEmptyString(new Date())).toBeFalsy();
expect(isNotEmptyString(2)).toBeFalsy();
expect(isNotEmptyString(-2)).toBeFalsy();
expect(isNotEmptyString({ test: 1 })).toBeFalsy();
});
test("should return true", () => {
expect(isNotEmptyString(" ")).toBeTruthy();
expect(isNotEmptyString("a")).toBeTruthy();
});
});
describe("it should exist a isBlankString function", () => {
test("should return true", () => {
expect(isBlankString("")).toBeTruthy();
expect(isBlankString(" ")).toBeTruthy();
});
test("should return false", () => {
expect(isBlankString(undefined)).toBeFalsy();
expect(isBlankString(null)).toBeFalsy();
expect(isBlankString("a")).toBeFalsy();
expect(isBlankString(new Date())).toBeFalsy();
expect(isBlankString(2)).toBeFalsy();
expect(isBlankString(-2)).toBeFalsy();
expect(isBlankString({ test: 1 })).toBeFalsy();
});
});
describe("it should exist a isNotBlankString function", () => {
test("should return false", () => {
expect(isNotBlankString("")).toBeFalsy();
expect(isNotBlankString(" ")).toBeFalsy();
expect(isNotBlankString(undefined)).toBeFalsy();
expect(isNotBlankString(null)).toBeFalsy();
expect(isNotBlankString(new Date())).toBeFalsy();
expect(isNotBlankString(2)).toBeFalsy();
expect(isNotBlankString(-2)).toBeFalsy();
expect(isNotBlankString({ test: 1 })).toBeFalsy();
});
test("should return true", () => {
expect(isNotBlankString("a")).toBeTruthy();
});
});
describe("it should exist a isBlank function", () => {
test("should return true", () => {
expect(isBlank("")).toBeTruthy();
expect(isBlank(" ")).toBeTruthy();
expect(isBlank(undefined)).toBeTruthy();
expect(isBlank(null)).toBeTruthy();
});
test("should return false", () => {
expect(isBlank("a")).toBeFalsy();
expect(isBlank(new Date())).toBeFalsy();
expect(isBlank(2)).toBeFalsy();
expect(isBlank(-2)).toBeFalsy();
expect(isBlank({ test: 1 })).toBeFalsy();
});
});
describe("it should exist a isNotBlank function", () => {
test("should return false", () => {
expect(isNotBlank("")).toBeFalsy();
expect(isNotBlank(" ")).toBeFalsy();
expect(isNotBlank(undefined)).toBeFalsy();
expect(isNotBlank(null)).toBeFalsy();
});
test("should return true", () => {
expect(isNotBlank("a")).toBeTruthy();
expect(isNotBlank(new Date())).toBeTruthy();
expect(isNotBlank(2)).toBeTruthy();
expect(isNotBlank(-2)).toBeTruthy();
expect(isNotBlank({ test: 1 })).toBeTruthy();
});
});
describe("it should exist a isBase64Encoded function", () => {
test("should return false", () => {
expect(isBase64Encoded(undefined)).toBeFalsy();
expect(isBase64Encoded(null)).toBeFalsy();
expect(isBase64Encoded("")).toBeFalsy();
expect(isBase64Encoded("test text")).toBeFalsy();
expect(isBase64Encoded(new Date())).toBeFalsy();
expect(isBase64Encoded(2)).toBeFalsy();
expect(isBase64Encoded(-2)).toBeFalsy();
expect(isBase64Encoded({ test: 1 })).toBeFalsy();
});
test("should return true", () => {
const validBase64Encoded =
"U29tZVN0cmluZ09idmlvdXNseU5vdEJhc2U2NEVuY29kZWQ=";
expect(isBase64Encoded(validBase64Encoded)).toBeTruthy();
});
});
|
d3b4868039b9d15d12b140b3fe90956b183f8213
|
TypeScript
|
jpatel3/typescript-edx
|
/edx_9/gen_constraints.ts
| 2.796875
| 3
|
class List<T extends IAccount>{
_items:T[] = [];
add(item:T){
this._items.push(item);
}
getItem(): T[{
return this._items;
}
}
|
f548f68086467639c16b1567f96024a7b55f8daa
|
TypeScript
|
ketFriendly/url-shortener-api
|
/src/controllers/url.controller.ts
| 2.609375
| 3
|
import { Controller, Get, HttpStatus, Post, Req, Res } from '@nestjs/common';
import { UrlService } from '../services/url.service';
import { Request, Response } from 'express';
import * as validUrl from 'valid-url';
import * as _ from 'lodash';
import * as UrlParse from 'url-parse';
@Controller('api')
export class UrlController {
constructor(private readonly urlService: UrlService) { }
@Post('/url/shorten')
async getShortUrl(@Req() req: Request, @Res() res: Response) {
const { longUrl } = req.body;
const baseUrl = process.env.BASE_URL;
const parsed = new UrlParse(longUrl);
if (!validUrl.isUri(baseUrl)) {
return res.status(HttpStatus.UNAUTHORIZED).json('Invalid base url')
}
else if (!validUrl.isUri(longUrl)) {
return res.status(HttpStatus.BAD_REQUEST).json('Invalid long url')
}
else if (parsed.pathname.length < 9) {
return res.status(HttpStatus.BAD_REQUEST).json('URL too short')
}
else {
try {
const shortenedUrl = await this.urlService.shortrenUrl(longUrl, baseUrl);
return res.json(shortenedUrl);
} catch (err) {
console.error(err);
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json('Server error.')
}
}
}
@Get(':code')
async redirectToLongURL(@Req() req: Request, @Res() res: Response) {
try {
const url = await this.urlService.findByCode(req.params.code);
if (!_.isEmpty(url)) {
//return res.redirect(HttpStatus.FOUND, url.longUrl);
return res.json(url);
} else {
return res.status(HttpStatus.NOT_FOUND).json('No url found');
}
} catch (err) {
console.error(err);
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json('Server error');
}
}
@Get('url/admin')
async getMostPopularUrls(@Req()req: Request, @Res() res: Response) {
try{
const popularUrls = await this.urlService.getPopularUrls();
if(_.isEmpty(popularUrls)){
return res.status(HttpStatus.NOT_FOUND).json('No urls found');
}
return res.json(popularUrls)
} catch (err) {
console.error(err);
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json('Server error');
}
}
}
|
95ae6cc95abaa9d8a7750732cb81e28d9b25844e
|
TypeScript
|
travetto/travetto
|
/module/di/test/deps.ts
| 3.09375
| 3
|
import { Injectable, Inject, InjectableFactory } from '../src/decorator';
import { DbConfig, AltConfig, Empty } from './config';
export abstract class BasePattern { }
@Injectable()
export class SpecificPattern extends BasePattern {
}
export class BaseTypeTarget { }
/**
* @concrete .:BaseTypeTarget
*/
export interface BaseType {
age: number;
}
@Injectable()
export class InterfaceType implements BaseType {
get age() {
return 20;
}
}
@Injectable()
export class Database {
@Inject()
dbConfig: DbConfig;
@Inject({ optional: true })
altConfig: AltConfig;
postConstruct() {
console.log('Creating database', { url: this.dbConfig.getUrl() });
}
query() {
console.log('Getting 350', { url: this.dbConfig.getUrl() });
}
}
@Injectable()
export class Service {
constructor(public db: Database) {
console.log('Creating service', { database: db.dbConfig });
}
doWork() {
this.db.query();
}
}
@Injectable()
export class ServiceInherit extends Service {
name = 'bob';
age = 30;
override doWork() {
this.db.query();
}
}
export const SERVICE_INHERIT_2 = Symbol.for('SVC_I_2');
export const SERVICE_INHERIT_3 = Symbol.for('SVC_I_3');
@Injectable(SERVICE_INHERIT_2)
export class ServiceInherit2 extends ServiceInherit {
age = 31;
}
export const CUSTOM_SERVICE_INHERIT = Symbol.for('Custom');
export const CUSTOM_DATABASE = Symbol.for('CUSTOM DB');
export const CUSTOM_EMPTY = Symbol.for('Custom EMPTY');
export const CUSTOM_INTERFACE = Symbol.for('CustomInterface');
class TestConfig {
@InjectableFactory(CUSTOM_EMPTY)
static getNewDb() {
const out = new DbConfig();
return out;
}
@InjectableFactory(CUSTOM_EMPTY)
static getNewEmpty() {
const out = new Empty();
out.age = 20;
console.log('Custom EMPTY 1', { out });
return out;
}
@InjectableFactory(CUSTOM_SERVICE_INHERIT)
static getObject(@Inject(SERVICE_INHERIT_2) svc: ServiceInherit) {
console.log('Did I find service 2', { svc, db: svc?.db });
const out: ServiceInherit = new ServiceInherit2(svc?.db ?? new Database());
out.age = 11;
return out;
}
@InjectableFactory(CUSTOM_DATABASE)
static getCustomDB(@Inject(CUSTOM_EMPTY) empty: Empty) {
console.log('Custom EMPTY 2', { empty });
const config = new DbConfig();
config.temp = 'any';
config.empty = empty;
const ret = new Database();
ret.dbConfig = config;
return ret;
}
@InjectableFactory(CUSTOM_INTERFACE)
static getIntType() {
return new InterfaceType();
}
}
@Injectable()
export class UsableMainClass { }
@Injectable()
export class UsableSubClass extends UsableMainClass { }
@Injectable()
export abstract class UsableSubSubClass extends UsableSubClass { }
@Injectable()
export class UsableSubSubAClass extends UsableSubSubClass { }
@Injectable()
export class UsableSubSubBClass extends UsableSubSubClass { }
export const LOOSE_SYM = Symbol.for('loose');
@Injectable()
export class LooseResolutionClass {
name = 'bob';
}
class Config {
@InjectableFactory(LOOSE_SYM)
static getLoose(): LooseResolutionClass {
return new class extends LooseResolutionClass {
name = 'george';
}();
}
}
@Injectable()
export class SetterInject {
_prop: LooseResolutionClass;
@Inject()
set res(res: LooseResolutionClass) {
this._prop = res;
}
}
|
78c266ba77cb8b8ba25ccfd58965247615e7a7f8
|
TypeScript
|
tabo-syu/backlog-issue-viewer
|
/src/BacklogIssuesTreeView.ts
| 2.5625
| 3
|
import { TreeDataProvider, TreeItem, TreeItemCollapsibleState } from 'vscode';
import BacklogApiClient from './utils/backlogApi';
import { IssueResponse } from './utils/backlogApi/types';
import path from 'path';
type Cache = IssueResponse[] | null;
export class BacklogIssuesTreeProvider implements TreeDataProvider<TreeItem> {
private cache: Cache;
constructor(private client: BacklogApiClient) {
this.cache = null;
}
private async fetch(): Promise<IssueResponse[]> {
const { id } = await this.client.users.fetch('myself');
const projects = await this.client.projects.fetch();
const allStatuses = (
await Promise.all(
projects.map((project) =>
this.client.projects.statuses(project.id.toString())
)
)
).flat();
// 完了は固定でidが4
const inProgressStatus = allStatuses.filter((status) => status.id !== 4);
const statusIdSet = Array.from(
new Set(inProgressStatus.map((status) => status.id))
);
const issues = await this.client.issues.fetch({
assigneeId: [id],
statusId: statusIdSet,
sort: 'dueDate',
order: 'asc',
});
return issues.filter((issue) => issue.dueDate !== null);
}
public getTreeItem(element: TreeItem): TreeItem {
return element;
}
public async getChildren(element?: TreeItem): Promise<TreeItem[]> {
const issues = this.cache === null ? await this.fetch() : this.cache;
if (this.cache === null) {
this.cache = issues;
}
if (element instanceof BacklogIssue) {
const issue = issues.find((issue) => issue.id === element.issue.id);
return [
new BacklogDueDate(
issue?.dueDate ?? '未定',
TreeItemCollapsibleState.None
),
];
}
if (!element) {
return issues.map(
(issue) => new BacklogIssue(issue, TreeItemCollapsibleState.Collapsed)
);
}
return [];
}
}
export class BacklogDueDate extends TreeItem {
constructor(
public readonly label: string,
public readonly collapsibleState: TreeItemCollapsibleState
) {
super(label, collapsibleState);
}
public iconPath = {
light: path.join(__filename, '..', '..', 'assets', 'event_note_black.svg'),
dark: path.join(__filename, '..', '..', 'assets', 'event_note_white.svg'),
};
}
export class BacklogIssue extends TreeItem {
constructor(
public readonly issue: IssueResponse,
public readonly collapsibleState: TreeItemCollapsibleState
) {
super(issue.summary, collapsibleState);
}
}
|
40d5293d2b4cae373f49d55526b7dfe23d865ff9
|
TypeScript
|
AdamCsordas21/codewars
|
/remove-first-and-last-char/index.spec.ts
| 2.96875
| 3
|
import {
removeChar
} from '.'
describe('removeChar', () => {
it('should remove first and last characther of a given element', () => {
const name1 = removeChar('Pogba')
const name2 = removeChar('Rashford')
const name3 = removeChar('Fernandes')
const name4 = removeChar('Cavani')
expect(name1).toEqual('ogb')
expect(name2).toEqual('ashfor')
expect(name3).toEqual('ernande')
expect(name4).toEqual('avan')
})
})
|
c9aadd1a455a20316df14ca271a0f39cf3101def
|
TypeScript
|
mcculleydj/rosetta-code
|
/ts/solutions/trees/trees_4.ts
| 3.34375
| 3
|
import { TreeNode } from './trees_1'
// for TreeNode class see Minimal BST
// O(n)
function isBST(
tn: TreeNode,
leftBound: number = null,
rightBound: number = null,
): boolean {
if (!tn) return true
if (leftBound !== null && tn.data <= leftBound) {
return false
}
if (rightBound !== null && tn.data > rightBound) {
return false
}
return (
isBST(tn.left, leftBound, tn.data) && isBST(tn.right, tn.data, rightBound)
)
}
|
6d9d1f5718ee9ed323694e77224822f6b14e38a0
|
TypeScript
|
andrewsantarin/rc-dock-extended
|
/src/rc-dock-extended.utilities/create-tab-data.ts
| 2.609375
| 3
|
import { createElement, Fragment } from 'react';
import { TabBase, TabData } from 'rc-dock';
/**
* Generates a tab data object.
*
* @param {(TabData | TabBase)} [options] Additional tab data options.
*
* @returns A new tab data object.
*/
export const createTabData = (options?: TabData | TabBase) => {
const tabData: TabData = {
title: '',
content: createElement(Fragment),
...options,
};
return tabData;
};
|
c4a31b272971b901d0638393ec68cbb0157fd932
|
TypeScript
|
bapinmalakar/basic_ionic4_demo
|
/src/app/services/helper.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
@Injectable()
export class HelperService {
constructor() { }
treatmentOnData(data) {
return this.removeEmptySlot(data);
}
removeEmptySlot(data) {
data = data.split(' ');
let filter_data = [];
data.filter((d) => {
if (d) {
filter_data.push(d);
}
});
return this.sortDataByFrequency(this.findFrequencyOfEachWord(filter_data));
}
findFrequencyOfEachWord(data) {
let filter_data = {};
for (let i = 0; i < data.length; i++) {
if (!filter_data[data[i]]) {
filter_data[data[i]] = { value: 1 };
} else {
filter_data[data[i]].value = filter_data[data[i]].value + 1;
}
}
let format_data = [];
for (let key in filter_data) {
let d = [key, filter_data[key].value];
format_data.push(d);
}
return format_data;
}
sortDataByFrequency(data) {
let d = data;
d.sort((a, b) => {
if (a[1] < b[1]) {
return 1;
} else {
return -1;
}
});
return d;
}
}
|
a7740d9e7ea0c49c610baad36cc36aeb8f383cf4
|
TypeScript
|
vtalas/koren
|
/src/modulove/demo/app.ts
| 2.78125
| 3
|
/// <reference path="../modulove.d.ts"/>
/// <reference path="../class.moduloveFactory.ts"/>
import ModuloveFactory = modulove.Modulove;
var itemData = [
[1, 1],
[1, 1],
[3, 3, 1, 1],
[3, 2],
[2, 2],
[3, 2],
[1, 1],
[1, 1],
];
var items = itemData.map((item) => {
return new grids.SimpleLocation([item[0], item[1], item[2], item[3]]);
}
);
var settings = {
width: 200,
step: 20
};
var x = new ModuloveFactory(settings, items);
//items should have positions computed
console.log(x.getLocations());
|
f8ed2c09529ef18a9b215d7fb8b71fcd55414f20
|
TypeScript
|
cdnjs/cdnjs
|
/ajax/libs/amcharts4/4.9.33/.internal/core/rendering/filters/LightenFilter.d.ts
| 2.859375
| 3
|
/**
* Module for "Lighten" filter.
*/
/**
* ============================================================================
* IMPORTS
* ============================================================================
* @hidden
*/
import { Filter, FilterProperties } from "./Filter";
import { AMElement } from "../AMElement";
/**
* ============================================================================
* REQUISITES
* ============================================================================
* @hidden
*/
/**
* Defines additional properties relative to the "Lighten" filter
*/
export interface LightenFilterProperties extends FilterProperties {
/**
* Lightness.
*/
lightness: number;
}
/**
* ============================================================================
* MAIN CLASS
* ============================================================================
* @hidden
*/
/**
* Creates a "Lighten" filter.
*/
export declare class LightenFilter extends Filter {
/**
* Defines property types.
*/
_properties: LightenFilterProperties;
/**
* A storage for Filter property/value pairs.
* @see [@link LightenFilterProperties]
*/
/**
* Reference to the `<feColorMatrix>` element.
*
* @ignore Exclude from docs
*/
feColorMatrix: AMElement;
/**
* Constructor
*/
constructor();
/**
* Lightness of the target colors.
*
* If `lightness` is a positive number, the filter will make all colors
* lighter.
*
* If `lightness` is negative, colors will be darkened.
*
* @param value Lightness
*/
/**
* @return Lightness
*/
lightness: number;
}
|
3045a5df7abd28d84ed7ccf316dfef73fa834c8a
|
TypeScript
|
azeem/webvs
|
/src/utils.ts
| 3.25
| 3
|
import flow from "lodash-es/flow";
import map from "lodash-es/map";
import { default as pr } from "lodash-es/partialRight";
import takeRight from "lodash-es/takeRight";
/**
* A No-Op function
*/
// tslint:disable-next-line:no-empty
export function noop() {}
/**
* Checks if an object contains the required properties. Throws an error
* for missing options
* @param options the options to be checked
* @param requiredOptions set of required options
*/
export function checkRequiredOptions(options: any, requiredOptions: string[]): void {
for (const optionName of requiredOptions) {
if (!(optionName in options)) {
throw new Error("Required option " + optionName + " not found");
}
}
}
/**
* Returns a floating point value representation of a number
* embeddable in glsl shader code
* @param val value to be converted
*/
export function glslFloatRepr(val): string {
return val + (parseFloat(val) % 1 === 0 ? ".0" : "");
}
/**
* Color type. R, G, B
*/
export type Color = [number, number, number];
/**
* Checks whether the argument is a Color or not
* @param color color to be checked
*/
function isColor(color: string | Color): color is Color {
return Array.isArray(color) && color.length === 3;
}
/**
* Parse css color string #RRGGBB or rgb(r, g, b)
* @param color the color value to be parsed
*/
export function parseColor(color: string | Color): Color {
if (isColor(color)) {
return color;
} else {
color = color.toLowerCase();
let match = color.match(/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/);
if (match) {
return flow([
pr(takeRight, 3),
pr(map, (channel) => {
return parseInt(channel, 16);
}),
])(match) as Color;
}
match = color.match(/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);
if (match) {
return flow([
pr(takeRight, 3),
pr(map, (channel) => {
return Math.min(parseInt(channel, 10), 255);
}),
])(match) as Color;
}
}
throw new Error("Invalid Color Format");
}
/**
* Parse css color string and return normalizes Color value
* @param color the color value to be parsed
*/
export function parseColorNorm(color: string | Color): Color {
return map(parseColor(color), (value) => value / 255) as Color;
}
/**
* Parses shader error message and displays readable information
* @param src source of the shader
* @param error error message
*/
export function logShaderError(src: string, error: string): void {
const lines = src.split("\n");
const ndigits = lines.length.toString().length;
const errorPosMatch = error.match(/(\d+):(\d+)/);
let errorPos: [number, number];
if (errorPosMatch) {
errorPos = [parseInt(errorPosMatch[1], 10), parseInt(errorPosMatch[2], 10)];
}
const numberedLines = map(lines, (line, index) => {
let i;
let lineNumber = (index + 1) + "";
for (i = 0; i < (ndigits - lineNumber.length); i++) {
lineNumber = "0" + lineNumber;
}
let errorIndicator = "";
if (errorPos && errorPos[1] === index + 1) {
let indent = "";
for (i = 0; i < errorPos[0] + ndigits + 2; i++) {
indent += " ";
}
errorIndicator = "\n" + indent + "^\n" + indent + error;
}
return lineNumber + ": " + line + errorIndicator;
}).join("\n");
// tslint:disable-next-line:no-console
console.log("Shader Error : \n" + numberedLines);
}
/**
* Blend Modes
*/
export enum BlendMode {
REPLACE = 1,
MAXIMUM,
MINIMUM,
FIFTY_FIFTY,
ADDITIVE,
SUB_DEST_SRC,
SUB_SRC_DEST,
MULTIPLY,
MULTIPLY2,
ADJUSTABLE,
ALPHA,
ABSOLUTE_DIFFERENCE,
}
/**
* AudioChannels
*/
export enum AudioChannels {
CENTER = 0,
LEFT,
RIGHT,
}
/**
* AudioSource
*/
export enum AudioSource {
SPECTRUM = 1,
WAVEFORM,
}
/**
* Returns a random string of given length
* @param count number of characters
* @param chars character set to choose from
*/
export function randString(count: number, chars: string): string {
const randStr = [];
chars = chars || "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < count; i++) {
randStr.push(chars.charAt(Math.floor(Math.random() * chars.length)));
}
return randStr.join("");
}
/**
* WebGL data types
*/
export enum WebGLVarType {
TEXTURE2D = "texture2D",
_1F = "1f", _2F = "2f", _3F = "3f", _4F = "4f",
_1I = "1i", _2I = "2i", _3I = "3i", _4I = "4i",
_1FV = "1fv", _2FV = "2fv", _3FV = "3fv", _4FV = "4fv",
_1IV = "1iv", _2IV = "2iv", _3IV = "3iv", _4IV = "4iv",
}
export type FloatArray = number[] | Float32Array | Float64Array;
export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array |
Int32Array | Uint32Array | Float32Array | Float64Array;
export function isTypedArray(array: any): array is TypedArray {
return (
array instanceof Int8Array ||
array instanceof Uint8Array ||
array instanceof Uint8ClampedArray ||
array instanceof Int16Array ||
array instanceof Uint16Array ||
array instanceof Int32Array ||
array instanceof Uint32Array ||
array instanceof Float32Array ||
array instanceof Float64Array
);
}
/**
* Clamp number between range
* @param num number to clamp
* @param min min value of the range
* @param max max value of the range
*/
export function clamp(num: number, min: number, max: number): number {
return Math.min(Math.max(num, min), max);
}
/**
* Returns the value of property given its (dot separated) path in an object
* @param obj object with the property
* @param name name of the property
*/
export function getProperty(obj: any, name: string | string[]): any {
if (typeof name === "string") {
name = name.split(".");
}
const value = obj[name.shift()];
if (value) {
if (name.length > 0) {
return getProperty(value, name);
} else {
return value;
}
}
}
/**
* Sets a property, given its (dot separated) path in an object
* @param obj the object in which the property is to be set
* @param name name of the property
* @param value value of the property
*/
export function setProperty(obj: any, name: string | string[], value: any): void {
if (typeof name === "string") {
name = name.split(".");
}
const propertyName = name.shift();
if (name.length === 0) {
obj[propertyName] = value;
} else {
setProperty(obj[propertyName], name, value);
}
}
/**
* flattens array of strings to single string
* @param value string or list of strings to be flattened
* @param sep seprator to flatten the strings with
*/
export function flatString(value: string | string[], sep: string = "\n"): string {
if (typeof(value) === "string") {
return value;
} else {
return value.join(sep);
}
}
|
970493d835092008aafd91c5a510c26fab15985d
|
TypeScript
|
bugkiwi/san-ssr-target-php
|
/src/utils/timing.ts
| 2.90625
| 3
|
class Measure {
private startTime: number
constructor () {
this.startTime = Date.now()
}
duration () {
const dur = Date.now() - this.startTime
return dur + 'ms'
}
}
export function startMeasure () {
return new Measure()
}
export function measure (fn: Function) {
const m = new Measure()
fn()
return m.duration()
}
|
6c0c8c68f4ac8e984bd5e3dacd67e82f679ddee2
|
TypeScript
|
Purdue-io/WebApp
|
/PurdueIoWebApp/Scripts/typescript/Pages/TermSelectPage.ts
| 2.6875
| 3
|
class TermSelectPage extends Page {
private terms: Array<Term>;
constructor(app: App) {
// Set component ID, page title
this.componentId = "TermSelectPage";
this.pageTitle = "Purdue.io";
super(app);
}
public show(): void {
if (this.terms == null) {
this.getApp().progressIndicator.pushWork();
this.getApp().dataSource.fetchTerms().then((terms) => {
this.terms = terms;
this.displayTerms(terms);
this.getApp().progressIndicator.popWork();
}, (error) => {
alert("Error fetching term list: " + error);
this.getApp().progressIndicator.popWork();
});
}
super.show();
}
public displayTerms(terms: Array<Term>) {
var termListElement = this.element.querySelector("ul");
for (var i in terms) {
var term = terms[i];
var termEl = document.createElement("a");
termEl.innerHTML = term.Name;
((term) => {
termEl.addEventListener("click", () => {
this.getApp().selectedTerm = term;
this.getApp().navigate(new LandingPage(this.getApp(), term));
});
})(term);
var termLi = document.createElement("li");
termLi.appendChild(termEl);
termListElement.appendChild(termLi);
}
}
}
|
e3c60f65ddfa97f35285fb38e8bcd7f7dd5c87f5
|
TypeScript
|
NickHeiner/iberville
|
/test/unit/is-equal-float.ts
| 2.640625
| 3
|
/// <reference path="../../typings/tsd.d.ts" />
import '../../types';
import '../types';
import isEqualFloat = require('../../lib/is-equal-float');
const tape = require('tape');
tape('isEqualFloat', function(t: IT) {
t.test('is equal – no floats', function(t: IT) {
t.plan(1);
t.equal(isEqualFloat({foo: 'bar'}, {foo: 'bar'}), true, 'two objects without floats are equivalent');
});
t.test('is not equal – no floats', function(t: IT) {
t.plan(1);
t.equal(isEqualFloat({foo: 'bar'}, {foo: 'asdf'}), false, 'two objects without floats are not equivalent');
});
t.test('is equal – floats', function(t: IT) {
t.plan(1);
t.equal(isEqualFloat({foo: .1}, {foo: .1 + 2e-10}), true, 'two objects with floats are equivalent');
});
t.test('is not equal – floats', function(t: IT) {
t.plan(1);
t.equal(isEqualFloat({foo: .1}, {foo: .1 + 2e-8}), false, 'two objects with floats not are equivalent');
});
t.test('is not equal - extraneous path', function(t: IT) {
t.plan(1);
t.equal(
isEqualFloat({key: 'val'}, {key: 'val', extraneous: 'value'}),
false,
'objects with different keys are not equal'
);
});
});
|
6d8f00be042e088ad63c30d58e6a188c01e4ca2e
|
TypeScript
|
andreyyyyyyyyy/tapzero
|
/test/zora/test-cases.ts
| 2.59375
| 3
|
'use strict'
import * as test from '@pre-bundled/tape'
import * as fs from 'fs'
import * as path from 'path'
import * as child_process from 'child_process'
import * as util from 'util'
import * as jsdiff from 'diff'
const readFile = util.promisify(fs.readFile)
const dir = path.join(__dirname, 'fixtures')
const files = fs.readdirSync(dir)
const JS_FILES = files.filter(f => f.endsWith('.js'))
for (const file of JS_FILES) {
const fileName = path.join(dir, file)
test(`test zora/case: ${file}`, async (t) => {
const info = await exec('node', [fileName])
const shouldErr = file.endsWith('_fail.js')
t.equal(info.exitCode, shouldErr ? 1 : 0)
const expected = await readFile(
fileName.replace('.js', '_out.txt'), 'utf8'
)
equalDiff(t, info.combined, expected)
t.end()
})
}
function equalDiff (
t: test.Test,
actual: string,
expected: string
): void {
t.equal(actual, expected)
if (actual !== expected) {
console.log('\n\n--------------diff:--------------\n')
var diff = jsdiff.diffChars(actual, expected);
process.stderr.write(gray('-------------------------\n'))
diff.forEach(function(part){
// green for additions, red for deletions
// grey for common parts
const color = part.added ? green :
part.removed ? red : null;
const str = color ? color(part.value) : part.value
process.stderr.write(str.replace(/\n/g, ' \n'));
});
process.stderr.write(gray('-------------------------\n'))
}
}
function exec(command: string, args: string[]): Promise<{
exitCode: number,
stdout: string,
stderr: string,
combined: string
}> {
return new Promise((resolve, reject) => {
const proc = child_process.spawn(command, args)
let stdout = ''
let stderr = ''
let combined = ''
proc.stdout.on('data', (buf) => {
const str = buf.toString()
stdout += str
combined += str
})
proc.stderr.on('data', (buf) => {
const str = buf.toString()
stderr += str
combined += str
})
proc.on('error', (err: Error) => {
reject(err)
})
proc.on('exit', (exitCode: number) => {
resolve({
exitCode, stdout, stderr, combined
})
})
})
}
function green (text: string): string {
return '\u001b[32m' + text + '\u001b[0m'
}
function red (text: string): string {
return '\u001b[31m' + text + '\u001b[0m'
}
function gray (text: string): string {
return '\u001b[30;1m' + text + '\u001b[0m'
}
|
0f8b2de662b71a955b8356b11ed9cd2254ffdf6b
|
TypeScript
|
viridia/vortex.web
|
/packages/vortex-client/src/operators/library/Blend.ts
| 2.671875
| 3
|
import { DataType, Input, Operator, Output, Parameter } from '..';
import {
Expr,
defineFn,
fork,
refInput,
refTexCoords,
refUniform,
getAttr,
multiply,
add,
subtract,
} from '../../render/Expr';
import { GraphNode } from '../../graph';
import { makeFunctionType } from '../FunctionDefn';
import { vec4, mix, max, min, abs } from '../../render/glIntrinsics';
enum BlendOp {
MIX = 0,
ADD = 1,
SUBTRACT = 2,
MULTIPLY = 3,
DIFFERENCE = 4,
LIGHTEN = 10,
DARKEN = 11,
SCREEN = 20,
OVERLAY = 21,
DODGE = 22,
BURN = 23,
}
export const blend_screen = defineFn({
name: 'blend_screen',
type: makeFunctionType({
result: DataType.VEC3,
args: [DataType.VEC3, DataType.VEC3, DataType.FLOAT],
}),
});
export const blend_overlay = defineFn({
name: 'blend_overlay',
type: makeFunctionType({
result: DataType.VEC3,
args: [DataType.VEC3, DataType.VEC3, DataType.FLOAT],
}),
});
export const blend_dodge = defineFn({
name: 'blend_dodge',
type: makeFunctionType({
result: DataType.VEC3,
args: [DataType.VEC3, DataType.VEC3, DataType.FLOAT],
}),
});
export const blend_burn = defineFn({
name: 'blend_burn',
type: makeFunctionType({
result: DataType.VEC3,
args: [DataType.VEC3, DataType.VEC3, DataType.FLOAT],
}),
});
export const clamp_color = defineFn({
name: 'clamp_color',
type: makeFunctionType({
result: DataType.VEC3,
args: [DataType.VEC3],
}),
});
class Blend extends Operator {
public readonly inputs: Input[] = [
{
id: 'a',
name: 'A',
type: DataType.VEC4,
},
{
id: 'b',
name: 'B',
type: DataType.VEC4,
},
];
public readonly outputs: Output[] = [
{
id: 'out',
name: 'Out',
type: DataType.VEC4,
},
];
public readonly params: Parameter[] = [
{
id: 'op',
name: 'Operator',
type: DataType.INTEGER,
enumVals: [
{ name: 'Mix', value: BlendOp.MIX },
{ name: 'Add', value: BlendOp.ADD },
{ name: 'Subtract', value: BlendOp.SUBTRACT },
{ name: 'Multiply', value: BlendOp.MULTIPLY },
{ name: 'Difference', value: BlendOp.DIFFERENCE },
{ name: 'Lighten', value: BlendOp.LIGHTEN },
{ name: 'Darken', value: BlendOp.DARKEN },
{ name: 'Screen', value: BlendOp.SCREEN },
{ name: 'Overlay', value: BlendOp.OVERLAY },
{ name: 'Color Dodge', value: BlendOp.DODGE },
{ name: 'Color Burn', value: BlendOp.BURN },
],
default: 1,
pre: true,
},
{
id: 'strength',
name: 'Strength',
type: DataType.FLOAT,
min: 0,
max: 1,
default: 1,
},
{
id: 'norm',
name: 'Normalize',
type: DataType.INTEGER,
enumVals: [
{ name: 'Off', value: 0 },
{ name: 'On', value: 1 },
],
default: 1,
pre: true,
},
];
public readonly description = `
Blends two source images, similar to layer operations in GIMP or PhotoShop.
* **operator** determines the formula used to blend the two images.
* **strength** affects how much of the original image shows through.
* **normalize** controls whether the result is clamped to a [0..1] range.
`;
constructor() {
super('filter', 'Blend', 'filter_blend');
}
public getImports(node: GraphNode): Set<string> {
const imports = new Set<string>();
const op: BlendOp = node.paramValues.get('op');
if (node.paramValues.get('norm')) {
imports.add('clamp_color');
}
if (op === BlendOp.OVERLAY) {
imports.add('blend_overlay');
} else if (op === BlendOp.SCREEN) {
imports.add('blend_screen');
} else if (op === BlendOp.DODGE) {
imports.add('blend_dodge');
} else if (op === BlendOp.BURN) {
imports.add('blend_burn');
}
return imports;
}
public getCode(node: GraphNode): Expr {
const tuv = fork(refTexCoords(), 'uv');
if (!node.getInputTerminal('a').connection) {
return vec4(0.5, 0.5, 0.5, 1);
}
const a = fork(refInput('a', DataType.VEC4, node, tuv), 'a');
const b = refInput('b', DataType.VEC4, node, tuv);
const strength = refUniform('strength', DataType.FLOAT, node);
const ca = getAttr(a, 'rgb', DataType.VEC3);
const cb = getAttr(b, 'rgb', DataType.VEC3);
const alpha = getAttr(a, 'a', DataType.FLOAT);
if (!node.getInputTerminal('b').connection) {
return a;
}
const op: BlendOp = node.paramValues.get('op');
const norm: boolean = node.paramValues.get('norm');
// Ops which don't require normalization
if (op === BlendOp.MIX) {
return vec4(mix(ca, cb, strength), alpha);
} else if (op === BlendOp.ADD) {
if (norm) {
return vec4(mix(ca, clamp_color(add(ca, cb, DataType.VEC3)), strength), alpha);
} else {
return vec4(mix(ca, add(ca, cb, DataType.VEC3), strength), alpha);
}
} else if (op === BlendOp.SUBTRACT) {
if (norm) {
return vec4(mix(ca, clamp_color(subtract(ca, cb, DataType.VEC3)), strength), alpha);
} else {
return vec4(mix(ca, subtract(ca, cb, DataType.VEC3), strength), alpha);
}
} else if (op === BlendOp.MULTIPLY) {
return vec4(mix(ca, multiply(ca, cb, DataType.VEC3), strength), alpha);
} else if (op === BlendOp.DIFFERENCE) {
return vec4(mix(ca, abs(subtract(ca, cb, DataType.VEC3)), strength), alpha);
} else if (op === BlendOp.LIGHTEN) {
return vec4(mix(ca, max(ca, cb), strength), alpha);
} else if (op === BlendOp.DARKEN) {
return vec4(mix(ca, min(ca, cb), strength), alpha);
} else if (op === BlendOp.OVERLAY) {
if (norm) {
return vec4(mix(ca, clamp_color(blend_overlay(ca, cb, DataType.VEC3)), strength), alpha);
} else {
return vec4(mix(ca, blend_overlay(ca, cb, DataType.VEC3), strength), alpha);
}
} else if (op === BlendOp.SCREEN) {
if (norm) {
return vec4(mix(ca, clamp_color(blend_screen(ca, cb, DataType.VEC3)), strength), alpha);
} else {
return vec4(mix(ca, blend_screen(ca, cb, DataType.VEC3), strength), alpha);
}
} else if (op === BlendOp.DODGE) {
if (norm) {
return vec4(mix(ca, clamp_color(blend_dodge(ca, cb, DataType.VEC3)), strength), alpha);
} else {
return vec4(mix(ca, blend_dodge(ca, cb, DataType.VEC3), strength), alpha);
}
} else if (op === BlendOp.BURN) {
if (norm) {
return vec4(mix(ca, clamp_color(blend_burn(ca, cb, DataType.VEC3)), strength), alpha);
} else {
return vec4(mix(ca, blend_burn(ca, cb, DataType.VEC3), strength), alpha);
}
}
throw Error('Invalid blend operator: ' + op);
}
}
export default new Blend();
|
aac971efb0c2f15ece9ba3e253f3bdf0978a8b88
|
TypeScript
|
iwe7/ngx-renderer
|
/src/renderer/advanced-renderer.ts
| 2.953125
| 3
|
import { ExpressionArguments } from './expression';
export type RendererGlobalTarget = 'window' | 'document';
export enum AdvancedRendererMethod {
execute,
invokeElementMethod,
invokeGlobalTargetMethod,
setGlobalTargetPropery,
getGlobalTargetProperty,
}
export abstract class AdvancedRenderer {
abstract execute(expression: string, args?: ExpressionArguments): Promise<any>;
abstract invokeElementMethod(element: any, method: string, args?: any[]): Promise<any>;
abstract invokeGlobalTargetMethod(target: RendererGlobalTarget, method: string, args?: any[]): Promise<any>;
abstract setGlobalTargetPropery(target: RendererGlobalTarget, prop: string, value: any): void;
abstract getGlobalTargetProperty(target: RendererGlobalTarget, prop: string): Promise<any>;
getMethod(method: AdvancedRendererMethod): (...args: any[]) => any {
switch (method) {
case AdvancedRendererMethod.execute: return this.execute;
case AdvancedRendererMethod.getGlobalTargetProperty: return this.getGlobalTargetProperty;
case AdvancedRendererMethod.invokeElementMethod: return this.invokeElementMethod;
case AdvancedRendererMethod.invokeGlobalTargetMethod: return this.invokeGlobalTargetMethod;
case AdvancedRendererMethod.setGlobalTargetPropery: return this.setGlobalTargetPropery;
default: throw Error(`AdvancedRenderer: Unkown method [${method}]`);
}
}
}
|
78a735da2a7768adc5337d70c5c32d268847aa98
|
TypeScript
|
PauloDevelo/enginemonitor.reactfront
|
/src/services/OnlineManager.ts
| 2.578125
| 3
|
import actionManager from './ActionManager';
import httpProxy from './HttpProxy';
import analytics from '../helpers/AnalyticsHelper';
export interface IOnlineManager {
isOnlineAndSynced(): Promise<boolean>;
isOnline(): Promise<boolean>;
isSynced(): boolean;
isOfflineModeActivated():boolean;
setOfflineMode(offlineMode: boolean):void;
registerIsOnlineListener(listener: (isOnline: boolean) => void):void;
unregisterIsOnlineListener(listenerToRemove: (isOnline: boolean) => void):void;
}
let onlineManager: IOnlineManager;
class OnlineManager implements IOnlineManager {
private firstCheckBackendReachability: Promise<void>;
private backendReachable: boolean|undefined = undefined;
private offlineModeActivated:boolean = false;
private listeners: ((isOnline: boolean) => void)[] = [];
constructor() {
window.addEventListener('offline', async () => (onlineManager as OnlineManager).setIsOnline(await onlineManager.isOnline()));
window.addEventListener('online', async () => (onlineManager as OnlineManager).setIsOnline(await onlineManager.isOnline()));
this.firstCheckBackendReachability = this.checkBackendReachability();
setInterval(this.checkBackendReachability, 15000);
}
// Function for the unit test. Since we cannot un load a module with import, I simulate a rebuild of onlineManager....
rebuild() {
this.backendReachable = undefined;
this.offlineModeActivated = false;
this.listeners = [];
this.firstCheckBackendReachability = this.checkBackendReachability();
setInterval(this.checkBackendReachability, 15000);
}
registerIsOnlineListener(listener: (isOnline: boolean) => void):void{
this.listeners.push(listener);
}
unregisterIsOnlineListener(listenerToRemove: (isOnline: boolean) => void):void{
this.listeners = this.listeners.filter((listener) => listener !== listenerToRemove);
}
isOnline = async (): Promise<boolean> => window.navigator.onLine === true && this.isOfflineModeActivated() === false && this.isBackendReachable()
isSynced = ():boolean => actionManager.countAction() === 0
isOnlineAndSynced = async (): Promise<boolean> => this.isSynced() && this.isOnline();
isOfflineModeActivated = ():boolean => this.offlineModeActivated
setOfflineMode(offlineMode: boolean): void {
this.offlineModeActivated = offlineMode;
this.isOnline().then((isOnline) => this.setIsOnline(isOnline));
analytics.setOffLineMode(offlineMode);
}
onUserStorageClosed = async (): Promise<void> => {}
private async triggerIsOnlineChanged(isOnline: boolean): Promise<void> {
this.listeners.map((listener) => listener(isOnline));
}
private checkBackendReachability = async (): Promise<void> => {
try {
const { pong } = await httpProxy.get(`${process.env.REACT_APP_API_URL_BASE}server/ping`, { timeout: 8000 });
this.setBackendReachable(pong);
} catch (error) {
this.setBackendReachable(false);
}
}
private setBackendReachable = (backendReachable: boolean) => {
if (this.backendReachable !== backendReachable) {
this.backendReachable = backendReachable;
this.isOnline().then((isOnline) => this.setIsOnline(isOnline));
}
}
private isBackendReachable = async (): Promise<boolean> => {
if (this.backendReachable === undefined) {
await this.firstCheckBackendReachability;
}
return this.backendReachable!;
}
private prevIsOnline: boolean | undefined;
private setIsOnline = async (isOnline: boolean): Promise<void> => {
if (isOnline !== this.prevIsOnline) {
await this.triggerIsOnlineChanged(isOnline);
this.prevIsOnline = isOnline;
}
}
}
onlineManager = new OnlineManager();
export default onlineManager as IOnlineManager;
|
daab0b96c369a4d11e1927bb5539bd3e8f42ed7c
|
TypeScript
|
cutaisyah/fe-assignemnt4
|
/src/app/services/auth-interceptor.ts
| 2.546875
| 3
|
import { UserService } from 'src/app/services/user.service';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Injectable} from '@angular/core';
import { catchError } from 'rxjs/operators';
import { TokenService } from './token.service';
import { Observable, throwError } from 'rxjs';
const TOKEN_HEADER_KEY = 'access_token'
@Injectable({
providedIn: 'root'
})
export class AuthInterceptorService {
constructor(private token: TokenService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let authReq = req;
const token = this.token.getToken();
if (token != null) {
authReq = req.clone({headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token )});
}
return next.handle(authReq);
}
}
@Injectable({providedIn:'root'})
export class ErrorInterceptor implements HttpInterceptor {
constructor(private userService: UserService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if ([401, 403].indexOf(err.status) !== -1) {
// auto logout if 401 Unauthorized or 403 Forbidden response returned from api
this.userService.logout();
window.location.reload();
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
|
d94f78fc4f52b25dfcd5b82b1817faf051db12a2
|
TypeScript
|
Firestitch/ngx-code-generator
|
/libs/schematics/src/utils/build-correct-path.ts
| 2.6875
| 3
|
import { buildRelativePath } from './find-module';
import { dasherize } from '@angular-devkit/core/src/utils/strings';
import { Tree } from '@angular-devkit/schematics';
/**
* Build right services's path for correct component
* @param options
* @returns {string}
*/
export function buildRelativePathForService(options): string {
const isDataServiceRegexp = /\.data\.ts$/;
const isDataServiceCorePathRegexp = /\/core\//;
if (
isDataServiceRegexp.test(options.service)
&& isDataServiceCorePathRegexp.test(options.servicePath)
) {
return '@app/core';
} else {
return buildRelativePath(
`${options.componentPath}/${dasherize(options.name)}/${dasherize(options.name)}.component.ts`,
`${options.servicePath}/${options.service}`
).replace('.ts', '');
}
}
/**
* Build right services's path for correct component
* @param options
* @returns {string}
*/
export function buildRelativePathForEnum(options): string {
return buildRelativePath(
`${options.componentPath}/${dasherize(options.name)}.const.ts`,
`${options.enumPath}`
).replace('.ts', '');
}
/**
* Get index.ts file position for component
* It can be module's root or /components folder (if it exists)
* @param {Tree} tree
* @param options
* @returns {{path}}
*/
export function getRootPath(tree: Tree, options): { path: string } {
const dir = tree.getDir(`${options.path}`);
if (options.type && options.type === 'view') {
const isViewsFolderExists = (dir.subdirs as string[]).indexOf('views') !== -1;
const path = options.path + ( isViewsFolderExists ? '/views' : '');
return { path };
} else {
const isComponentFolderExists = (dir.subdirs as string[]).indexOf('components') !== -1;
const path = options.path + ( isComponentFolderExists ? '/components' : '');
return { path };
}
}
/**
* Get current component's location (include nestedPath)
* @param path
* @param routable
* @returns {{path}}
*/
export function getComponentPath(path: string, routable: string | boolean): string {
if (routable === 'true' || routable === true) {
path += '/views';
} else {
path += '/components';
}
return path ;
}
|
a5dd64b3fc1f5994172af172ce83b4f88e36849d
|
TypeScript
|
nbeach/function-injection
|
/src/inject.spec.ts
| 2.90625
| 3
|
import {inject} from "./inject"
import {expect} from "chai"
describe(inject.name, () => {
const objectify = (a: string, b: number, c: boolean) => ({a, b, c})
it("can partially apply some parameters of the source function", () => {
const injected = inject(objectify, "X", 5)
expect(injected(true)).to.deep.equal({a: "X", b: 5, c: true})
})
it("can partially apply all parameters of the source function", () => {
const injected = inject(objectify, "X", 5, true)
expect(injected()).to.deep.equal({a: "X", b: 5, c: true})
})
it("allows access to the source function", () => {
const injected = inject(objectify, "X", 5)
expect(injected.source("A", 10, false)).to.deep.equal({a: "A", b: 10, c: false})
})
})
|
e6a6983c71de6181555a28dc7c418f99d9ef21a9
|
TypeScript
|
IvanKuzyshyn/modest-trello
|
/src/scenes/board-page/selectors/card.ts
| 2.578125
| 3
|
import { StateAccessor } from '../../../context/types/state'
import { Card } from '../types/card'
export const getCardsByColumnId: StateAccessor<Card[]> = (
state,
columnId: number
) => state.cards.filter((card) => card.columnId === columnId)
export const getCardById: StateAccessor<Card | undefined> = (
state,
id?: number
) => {
if (!id) {
return undefined
}
return state.cards.find((card) => card.id === id)
}
export const isCardManagerShown: StateAccessor<boolean> = (state) =>
state.cardManager.isShown
export const getManagingCardId: StateAccessor<number | null> = (state) =>
state.cardManager.id
export const getManagingCardColumnId: StateAccessor<number | null> = (state) =>
state.cardManager.columnId
|
50926cee0197b1e081a30e01a302e03948fe21b7
|
TypeScript
|
mattsetyadi/QS-inventoryv2-TS
|
/src/Modules/Supplier/Store/SupplierReducer.ts
| 2.78125
| 3
|
import { Action } from 'redux';
import { IFetchSupplier } from './SupplierAction';
export const initialState: any = {
list: [],
};
export default function SupplierReducer(state = initialState, action: Action) {
if (!action) return state;
const newState = Object.assign({}, state);
switch (action.type) {
case 'FETCH_SUPPLIER_LIST_FINISHED': {
const fetchSupplier = action as IFetchSupplier;
newState.list = fetchSupplier.data;
return { ...newState };
}
}
return state;
}
|
b317ec0886841305982e94cdc1f204fcdff523a5
|
TypeScript
|
Rasmoh/cactbot
|
/src/types.ts
| 2.703125
| 3
|
// Name the lines and which indices in an array of nine elements are members of that line
type LineDefinition = {
name: string;
indices: number[];
};
export const LineDefinitions: LineDefinition[] = [
{ name: "Top Row", indices: [0, 1, 2] },
{ name: "Middle Row", indices: [3, 4, 5] },
{ name: "Bottom Row", indices: [6, 7, 8] },
{ name: "Left Column", indices: [0, 3, 6] },
{ name: "Middle Column", indices: [1, 4, 7] },
{ name: "Right Column", indices: [2, 5, 8] },
{ name: "\\ Diagonal", indices: [0, 4, 8] },
{ name: "/ Diagonal", indices: [2, 4, 6] },
];
// The payout value of each possible line sum
export const Payouts = [
0, 0, 0, 0, 0, 0, 10000, 36, 720, 360, 80, 252, 108, 72, 54, 180, 72, 180, 119, 36, 306, 1080, 144, 1800, 3600,
];
|
ebe7003fc2c885a544c355be8945ebfd30562b91
|
TypeScript
|
alistairvu/mern-ecommerce
|
/frontend/src/redux/user/userAuthSlice.ts
| 2.578125
| 3
|
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import axios from "axios"
export const registerUser = createAsyncThunk(
"user/registerUser",
async (
{
name,
email,
password,
}: { name: string; email: string; password: string },
thunkApi
) => {
try {
const config = {
headers: {
"Content-Type": "application/json",
},
}
const { data } = await axios.post(
"/api/users",
{ name, email, password },
config
)
return data
} catch (error) {
const message =
error.response && error.response.data.message
? error.response.data.message
: error.message
return thunkApi.rejectWithValue(message)
}
}
)
export const loginUser = createAsyncThunk(
"user/loginUser",
async (
{ email, password }: { email: string; password: string },
thunkApi
) => {
try {
const config = {
headers: {
"Content-Type": "application/json",
},
}
const { data } = await axios.post(
"/api/users/login",
{ email, password },
config
)
return data
} catch (error) {
const message =
error.response && error.response.data.message
? error.response.data.message
: error.message
return thunkApi.rejectWithValue(message)
}
}
)
const blankUser = {
_id: "",
name: "",
email: "",
isAdmin: false,
token: "",
}
const initialState = {
loading: false,
error: "",
userInfo: blankUser,
}
const userAuthSlice = createSlice({
name: "user",
initialState: initialState,
reducers: {
userLogout: () => initialState,
},
extraReducers: (builder) => {
builder.addCase(loginUser.pending, (state, action) => ({
error: "",
userInfo: blankUser,
loading: true,
}))
builder.addCase(loginUser.rejected, (state, action) => ({
loading: false,
userInfo: blankUser,
error: action.payload as string,
}))
builder.addCase(loginUser.fulfilled, (state, action) => ({
loading: false,
userInfo: action.payload,
error: "",
}))
builder.addCase(registerUser.pending, (state, action) => ({
error: "",
userInfo: blankUser,
loading: true,
}))
builder.addCase(registerUser.rejected, (state, action) => ({
loading: false,
userInfo: blankUser,
error: action.payload as string,
}))
builder.addCase(registerUser.fulfilled, (state, action) => ({
loading: false,
userInfo: action.payload,
error: "",
}))
},
})
const { actions, reducer: userAuthReducer } = userAuthSlice
export const { userLogout } = actions
export default userAuthReducer
|
efd0fa10b03c0bf28722825f650df0cd4bfca05f
|
TypeScript
|
dchambers/noforms-with-chakra-plus-nodetap
|
/src/pages/user-account/register/register-reducer.ts
| 2.890625
| 3
|
import makeError from 'make-error'
import { registerViewModel } from './register-view-model'
const InvalidStateError = makeError('InvalidStateError')
export type RegisterFormState = {
email: string
password: string
confirmationPassword: string
emailAlreadyRegistered: boolean
actionUnderway: boolean
verificationEmailSent: boolean
}
type EmailUpdateAction = {
type: 'EMAIL_UPDATED'
email: string
}
type EmailRegisteredCheckReceived = {
type: 'EMAIL_REGISTERED_CHECK_RECEIVED'
alreadyRegistered: boolean
}
type PasswordUpdateAction = {
type: 'PASSWORD_UPDATED'
password: string
}
type ConfirmationPasswordUpdateAction = {
type: 'CONFIRMATION_PASSWORD_UPDATED'
confirmationPassword: string
}
type RegisterButtonClickedAction = {
type: 'REGISTER_BUTTON_CLICKED'
}
type VerificationEmailSentAction = {
type: 'VERIFICATION_EMAIL_SENT'
}
export type RegisterFormAction =
| EmailUpdateAction
| EmailRegisteredCheckReceived
| PasswordUpdateAction
| ConfirmationPasswordUpdateAction
| RegisterButtonClickedAction
| VerificationEmailSentAction
export const defaultState: RegisterFormState = {
email: '',
password: '',
confirmationPassword: '',
emailAlreadyRegistered: false,
actionUnderway: false,
verificationEmailSent: false,
}
const registerReducer = (
state: RegisterFormState,
action: RegisterFormAction
): RegisterFormState => {
switch (action.type) {
case 'EMAIL_UPDATED': {
return {
...state,
email: action.email,
emailAlreadyRegistered: false,
}
}
case 'EMAIL_REGISTERED_CHECK_RECEIVED': {
return {
...state,
emailAlreadyRegistered: action.alreadyRegistered,
}
}
case 'PASSWORD_UPDATED': {
return {
...state,
password: action.password,
}
}
case 'CONFIRMATION_PASSWORD_UPDATED': {
return {
...state,
confirmationPassword: action.confirmationPassword,
}
}
case 'REGISTER_BUTTON_CLICKED': {
const view = registerViewModel(state)
if (!view.registerButtonEnabled) {
throw new InvalidStateError(
'Form can not be submitted while incomplete or invalid'
)
}
return {
...state,
actionUnderway: true,
}
}
case 'VERIFICATION_EMAIL_SENT': {
const view = registerViewModel(state)
if (!view.registerButtonLoading) {
throw new InvalidStateError(
'Verification email should be sent after register button is clicked'
)
}
return {
...state,
verificationEmailSent: true,
}
}
}
}
export default registerReducer
|
d2f793ac6279f80e1d1ecf3d3ac4c91f5d4eed77
|
TypeScript
|
Vulxan/react
|
/components/tabs/tabs-context.ts
| 2.546875
| 3
|
import React, { CSSProperties, MouseEvent } from 'react'
export type TabsInternalCellProps = {
onClick: (value: string) => void
onMouseOver: (e: MouseEvent<HTMLDivElement>) => void
activeClassName?: string
activeStyle?: CSSProperties
hideBorder?: boolean
}
export type TabsInternalCell = React.FC<TabsInternalCellProps>
export interface TabsHeaderItem {
value: string
cell: TabsInternalCell
}
export interface TabsConfig {
register?: (item: TabsHeaderItem) => void
currentValue?: string
inGroup: boolean
leftSpace?: CSSProperties['marginLeft']
}
const defaultContext = {
inGroup: false,
}
export const TabsContext = React.createContext<TabsConfig>(defaultContext)
export const useTabsContext = (): TabsConfig => React.useContext<TabsConfig>(TabsContext)
|
f108e5e988d5b7bf14c3337c6f2df6311ae4b6e3
|
TypeScript
|
MoranGoz/ezxpress
|
/src/app/map.service.ts
| 2.609375
| 3
|
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable()
export class MapService {
public addressUpdated : Observable<any>;
public addressSubject: Subject<any>;
localAddress : string;
constructor() {
this.addressSubject = new Subject<any>();
this.addressUpdated = this.addressSubject.asObservable();
this.addressSubject.next("test")
}
reverseAddress(lat, lng){
var geocoder: google.maps.Geocoder = new google.maps.Geocoder;
//alert("teste "+ lat + ' ' + lng)
//var latlng = new google.maps.LatLng(31.813506, 35.216292);
//var request = { latLng: latlng };
var latlng = {lat: lat , lng: lng};
geocoder.geocode({"location": latlng }, (results, status) => {
console.log(results)
this.localAddress = results[0].formatted_address
console.log(this.localAddress)
this.addressSubject.next(this.localAddress)
});
}
}
|
3933c3ac2cbfedbd76d50475d4393ec112aaf636
|
TypeScript
|
ColdFire87/beenion
|
/application/link.ts
| 2.578125
| 3
|
import { getLinkId } from '../model/link/getLinkId'
import { EventStore } from '../infrastructure/databases/eventstore/eventStore'
import { linkReducer } from '../model/link/reducers/linkReducer'
import { rate } from '../model/link/command/rate'
export const linkCommandHandlers = (
eventStore: EventStore,
userId: string
) => ({
rate: async (params: {
linkUrl?: string
title?: string
rating?: number
image?: string
tags?: string[]
}) => {
const linkId = getLinkId(userId, params.linkUrl)
const linkEvents = await eventStore.getById(linkId, {
returnEmptyArrOn404: true
})
const toCommit = rate({
link: linkReducer(linkEvents),
userId,
linkId,
linkUrl: params.linkUrl,
rating: params.rating,
image: params.image,
tags: params.tags,
title: params.title
})
return eventStore.save({
events: toCommit,
streamId: linkId,
expectedVersion: linkEvents.length
})
}
})
|
cf1421e2e343ab4187a9b4836ca6fbe2104d7670
|
TypeScript
|
epicmaxco/vuestic-ui
|
/packages/ui/src/composables/useDebounce.ts
| 2.75
| 3
|
import { isRef, Ref, unref, watch } from 'vue'
import debounce from 'lodash/debounce.js'
export const useDebounce = <T>(onUpdate: () => any, timeout: Ref<number> | number) => {
const createDebounced = () => {
return debounce(() => {
onUpdate()
}, unref(timeout))
}
let debounced = createDebounced()
if (isRef(timeout)) {
watch(timeout, () => { debounced = createDebounced() })
}
return {
// todo check if we need to create proxy here
debounced,
}
}
/** Used for debounced callbacks. Can be used to show cb near debounce call in code structure. */
export const useDebounceFn = (timeout: Ref<number> | number) => {
let callback: (() => void) | null = null
const createDebounced = () => {
return debounce(() => {
callback?.()
callback = null
}, unref(timeout))
}
let debounced = createDebounced()
if (isRef(timeout)) {
watch(timeout, () => { debounced = createDebounced() })
}
return {
// todo check if we need to create proxy here
debounced: (cb: (() => void)) => { callback = cb; debounced() },
cancel: () => debounced.cancel(),
}
}
|
30353e16ac7b07eab0566c8a3253aecd3f08cd35
|
TypeScript
|
sebastiangolian/angular-ngrx-playground
|
/src/app/todo/store/todo.reducer.ts
| 2.625
| 3
|
import { Action, createReducer } from '@ngrx/store';
import { Todos } from '../interfaces/todo.interface';
export const key = 'todos';
export const initialState: Todos = {
todos: [
{ id: 1, title: 'todo 1', completed: true },
{ id: 2, title: 'todo 2', completed: false },
],
};
const todoReducer = createReducer(initialState);
export function reducer(state: Todos, action: Action) {
return todoReducer(state, action);
}
|
e46563fc2ad4ad2a0ff8bd233d4fb05a12c43fdc
|
TypeScript
|
kilicmu/ToyScript
|
/test/peek-generator.test.ts
| 2.84375
| 3
|
import { PeekGenerator } from './../src/common/PeekGenerator';
import { array2Gen } from '../src/common/array2Gen';
import { equal } from '../src/common/equal';
describe('PeekGenerator test', () => {
const str = "abcdefghijklmnopqrstuvwxyz";
let gen: Generator;
let iter: PeekGenerator<string>;
beforeEach(() => {
gen = array2Gen(str);
iter = new PeekGenerator<string>(gen, '\0');
})
it('pushBack test', () => {
equal(iter.next(), 'a');
iter.pushBack();
equal(iter.next(), 'a');
equal(iter.next(), 'b');
equal(iter.next(), 'c');
iter.pushBack();
equal(iter.peek(), 'c');
})
it('peek test', () => {
equal(iter.peek(), 'a');
equal(iter.next(), 'a');
equal(iter.peek(), 'b');
equal(iter.next(), 'b');
equal(iter.next(), 'c');
equal(iter.peek(), 'd');
})
it('end Token test', () => {
for (let i of str) {
equal(iter.next(), i);
}
equal(iter.hasNext(), '\0');
equal(iter.next(), '\0');
equal(iter.hasNext(), false);
})
})
|
f7edc9f7e2fc5dc463403210a76be10a60cbe403
|
TypeScript
|
qnighy/sourcemap-explorer
|
/src/parse.ts
| 2.6875
| 3
|
import { SourceFileState, UploadedFileState } from "./file_states";
export interface ParseResult {
files: Map<string, ParsedFile>;
sourceFiles: Map<string, SourceFileState>;
}
const initResult = (): ParseResult => ({
files: new Map(),
sourceFiles: new Map(),
});
export interface ParsedFile {
content: ArrayBuffer;
sourceMap?: SourceMapContent;
sourceMapRef?: string;
}
export interface SourceMapContent {
version: 3;
file?: string;
sourceRoot?: string;
sources: string[];
sourcesContent?: (string | null)[];
mappings: Segment[][];
}
export interface UnmappedSegment {
column: number;
source?: undefined;
sourceLine?: undefined;
sourceColumn?: undefined;
name?: undefined;
}
export interface MappedSegment {
column: number;
source: string;
sourceLine: number;
sourceColumn: number;
name?: string;
}
export type Segment = UnmappedSegment | MappedSegment;
export const parseFiles = (
uploadedFiles: Map<string, UploadedFileState>,
prev: ParseResult = initResult()
): ParseResult => {
const files = new Map<string, ParsedFile>();
for (const [name, uploadedFile] of Array.from(uploadedFiles.entries())) {
const prevFile = prev.files.get(name);
if (prevFile && prevFile.content === uploadedFile.content) {
files.set(name, prevFile);
} else {
files.set(name, parseFile(name, uploadedFile.content));
}
}
// Return prev if nothing has been changed.
if (equalFiles(prev.files, files)) {
return prev;
}
const sourceFiles = new Map<string, SourceFileState>();
for (const file of Array.from(files.values())) {
if (file.sourceMap) {
for (const source of file.sourceMap.sources) {
// TODO: sourceRoot
sourceFiles.set(source, { state: "missing" });
}
}
}
for (const file of Array.from(files.values())) {
if (file.sourceMap && file.sourceMap.sourcesContent) {
for (const [i, source] of Array.from(file.sourceMap.sources.entries())) {
// TODO: sourceRoot
const sourceContent = file.sourceMap.sourcesContent[i];
if (sourceContent) {
sourceFiles.set(source, {
state: "bundled",
content: new TextEncoder().encode(sourceContent),
});
}
}
}
}
for (const [name, uploadedFile] of Array.from(uploadedFiles.entries())) {
if (sourceFiles.has(name)) {
sourceFiles.set(name, {
state: "uploaded",
content: uploadedFile.content,
});
}
}
return {
files,
sourceFiles,
};
};
const parseFile = (name: string, content: ArrayBuffer): ParsedFile => {
if (name.match(/\.map$/)) {
return {
content,
sourceMap: parseSourceMap(content),
};
}
let sourceMapRef: string | undefined;
const contentText = new TextDecoder().decode(content);
const matchJS = contentText.match(/^\/\/# sourceMappingURL=(.*)$/m);
const matchCSS = contentText.match(/^\/\*# sourceMappingURL=(.*) \*\/$/m);
if (matchJS) {
sourceMapRef = matchJS[1];
} else if (matchCSS) {
sourceMapRef = matchCSS[1];
}
return { content, sourceMapRef };
};
const parseSourceMap = (content: ArrayBuffer): SourceMapContent => {
const json: unknown = JSON.parse(new TextDecoder().decode(content));
if (typeof json !== "object" || json === null || Array.isArray(json)) {
throw new Error("SourecMap should be an object");
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/ban-types
const _typecheck_json: object = json;
const {
version,
file,
sourceRoot,
sources,
sourcesContent,
names,
mappings,
} = json as { [key in string]?: unknown };
if (version !== 3) {
throw new Error("Invalid version");
}
if (typeof file !== "undefined" && typeof file !== "string") {
throw new Error("file must be a string");
}
if (typeof sourceRoot !== "undefined" && typeof sourceRoot !== "string") {
throw new Error("sourceRoot must be a string");
}
if (!isArrayOf(sources, isString)) {
throw new Error("sources must be an array of strings");
}
if (
typeof sourcesContent !== "undefined" &&
!isArrayOf(sourcesContent, isStringOrNull)
) {
throw new Error("sourcesContent must be an array of strings or nulls");
}
if (!isArrayOf(names, isString)) {
throw new Error("names must be an array of strings");
}
if (typeof mappings !== "string") {
throw new Error("mappings must be a string");
}
return {
version,
file,
sourceRoot,
sources,
sourcesContent,
mappings: parseMappings(mappings, sources, names),
};
};
const isString = (x: unknown): x is string => typeof x === "string";
const isStringOrNull = (x: unknown): x is string | null =>
typeof x === "string" || x === null;
const isArrayOf = <T>(
arr: unknown,
pred: (x: unknown) => x is T
): arr is T[] => {
if (!Array.isArray(arr)) {
return false;
}
for (const elem of arr) {
if (!pred(elem)) return false;
}
return true;
};
const equalFiles = (
files1: Map<string, ParsedFile>,
files2: Map<string, ParsedFile>
): boolean => {
for (const name of Array.from(files1.keys()).concat(
Array.from(files2.keys())
)) {
if (files1.get(name) !== files2.get(name)) {
return false;
}
}
return true;
};
const parseMappings = (
mappings_: string,
sources: string[],
names: string[]
): Segment[][] => {
const mappings = mappings_ + ";";
const lines: Segment[][] = [];
let segments: Segment[] = [];
let lastColumn = 0;
let lastSourceIndex = 0;
let lastSourceLine = 0;
let lastSourceColumn = 0;
let lastNameIndex = 0;
let currentSegment: number[] = [];
let current = 0;
let currentBits = 0;
for (let i = 0; i < mappings.length; i++) {
const charCode = mappings.charCodeAt(i);
if (charCode === 0x3b /* ; */ || charCode === 0x2c /* , */) {
if (current !== 0 || currentBits !== 0) throw new Error("VLQ runover");
if (currentSegment.length === 0 && charCode === 0x3b /* ; */) {
lines.push(segments);
segments = [];
lastColumn = 0;
continue;
}
if (currentSegment.length === 0) throw new Error("Segment too short");
const columnDiff = toSigned(currentSegment[0]);
if (columnDiff < 0) throw new Error("column must be monotonic");
lastColumn += columnDiff;
if (currentSegment.length === 4 || currentSegment.length === 5) {
const sourceIndexDiff = toSigned(currentSegment[1]);
const sourceLineDiff = toSigned(currentSegment[2]);
const sourceColumnDiff = toSigned(currentSegment[3]);
lastSourceIndex += sourceIndexDiff;
lastSourceLine += sourceLineDiff;
lastSourceColumn += sourceColumnDiff;
if (currentSegment.length === 5) {
lastNameIndex += toSigned(currentSegment[4]);
}
} else if (currentSegment.length !== 1) {
throw new Error("Invalid segment length");
}
segments.push({
column: lastColumn,
// TODO: check index
source: sources[lastSourceIndex],
sourceLine: lastSourceLine,
sourceColumn: lastSourceColumn,
name: currentSegment.length === 5 ? names[lastNameIndex] : undefined,
});
currentSegment = [];
if (charCode === 0x3b /* ; */) {
lines.push(segments);
segments = [];
lastColumn = 0;
}
continue;
}
const b = base64val(charCode);
if (b < 32) {
currentSegment.push(current | (b << currentBits));
current = 0;
currentBits = 0;
} else {
current |= (b & 31) << currentBits;
currentBits += 5;
}
}
return lines;
};
const base64val = (charCode: number): number => {
if (charCode >= 0x41 /* A */ && charCode <= 0x5a /* Z */) {
return charCode - 0x41;
} else if (charCode >= 0x61 /* a */ && charCode <= 0x7a /* z */) {
return charCode - (0x61 - 26);
} else if (charCode >= 0x30 /* 0 */ && charCode <= 0x39 /* 9 */) {
return charCode + (52 - 0x30);
} else if (charCode === 0x2b /* + */) {
return 62;
} else if (charCode === 0x2f /* / */) {
return 63;
} else {
throw new Error(`Invalid base64 value: ${charCode}`);
}
};
const toSigned = (n: number): number => {
if (n & 1) {
return -(n >> 1);
} else {
return n >> 1;
}
};
|
b80da13e66758803ada34d0e9e0ec71979ddd7aa
|
TypeScript
|
staeke/minimal-html-parser
|
/parser.test.ts
| 2.90625
| 3
|
import {Comment, Element, parseHtml} from './parser';
test('basic test', () => {
const dom = parseHtml('<b>Hello</b>');
expect(dom[0]).toBeInstanceOf(Element);
expect((dom[0] as Element).tagName).toBe('b');
expect((dom[0] as Element).innerText).toBe('Hello');
});
test('Test with comment', () => {
const dom = parseHtml('<!--ABC-->');
expect(dom[0]).toBeInstanceOf(Comment);
expect((dom[0] as Comment).innerText).toBe('ABC');
});
test('Test complex innerText', () => {
const dom = parseHtml('<div> A \n<br>B</div>');
expect(dom[0]).toBeInstanceOf(Element);
expect((dom[0] as Element).innerText).toBe(' A \nB');
});
test('Test parse attributes', () => {
const dom = parseHtml('<div style="color: black" id="x"></div>');
expect(dom[0]).toBeInstanceOf(Element);
expect((dom[0] as Element).attributes).toEqual({style: 'color: black', id: 'x'});
});
|
77081427e6be931674caf602f56907f743a08b7d
|
TypeScript
|
UgurAsaner/shoppingCart-NodeJS
|
/src/models/Coupon.ts
| 2.8125
| 3
|
import { DiscountType } from "./DiscountType";
import Discount from "./Discounts";
export default class Coupon extends Discount {
private minPurchase: number;
constructor(minPurchase: number, discount: number, discountType: DiscountType) {
super(discount, discountType);
this.minPurchase = minPurchase;
this.title += ` Coupon`;
}
public getPrintable(): object {
return {
title: this.title,
'min purchase': this.minPurchase,
discount: this.getDiscountString()
};
}
public getDiscountAmount(totalPrice: number): number {
if (totalPrice < this.minPurchase) {
return 0;
}
if (this.isRateTyped()) {
return (totalPrice * this.discount) / 100;
} else {
return this.discount;
}
}
}
|
0b16841f01e98f61d0fb9c32fe4bb5bc1039d8bd
|
TypeScript
|
ShatDev/bsc-sniper
|
/bot.ts
| 2.546875
| 3
|
import { Contract } from 'ethers';
import { bnbAmount, tokenAddress, token } from './config.json';
import {
getFactory,
getRouter,
getTokenConfig,
TokenConfig,
fetchBuy,
} from './util';
const bot = async (
router: Contract,
factory: Contract,
config: TokenConfig
) => {
const wbnbAddressLower = String(config.wbnbAddress).toLocaleLowerCase();
const tokenAddressLower = String(tokenAddress).toLocaleLowerCase();
// This will trigger for ALL pair creation on pancakeswap. We have to filter down for just the pair we want.
// NOTE: This will never fetchBuy if pair is already created!
factory.on('PairCreated', async (token0, token1, pairAddress) => {
let tokenIn, tokenOut;
const token0Lower = String(token0).toLocaleLowerCase();
const token1Lower = String(token1).toLocaleLowerCase();
/* console.log(`
=================
New pair detected
token0: ${token0}
token1: ${token1}
pairAddress: ${pairAddress}
`); */
if (token0Lower === wbnbAddressLower) {
tokenIn = token0Lower;
tokenOut = token1Lower;
}
if (token1Lower === wbnbAddressLower) {
tokenIn = token1Lower;
tokenOut = token0Lower;
}
if (typeof tokenIn === 'undefined' || tokenOut != tokenAddressLower) {
/* console.log(`
This is not the pair you're looking for
=================
`); */
return;
}
console.log(
`EXPECTED PAIR FOUND with address ${pairAddress}. Sniping immediately!`
);
await fetchBuy(router, config, false);
process.exit(0);
});
console.log(
`Sniper loaded with ${bnbAmount} ${token} rounds. Watching for pair creation to fire immediately...`
);
};
const botAsync = async () => {
const config = await getTokenConfig();
const router = getRouter(config);
const factory = getFactory(config);
await bot(router, factory, config);
};
botAsync();
|
bee07e1c68f58cae3ad2280f696e9361db469a88
|
TypeScript
|
galvc/angular-eventapp-clone
|
/src/app/events.service.ts
| 2.546875
| 3
|
import { Injectable } from "@angular/core";
import { HttpHeaders, HttpClient } from "@angular/common/http";
import { Observable, of } from "rxjs";
import { Event } from "./event";
import { catchError, map, tap } from "rxjs/operators";
@Injectable({
providedIn: "root"
})
export class EventsService {
order = {
event: null,
quantity: null,
total: null,
fees: null,
customer: null
};
fees: number = 0.1;
private eventsUrl = "api/events";
//the collection name must be the same as the object i returned from the other service
httpOptions = {
headers: new HttpHeaders({ "Content-Type": "application/json" })
};
constructor(private http: HttpClient) {}
getAllEvents(): Observable<Event[]> {
// return this.http.get('https://samplewebappi.azurewebsites.net/api/todoitems');
// return this.http.get('assets/mock-events.json');
return this.http.get<Event[]>(this.eventsUrl);
}
getEvent(id: number): Observable<Event> {
const url = `${this.eventsUrl}/${id}`;
return this.http.get<Event>(url);
}
updateEvent(event: Event): Observable<any> {
return this.http.put(this.eventsUrl, event, this.httpOptions);
}
searchEvent(term: string): Observable<Event[]> {
if (!term.trim()) {
return of([]);
}
console.log("service searching");
return this.http.get<Event[]>(`${this.eventsUrl}/?title=${term}`);
}
addEvent(event): Observable<Event> {
console.log('adding event from services' + event)
return this.http.post<any>(this.eventsUrl, event, this.httpOptions);
}
deleteEvent(eventId: number): Observable<Event> {
// const id = typeof hero === "number" ? hero : hero.id;
const url = `${this.eventsUrl}/${eventId}`;
return this.http.delete<Event>(url, this.httpOptions);
}
addToOrder(event, quantity) {
this.order.event = event;
this.order.quantity = quantity;
this.order.fees = event.price * quantity * this.fees;
this.order.total = event.price * quantity + this.order.fees;
console.log("thsi is the order frm services " + this.order.quantity);
}
getOrder() {
return this.order;
}
private handleError<T>(operation = "operation", result?: T) {
return (error: any): Observable<T> => {
console.error(error);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}
|
3ac39c8978675c4fcba6d3900d254b5aadf0ddc6
|
TypeScript
|
davezabriskie/variate-generation
|
/src/app/variate-functions/functions/weibull/weibull.ts
| 3.453125
| 3
|
export class Weibull {
private shape: number = 1;
private scale: number = 2;
constructor(shape: number, scale: number) {
this.updateShape(shape);
this.updateScale(scale);
}
updateShape(shape: number): void {
if (shape > 0) {
this.shape = shape;
}
}
updateScale(scale: number): void {
if (scale > 0) {
this.scale = scale;
}
}
calculateValue(input: number): number {
if (input > 0) {
const exp = Math.exp(-1 * Math.pow(input / this.scale, this.shape));
return (this.shape / this.scale) * Math.pow(input / this.scale, this.shape - 1) * exp;
}
return 0;
}
}
|
51d15fa5de9fa2ce14f578956caeacc1869c7b68
|
TypeScript
|
octoml/relay-to-js
|
/src/nodes/common.ts
| 3.125
| 3
|
import {GenericNode} from './';
export type BaseType = {
id: number;
};
export type DType = 'float32' | 'int32' | string;
export type GType = GenericNode.Type;
export type GSType = GenericNode.SType;
export type FromTVMParams = {
id: number;
nodes: GSType[];
visited: GType[];
};
export const typeMismatch = (expect: string, received: string) =>
`Type mismatch from TVM, expecting "${expect}", but receiving "${received}"`;
export const visitedTypeMismatch = (
idx: number,
expect: string,
received: string,
) =>
`This node is visited at index ${idx} but has a different type ("${expect}") instead of "${received}"`;
export type Test<T extends GType> = ((node: GType) => node is T) & {
type: string[];
};
export function testFactory<T extends GType>(
type_key: string | string[],
): Test<T> {
type_key = Array.isArray(type_key) ? type_key : [type_key];
return Object.assign(
(node: GType): node is T => node && type_key.includes(node.type_key),
{type: type_key},
);
}
export type STest<RT extends GSType> = ((node: GSType) => node is RT) & {
type: string[];
};
export function stestFactory<RT extends GSType>(
type_key: string | string[],
): STest<RT> {
type_key = Array.isArray(type_key) ? type_key : [type_key];
return Object.assign(
(node: GSType): node is RT => node && type_key.includes(node.type_key),
{type: type_key},
);
}
|
771c6cd711d498dc9664e651e8722dc82d0812f1
|
TypeScript
|
bzlibby/textual-engine
|
/src/service/loader/index.ts
| 2.75
| 3
|
import { Service } from '..';
import { DataFile } from '../../model/file/Data';
export interface LoaderService extends Service {
/**
* Write a debug payload to a local path.
*
* This always writes to a local resource, even for network-based loaders.
*/
dump(path: string, data: Buffer): Promise<void>;
/**
* Load a resource by path.
*/
load(path: string): Promise<Buffer>;
/**
* Save a resource by path.
*/
save(path: string, data: Buffer): Promise<void>;
/**
* Load a resource and parse the data as a UTF-8 string.
*/
loadStr(path: string): Promise<string>;
/**
* Save a resource from a UTF-8 string.
*/
saveStr(path: string, data: string): Promise<void>;
loadData(path: string): Promise<DataFile>;
saveData(path: string, data: DataFile): Promise<void>;
}
|
f61804f9c04bb2358eb3b27c028e4c845eb88726
|
TypeScript
|
zacharyplat/iabtcf-es
|
/modules/core/src/tcstring/encoders/VendorVectorEncoder.ts
| 3.03125
| 3
|
import {SpecificEncoder} from './SpecificEncoder';
import {VectorEncodingTypeEnum} from '../VectorEncodingTypeEnum';
import {IntEncoder} from './IntEncoder';
import {BooleanEncoder} from './BooleanEncoder';
import {BitLength} from '../../model/BitLength';
import {Vector} from '../../model/Vector';
export class VendorVectorEncoder implements SpecificEncoder {
public static readonly RANGE_DEFAULT: boolean = false;
private intEncoder: IntEncoder = new IntEncoder();
private boolEnc: BooleanEncoder = new BooleanEncoder();
private bitString: string;
private ranges: number[][];
private maxId: number;
public encode(vector: Vector): string {
let range: number[] = [];
let bitString = '';
this.ranges = [];
this.maxId = vector.maxId;
let bitField = '';
vector.forEach((curValue: boolean, i): void => {
// build our bitfield no matter what
bitField += this.boolEnc.encode(curValue);
/**
* if our value is positive and we're still assuming range encoding we
* may want to start building a range or add this to an existing range
*/
if (curValue) {
/**
* Look ahead to see if this is the last value in our range
*/
const nextValue = vector.has(i + 1);
// if there isn't a next value, then we'll wrap up this range
if (!nextValue) {
/**
* this is the last value of the range, so we'll push it on to the
* end into position 1
*/
range.push(i);
// store the array in our bigger array
this.ranges.push(range);
// clear the array for the next range
range = [];
} else if (range.length === 0) {
// this is the first value for this range
range.push(i);
}
}
});
const encodingType: VectorEncodingTypeEnum = this.rangeIsSmaller()
? VectorEncodingTypeEnum.RANGE
: VectorEncodingTypeEnum.FIELD;
// maxId
bitString = this.intEncoder.encode(this.maxId, BitLength.maxId);
// encoding type
bitString += encodingType + '';
if (encodingType === VectorEncodingTypeEnum.RANGE) {
bitString += this.buildRangeEncoding();
} else {
bitString += bitField;
}
this.ranges = [];
return bitString;
}
private buildRangeEncoding(): string {
const numEntries = this.ranges.length;
// set with range default (always 0 because there is no practical case for a default of 1)
let rangeString = this.boolEnc.encode(VendorVectorEncoder.RANGE_DEFAULT);
// describe the number of entries to follow
rangeString += this.intEncoder.encode(numEntries, BitLength.rangeEncodingNumEntries);
// each range
this.ranges.forEach((range: number[]): void => {
// is this range a single?
const single = (range.length === 1);
// first is the indicator of whether this is a single id or range (two)
// 0 is single and range is 1
rangeString += this.boolEnc.encode(!single);
// second is the first (or only) vendorId
rangeString += this.intEncoder.encode(range[0], BitLength.vendorId);
if (!single) {
// add the second id if it exists
rangeString += this.intEncoder.encode(range[1], BitLength.vendorId);
}
});
return rangeString;
}
private rangeIsSmaller(): boolean {
// the one is for the default consent value
let rLength = BitLength.rangeEncodingDefaultConsent + BitLength.rangeEncodingNumEntries;
this.ranges.forEach((range: number[]): void => {
const single = (range.length === 1);
rLength += BitLength.vendorId;
rLength += (single) ? 0 : BitLength.vendorId;
});
return rLength < this.maxId;
}
};
|