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
|
|---|---|---|---|---|---|---|
e7c9ef37d3a49d5fd78a37da664d35fd2d82e57f
|
TypeScript
|
maaqoul/typescript-exertion
|
/difference-of-squares/difference-of-squares.ts
| 3.4375
| 3
|
export default class Squares {
squareOfSum:number;
sumOfSquares:number;
difference:number;
constructor (public number: number) {
this.SquareOfSum();
this.SumOfSquares();
this.Difference();
}
public SquareOfSum = (): number => {
let sum:number = 0;
for (let i = 1; i <= this.number; ++i) {
sum += i;
}
return this.squareOfSum = sum**2;
};
public SumOfSquares = (): number => {
let squares:number = 0;
for (let i = 1; i <= this.number; ++i) {
squares += i**2;
}
return this.sumOfSquares = squares;
};
public Difference = ():number => this.difference = this.SquareOfSum() - this.SumOfSquares();
}
|
8e053de07a4e5b9c77d2cbd06bc5405d02333464
|
TypeScript
|
Mikhail-Hursky/rsclone
|
/src/script/appliation/games/menu/PauseMenu.ts
| 2.53125
| 3
|
import * as Phaser from 'phaser';
// @ts-ignore
import Memory from '../Memory.ts';
// @ts-ignore
import CustomButton from '../buttons/CustomButton.ts';
const style = {
fontFamily: 'Pixel',
color: '#fff',
fontSize: '39px',
};
export default class PauseMenu extends Phaser.Scene {
private title: Phaser.GameObjects.Text;
private Memory: Memory;
private config: { type: number;
physics: { default: string };
width: number;
height: number;
parent: string;
scene: any[] };
constructor() {
super('PauseMenu');
this.Memory = new Memory();
this.config = this.Memory.getConfig();
}
create() {
this.add.tileSprite(0, 0, 220, 460, 'defaultScreen').setOrigin(0, 0);
this.title = this.add.text(0, 110, 'Pause', style);
this.title.setStroke('#000', 0.7);
this.title.x = (this.config.width - this.title.width) / 2;
const btnReturnGame = new CustomButton(this, 110, 200, 'Return');
const btnRestart = new CustomButton(this, 110, 240, 'Restart');
this.add.existing(btnReturnGame);
this.add.existing(btnRestart);
btnReturnGame.setInteractive()
.on(Phaser.Input.Events.GAMEOBJECT_POINTER_DOWN, () => {
this.scene.resume(this.Memory.getPrevGame());
this.scene.stop();
});
btnRestart.setInteractive().on(Phaser.Input.Events.GAMEOBJECT_POINTER_DOWN, () => {
this.scene.start(this.Memory.getPrevGame());
this.scene.stop();
});
}
}
|
5802113b7f1269538b3743b5edb5a0450afb474f
|
TypeScript
|
aino-gautam/CanvasBenchTest
|
/canvasBenchTest/src/main/webapp/CanvasTestJs/app.ts
| 2.71875
| 3
|
/// <reference path="./fabricjs.d.ts" />
module App {
export class myApp {
//public resizeOnMove: boolean;
public createBasicVisual(canvasId: string, numberOfElements: number, radiusSize: number = 5): Visual {
return new Visual(canvasId, numberOfElements, radiusSize);
}
public setResizeAbility(interact, resize_canvas, resizeClass, outputElement, resizeOnMoveElement) {
var resizeStart;
var resizeCount;
var resizeOnMove = resizeOnMoveElement.checked;
interact(resizeClass).draggable({ onmove: (<any>window).dragMoveListener }).resizable({
preserveAspectRatio: false,
edges: { left: true, right: true, bottom: true, top: true }
}).on('resizestart', function (event) {
resizeOnMove = resizeOnMoveElement.checked;
if (resizeOnMove) {
resizeStart = new Date().getTime();
}
resizeCount = 0;
}).on('resizemove', function (event) {
var target = event.target,
x = (parseFloat(target.getAttribute('data-x')) || 0),
y = (parseFloat(target.getAttribute('data-y')) || 0);
// update the element's style
target.style.width = event.rect.width + 'px';
target.style.height = event.rect.height + 'px';
// translate when resizing from top or left edges
x += event.deltaRect.left;
y += event.deltaRect.top;
target.style.webkitTransform = target.style.transform = 'translate(' + x + 'px,' + y + 'px)';
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
if (resizeOnMove) {
resize_canvas();
resizeCount++;
}
}).on('resizeend', function (event) {
if (!resizeOnMove) {
resizeStart = new Date().getTime();
resizeCount++;
resize_canvas();
}
var elapsed = new Date().getTime() - resizeStart;
outputElement.innerText = ' Resized ' + resizeCount + ' times in ' + elapsed / 1000 + 's';
});
}
}
export class Visual {
public id: string;
public numberOfElements: number;
public radiusSize: number;
public data: any[] = [];
public canvas: HTMLCanvasElement;
public canvasTop: HTMLCanvasElement;
constructor(canvasId: string, numberOfElements: number, radiusSize: number) {
this.id = canvasId;
this.numberOfElements = numberOfElements;
this.radiusSize = radiusSize;
this.canvas = <HTMLCanvasElement>document.getElementById(canvasId);
this.canvasTop = document.createElement('canvas');
this.canvasTop.id = this.id + 'Top';
var wrapper = this.canvas.parentElement;
wrapper.appendChild(this.canvasTop);
this.setSize();
this.data = this.getData();
this.draw();
this.canvasTop.addEventListener('click', (event) => this.onClick(event), false);
}
public onClick(event: MouseEvent) {
var x = event.layerX - this.canvasTop.offsetLeft,
y = event.layerY - this.canvasTop.offsetTop;
var clickingText = <HTMLCanvasElement>document.getElementById("clickingText");
clickingText.innerText = "clicked on (" + x + ',' + y + ")";
//this.drawRect(this.canvasTop.getContext('2d'), x, y, this.radiusSize * 2, 'yellow');
}
public setSize() {
this.canvasTop.width = this.canvas.width = this.canvas.parentElement.clientWidth - 20;
this.canvasTop.height = this.canvas.height = this.canvas.parentElement.clientHeight - 20;
}
public clear() {
var context = this.canvas.getContext('2d');
context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
public getData(): any[] {
var result = [];
for (var i = 0; i < this.numberOfElements; i++) {
result.push({ x: (Math.random()), y: (Math.random()) });
}
return result;
}
public setData() {
this.data = this.getData();
}
public draw() {
//this.drawRects(this.canvas);
this.drawCircles(this.canvas);
}
public drawCircles(canvas) {
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
//var c = new fabric.Canvas(canvas);
for (var i = 0; i < this.numberOfElements; i++) {
var x = this.data[i].x * canvas.width;
var y = this.data[i].y * canvas.height;
this.drawCircle(context, x, y, this.radiusSize, 'green');
//var circle = new fabric.Circle({ radius: this.radiusSize, fill: 'green', left: x, top: y });
//c.add(circle);
}
}
public drawCircle(context: any, x: number, y: number, radius: number, color: string) {
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.fillStyle = color;
context.fill();
context.lineWidth = 2;
context.strokeStyle = '#003300';
context.stroke();
context.closePath();
}
public drawRects(canvas) {
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var fillStyles = [];
var squareSize = this.radiusSize * 2;
for (var i = 0; i < this.numberOfElements; i++) {
var x = this.data[i].x * canvas.width;
var y = this.data[i].y * canvas.height;
this.drawRect(context, x, y, this.radiusSize * 2, 'green');
}
}
public drawRect(context: any, x: number, y: number, squareSize: number, color: string) {
context.fillStyle = color;
context.fillRect(x, y, squareSize, squareSize);
context.lineWidth = 1;
context.strokeStyle = '#000000';
context.strokeRect(x, y, squareSize, squareSize);
}
public toSvg() {
//var c = new fabric.Canvas('myCanvas');
var object = fabric.util.object.clone((<any>this.canvas).getActiveObject());
var c = new fabric.Canvas(object);
c.calcOffset();
var opt: fabric.IToSVGOptions = {
encoding: "utf8",
suppressPreamble: false,
viewBox: { x: 0, y: 0, width: 1600, height: 700 }
};
return c.toSVG(opt);
}
}
}
|
9acad8a0d5b6c8538d318a376bd2ceafb665f171
|
TypeScript
|
hdt3781/CSIA-AnuglarFrontend
|
/src/app/services/filter-sort.service.ts
| 3.09375
| 3
|
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class FilterSortService {
localSearch = null;
constructor() {
}
// Create function GetSortorder with parameter prop.
GetSortOrder(prop) {
// Creates two objects, a and b.
return (a, b) => {
if (a[prop] > b[prop]) {
return 1;
} else if (a[prop] < b[prop]) {
return -1;
}
return 0;
};
}
// Create function checkCategory
checkCategory(product) {
// Create a variable re to which the input value (by user) is assigned
const re = new RegExp(this.localSearch.toLocaleUpperCase().trim(), 'g');
// Setting the value of retFlag to false
let retFlag = false;
// If the localSearch (input value by user) is defined and
// if the value or 're' matches the category of a given product
// set retFlag to true.
if (typeof this.localSearch !== 'undefined') {
if (product.category.toLocaleUpperCase().trim().match(re)) {
retFlag = true;
}
return retFlag;
}
}
// Create function filterAndSort
filterAndSort(inpProducts, fc, sk) {
// Set the value of localSearch to the fc (filter criteria - user's chosen category).
this.localSearch = fc;
let filteredObjects;
// The filtered inpProducts (array of all products) is assigned to filteredObjects.
// The filter function is performed on each element of the products array.
filteredObjects = inpProducts.filter(el => {
// Create a variable re to which the input value (by user) is assigned
const re = new RegExp(this.localSearch.toLocaleUpperCase().trim(), 'g');
// Setting the value of retFlag to false
let retFlag = false;
// If the localSearch (input value by user) is defined and
// if the value or 're' matches the category of a given product
// set retFlag to true.
if (typeof this.localSearch !== 'undefined') {
if (el.category.toLocaleUpperCase().trim().match(re)) {
retFlag = true;
}
return retFlag;
}
});
// Sort through the filteredObjects array, performing the GetSortOrder function to sort the array.
filteredObjects.sort(this.GetSortOrder(sk));
return (filteredObjects);
}
}
|
fa6689ad7acabb30eac3c8f539df5594074ba762
|
TypeScript
|
real-marshal/binance-hotkeys
|
/src/common/utils.ts
| 2.671875
| 3
|
// Make some fields of T optional
export type Optional<T, K extends string> = Omit<T, K> & Partial<T>
|
4691796981e83993cbc6ed50875aa76fb4f2f922
|
TypeScript
|
arjit95/routi
|
/packages/routi-core/src/server/request.ts
| 2.5625
| 3
|
import { IncomingMessage } from 'http';
export type NextFunction = (...args: unknown[]) => void;
export interface Request extends IncomingMessage {
next?: NextFunction;
[key: string]: unknown;
// Native request object for the framework
readonly root: unknown;
}
|
acbe39b2689ea3cac2092ae593fb7473090f1686
|
TypeScript
|
Polanco10/configurable-form
|
/src/app/field.interface.ts
| 2.578125
| 3
|
export interface Validator {
name: string;
validator: any;
message: string;
}
export interface FieldConfig {
label?: string; //Label del campo
name?: string; //Nombre de formControl
inputType?: string; //Tipo de input (text, email, password)
options?: string[]; //Opciones para select y para checkbox
collections?: any;
type?: string; //Tipo de field (input,radiobutton,select)
value?: any; //Valor del campo por defecto
validations?: Validator[]; //Validaciones
inputs?: []; //Array de inputs
}
|
5b33ae874b29495af71d87831f538fd99c2e9928
|
TypeScript
|
1337programming/leviathan
|
/kiosk/app/src/common/services/random.service.ts
| 2.953125
| 3
|
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
@Injectable()
export class Random {
private static getRandomIntInclusive(min: number, max: number): number {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
constructor() {
}
public nextInt(min: number, max: number): number {
return min + Math.floor(Math.random() * (max - min));
}
public element<T>(array: T[]): any {
return array[this.nextInt(0, array.length)];
}
public sampler<T>(array: T[]) {
let previous: T;
return () => {
const options: any = array.slice(0).filter((x) => x !== previous);
return previous = this.element(options);
};
}
public markovProcess(minDelay: number, maxDelay: number): boolean {
return Observable.create((observer) => {
let running: boolean = true;
let next: Function = () => {
if (running) {
observer.next();
setTimeout(next, this.nextInt(minDelay, maxDelay));
}
};
next();
return () => running = false;
});
}
public randomWalk(startStep: number, minChange: number, maxChange: number): boolean {
return Observable.create((observer) => {
let running: boolean = true;
let step: number = startStep;
let next = () => {
if (running) {
step += this.nextInt(minChange, maxChange);
observer.next();
setTimeout(next, step);
}
};
next();
return () => running = false;
});
}
public constrainedRandomWalk(startStep: number, minStep: number, maxStep: number,
minChange: number, maxChange: number): boolean {
return Observable.create((observer) => {
let running: boolean = true;
let step: number = startStep;
/*(async () => {
while (running) {
step += this.nextInt(minChange, maxChange);
step = Math.min(step, maxStep);
step = Math.max(step, minStep);
observer.next();
await this.sleep(step);
}
})();*/
return () => running = false;
});
}
public randomWalkInterp(min, max, stepsPerInterval): boolean {
return Observable.create((observer) => {
let running: boolean = true;
let current: number = this.nextInt(min, max);
let next: number = this.nextInt(min, max);
let step: number = 0;
/*(async () => {
while (running) {
const diff = next - current;
const stepFraction = step / stepsPerInterval;
const val = current + stepFraction * diff;
observer.next();
await this.sleep(val);
step++;
if (step === stepsPerInterval) {
current = next;
next = this.nextInt(min, max);
step = 0;
}
}
})();*/
return () => running = false;
});
}
public noise(x: number): number {
x = (x << 13) ^ x;
return (1.0 - ((x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0);
}
public linearInterpolate(a, b, x): number {
return a * (1 - x) + b * x;
}
public cosineInterpolate(a: number, b: number, x: number): number {
const ft: number = x * Math.PI;
const f: number = (1 - Math.cos(ft)) * .5;
return a * (1 - f) + b * f;
}
public interpolatedNoise(x): number {
const xFloor: number = Math.floor(x);
const xFraction: number = x - xFloor;
const v1: number = this.noise(xFloor);
const v2: number = this.noise(xFloor + 1);
return this.cosineInterpolate(v1, v2, xFraction);
}
public perlinNoise(initialDelay, sleepTime = 200, adjust = 5): boolean {
const persistence: number = 1 / 2;
const numberOfOctaves: number = 4;
return Observable.create((observer) => {
let running: boolean = true;
let x: number = Math.random();
/*let nextNoise = async () => {
await this.sleep(initialDelay);
while (running) {
let total = 0;
for (let i=0 ; i < numberOfOctaves - 1 ; i++) {
const frequency = 2 ** i;
const amplitude = persistence ** i;
total = total + this.interpolatedNoise(x * frequency) * amplitude;
}
const probability = (total + 1) / adjust;
const yes = (Math.random() < probability);
if (yes) {
observer.next();
}
await this.sleep(sleepTime);
x += 0.2;
}
};
nextNoise();*/
return () => running = false;
});
}
public simpleCurve(samplesPerStep: number = 10): Observable<any> {
return Observable.interval(100)
.map(i => i / samplesPerStep)
.map(step => this.interpolatedNoise(step));
}
private sleep(ms: number): any {
return new Promise(resolve => setTimeout(resolve, ms));
}
private randomSentiment(): string {
let sentiments: any = {
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
'5': 'five',
'6': 'six',
'7': 'seven',
'8': 'eight',
'9': 'nine',
'10': 'ten'
};
let index: string = Random.getRandomIntInclusive(0, 10).toString();
return sentiments[index];
}
private randomStatement(): string {
let statements: Array<string> = [
'Lorem ipsum dolor sit amet, eu quo vide hendrerit, quem quod tritani eum ut.',
'Alii definitionem ne his, dicta deseruisse an vix, mea maiorum deterruisset at.',
'Id quo viderer appetere pertinacia, te vim dicit dolorum singulis.',
'Ad vis repudiare aliquando, stet graeco at sed.',
'Nam ei omnium honestatis, eos dicat verear ut. Ubique legendos eam an',
'Pro labores sensibus moderatius cu, mei consequat philosophia no.',
'Eu hinc assentior vim, possit sapientem eu ius, modus labitur percipit eam ad.',
'Cu graeco iuvaret constituto nec.',
'Et iisque interpretaris eos.',
'Ius molestiae dissentiunt efficiantur id, ei vim vivendo definiebas, per ei invenire splendide gloriatur.',
'No rebum sensibus has, maiorum tacimates at pri.',
'Quo ne homero graeco, te quo assentior expetendis.',
'Aperiri verterem per eu, nam ex verear accusata elaboraret.',
'Mea at lorem appetere, errem gubergren eam te.'
];
return statements[Random.getRandomIntInclusive(0, statements.length - 1)];
}
private randomTopic(): string {
let topics: Array<string> = [
'Tmobile',
'Election'
];
return topics[Random.getRandomIntInclusive(0, topics.length - 1)];
}
}
|
409b279a48187c82fc1395ccf1304fa09e676b91
|
TypeScript
|
ElLuchoMan/SanyuFront
|
/src/app/Shared/models/rol.ts
| 2.828125
| 3
|
//Interface que permite concer los tipos de dato que contiene un Rol
export interface Rol {
estadoRol: string,
idRol: number,
nombreRol: string,
}
|
5fb9c77152276cf0db016af58c30f4e6f0bad934
|
TypeScript
|
stencila/encoda
|
/src/codecs/types.ts
| 2.84375
| 3
|
import { Jesta } from '@stencila/jesta'
import schema from '@stencila/schema'
import { fromFiles } from '../util/media/fromFiles'
import { resolveFiles } from '../util/media/resolveFiles'
import { toFiles } from '../util/media/toFiles'
import { reshape } from '../util/reshape'
import * as vfile from '../util/vfile'
const jesta = new Jesta()
/**
* Encoding options that are common to all codecs.
*
* Codecs are encouraged to respect these options but
* are not forced to. Indeed, some options do not make sense for
* some codecs. For example, for the PDF codec `isStandalone`
* is always `true` so if `isStandalone: false` is supplied
* as an option it will be ignored. Futhermore, some combinations
* of options are pointless e.g. a `theme` when `isStandalone: false`
*/
export interface CommonEncodeOptions {
format?: string
filePath?: string
isStandalone?: boolean
isBundle?: boolean
theme?: string
}
/**
* Default values for encoding options.
*
* This set of defaults provide a way of promoting consistency amongst
* codecs. Instead of, for example, one codec defaulting
* to `isStandalone: true` and another to `false`. It does not
* enforce consistency however.
*/
type CommonEncodeDefaults = Required<
Pick<CommonEncodeOptions, 'isStandalone' | 'isBundle' | 'theme'>
>
export const commonEncodeDefaults: CommonEncodeDefaults = {
isStandalone: false,
isBundle: false,
theme: 'stencila',
}
/**
* Decoding options that are common to all codecs.
*
* See notes for `CommonEncodeOptions` for how these are used.
*/
export interface CommonDecodeOptions {
/**
* The format to decode content from.
*
* Most codecs only decode from one format. However,
* for those codecs that support multiple formats,
* this options lets the user specify which one.
*/
format?: string
/**
* Should the content be treated as a standalone
* document or as a fragment?
*
* This option affects whether codecs will attempt
* to extract metadata etc from the content. If this
* option is `false`, some codecs will default to returning
* an array of content nodes, instead of for example an
* `Article` node.
*/
isStandalone?: boolean
/**
* The node type to decode content to.
*
* Many codecs decode to a single node type.
* e.g. the `docx` codec always decodes to an `Article`.
* However, some `codecs` can decode to multiple node types.
* e.g. the `yaml` and `xlsx` codecs.
* This option allows the user to be explicit about which node type
* they expect content to be decode to.
*/
asType?: keyof schema.Types
/**
* Should the decoded node have the `coerce` function applied to it?
*/
shouldCoerce?: boolean
/**
* Should the decoded node have the `reshape` function applied to it?
*/
shouldReshape?: boolean
}
/**
* Default values for encoding options.
*
* See notes for `commonEncodeDefaults` for why these exist.
*/
type CommonDecodeDefaults = Required<
Pick<CommonDecodeOptions, 'isStandalone' | 'shouldCoerce' | 'shouldReshape'>
>
export const commonDecodeDefaults: CommonDecodeDefaults = {
// To avoid breaking changes this is true, but may be changed to
// false for consistency with default for encoding (false)
isStandalone: true,
// Coerce by default
shouldCoerce: false,
// Reshape by default
shouldReshape: true,
}
/**
* The interface for a codec.
*
* Note that our use of the term "codec", is consistent with our usage elsewhere in Stencila
* as something that creates or modifies executable document, and
* differs from the usage of [`unified`](https://github.com/unifiedjs/unified#processorcodec).
*/
export abstract class Codec<
EncodeOptions extends CommonEncodeOptions = {},
DecodeOptions extends CommonDecodeOptions = {}
> {
/**
* An array of [IANA Media Type](https://www.iana.org/assignments/media-types/media-types.xhtml)
* that the codec can decode/encode.
*/
public readonly mediaTypes?: string[]
/**
* Any array of file names to use to match the codec.
* This can be useful for differentiating between
* "flavors" of formats e.g. `datapackage.json` versus any old `.json` file.
*/
public readonly fileNames?: string[]
/**
* Any array of file name extensions to register for the codec.
* This can be useful for specifying conversion to less well known media types
* e.g. `--to tdp` for outputting `datapackage.json` to the console.
*/
public readonly extNames?: string[]
/**
* A function that does [content sniffing](https://en.wikipedia.org/wiki/Content_sniffing)
* to determine if the codec is able to decode the content. As well as raw content, the content
* string could be a file system path and the codec could do "sniffing" of the file system
* (e.g. testing if certain files are present in a directory).
*/
public readonly sniff?: (content: string) => Promise<boolean>
/**
* The default encode options for this codec
*/
protected commonEncodeDefaults: CommonEncodeDefaults = commonEncodeDefaults
/**
* The default decode options for this codec
*/
protected commonDecodeDefaults: CommonDecodeDefaults = commonDecodeDefaults
/**
* Decode a `VFile` to a `stencila.Node`.
*
* @param file The `VFile` to decode
* @param options Decoding options
* @returns A promise that resolves to a `stencila.Node`
*/
public abstract readonly decode: (
file: vfile.VFile,
options?: DecodeOptions
) => Promise<schema.Node>
/**
* Encode a `stencila.Node` to a `VFile`.
*
* @param node The `stencila.Node` to encode
* @param options Encoding options
* @returns A promise that resolves to a `VFile`
*/
public abstract readonly encode: (
node: schema.Node,
options?: EncodeOptions
) => Promise<vfile.VFile>
/**
* Decode a `stencila.Node` from a `string`.
*
* This is a convenience method which simply
* reads the content of the `VFile` and passes
* it to the `decode` method.
*
* @param content The `string` to decode
* @param options Decoding options
* @returns A promise that resolves to a `stencila.Node`
*/
public async load(
content: string,
options?: DecodeOptions
): Promise<schema.Node> {
const { shouldCoerce = false, shouldReshape = true } = options ?? {}
let node = await this.decode(vfile.load(content), options)
if (shouldCoerce) node = await jesta.validate(node, true)
if (shouldReshape) node = await reshape(node)
return node
}
/**
* Transform a node prior to dumping it.
*
* Defaults to "bundling" the file i.e reading
* media content from files into data URIs.
* This default can be overridden using the `isBundle: false` option
* but is usually appropriate for `dump`ing to a string (cf `write` which
* writes to files).
* Derived classes may override this method to perform alternative
* transformations to the node, prior to dumping it.
*
* @param node The `stencila.Node` to write
* @param filePath The path of the file
* @param options Encoding options
*/
public preDump(
node: schema.Node,
options?: EncodeOptions
): Promise<schema.Node> {
const { isBundle = true } = { ...options }
return isBundle ? fromFiles(node) : Promise.resolve(node)
}
/**
* Encode a `stencila.Node` to a `string`.
*
* This is a convenience method which simply
* dumps the content of the `VFile` created by
* the `encode` method.
*
* @param node The `stencila.Node` to dump
* @returns A promise that resolves to a `string`
*/
public async dump(
node: schema.Node,
options?: EncodeOptions
): Promise<string> {
return vfile.dump(
await this.encode(await this.preDump(node, options), options)
)
}
/**
* Read a `stencila.Node` from a file.
*
* This is a convenience method which reads the file into a `VFile`,
* makes any references to local files absolute, and passes
* it to the `decode` method.
*
* @param filePath The path of the file
* @param options Decoding options
* @returns A promise that resolves to a `stencila.Node`
*/
public async read(
filePath: string,
options?: DecodeOptions
): Promise<schema.Node> {
const { shouldCoerce = false, shouldReshape = true } = options ?? {}
let node = await this.decode(await vfile.read(filePath), options)
if (shouldCoerce) node = await jesta.validate(node)
if (shouldReshape) node = await reshape(node)
return resolveFiles(node, filePath)
}
/**
* Transform a node prior to writing it.
*
* Writes data URI or file system media content to a sibling folder.
* This default behavior can be overridden using the `isBundle: true`
* option, but is usually appropriate for `write`ing files (cf `dump`
* which bundles them.
*
* Derived classes may override this method to perform alternative
* transformations to the node, prior to writing it.
*
* @param node The `stencila.Node` to write
* @param filePath The path of the file
* @param options Encoding options
*/
public preWrite(
node: schema.Node,
filePath: string,
options?: EncodeOptions
): Promise<schema.Node> {
const { isBundle = false } = { ...options }
return isBundle
? fromFiles(node)
: toFiles(node, filePath, ['data', 'file'])
}
/**
* Encode a `stencila.Node` to a file
*
* This is a convenience method which writes the content of the `VFile` created by
* the `encode` method.
*
* @param node The `stencila.Node` to write
* @param filePath The path of the file
* @param options Encoding options
*/
public async write(
node: schema.Node,
filePath: string,
options?: EncodeOptions
): Promise<void> {
return vfile.write(
await this.encode(await this.preWrite(node, filePath, options), {
filePath,
...options,
} as EncodeOptions),
filePath
)
}
}
|
8d088c7b22f88ce8c7bb5dde008191c4e736fd57
|
TypeScript
|
tbknl/specified
|
/src/constraint.ts
| 3.09375
| 3
|
export const Constraint = {
generic: {
oneOf: <T>(...options: T[]) => {
return {
version: 1 as 1,
definition: {
name: "oneOf",
settings: { options }
},
eval: (value: T) => {
return { err: options.indexOf(value) < 0 ? {
code: "constraint.generic.oneOf.unknown_value",
value,
allowed: options,
message: "Not one of the accepted options."
} : null };
}
};
}
},
number: {
integer: {
version: 1 as 1,
definition: {
name: "integer"
},
eval: (value: number) => {
return { err: value % 1 !== 0 ? {
code: "constraint.number.integer",
value,
message: "Not an integer."
} : null };
}
},
finite: {
version: 1 as 1,
definition: {
name: "finite"
},
eval: (value: number) => {
return { err: !Number.isFinite(value) ? {
code: "constraint.number.finite",
value,
message: "Not a finite number."
} : null };
}
},
above: (lowerLimit: number) => {
return {
version: 1 as 1,
definition: {
name: "above",
settings: { lowerLimit }
},
eval: (value: number) => {
return { err: !(value > lowerLimit) ? {
code: "constraint.number.above",
value,
message: `Not above ${lowerLimit}.`
} : null };
}
};
},
below: (upperLimit: number) => {
return {
version: 1 as 1,
definition: {
name: "below",
settings: { upperLimit }
},
eval: (value: number) => {
return { err: !(value < upperLimit) ? {
code: "constraint.number.below",
value,
message: `Not below ${upperLimit}.`
} : null };
}
};
},
atLeast: (lowerLimit: number) => {
return {
version: 1 as 1,
definition: {
name: "atLeast",
settings: { lowerLimit }
},
eval: (value: number) => {
return { err: !(value >= lowerLimit) ? {
code: "constraint.number.atLeast",
value,
message: `Less than ${lowerLimit}.`
} : null };
}
};
},
atMost: (upperLimit: number) => {
return {
version: 1 as 1,
definition: {
name: "atMost",
settings: { upperLimit }
},
eval: (value: number) => {
return { err: !(value <= upperLimit) ? {
code: "constraint.number.atMost",
value,
message: `Larger than ${upperLimit}.`
} : null };
}
};
}
},
string: {
notEmpty: {
version: 1 as 1,
definition: {
name: "notEmpty"
},
eval: (value: string) => {
return { err: value === "" ? {
code: "constraint.string.notEmpty",
value,
message: "Empty string."
} : null };
}
},
length: ({ min, max }: { min?: number, max: number } | { min: number, max?: number }) => {
return {
version: 1 as 1,
definition: {
name: "length",
settings: { min, max }
},
eval: (value: string) => {
if (typeof min !== "undefined" && value.length < min) {
return { err: {
code: "constraint.string.length.too_short",
value,
message: `String length less than ${min}`
} };
}
else if (typeof max !== "undefined" && value.length > max) {
return { err: {
code: "constraint.string.length.too_long",
value,
message: `String length greater than ${max}`
} };
}
return { err: null };
}
};
},
regex: (re: RegExp, custom: { errorMessage: string; errorCode: string; } = { errorMessage: "Regex mismatch.", errorCode: "constraint.string.regex" }) => {
return {
version: 1 as 1,
definition: {
name: "regex",
settings: { expression: re.source }
},
eval: (value: string) => {
return { err: !re.test(value) ? {
code: custom.errorCode,
value,
allowed: re.source,
message: custom.errorMessage
} : null };
}
};
},
startsWith: (prefix: string) => {
return {
version: 1 as 1,
definition: {
name: "startsWith",
settings: { prefix }
},
eval: (value: string) => {
return { err: value.substr(0, prefix.length) !== prefix ? {
code: "constraint.string.startsWith",
value,
message: `String does not start with '${prefix}'.`
} : null };
}
};
},
endsWith: (suffix: string) => {
return {
version: 1 as 1,
definition: {
name: "endsWith",
settings: { suffix }
},
eval: (value: string) => {
return { err: value.substr(value.length - suffix.length) !== suffix ? {
code: "constraint.string.endsWith",
value,
message: `String does not end with '${suffix}'.`
} : null };
}
};
}
},
map: {
size: <T extends {}>({ min, max }: { min?: number, max: number } | { min: number, max?: number }) => {
return {
version: 1 as 1,
definition: {
name: "size",
settings: { min, max }
},
eval: (value: T) => {
const numKeys = Object.keys(value).length ;
if (typeof min !== "undefined" && numKeys < min) {
return { err: {
code: "constraint.map.size.too_small",
value,
message: `Object size less than ${min}`
} };
}
else if (typeof max !== "undefined" && numKeys > max) {
return { err: {
code: "constraint.map.size.too_large",
value,
message: `Object size greater than ${max}`
} };
}
return { err: null };
}
};
}
},
array: {
length: <T>({ min, max }: { min?: number, max: number } | { min: number, max?: number }) => {
return {
version: 1 as 1,
definition: {
name: "length",
settings: { min, max }
},
eval: (value: T[]) => {
return { err:
(typeof min !== "undefined" && value.length < min) ? {
code: "constraint.array.length.too_short",
value,
message: `Array length less than ${min}`
} :
(typeof max !== "undefined" && value.length > max) ? {
code: "constraint.array.length.too_long",
value,
message: `Array length greater than ${max}`
} :
null
};
}
};
},
includes: <T>(includedValue: T) => {
return {
version: 1 as 1,
definition: {
name: "includes",
settings: { value: includedValue }
},
eval: (value: T[]) => {
return { err: value.indexOf(includedValue) < 0 ? {
code: "constraint.array.includes",
value,
message: "Value is not included in array."
} : null };
}
};
},
unique: <U, T extends U>(equalsFunc: (a: U, b: U) => boolean = (a: U, b: U) => a === b) => {
return {
version: 1 as 1,
definition: {
name: "unique"
},
eval: (value: T[]) => {
for (let i = 0; i < value.length; i++) {
for (let j = i + 1; j < value.length; j++) {
if (equalsFunc(value[i], value[j])) {
return { err: {
code: "constraint.array.unique",
value,
message: `Array has duplicate elements at index ${i} and ${j}.`
} };
}
}
}
return { err: null };
}
};
}
}
};
|
051b9e63dc72347b7624fdd2c4fa40fa66cb7338
|
TypeScript
|
BinPar/legendPrototype
|
/test/tests/legends/avoidCrossingLegendsStress.ts
| 2.734375
| 3
|
import generateRandomLegends from '../../../utils/generateRandomLegends';
import removeCrossingLines from '../../../utils/removeCrossingLines';
import {
marcCrossingLines,
haveCrossingLines,
} from '../../../utils/detectCrossingLines';
/**
* Test to check if the system can fix all the crossing segments
* situations in 1000 different charts
*/
export default test('Stress test legend generator', (): void => {
for (let i = 0; i < 1000; i++) {
let legends = generateRandomLegends(i.toString(), {
width: 1024,
height: 768,
});
if (haveCrossingLines(legends)) {
legends = marcCrossingLines(legends);
expect(
legends.filter((legend) => legend.isCrossed).length,
).toBeGreaterThan(0);
legends = removeCrossingLines(legends);
const isCrossingNow = haveCrossingLines(legends);
if (isCrossingNow) {
// eslint-disable-next-line no-console
console.error(`Found one problematic seed: ${i}`);
}
expect(isCrossingNow).toBeFalsy();
}
}
});
|
792a73339223017628f929acb871065c1ebb8375
|
TypeScript
|
zys-contrib/examples
|
/solutions/mint-nft/helpers/constant.helpers.ts
| 2.59375
| 3
|
type SupportedNetworks = "0x1" | "0x4"
// this example would work on ethereum mainnet but Rinkeby is used to showcase. For main network change to "0x1"
export const NETWORK_ID = "0x4"
export const ChainLabelMap: Record<SupportedNetworks, string> = {
"0x1": 'Ethereum',
"0x4": 'Rinkeby',
}
export const currentChainLabel = ChainLabelMap[NETWORK_ID]
|
c536d46eeb4a488a608ef47fd83bbb0fd6b5fa23
|
TypeScript
|
ravi221/met-gpr
|
/src-31052018-currently-working/app/ui-controls/services/tooltip.service.ts
| 2.796875
| 3
|
import {Injectable, OnDestroy} from '@angular/core';
import {ITooltip} from '../interfaces/iTooltip';
import {TooltipContentComponent} from '../components/tooltip/tooltip-content.component';
import {Guid} from '../../core/utilities/guid';
import {isNil} from 'lodash';
import {Observable} from 'rxjs/Observable';
import {Subscription} from 'rxjs/Subscription';
import {SubscriptionManager} from '../../core/utilities/subscription-manager';
/**
* Service to keep track of all tooltips on a given page, only allowing one to show at a given time
*/
@Injectable()
export class TooltipService implements OnDestroy {
/**
* An array of {@link ITooltip}
*/
public tooltips: ITooltip[] = [];
/**
* An observable to watch the window resize
* @type {Observable<any>}
*/
private _click$: Observable<any> = Observable.fromEvent(window, 'click');
/**
* An observable to watch the window resize
* @type {Observable<any>}
*/
private _resize$: Observable<any> = Observable.fromEvent(window, 'resize');
/**
* An observable to watch the window scroll
* @type {Observable<any>}
*/
private _scroll$: Observable<any> = Observable.fromEvent(window, 'scroll');
/**
* A subscription to watch the click event
*/
private _clickSubscription: Subscription;
/**
* A subscription to watch the resize event
*/
private _resizeSubscription: Subscription;
/**
* A subscription to watch the scroll event
*/
private _scrollSubscription: Subscription;
/**
* Creates the tooltip service
*/
constructor() {
this._clickSubscription = this._click$.subscribe(($event: any) => {
this._updateTooltipVisibility($event);
});
this._resizeSubscription = this._resize$.subscribe(() => {
this._updateTooltipPositions();
});
this._scrollSubscription = this._scroll$.subscribe(() => {
this._updateTooltipPositions();
});
}
/**
* On destroy, remove subscriptions to the window
*/
ngOnDestroy(): void {
const subscriptions: Subscription[] = [
this._clickSubscription,
this._resizeSubscription,
this._scrollSubscription
];
SubscriptionManager.massUnsubscribe(subscriptions);
}
/**
* Creates a new tooltip
* @param {TooltipContentComponent} tooltipContent The content of the new tooltip
*/
public create(tooltipContent: TooltipContentComponent): ITooltip {
const id = Guid.create();
const isVisible = false;
const tooltip: ITooltip = {id, tooltipContent, isVisible};
this.tooltips.push(tooltip);
return tooltip;
}
/**
* Removes the tooltip from our list of tooltips
* @param {ITooltip} tooltip The tooltip to remove
*/
public destroy(tooltip: ITooltip): void {
if (isNil(tooltip)) {
return;
}
const index = this.tooltips.findIndex((t: ITooltip) => {
return t.id === tooltip.id;
});
const doesTooltipExist = index !== -1;
if (!doesTooltipExist) {
return;
}
tooltip.isVisible = false;
tooltip.tooltipContent.setVisiblity(false);
this.tooltips.splice(index, 1);
}
/**
* Toggles whether to hide or show the tooltip
* @param {ITooltip} tooltip The tooltip that is being hidden/shown
*/
public toggle(tooltip: ITooltip): void {
tooltip.isVisible = !tooltip.isVisible;
if (tooltip.isVisible) {
this.show(tooltip);
} else {
this.hide(tooltip);
}
}
/**
* Called to hide the tooltip
* @param {ITooltip} tooltip The tooltip to hide
*/
public hide(tooltip: ITooltip): void {
tooltip.isVisible = false;
tooltip.tooltipContent.setVisiblity(false);
}
/**
* Called to show the tooltip
* @param {ITooltip} tooltip The tooltip to show
*/
public show(tooltip: ITooltip): void {
this.hideAllTooltips();
tooltip.isVisible = true;
tooltip.tooltipContent.setVisiblity(true);
}
/**
* Hides all other tooltips
*/
public hideAllTooltips(): void {
this.tooltips.forEach((tooltip: ITooltip) => {
this.hide(tooltip);
});
}
/**
* Updates visible tooltips when the document is clicked
* @param {any} $event
* @private
*/
private _updateTooltipVisibility($event: any): void {
const visibleTooltips = this.tooltips.filter(tooltip => tooltip.isVisible);
visibleTooltips.forEach(tooltip => {
tooltip.tooltipContent.handleDocumentClick($event);
});
}
/**
* Updates the tooltip positions, updated when the window resizes or scrolls
* @private
*/
private _updateTooltipPositions(): void {
const visibleTooltips = this.tooltips.filter(tooltip => tooltip.isVisible);
visibleTooltips.forEach(tooltip => {
tooltip.tooltipContent.updateTooltipPosition();
});
}
}
|
2c8672388b0da01b489b143fdac63a133ea2cd52
|
TypeScript
|
MaorZ/JackSyncJS
|
/src/patchOperations/operations/addOperation.spec.ts
| 2.765625
| 3
|
import { AddOpertaion } from "./addOperation";
let addOperation: AddOpertaion;
describe("Add Operation spec", () => {
beforeEach(() => {
});
it("should add a title", () => {
let actual = {
name: "My Name"
};
let expected = {
name: "My Name",
title: "My Title"
};
addOperation = new AddOpertaion({
path: "/title",
value: "My Title"
});
addOperation.apply(actual);
expect(actual).toEqual(expected);
});
it("should add an author", () => {
let actual = {
name: "My Name"
};
let expected = {
name: "My Name",
author: {
firstName: "James",
lastName: "Bond",
email: "James.Bond@007.com"
}
};
addOperation = new AddOpertaion({
path: "/author",
value: {
firstName: "James",
lastName: "Bond",
email: "James.Bond@007.com"
}
});
addOperation.apply(actual);
expect(actual).toEqual(expected);
});
it("should add an author first name", () => {
let actual = {
name: "My Name",
author: {
lastName: "Bond",
email: "James.Bond@007.com"
}
};
let expected = {
name: "My Name",
author: {
firstName: "James",
lastName: "Bond",
email: "James.Bond@007.com"
}
};
addOperation = new AddOpertaion({
path: "/author/firstName",
value: "James"
});
addOperation.apply(actual);
expect(actual).toEqual(expected);
});
});
|
71ba18d250c7717287174982906b0d6b169c4029
|
TypeScript
|
WhiteMIron/TodoList-Nest.js-backend
|
/src/todo/entities/todo.entity.ts
| 2.515625
| 3
|
import { ApiProperty } from '@nestjs/swagger';
import { IsString } from 'class-validator';
import { Common } from 'src/common/entities/common.entity';
import {
Column,
CreateDateColumn,
Entity,
PrimaryColumn,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity()
export class Todo extends Common {
@PrimaryGeneratedColumn()
id: number;
@IsString()
@ApiProperty({
example: 'Eat',
description: '투두리스트이 타이틀',
})
@Column('varchar')
title: string;
@IsString()
@ApiProperty({
example: 'Eat hamberger',
description: '투두리스트이 설명',
})
@Column('varchar')
desc: string;
@Column('boolean', { default: false })
isComplete: boolean;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updateAt: Date;
}
|
befb38b2fbab0495ffe87015f407f7c03558f7b8
|
TypeScript
|
andyfangdz/d3-openord
|
/src/Node.ts
| 2.890625
| 3
|
/**
* Created by andy on 7/12/16.
*/
export default class Node {
public id: number;
public fixed: boolean;
public x: number;
public y: number;
public subX: number;
public subY: number;
public energy: number;
constructor(id: number) {
this.id = id;
this.fixed = false;
this.x = this.y = 0;
this.subX = this.subY = 0;
this.energy = 0;
}
public clone() {
return Object.assign({}, this);
}
}
|
90faa946df16cd712a77623687f1597827224f0c
|
TypeScript
|
ziggy6792/homage-reservations
|
/packages/lambda-gq-resolver/src/utils/utility.ts
| 2.546875
| 3
|
import getEnvConfig from 'src/config/get-env-config';
import { commonUtils } from '@alpaca-backend/common';
import { CreatableClassType } from 'src/types';
import Creatable from 'src/domain/interfaces/creatable';
import CreatableService from 'src/services/creatable.service';
const envConig = getEnvConfig();
export const VALUE = {
NULL: 'NULL',
};
export const valueIsNull = (value: any): boolean => value === null || value === undefined || value === VALUE.NULL;
export const getTableName = (tableName: string): string => {
const ret = commonUtils.getTableName(tableName, envConig.env);
return ret;
};
export const mapDbException = (err: any, message: string): Error => {
if (err?.code === 'ConditionalCheckFailedException') {
return new Error(message);
}
return err;
};
export const multitableGet = async (
possibleTypes: CreatableClassType[],
getFunction: (createable: CreatableClassType) => Promise<Creatable>
): Promise<Creatable> => {
const results = await Promise.allSettled(possibleTypes.map((entity) => getFunction(entity)));
const fullfilledResults = results.filter((res) => res.status === 'fulfilled');
if (fullfilledResults.length > 0 && fullfilledResults[0].status === 'fulfilled') {
return fullfilledResults[0].value;
}
return null;
};
export const multiServiceGet = async (services: CreatableService<any>[], partitionKey: string, sortKey?: string): Promise<Creatable> => {
const results = await Promise.allSettled(services.map((service) => service.getOne(partitionKey, sortKey)));
const fullfilledResults = results.filter((res) => res.status === 'fulfilled');
if (fullfilledResults.length > 0 && fullfilledResults[0].status === 'fulfilled') {
return fullfilledResults[0].value;
}
return null;
};
|
9efd1cbac99081432f80b8731eb37e3f8cf2948d
|
TypeScript
|
horvathgyozo/progenv-v3-proba-typescript
|
/src/services/authStore.ts
| 2.546875
| 3
|
import { action, computed, observable } from 'mobx';
export class AuthStore {
@observable private authenticated: boolean = false;
@computed get isAuthenticated(): boolean {
return this.authenticated ? true : false
}
@action.bound
public authenticate() {
setTimeout(action(() => this.authenticated = !this.authenticated), 100) // fake async
}
@action.bound
public signout() {
this.authenticated = false
}
}
|
73c985cacfd56d630fe9479684563b25a4695da3
|
TypeScript
|
HossamElharmeil/soduko
|
/src/utils/indetify-square/index.ts
| 3.1875
| 3
|
import { GRID, GRID_INDEX, SQUARE } from 'typings'
interface IInput {
col: GRID_INDEX
grid: GRID
row: GRID_INDEX
}
/**
* A function that returns a soduko square from inside a soduko grid given a cell identified by a row and column
* @param input The column index, the actual grid and the row index
*/
function identifySquare({ col, grid, row }: IInput): SQUARE {
let square = []
let squareStartRow = Math.floor(row / 3) * 3
let squareStartCol = Math.floor(col / 3) * 3
for (let i = 0; i < 3; i++) {
square.push([
grid[squareStartRow + i][squareStartCol],
grid[squareStartRow + i][squareStartCol + 1],
grid[squareStartRow + i][squareStartCol + 2],
])
}
return square as SQUARE
}
export default identifySquare
|
895b9b7dcda231b201e25c8f90388308d500c991
|
TypeScript
|
cesschneider/currency-converter-netjs-react-app
|
/nest-app/src/app.controller.ts
| 2.546875
| 3
|
import { Controller, Get, Query, HttpException } from '@nestjs/common';
import { CurrencyService } from './currency.service';
@Controller('currency')
export class AppController {
constructor(private readonly currencyService: CurrencyService) {}
@Get('/quote')
async getQuoteForPair(
@Query('inputCurrency') inputCurrency: string,
@Query('outputCurrency') outputCurrency: string,
): Promise<number> {
if (!inputCurrency || !outputCurrency) {
throw new HttpException('Incomplete currency information', 400);
}
return await this.currencyService.getQuote(inputCurrency, outputCurrency);
}
}
|
e7acb13a38e8fa3fc1a4acd6e0395e91da1bc8fb
|
TypeScript
|
sanen/sitdown
|
/packages/core/src/service/Node/isBlank.ts
| 2.609375
| 3
|
import isVoid, { voidElements } from '../../util/isVoid';
import { Node } from '../../types';
var voidSelector = voidElements.join();
function hasVoid(node: Node) {
return node.querySelector && node.querySelector(voidSelector);
}
export default function isBlank(node: Node) {
return (
['A', 'TH', 'TD', 'IFRAME', 'SCRIPT', 'AUDIO', 'VIDEO'].indexOf(
node.nodeName
) === -1 &&
/^\s*$/i.test(node.textContent || '') &&
!isVoid(node) &&
!hasVoid(node)
);
}
|
a22503f68b026368a05e916ce0e9044065354ef1
|
TypeScript
|
wwags33/JavaScript30
|
/09 - Dev Tools Domination/typescripts.ts
| 3.46875
| 3
|
/**
* JavaScript30 by Wes Bos, https://javascript30.com/
* TypeScript implementation by Will Wager
* Project: Dev Tools Domination
* Concepts: Console methods
* Key takeaways: Lots of options to log effectively; grouping, counting, and timing is simple
* Sidenotes: DOM Mutation Breakpoints did not work for me in Firefox on Linux, but the debugger command does.
* Compilation command:
* tsc --removeComments --strictNullChecks --noImplicitAny --target es5 typescripts.ts
*/
const dogs = [{ name: 'Snickers', age: 2 }, { name: 'hugo', age: 8 }];
function makeGreen() {
const p = document.querySelector('p')!;
debugger; // Adds a breakpoint in the code.
p.style.color = '#BADA55';
p.style.fontSize = '50px';
}
console.clear();
// Regular
console.log('hello');
// Interpolated
console.log('Hello, I am a %s string', '💩');
// Styled
console.log('%c I am some great text', 'font-size: 50px; background-color: red; text-shadow: 2px 2px 4px blue;');
// warning!
console.warn('OH NOOO');
// Error :|
console.error('Shoot!');
// Info
console.info('Crocodiles eat 3-4 people per year');
// Testing
const p = document.querySelector('p')!;
console.assert(p.classList.contains('ouch'), 'That is wrong!');
// clearing
// console.clear();
// Viewing DOM Elements
console.log(p);
// console.dir(p);
// Grouping together
dogs.forEach(dog => {
console.groupCollapsed(`This is ${dog.name}`);
console.log(`${dog.name} is ${dog.age} years old.`);
console.log(`${dog.name} is ${dog.age * 7} dog years old`);
console.groupEnd();
});
// counting
console.count('Will');
console.count('Will');
console.count('Will');
console.count('Wags');
console.count('Will');
console.count('Wags');
console.count('Will');
console.count('Wags');
console.count('Wags');
console.count('Wags');
// timing
console.time('fetching data');
fetch('https://api.github.com/users/wwags33')
.then(data => data.json())
.then(data => {
console.timeEnd('fetching data');
console.log(data);
});
console.table(dogs);
|
648252c8dbcd205740fe168e83c10cf0efbe6b46
|
TypeScript
|
hzzlyzz/zodash
|
/packages/signature/src/wechat/jssdk.ts
| 2.8125
| 3
|
import sha1 from '@zodash/sha1';
export interface IData {
url: string;
jsapi_ticket: string;
noncestr: string;
timestamp: number;
}
export function sign(data: IData) {
// 1. 按照字段名的ASCII 码从小到大排序(字典序)
const _data = [
'url',
'jsapi_ticket',
'noncestr',
'timestamp',
].sort((a, b) => a.localeCompare(b));
const paris = _data.map((key) => [key, data[key]]);
const text = paris.map(([key, value]) => `${key}=${value}`).join('&');
// 2. sha1
return sha1(text);
}
|
5f330cee66da07cffe0c3be8316b746cd49d898b
|
TypeScript
|
viniciuslj/busca-publicacoes
|
/webapp/src/main/webapp/app/shared/model/quadro.model.ts
| 2.78125
| 3
|
export interface IQuadro {
id?: number;
nome?: string;
nomeLongo?: string;
}
export class Quadro implements IQuadro {
constructor(public id?: number, public nome?: string, public nomeLongo?: string) {}
}
|
73915a0b50bf730ace1db2d3fb140d2a39654e24
|
TypeScript
|
zhylmzr/word-pinyin
|
/test/word-pinyin.test.ts
| 2.890625
| 3
|
import PinYin from "../word-pinyin";
test("get first letter", () => {
expect(PinYin.getFirstLetter("孙先生")).toBe("SXS");
});
test("get word's pinyin", () => {
expect(PinYin.getPinyin("孙先生")).toBe("sun xian sheng");
});
test(`get word's pinyin to use ", "`, () => {
expect(PinYin.getPinyin("孙先生", ", ")).toBe("sun, xian, sheng");
});
test(`宁 word`, () => {
expect(PinYin.getPinyin("宁")).toBe("ning");
expect(PinYin.getFirstLetter("宁")).toBe("N");
});
|
6f5f3620c3b69b52676de812c53e2f92e8fa7879
|
TypeScript
|
hsnks100/acmicpc
|
/tsc.ts
| 3.796875
| 4
|
function append(str1:string,
str2:string):string{
return str1 + str2;
}
var str:string = append('hello',
' Typescript!!');
class Greeter{
greeting:string;
constructor(message: string){
this.greeting = message;
}
greet(){
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("world");
console.log(str);
|
9c6b320cbcc5fa2ff7cfd43126b08872325dc551
|
TypeScript
|
CaptainLiao/wechat-mini
|
/week-star-lite/src/utils/validate.ts
| 3.3125
| 3
|
// 验证邮箱
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
// 验证中文字符
function validateCnText(str) {
var pattern = /^([\u4E00-\u9FA5]|[\uFE30-\uFFA0])*$/gi;
return pattern.test(str);
}
/*
根据〖中华人民共和国国家标准 GB 11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。
地址码表示编码对象常住户口所在县(市、旗、区)的行政区划代码。
出生日期码表示编码对象出生的年、月、日,其中年份用四位数字表示,年、月、日之间不用分隔符。
顺序码表示同一地址码所标识的区域范围内,对同年、月、日出生的人员编定的顺序号。顺序码的奇数分给男性,偶数分给女性。
校验码是根据前面十七位数字码,按照ISO 7064:1983.MOD 11-2校验码计算出来的检验码。
出生日期计算方法。
15位的身份证编码首先把出生年扩展为4位,简单的就是增加一个19或18,这样就包含了所有1800-1999年出生的人;
2000年后出生的肯定都是18位的了没有这个烦恼,至于1800年前出生的,那啥那时应该还没身份证号这个东东,⊙﹏⊙b汗...
下面是正则表达式:
出生日期1800-2099 (18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])
身份证正则表达式 /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i
15位校验规则 6位地址编码+6位出生日期+3位顺序号
18位校验规则 6位地址编码+8位出生日期+3位顺序号+1位校验位
校验位规则 公式:∑(ai×Wi)(mod 11)……………………………………(1)
公式(1)中:
i----表示号码字符从由至左包括校验码在内的位置序号;
ai----表示第i位置上的号码字符值;
Wi----示第i位置上的加权因子,其数值依据公式Wi=2^(n-1)(mod 11)计算得出。
i 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Wi 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 1
*/
//身份证号合法性验证
//支持15位和18位身份证号
//支持地址编码、出生日期、校验位验证
function validateIdCode(code) {
var city = { 11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江 ', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北 ', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏 ', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外 ' };
var tip = '';
var pass = true;
if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
tip = '身份证号格式错误';
pass = false;
}
else if (!city[code.substr(0, 2)]) {
tip = '地址编码错误';
pass = false;
}
else {
//18位身份证需要验证最后一位校验位
if (code.length == 18) {
code = code.split('');
//∑(ai×Wi)(mod 11)
//加权因子
var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
//校验位
var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
var sum = 0;
var ai = 0;
var wi = 0;
for (var i = 0; i < 17; i++) {
ai = code[i];
wi = factor[i];
sum += ai * wi;
}
var last = parity[sum % 11];
if (parity[sum % 11] != code[17]) {
tip = '校验位错误';
pass = false;
}
}
}
return {
result: pass,
tip: tip
};
}
function validatePhone(num: string): boolean {
var pattern = /^1(3|4|5|7|8)\d{9}$/;
return pattern.test(num); // regexObj.prototype.test(str)
}
export {
validateEmail as email,
validateIdCode as idCode,
validateCnText as cnText,
validatePhone as phone
};
|
9ad8c12cf770a8906c4606946d8e40c1add55430
|
TypeScript
|
DSE-AB/angular-gantt
|
/src/plugins/dependencies/dependenciesChecker.factory.ts
| 2.546875
| 3
|
export default function () {
'ngInject'
/**
* Creates a new DependenciesChecker object.
*
* @constructor
*/
let GanttDependenciesChecker = function (manager) {
function handleTaskConflict (conflictsList, task) {
if (!(task.model.id in conflictsList) && task.$element) {
task.$element.addClass('gantt-task-conflict')
conflictsList[task.model.id] = task
}
}
function handleTaskNonConflict (conflictsList, allTasks) {
// tslint:disable:one-variable-per-declaration
for (let i = 0, l = allTasks.length; i < l; i++) {
let task = allTasks[i]
if (!(task.model.id in conflictsList) && task.$element) {
task.$element.removeClass('gantt-task-conflict')
}
}
}
/**
* Refresh the conflict status of given tasks.
*
* @param tasks
*/
this.refresh = function (tasks) {
let allTasks = tasks.slice(0)
let conflictsList = []
for (let task of tasks) {
let taskDependencies = manager.getTaskDependencies(task)
for (let dependency of taskDependencies) {
let fromTask = dependency.getFromTask()
let toTask = dependency.getToTask()
if (!(fromTask in allTasks)) {
allTasks.push(fromTask)
}
if (!(toTask in allTasks)) {
allTasks.push(toTask)
}
if (fromTask.model.to > toTask.model.from) {
handleTaskConflict(conflictsList, fromTask)
handleTaskConflict(conflictsList, toTask)
}
}
}
handleTaskNonConflict(conflictsList, allTasks)
}
this.removeConflictClass = function (task) {
task.$element.removeClass('gantt-task-conflict')
}
/**
* Remove the conflict status of given tasks.
*
* @param tasks
*/
this.clear = function (tasks) {
let allTasks = tasks.slice(0)
handleTaskNonConflict([], allTasks)
}
}
return GanttDependenciesChecker
}
|
ae52510aa0d9a5f59cd2448fe6e6531732b0c269
|
TypeScript
|
zhoujian521/showcase
|
/app/service/github.ts
| 2.71875
| 3
|
import { Service } from "egg";
export default class GitbubService extends Service {
checkSuccess(result) {
const { ctx } = this;
const { status, data } = result;
if (status !== 200) {
const errorMsg =
data && data.error_msg ? data.error_msg : "unknown error";
ctx.throw(status, errorMsg);
}
// if (!result.data.success) {
// // 远程调用返回格式错误
// ctx.throw(500, "remote response error", { data: result.data });
// }
}
checkUrl(url) {
const { ctx } = this;
if (!url) {
ctx.throw(400, "缺少请求Api路径", { code: 400201 });
}
}
// method 请求方法,默认为GET。可以是GET,POST,DELETE或PUT
// data 要发送的数据。将自动进行字符串化
// dataType 字符串-响应数据的类型。可能是text或json
// headers 请求标头
// timeout 请求超时
// auth username:password在HTTP基本授权中使用
// gzip 让您在请求连接时获取res对象,默认为false
// nestedQuerystring urllib默认使用querystring对不支持嵌套对象的表单数据进行字符串化,通过将此选项设置为true,将使用qs而不是querystring支持嵌套对象
public async index() {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Git = require("nodegit");
try {
// Clone a given repository into the `./tmp` folder.
Git.Clone(
"https://github.com/zhoujian521/showcase.git",
"/Users/zhoujian/Desktop/PlayGround/test",
)
// Look up this known commit.
.then(function(repo) {
// Use a known commit sha from this repository.
return repo.getCommit("59b20b8d5c6ff8d09518454d4dd8b7b30f095ab5");
})
// Look up a specific file within that commit.
.then(function(commit) {
return commit.getEntry("README.md");
})
// Get the blob contents from the file.
.then(function(entry) {
// Patch the blob to contain a reference to the entry.
return entry.getBlob().then(function(blob) {
blob.entry = entry;
return blob;
});
})
// Display information about the blob.
.then(function(blob) {
// Show the path, sha, and filesize in bytes.
console.log(
blob.entry.path() + blob.entry.sha() + blob.rawsize() + "b",
);
// Show a spacer.
console.log(Array(72).join("=") + "\n\n");
// Show the entire file.
console.log(String(blob));
})
.catch(function(err) {
console.log(err);
});
} catch (error) {
console.log("============Clone========================");
console.log(error);
console.log("============Clone========================");
}
// try {
// // Open the repository directory.
// Git.Repository.open("/Users/zhoujian/Desktop/PlayGround/showcase/")
// // Open the master branch.
// .then(function (repo) {
// return repo.getMasterCommit();
// })
// // Display information about commits on master.
// .then(function (firstCommitOnMaster) {
// // Create a new history event emitter.
// var history = firstCommitOnMaster.history();
// // Create a counter to only show up to 9 entries.
// var count = 0;
// // Listen for commit events from the history.
// history.on("commit", function (commit) {
// // Disregard commits past 9.
// if (++count >= 9) {
// return;
// }
// // Show the commit sha.
// console.log("commit " + commit.sha());
// // Store the author object.
// var author = commit.author();
// // Display author information.
// console.log(
// "Author:\t" + author.name() + " <" + author.email() + ">"
// );
// // Show the commit date.
// console.log("Date:\t" + commit.date());
// // Give some space and show the message.
// console.log("\n " + commit.message());
// });
// // Start emitting events.
// history.start();
// });
// console.log("========Git============================");
// console.log(Git.version);
// console.log("========Git============================");
// // Git.Clone("https://github.com/christkv/node-git.git", "nodegit").then(
// // function (repository) {
// // console.log("===========repository=========================");
// // console.log(repository);
// // console.log("===========repository=========================");
// // }
// // );
// } catch (error) {
// console.log("============error========================");
// console.log(error);
// console.log("============error========================");
// }
// const { ctx } = this;
// // 更多配置,查看 https://www.npmjs.com/package/urllib
// const result = await ctx.curl(
// "https://api.github.com/repos/zhoujian521/showcase/contents/test.ts",
// {
// method: "PUT",
// // auth: "zhoujian521:xingchen52571413",
// headers: {
// "Content-Type": "application/x-www-form-urlencoded",
// Authorization: "token e5a7e1f2152992dc3856a97d1b1234806b08d9d9",
// },
// contentType: "json",
// data: {
// message: "commit from INSOMNIA",
// // bXkgbmV3IGZpbGUgY29udGVudHM=
// content: "",
// },
// dataType: "json",
// }
// );
// console.log("========result============================");
// console.log(result);
// console.log("========result============================");
// // 检查调用是否成功,如果调用失败会抛出异常
// // this.checkSuccess(result);
// const { data } = result;
// return data;
return "data";
}
async tarsServerHttp(url = "", options?: any) {
this.checkUrl(url);
const { ctx } = this;
const {
host = "", // 配置请求地址域名
method = "GET",
data = {},
dataType = "json",
headers = {},
timeout = 10 * 1000,
nestedQuerystring = false,
} = options || {};
const result = await ctx.curl(`${host}${url}`, {
method,
data,
dataType,
headers,
timeout,
nestedQuerystring,
});
this.checkSuccess(result);
return result;
}
}
|
dbd58a2689285929defbc7b7cad9b8154426d679
|
TypeScript
|
Blackbaud-JaminQuimby/skyux2
|
/src/modules/list/helpers.spec.ts
| 2.890625
| 3
|
import {
getData
} from './helpers';
describe('list helpers', () => {
it('gets data based on a standard selector', () => {
let data = {
myResult: 'something',
otherResult: 'nothing'
};
let result = getData(data, 'myResult');
expect(result).toBe('something');
});
it('shifts data appropriately when a selector is at the front', () => {
let data = {
myResult: 'something',
otherResult: 'nothing'
};
let result = getData(data, '.myResult');
expect(result).toBe('something');
});
it('returns properly when null data', () => {
/* tslint:disable */
let data: any = {
myResult: null,
otherResult: 'nothing'
};
/* tslint:enable */
let result = getData(data, 'myResult');
expect(result).toBeNull();
});
it('returns null when empty string selector defined', () => {
let data = {
myResult: 'something',
otherResult: 'nothing'
};
let result = getData(data, '');
expect(result).toBe(undefined);
});
});
|
0c74868dbc22acc17495b7d44a37f8545930572c
|
TypeScript
|
BenTels/Roundtrip
|
/roundtrip-client/src/app/click-listener.service.ts
| 2.609375
| 3
|
import { Injectable } from '@angular/core';
import { Observable, Observer, Subject } from 'rxjs';
import { AnonymousSubject } from 'rxjs/internal/Subject';
@Injectable({
providedIn: 'root'
})
export class ClickListenerService {
private subject: Subject<string> | null = null;
constructor() { }
public connect(url: string): Subject<string> {
if (!this.subject) {
this.subject = this.create(url);
console.log("Successfully connected: " + url);
}
return this.subject!;
}
private create(url: string): Subject<string> {
let ws: WebSocket = new WebSocket(url);
let observable: Observable<string> = new Observable((obs: Observer<string>) => {
ws.onmessage = (ev: MessageEvent<string>) => obs.next(ev.data);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
});
let observer: Observer<string> = {
next: (data: string) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(data);
}
},
error: (err: Error) => console.log(err),
complete: () => console.log('Complete')
};
return new AnonymousSubject<string>(observer, observable);
}
}
|
c539635e7e9f9955d0835a5432c34c7b4992a28d
|
TypeScript
|
ralonsodeniz/react-typescript-basic-maps-app
|
/src/models/Map/index.ts
| 2.703125
| 3
|
import { Mappable } from '../common';
export class Map {
private readonly googleMap: google.maps.Map;
constructor(
private mapElement: Element,
private mapOptions: google.maps.MapOptions,
) {
this.googleMap = new google.maps.Map<Element>(mapElement, mapOptions);
}
addMarker(source: Mappable): void {
const marker = new google.maps.Marker({
map: this.googleMap,
position: {
lat: source.location.lat,
lng: source.location.lng,
},
});
marker.addListener('click', () => {
const infoWindow = new google.maps.InfoWindow({
content: source.markerContent(),
});
infoWindow.open(this.googleMap, marker);
});
}
}
|
bbc603d51b693b8dbd6611d685aae2d53ddba9c0
|
TypeScript
|
ianstormtaylor/slate
|
/packages/slate/src/utils/get-default-insert-location.ts
| 3.046875
| 3
|
import { Editor, Location } from '../interfaces'
/**
* Get the default location to insert content into the editor.
* By default, use the selection as the target location. But if there is
* no selection, insert at the end of the document since that is such a
* common use case when inserting from a non-selected state.
*/
export const getDefaultInsertLocation = (editor: Editor): Location => {
if (editor.selection) {
return editor.selection
} else if (editor.children.length > 0) {
return Editor.end(editor, [])
} else {
return [0]
}
}
|
ee92156eb5d6ba6101f3c65f3ac6604d642297fe
|
TypeScript
|
braivs/iti_js_ts
|
/src/09_ref_mutab/09_01.test.ts
| 3.65625
| 4
|
function IncreaseAge(u: UserType) {
u.age++;
}
type UserType = {
name: string
age: number
address: {title: string}
}
test('reference type test', () => {
let user: UserType = {
name: 'Briws',
age: 34,
address: {
title: 'Querim'
}
}
IncreaseAge(user)
expect(user.age).toBe(35)
const superman = user
superman.age = 1000
expect(user.age).toBe(1000)
})
test('array reference test', () => {
let users = [
{
name: 'Briws',
age: 34,
address: {
title: 'Querim'
}
},
{
name: 'Dimich',
age: 32
}
]
let admins = users
admins.push({name: 'Bandyugan', age: 10})
expect(users[2]).toEqual({name: 'Bandyugan', age: 10})
})
test('value type test', () => {
let usersCount = 100;
let adminsCount = usersCount
// adminsCount = adminsCount + 1;
// Тоже самое что и:
// adminsCount = 101
adminsCount++;
expect(users[2]).toEqual({name: 'Bandyugan', age: 10})
})
test('reference type test 2', () => {
let address = {
title: 'Minsk'
}
let user: UserType = {
name: 'Briws',
age: 34,
address: address
}
let addr = user.address
let user2: UserType = {
name: 'Natasha',
age: 30,
address: address
}
address.title = 'Minsk City'
expect(user.address).toBe(user2.address)
expect(user.address.title).toBe('Minsk City')
})
test('reference type array test', () => {
let address = {
title: 'Minsk'
}
let user: UserType = {
name: 'Briws',
age: 34,
address: address
}
let user2: UserType = {
name: 'Natasha',
age: 30,
address: address
}
const users = [ user, user2, {name: 'Katya', age: 18, address: address}]
const admins = [user, user2]
admins[0].name = 'Dmitry'
address.title = 'Minsk City'
expect(users[0].name).toBe('Dmitry')
expect(user.name).toBe('Dmitry')
})
test('sort array test', () => {
const letters = ['c', 'd', 'a', 'z', 'e']
passportist(letters);
expect(letters).toEqual(['c', 'd', 'a', 'z', 'e'])
} );
function passportist(letters: any) {
const copy = [...letters].sort();
console.log(copy)
}
|
ec43c4462c28459f1962b6ba24f3c82036b86386
|
TypeScript
|
y2bd/magnum-dork
|
/src/api/search.types.ts
| 2.515625
| 3
|
export interface SearchResults {
results: SearchResult[];
limit: number;
offset: number;
total: number;
}
export interface SearchResult {
result: ResultEnum;
data: Data;
relationships: Relationship[];
}
export interface Data {
id: string;
type: DataType;
attributes: DataAttributes;
}
export interface DataAttributes {
title: Description;
altTitles: Description[];
description: Description;
isLocked: boolean;
links: Links;
originalLanguage: OriginalLanguage;
lastVolume: null | string;
lastChapter: string;
publicationDemographic: null | string;
status: Status;
year: null;
contentRating: ContentRating;
tags: Tag[];
createdAt: Date;
updatedAt: Date;
version: number;
}
export interface Description {
en: string;
}
export enum ContentRating {
Safe = "safe",
Suggestive = "suggestive",
}
export interface Links {
al: string;
ap: string;
kt: string;
mu: string;
nu?: string;
mal: string;
raw?: string;
engtl?: string;
bw?: string;
amz?: string;
cdj?: string;
ebj?: string;
dj?: string;
}
export enum OriginalLanguage {
Ja = "ja",
Ko = "ko",
}
export enum Status {
Ongoing = "ongoing",
}
export interface Tag {
id: string;
type: TagType;
attributes: TagAttributes;
}
export interface TagAttributes {
name: Description;
description: any[];
group: Group;
version: number;
}
export enum Group {
Content = "content",
Format = "format",
Genre = "genre",
Theme = "theme",
}
export enum TagType {
Tag = "tag",
}
export enum DataType {
Manga = "manga",
}
export interface Relationship {
id: string;
type: RelationshipType;
}
export enum RelationshipType {
Artist = "artist",
Author = "author",
CoverArt = "cover_art",
}
export enum ResultEnum {
Ok = "ok",
}
|
6bdc0b9e17f039fa05d57f5d104d0439ff30edd1
|
TypeScript
|
willingtonortiz/agro-demo
|
/src/app/services/coordinate-converter.service.ts
| 2.71875
| 3
|
import { Injectable } from '@angular/core';
import * as Leaflet from "leaflet";
@Injectable({
providedIn: 'root'
})
export class CoordinateConverterService {
constructor() { }
public coordinatesToLatLngBounds(coordinates: Array<Array<number>>): Leaflet.LatLngBounds {
let lonMin: number = coordinates[0][0];
let lonMax: number = coordinates[0][0];
let latMin: number = coordinates[0][1];
let latMax: number = coordinates[0][1];
coordinates.forEach((coordinate) => {
lonMax = Math.max(lonMax, coordinate[0]);
lonMin = Math.min(lonMin, coordinate[0]);
latMax = Math.max(latMax, coordinate[1]);
latMin = Math.min(latMin, coordinate[1]);
});
const southWest = Leaflet.latLng(latMax, lonMax);
const northEast = Leaflet.latLng(latMin, lonMin);
return Leaflet.latLngBounds(southWest, northEast);
}
public coordinatesToArrayLatLngExpression(coordinates: Array<Array<number>>): Array<Leaflet.LatLngExpression> {
let lCoordinates: Array<Leaflet.LatLngExpression> = new Array<Leaflet.LatLngExpression>();
coordinates.forEach(cnd => {
lCoordinates.push(Leaflet.latLng(cnd[1], cnd[0]));
});
return lCoordinates;
}
public coordinatesToArrayLatLng(coordinates): Array<Leaflet.LatLng> {
let lCoordinates: Array<Leaflet.LatLng> = new Array<Leaflet.LatLng>();
coordinates.forEach(cnd => {
lCoordinates.push(Leaflet.latLng(cnd[1], cnd[0]));
});
return lCoordinates;
}
}
|
c0a755e5c12a86b2570088a5b5f04bc09af2c782
|
TypeScript
|
yogevizhak/BerryForms
|
/client/angular/components/fieldTypes/fieldTypesRegistry.ts
| 2.578125
| 3
|
/// <reference path="../../../extensions/arrayExtensions.ts" />
/// <reference path="../../interfaces/components/fieldTypes/IFieldType.ts" />
/// <reference path="../../interfaces/components/fieldTypes/IFieldTypesRegistry.ts" />
var _global:any = this;
_global.Components = _global.Components || {};
_global.Components.FieldTypes = [];
module Components.FieldTypes {
'use strict';
export class FieldTypesRegistry implements IFieldTypesRegistry {
private RegisteredComponents:IFieldType[];
//@ngInject
constructor() {
this.RegisteredComponents = _global.Components.FieldTypes;
_global.Instances.FieldTypesRegistry = this;
}
public GetFieldType(fieldTypeName:string, useDefaultForNonExisting:boolean):IFieldType {
var findFunction:(ft:IFieldType) => boolean = function (ft:IFieldType):boolean {
return ft.FieldName === fieldTypeName;
};
var findFunctionDefault:(ft:IFieldType) => boolean = function (ft:IFieldType):boolean {
return ft.FieldName === 'Text';
};
var registeredType:IFieldType = this.RegisteredComponents.single(findFunction);
if (!registeredType && useDefaultForNonExisting) {
return this.RegisteredComponents.single(findFunctionDefault);
} else {
return registeredType;
}
}
}
}
|
a2ef2a65c949ed2643d884a390dc5ff9a44ff7d1
|
TypeScript
|
nitincp/supreme-octo-disco
|
/src/getRow.ts
| 2.859375
| 3
|
import { Column, Position, Cell, Range } from "./index";
export interface Row<T> {
cells: Cell<T>[];
outlineLevel?: number
}
export type Rows<T> = Row<T>[];
export interface RowsWithRange<T> {
rows: Rows<T>,
range: Range
}
export function getRow<T>(item: T, columns: Column<T>[], startAt: Position): RowsWithRange<T> {
let rowNum = startAt.row;
let colNum = startAt.column;
const cells = columns.map<Cell<T>>(col => ({ row: rowNum, column: colNum++, value: col.value(item) }));
const rows = [{ cells }];
const range: Range = { min: startAt, max: { row: rowNum, column: colNum - 1 } };
return { rows, range };
}
|
fff1bff759a5dcef22a83d7336e23d3eb0e33ee4
|
TypeScript
|
nielsjani/phaserrpg_typescript
|
/src/classes/util/ObjectAmountMap.ts
| 3.0625
| 3
|
export class ObjectAmountMap {
private oaMap:Map<any, number>= new Map();
constructor(private equalsFunction: any){}
set(key: any, value: number){
if(this.has(key)){
this.oaMap.set(this.getRealKey(key), value);
} else {
this.oaMap.set(key, value);
}
}
has(key: any){
return this.getRealKey(key) !== undefined;
}
get(key: any) {
let realKey = this.getRealKey(key);
if(realKey){
return this.oaMap.get(realKey);
}
return undefined;
}
private getRealKey(key: any) {
return Array.from(this.oaMap.keys()).filter(oaItem => this.equalsFunction(oaItem, key))[0];
}
getAll() {
return this.oaMap;
}
remove(item: any) {
this.oaMap.delete(this.getRealKey(item));
}
}
|
a01e06e2c30be53568f62e7ccfbcedcc7a70ac75
|
TypeScript
|
LazarPetrovic1/newstackbasic
|
/src/messages/messages.controller.ts
| 2.515625
| 3
|
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
import { Message } from 'src/entities/Message';
import { CreateMessageDTO } from './dto/create-message.dto';
import { MessagesService } from './messages.service';
@Controller('messages')
export class MessagesController {
constructor(private messagesService: MessagesService) {}
@Get("/from/:id")
async findAllOfUser(@Param("id") id: number) : Promise<Message[]> {
return await this.messagesService.findAllOfUser(id)
}
@Get("/to/:id")
async findAllToUser(@Param("id") id: number) : Promise<Message[]> {
return await this.messagesService.findAllToUser(id)
}
@Get(":id")
async findOne(@Param("id") id: number) : Promise<Message> {
return await this.messagesService.findOne(id)
}
@Post()
async create(@Body() createMessageDto: CreateMessageDTO) : Promise<Message> {
console.log("BARI", createMessageDto);
return await this.messagesService.create(createMessageDto)
}
@Delete(":id")
remove(@Param("id") id: number) : Promise<Message> {
return this.messagesService.remove(id)
}
@Put(":id")
async update(@Body() updateMessageDto: CreateMessageDTO, @Param("id") id: number) : Promise<Message> {
return await this.messagesService.update(id, updateMessageDto)
}
@Put("/status/:id")
async updateStatus(@Body() updateMessageDto: CreateMessageDTO, @Param("id") id : number) : Promise<Message> {
return await this.messagesService.updateStatus(id, updateMessageDto)
}
}
|
d4329e33b3c02d480ca5af7d78b2bc8f1eb9b515
|
TypeScript
|
marcosavalle/gifts-frontend
|
/src/features/provinces/store/provinces.reducer.ts
| 2.703125
| 3
|
import { Reducer } from 'redux';
import {
ProvincesState,
ProvincesActionTypes,
ProvincesActions,
} from '../models/provinces.model';
export const initialState: ProvincesState = {
loading: false,
data: [],
error: undefined,
isFetchCompleted: false,
};
const reducer: Reducer<ProvincesState> = (
state = initialState,
action: ProvincesActions
) => {
switch (action.type) {
case ProvincesActionTypes.FETCH_REQUEST: {
return { ...state, loading: true, isFetchCompleted: false };
}
case ProvincesActionTypes.FETCH_SUCCESS: {
return {
...state,
loading: false,
data: action.payload,
isFetchCompleted: true,
};
}
case ProvincesActionTypes.FETCH_ERROR: {
return {
...state,
loading: false,
error: action.payload,
isFetchCompleted: true,
};
}
default: {
return state;
}
}
};
export { reducer as provincesReducer };
|
c139ef9b88c151dfb47410723ece725852855666
|
TypeScript
|
gameforks/Incremental
|
/Technomancy/locations/sharks/marine.ts
| 2.59375
| 3
|
({
"unlocked": function () { return true; },
"go_again_text": "Dive",
"encounters": [
({
"condition": function () { return true; },
"types": [],
"weight": 1,
"title": "Deep Sea Casino",
"run_encounter": function casino () {
/* Use a special token for the table in case it gets closed/reopened before the interval clears. */
const TOKEN_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let table_token = "slots_";
for (let i = 0; i < 5; i++) {
table_token += TOKEN_CHARS.charAt(Math.floor(Math.random() * TOKEN_CHARS.length));
}
/* Define all our adventure data we need to keep track of. This lets us later use it without caring if it's in adventure data (it is). */
if (adventure_data["casino_tokens"] == undefined) {
adventure_data["casino_tokens"] = 0;
}
if (adventure_data["slots_less"] == undefined) {
adventure_data["slots_less"] = 0;
}
if (adventure_data["slots_time"] == undefined) {
adventure_data["slots_time"] = 1;
}
if (adventure_data["slots_reward"] == undefined) {
adventure_data["slots_reward"] = 1;
}
if (adventure_data["key_piece_1"] == undefined) {
adventure_data["key_piece_1"] = 0;
}
if (adventure_data["key_piece_2"] == undefined) {
adventure_data["key_piece_2"] = 0;
}
if (adventure_data["key_piece_3"] == undefined) {
adventure_data["key_piece_3"] = 0;
}
$("#character").addClass("hidden");
$("#events_content").html("Welcome to the Casino of Bad Slot Machines!<br />");
$("#events_content").append("You currently have <span id='casino_tokens'>0</span> casino tokens!<br />");
if (adventure_data["luck_key"] === undefined) {
$("#events_content").append("You currently have <span id='key1'>0</span> strange gold bits!<br />");
$("#events_content").append("You currently have <span id='key2'>0</span> odd gold bits!<br />");
$("#events_content").append("You currently have <span id='key3'>0</span> weird gold bits!<br />");
}
$("#events_content").append(
"<table id='" + table_token + "'>" +
"<tr>" +
"<td id='slot_0_0'>A</td>" +
"<td id='slot_0_1'>v</td>" +
"<td id='slot_0_2'>Q</td>" +
"</tr>" +
"<tr>" +
"<td id='slot_1_0'>S</td>" +
"<td id='slot_1_1'>l</td>" +
"<td id='slot_1_2'>v</td>" +
"</tr>" +
"<tr>" +
"<td id='slot_2_0'>R</td>" +
"<td id='slot_2_1'>s</td>" +
"<td id='slot_2_2'>N</td>" +
"</tr>" +
"</table><br />");
function token_updates() {
if (!$("#events").hasClass("hidden") && $("#" + table_token).length != 0) {
setTimeout(token_updates, 50);
$("#casino_tokens").html(format_num(adventure_data["casino_tokens"]));
$("#key1").html(format_num(adventure_data["key_piece_1"]));
$("#key2").html(format_num(adventure_data["key_piece_2"]));
$("#key3").html(format_num(adventure_data["key_piece_3"]));
if (adventure_data["luck_key"] === undefined && adventure_data["key_piece_1"] >= 5 && adventure_data["key_piece_2"] >= 5 && adventure_data["key_piece_3"] >= 1) {
$("#key_buy").removeClass("hidden");
}
}
}
token_updates();
/* Run our slot machine! */
let slot_strength = 0;
let chars = "ABCDEFabcdefVWXYwvxy$?!";
chars = chars.slice(adventure_data["slots_less"], chars.length);
if (adventure_data["slots_double"]) {
chars += "*$!?$!?$!?$!?$!?*"; /* one *, 5x $!?, then one * */
}
function slots() {
/* Move up all columns. Sometimes we'll skip one. So 70% chance of skipping a random column. */
let colskip = Math.random() > 0.7 ? Math.floor(Math.random() * 3) : -1;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j == colskip) continue;
let char = "";
if (i == 2) {
char = chars[Math.floor(Math.random() * chars.length)];
} else {
char = $("#" + table_token + " #slot_" + (i + 1).toString() + "_" + j.toString()).html();
}
$("#" + table_token + " #slot_" + i.toString() + "_" + j.toString()).html(char);
}
}
/* If events is hidden (they closed it) or we can't find the slot table, we're done. Clear it. */
if (!$("#events").hasClass("hidden") && $("#" + table_token).length != 0) {
slot_strength--;
if (slot_strength > 0) {
let time = 300 - (slot_strength * 6);
time /= adventure_data["slots_time"];
setTimeout(slots, time);
} else {
/* Slot machine finished, so total up results. */
if ($("#" + table_token + " #slot_1_0").html() == $("#" + table_token + " #slot_1_1").html() && $("#" + table_token + " #slot_1_0").html() == $("#" + table_token + " #slot_1_2").html()) { /* All 3 in the center row match. */
$("#slot_results").html("You win!");
adventure_data["casino_tokens"] += 5 * adventure_data["slots_reward"];
/* Check for special symbols and do what they do. */
if ($("#" + table_token + " #slot_1_0").html() == "$") {
$("#slot_results").append(" Jackpot! That's a lot of these tokens!");
adventure_data["casino_tokens"] += 95 * adventure_data["slots_reward"]; /* Total of 100 tokens/reward level*/
} else if ($("#" + table_token + " #slot_1_0").html() == "?") {
$("#slot_results").append(" Weird. Whats this symbol mean? Hey, you got some gold thing though!");
adventure_data["key_piece_1"]++;
adventure_data["casino_tokens"] += 45 * adventure_data["slots_reward"];
} else if ($("#" + table_token + " #slot_1_0").html() == "!") {
$("#slot_results").append(" You're really excited! Oh nice, that's a bit of gold!");
adventure_data["key_piece_2"]++;
adventure_data["casino_tokens"] += 45 * adventure_data["slots_reward"];
} else if ($("#" + table_token + " #slot_1_0").html() == "*") {
$("#slot_results").append(" Woah, that's a special character! And a shiny piece of something golden!");
adventure_data["key_piece_3"]++;
adventure_data["casino_tokens"] += 495 * adventure_data["slots_reward"];
}
/* Color the center row. Because looking nice is always good. */
$("#" + table_token + " #slot_1_0").html("<span style='color: yellow'>" + $("#" + table_token + " #slot_1_0").html() + "</span>");
$("#" + table_token + " #slot_1_1").html("<span style='color: yellow'>" + $("#" + table_token + " #slot_1_1").html() + "</span>");
$("#" + table_token + " #slot_1_2").html("<span style='color: yellow'>" + $("#" + table_token + " #slot_1_2").html() + "</span>");
} else if ($("#" + table_token + " #slot_1_0").html() == $("#" + table_token + " #slot_1_1").html() || $("#" + table_token + " #slot_1_1").html() == $("#" + table_token + " #slot_1_2").html()) {
$("#slot_results").html("You won! You get... a plastic coin? Come on!");
adventure_data["casino_tokens"] += adventure_data["slots_reward"];
} else {
$("#slot_results").html("You lose :(");
}
}
}
};
$("#events_content").append("<span class='clickable'>Play</span> the slot machine (1M money)<br />");
$("#events_content").append("<div id='slot_results'></div>");
$("#events_content span").last().click(function () {
if (resources["money"].amount >= 1000000 && slot_strength <= 0) {
resources["money"].amount -= 1000000
slot_strength = Math.round(Math.random() * 30) + 20;
slots();
}
});
if (adventure_data["slots_less"] < 17) { /* Arbitrary value less than 23. */
$("#events_content").append("<span class='clickable'>Improve</span> slot machine odds (" + format_num(adventure_data["slots_less"] + 1, false) + " tokens)<br />");
$("#events_content span").last().click(() => {
if (adventure_data["casino_tokens"] > adventure_data["slots_less"]) {
adventure_data["slots_less"]++;
adventure_data["casino_tokens"] -= adventure_data["slots_less"];
this.run_encounter();
}
});
} else if (adventure_data["slots_double"] == undefined) {
$("#events_content").append("<span class='clickable'>Improve</span> slot machine odds (50 tokens)<br />");
$("#events_content span").last().click(() => {
if (adventure_data["casino_tokens"] >= 50) {
adventure_data["slots_double"] = true;
adventure_data["casino_tokens"] -= 50;
this.run_encounter();
}
});
}
if (adventure_data["slots_time"] < 7) { /* Arbitrary value. */
$("#events_content").append("<span class='clickable'>Increase</span> slot machine speed (" + format_num(adventure_data["slots_time"], false) + " tokens)<br />");
$("#events_content span").last().click(() => {
if (adventure_data["casino_tokens"] >= adventure_data["slots_time"]) {
adventure_data["casino_tokens"] -= adventure_data["slots_time"];
adventure_data["slots_time"]++;
this.run_encounter();
}
});
}
if (adventure_data["slots_reward"] < 5) { /* Yet another arbitrary value. */
let cost = Math.pow(2, adventure_data["slots_reward"]) + adventure_data["slots_reward"];
$("#events_content").append("<span class='clickable'>Increase</span> slot machine reward (" + format_num(cost, false) + " tokens)<br />");
$("#events_content span").last().click(() => {
if (adventure_data["casino_tokens"] >= cost) {
adventure_data["casino_tokens"] -= cost;
adventure_data["slots_reward"]++;
this.run_encounter();
}
});
}
$("#events_content").append("<div id='key_buy' class='hidden'></div>");
$("#key_buy").append("Hmm, you have a lot of those golden bits. Maybe try to tinker with them and see what you canget<br/>");
$("#key_buy").append("<button class='fgc bgc_second'>Combine</button> the pieces<br/>");
$("#key_buy button").last().click(() => {
adventure_data["luck_key"] = true;
$("#events_content").html("You take some of the parts and manage to put them together into a nice golden key! Sweet, Iwonder what it goes to!");
$("#events_content").append(exit_button("Done"));
});
if (adventure_data["casino_tokens"] >= 25) { /* They have a bunch of tokens. */
$("#events_content").append("<table id='slot_prizes'><caption>Prize Wall</caption></table>");
$("#slot_prizes").append("<tr><th>Prize</td><th>Token Cost</td></tr>");
$("#slot_prizes").append("<tr><td class='clickable'>500 Steel</td><td>10</td></tr>");
$("#slot_prizes td.clickable").last().click(() => {
if (adventure_data["casino_tokens"] >= 10) {
adventure_data["casino_tokens"] -= 10;
resources["steel_beam"].amount += 500;
}
});
$("#slot_prizes").append("<tr><td class='clickable'>250 Fuel</td><td>10</td></tr>");
$("#slot_prizes td.clickable").last().click(() => {
if (adventure_data["casino_tokens"] >= 10) {
adventure_data["casino_tokens"] -= 10;
resources["fuel"].amount += 250;
}
});
if (resources["mithril"].amount >= 100) {
$("#slot_prizes").append("<tr><td class='clickable'>100 Mithril</td><td>25</td></tr>");
$("#slot_prizes td.clickable").last().click(() => {
if (adventure_data["casino_tokens"] >= 25) {
adventure_data["casino_tokens"] -= 25;
resources["mithril"].amount += 100;
}
});
}
$("#slot_prizes").append("<tr><td class='clickable'>1 Void</td><td>50</td></tr>");
$("#slot_prizes td.clickable").last().click(() => {
if (adventure_data["casino_tokens"] >= 50) {
adventure_data["casino_tokens"] -= 50;
resources["void"].amount += 1;
}
});
}
$("#events_content").append(exit_button("Leave") + " the casino.<br/>");
} /* End run_encounter*/
}),
({
"condition": function () { return event_flags["alchemist_ingredients"] != undefined && event_flags["alchemist_ingredients"]["core"] && Math.random() > 0.9; },
"types": ["noncombat"],
"weight": 1,
"title": "Gate",
"run_encounter": function () {
$("#events_content").html("Gate.<br/>The gate is.<br/>The gate is the world. Between worlds. Beyond. The gate. The gate. The gate. Gate. Gate.gate.gategategategate.<br /><span class='clickable'>Gate</span>");
$("#events_content > span").last().click(() => {
$("#events_content").html("You obtain it.<br /><span class='clickable' onclick='start_adventure()'>Yay!</span>");
adventure_data["alchemy_ingredients"]["Dimensional Core"]++;
});
},
}), /* Dimensional Core */
],
"connects_to": ["sharks/abandoned", "sharks/gate"],
"enter_cost": 7,
"leave_cost": 3,
"name": "Marine World",
})
|
2b1f864aff3f03b84d687948cdb84009ea58f7a2
|
TypeScript
|
felippeefreire/redis-gui
|
/renderer/core/services/ConnectionService.ts
| 2.515625
| 3
|
import {IConnection} from "../interfaces/IConnection";
const connections = [
{
id: '1',
name: 'example'
}
];
export class ConnectionService {
static list(): IConnection[] {
return connections;
}
static async delete(connection: IConnection): Promise<void> {
}
}
|
08b1fb5261ac05eff6630e1d23f1980cbbd30b7f
|
TypeScript
|
amyaim99/Casino-TypeScript
|
/ts/Deck.ts
| 3.21875
| 3
|
/// <reference path="Card.ts" />
class Deck{
cards:Card[] = []
constructor(){
for(let i=0; i<4; i++){
var suitArray: Suit[] =[Suit.CLUB, Suit.DIAMOND, Suit.HEART, Suit.SPADE]
for(let j=0; j<13;j++){
var rankArray: Rank[] = [Rank.ACE, Rank.TWO, Rank.THREE, Rank.FOUR, Rank.FIVE,
Rank.SIX, Rank.SEVEN, Rank.EIGHT, Rank.NINE, Rank.TEN, Rank.JACK, Rank.QUEEN,Rank.KING]
var card: Card = new Card(rankArray[j], suitArray[i])
this.cards.push(card)
}
}
for (let i: number = this.cards.length - 1; i >= 0; i--){
var randomIndex: number = Math.floor(Math.random() * (i + 1));
var itemAtIndex: Card = this.cards[randomIndex];
this.cards[randomIndex] = this.cards[i];
this.cards[i] = itemAtIndex;
}
}
}
|
4ffca07af8040a230bfa8e0d24407cb211959013
|
TypeScript
|
ZITOUNIMED/tuto-share-app
|
/src/app/shared/loading.actions.ts
| 2.5625
| 3
|
import {Action} from '@ngrx/store';
export const START_LOADING_ACTION_TYPE = 'START_LOADING_ACTION_TYPE';
export const STOP_LOADING_ACTION_TYPE = 'STOP_LOADING_ACTION_TYPE';
export type LoadingActions = StartLoadingAction | StopLoadingAction;
export class StartLoadingAction implements Action {
readonly type = START_LOADING_ACTION_TYPE;
constructor() {}
}
export class StopLoadingAction implements Action {
readonly type = STOP_LOADING_ACTION_TYPE;
constructor() {}
}
|
7eab2355aa7b4bb890032ab00f00063e8a831dbf
|
TypeScript
|
pruthvirajpatel/pruthvirajpatel.github.io
|
/src/app/form/form.component.ts
| 2.53125
| 3
|
import { Component } from '@angular/core';
import { Form } from './form';
import { List } from './list';
interface IShape {
area(): number;
}
interface EnumServiceItem {
id: number; label: string; key: any
}
interface EnumServiceItems extends Array<EnumServiceItem> { }
// Option A
var result: EnumServiceItem[] = [
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
];
@Component({
templateUrl: './form.component.html',
styleUrls: ['./form.css']
})
export class FormComponent implements IShape {
powers: Array<string>
list: Array<object>
userList: Array<EnumServiceItem>
submitted: boolean = false;
constructor(private length: number, private breadth: number) {
this.powers = ['Really Smart', 'Super Flexible','Super Hot', 'Weather Changer'];
this.list = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }];
this.length = 1;//'qwqw';
this.breadth = 1;
console.log(this.area());
this.userList = localStorage.getItem('list') ? JSON.parse(localStorage.getItem('list')):[{name:'sdsd'}];
}
area(): number {
return this.length * this.breadth;
}
model = new Form(18, 'Dr IQ', this.powers[0], 'Chuck Overstreet');
onSubmit() { this.submitted = true; }
newHero() {
this.model = new Form(42, '', '');
}
// TODO: Remove this when we're done
get diagnostic() { return JSON.stringify(this.model); }
}
|
fcac8dc05866e71a01ed11aeba3b7a755a34bf69
|
TypeScript
|
Abbondanzo/SubDom
|
/src/redirectProxy.ts
| 3.234375
| 3
|
interface RedirectProxyOptions {
baseUrl: string;
useSSL: boolean;
writeToFile: boolean;
initialProxies: Proxies;
onError?: ErrorCallback;
}
type Url = string;
export type Proxies = {
[alias: string]: Url;
};
type ErrorCallback = (error: any) => void;
export class RedirectProxy {
private readonly baseUrl: string;
private readonly useSSL: boolean;
private readonly fileName: string | null;
private readonly proxies: Proxies;
private readonly onError: ErrorCallback;
constructor(options: RedirectProxyOptions) {
this.baseUrl = options.baseUrl.toLowerCase().replace(/^https?:\/\//, "");
this.useSSL = options.useSSL;
this.fileName = options.writeToFile ? `${this.baseUrl}.config.json` : null;
this.proxies = options.initialProxies;
this.onError = options.onError || noop;
}
/**
* Given a full hostname with base URL, parse and return a redirect URL if one exists.
*
* @param host full host including base URL
*/
public getRedirect(host: string): string | null {
const subdomain = this.parseHostForAlias(host);
if (!subdomain) {
return null;
}
return this.proxies[subdomain] || null;
}
public setRedirect(alias: string, redirect: string) {
redirect = this.domainWithProtocol(redirect);
this.proxies[alias.toLowerCase()] = redirect;
this.updateFile();
}
public matchesBaseUrl(url: string): boolean {
return url === this.baseUrl;
}
public getBaseUrl(): string {
return this.useSSL ? `https://${this.baseUrl}` : `http://${this.baseUrl}`;
}
public hasAlias(alias: string): boolean {
return Boolean(this.proxies[alias]);
}
private parseHostForAlias(host: string): string | null {
const split = host.toLowerCase().split(this.baseUrl);
if (split.length !== 2 || split[1] !== "") {
return null;
}
const alias = split[0];
if (alias.endsWith(".")) {
return alias.slice(0, -1);
}
return alias;
}
private domainWithProtocol(domain: string): string {
if (!domain.match(/^https?:\/\//)) {
return `https://${domain}`;
} else {
return domain;
}
}
private updateFile() {
if (this.fileName === null) {
return;
}
this.onError("WRITING NOT IMPLEMENTED");
// TODO: Write to config
}
}
const noop = (_: any) => {};
|
eeacb69ceb5055beeb5dc9d16a142778baf3af4f
|
TypeScript
|
ninthworld/Phaseroids
|
/src/utils/Vec2.ts
| 3.6875
| 4
|
export class Vec2 {
public x: number;
public y: number;
constructor();
constructor(x: number, y: number);
constructor(x: number = 0, y: number = 0) {
this.x = x;
this.y = y;
}
public clone(): Vec2 {
return new Vec2(this.x, this.y);
}
public distanceTo(other: Vec2): number {
return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2));
}
}
|
17c22cff658a363f6b99aee3d64c1442728f7f9d
|
TypeScript
|
lifaon74/observables
|
/src/observables/distinct/distinct-value-observable/sync/functions.ts
| 2.625
| 3
|
import { IDistinctValueObservable } from './interfaces';
import {
DISTINCT_VALUE_OBSERVABLE_PRIVATE, IDistinctValueObservableInternal, IDistinctValueObservablePrivate
} from './privates';
import { ObservableEmitAll } from '../../../../core/observable/functions';
/** FUNCTIONS **/
export function DistinctValueObservableEmit<T>(instance: IDistinctValueObservable<T>, value: T): void {
const privates: IDistinctValueObservablePrivate<T> = (instance as IDistinctValueObservableInternal<T>)[DISTINCT_VALUE_OBSERVABLE_PRIVATE];
if (value !== privates.value) {
privates.value = value;
privates.count++;
ObservableEmitAll<T>(instance, value);
}
}
|
f3f1c81b84da7017acbee26a5890670b9452b360
|
TypeScript
|
simonzm7/adn-nodejs
|
/src/infraestructure/TRM/adapters/Handlers/Requests.ts
| 2.515625
| 3
|
import axios from 'axios';
import { BussinessExcp } from 'src/domain/Exceptions/BussinessExcp';
import { MethodType } from 'src/domain/Trm/port/Enums/MethodType';
export interface IRequest {
url: string;
method: MethodType;
headers: {};
data: string;
errorCode: string;
}
export class Requests {
private static Singleton: Requests;
public static Instance = () => {
if (!Requests.Singleton) {
Requests.Singleton = new Requests();
}
return Requests.Singleton;
};
public createRequest = async ({ url, method, headers, data, errorCode }: IRequest) => {
return axios({
method,
url,
headers,
data
})
.then((resp) => resp.data)
.catch(() => {
throw new BussinessExcp({ code: errorCode });
});
};
}
|
e46d2159f9153b89b9de58c637a34ff7e0bcc4e0
|
TypeScript
|
emreturgutce/clothing-store
|
/src/utils/format-error.ts
| 2.578125
| 3
|
import { GraphQLError, GraphQLFormattedError } from 'graphql';
import { NODE_ENV } from '../config';
export const formatError = (
err: GraphQLError,
): GraphQLFormattedError<Record<string, any>> => {
if (err.message.match(/validation error/i)) {
const errors: string[] = [];
if (err.extensions) {
for (const { constraints } of err.extensions!.exception
.validationErrors) {
const error = Object.values(constraints).toString();
errors.push(error);
}
} else {
errors.push(err.message);
}
return { message: errors.toString() };
}
if (err.message.match(/Could not find any entity of type "Address"/gi)) {
return { message: 'Could not find any entity of type "Address"' };
}
if (err.message.match(/Duplicate key value violates unique constraint/gi)) {
return { message: 'Field already in use' };
}
return {
message:
NODE_ENV === 'development' ? err.message : 'Something went wrong!',
};
};
|
b92f37639fc16ebf382b7ae7ed76a816882f84ce
|
TypeScript
|
webhintio/hint
|
/packages/formatter-stylish/src/formatter.ts
| 2.65625
| 3
|
/**
* @fileoverview The stylish formatter, it outputs the results in a table format with different colors.
*
* This formatter is based on [eslint stylish formatter](https://github.com/eslint/eslint/blob/master/lib/formatters/stylish.js)
*/
/*
* ------------------------------------------------------------------------------
* Requirements
* ------------------------------------------------------------------------------
*/
import * as chalk from 'chalk';
import forEach = require('lodash/forEach');
import groupBy = require('lodash/groupBy');
import reduce = require('lodash/reduce');
import sortBy = require('lodash/sortBy');
import * as table from 'text-table';
const stripAnsi = require('strip-ansi');
import { logger, severityToColor, occurencesToColor } from '@hint/utils';
import { cutString } from '@hint/utils-string';
import { writeFileAsync } from '@hint/utils-fs';
import { debug as d } from '@hint/utils-debug';
import { FormatterOptions, IFormatter } from 'hint';
import { Problem, Severity } from '@hint/utils-types';
import { getMessage, MessageName } from './i18n.import';
const _ = {
forEach,
groupBy,
reduce,
sortBy
};
const debug = d(__filename);
const printPosition = (position: number, text: string) => {
if (position === -1) {
return '';
}
return `${text} ${position}`;
};
/*
* ------------------------------------------------------------------------------
* Formatter
* ------------------------------------------------------------------------------
*/
export default class StylishFormatter implements IFormatter {
/** Format the problems grouped by `resource` name and sorted by line and column number */
public async format(messages: Problem[], options: FormatterOptions = {}) {
const language: string = options.language!;
debug('Formatting results');
if (messages.length === 0) {
return;
}
const resources: _.Dictionary<Problem[]> = _.groupBy(messages, 'resource');
const totals = {
[Severity.error.toString()]: 0,
[Severity.warning.toString()]: 0,
[Severity.information.toString()]: 0,
[Severity.hint.toString()]: 0
};
let result = _.reduce(resources, (total: string, msgs: Problem[], resource: string) => {
const partials = {
[Severity.error.toString()]: 0,
[Severity.warning.toString()]: 0,
[Severity.information.toString()]: 0,
[Severity.hint.toString()]: 0
};
const sortedMessages: Problem[] = _.sortBy(msgs, ['location.line', 'location.column']);
const tableData: string[][] = [];
let hasPosition: boolean = false;
let partialResult = `${chalk.cyan(cutString(resource, 80))}\n`;
_.forEach(sortedMessages, (msg: Problem) => {
const color = severityToColor(msg.severity);
const severity = color(getMessage(`capitalized${Severity[msg.severity].toString()}` as MessageName, language));
partials[msg.severity.toString()]++;
const line: string = printPosition(msg.location.line, getMessage('line', language));
const column: string = printPosition(msg.location.column, getMessage('col', language));
if (line) {
hasPosition = true;
}
tableData.push([line, column, severity, msg.message, msg.hintId]);
});
/*
* If no message in this resource has a position, then we remove the
* position components from the array to avoid unnecessary white spaces
*/
if (!hasPosition) {
tableData.forEach((row: string[]) => {
row.splice(0, 2);
});
}
partialResult += `${table(tableData)}\n`;
const color = occurencesToColor(partials);
totals[Severity.error] += partials[Severity.error];
totals[Severity.warning] += partials[Severity.warning];
totals[Severity.information] += partials[Severity.information];
totals[Severity.hint] += partials[Severity.hint];
const foundMessage = getMessage('partialFound', language, [
partials[Severity.error].toString(),
partials[Severity.error] === 1 ? getMessage('error', language) : getMessage('errors', language),
partials[Severity.warning].toString(),
partials[Severity.warning] === 1 ? getMessage('warning', language) : getMessage('warnings', language),
partials[Severity.hint].toString(),
partials[Severity.hint] === 1 ? getMessage('hint', language) : getMessage('hints', language),
partials[Severity.information].toString(),
partials[Severity.information] === 1 ? getMessage('information', language) : getMessage('informations', language)
]);
partialResult += color.bold(`× ${foundMessage}`);
partialResult += '\n\n';
return total + partialResult;
}, '');
const color = occurencesToColor(totals);
const foundTotalMessage = getMessage('totalFound', language, [
totals[Severity.error].toString(),
totals[Severity.error] === 1 ? getMessage('error', language) : getMessage('errors', language),
totals[Severity.warning].toString(),
totals[Severity.warning] === 1 ? getMessage('warning', language) : getMessage('warnings', language),
totals[Severity.hint].toString(),
totals[Severity.hint] === 1 ? getMessage('hint', language) : getMessage('hints', language),
totals[Severity.information].toString(),
totals[Severity.information] === 1 ? getMessage('information', language) : getMessage('informations', language)
]);
result += color.bold(`× ${foundTotalMessage}`);
if (!options.output) {
logger.log(result);
return;
}
await writeFileAsync(options.output, stripAnsi(result));
}
}
|
b3231a7c3957cd627887cfe49f6486f13f78861d
|
TypeScript
|
mjavadalj/NestGrpcMicroservices
|
/user/src/user.repository.ts
| 2.671875
| 3
|
import { EntityRepository, Repository } from 'typeorm';
import { AuthCredential } from './auth/dto/authCredential.dto';
import { CreateUserDto } from './dto/createUser.dto';
import { User } from './user.entity';
import * as bcrypt from 'bcrypt';
@EntityRepository(User)
export class UserRepository extends Repository<User> {
private async hashPassword(password: string, salt: string): Promise<string> {
return bcrypt.hash(password, salt);
}
async addUser(createUserDto: CreateUserDto): Promise<User> {
const { firstName, lastName, username, type, password } = createUserDto;
const user = new User();
user.firstName = firstName;
user.lastName = lastName;
user.username = username;
user.type = type;
user.comments = ['null'];
user.salt = await bcrypt.genSalt();
user.password = await this.hashPassword(password, user.salt);
await user.save();
return user;
}
async login(authCredential: AuthCredential): Promise<User> {
const { username, password } = authCredential;
const user = await this.findOne({ username });
if (user && (await user.validatePassword(password))) {
return user;
}
}
}
|
bfdfef28ca67fb3fd7ed1538bc627906c27c90f3
|
TypeScript
|
aca-js-angular/shop
|
/shop/src/app/validators/adress.validator.ts
| 2.65625
| 3
|
import { FormControl, ValidationErrors, ValidatorFn, AbstractControl } from '@angular/forms';
export function _adress(control: AbstractControl): ValidationErrors | null {
const source = control.value
const number = new RegExp(/\b\d\b/)
const char = new RegExp(/[A-Za-z]/)
if(char.test(source) && number.test(source)){
return null
}else{
return {_adress: {message: 'Adress must contain at least "street" and "house-index"'}}
}
}
|
d8dd81dd9f9e4e9832c87cbf3c51c430179e2697
|
TypeScript
|
amidos2006/BAMLike
|
/src/SoundManager.ts
| 3
| 3
|
class SoundManager{
static MAX_MUSIC:number=0;
static MUSIC_VOLUME:number = 0.2;
static SOUND_VOLUME:number = 0.3;
sound:boolean;
music:boolean;
game:Phaser.Game;
currentMusicIndex:number;
currentMusic:Phaser.Sound;
currentSounds:Phaser.Sound[];
constructor(game:Phaser.Game){
this.sound = true;
this.music = true;
this.game = game;
this.currentSounds = [];
this.currentMusicIndex = this.game.rnd.integerInRange(0, SoundManager.MAX_MUSIC - 1);
this.currentMusic = null;
}
playMusic(index:number, position:number = 0):void{
if(this.currentMusic == null || this.currentMusicIndex != index){
this.stopMusic();
this.currentMusicIndex = index;
this.currentMusic = this.game.add.audio("music" + this.currentMusicIndex);
this.currentMusic.play("", position, SoundManager.MUSIC_VOLUME);
}
}
stopMusic():void{
if(this.currentMusic != null){
this.currentMusic.stop();
this.currentMusic.destroy();
this.currentMusic = null;
}
}
playSound(key:string):void{
if(this.sound){
this.currentSounds.push(this.game.add.audio(key));
this.currentSounds[this.currentSounds.length - 1].play("", 0, SoundManager.SOUND_VOLUME);
}
}
playCorrectTrack():void{
if(SoundManager.MAX_MUSIC > 0 && (this.currentMusic == null ||
(!this.currentMusic.isPlaying && this.currentMusic.currentTime > 10))){
this.playMusic((this.currentMusicIndex +
this.game.rnd.integerInRange(1, SoundManager.MAX_MUSIC - 1)) % SoundManager.MAX_MUSIC);
}
}
update():void{
if(!this.music){
this.stopMusic();
}
else{
this.playCorrectTrack();
}
for(let i:number=0; i<this.currentSounds.length; i++){
if(!this.currentSounds[i].isPlaying){
this.currentSounds[i].destroy();
this.currentSounds.splice(i, 1);
i--;
}
}
}
}
|
cf3616be8b12ede4911da60352d5ae0e60fad121
|
TypeScript
|
jcgurango/denim-lemonade
|
/packages/denim-forms/forms/utils/useScreenSize.native.ts
| 2.6875
| 3
|
import { useEffect, useState } from 'react';
import { Dimensions, ScaledSize } from 'react-native';
const useScreenSize = () => {
const [screenData, setScreenData] = useState<{ width: number, height: number }>(() => {
const { width, height } = Dimensions.get('window');
return { width, height };
});
useEffect(() => {
const onChange = (result: { window: ScaledSize, screen: ScaledSize }) => {
setScreenData(result.window);
};
Dimensions.addEventListener('change', onChange);
return () => {
Dimensions.removeEventListener('change', onChange);
};
});
return screenData;
};
export default useScreenSize;
|
7fa306f7031dd16dd9a08415f2602bea9f7f1ed7
|
TypeScript
|
liangchunn/automata
|
/src/internal/RegExp/applySRule.ts
| 3.265625
| 3
|
import { difference } from 'lodash'
import {
AutomatonDescriptor,
ApplySType,
RegExpStep,
AutomatonSymbol,
} from '../../types'
/**
* Applies the S rule by removing loop states and merging them to the outgoing transitions of a particular state
* @param automaton
*/
export function applySRule(
automaton: Readonly<AutomatonDescriptor>
): ApplySType {
// gets all transitions with loops
const transitionsWithLoops = automaton.transitions.filter(
transition => transition.from === transition.to
)
if (!transitionsWithLoops.length) {
return {
automaton,
kind: RegExpStep.NO_OP,
}
}
// gets the negated set of the automaton's transitions with the transitions with loops
let transitionsWithoutLoops = difference(
automaton.transitions,
transitionsWithLoops
)
const mergedTransitions: {
from: string
to: string
alphabet: string
}[] = []
for (const transition of transitionsWithLoops) {
const state = transition.from
const kleeneStarredAlphabet =
transition.alphabet.length > 1
? `(${transition.alphabet})${AutomatonSymbol.KLEENE_STAR}`
: `${transition.alphabet}${AutomatonSymbol.KLEENE_STAR}`
// get all the outgoing transitions of a state
const outgoingTransitions = transitionsWithoutLoops.filter(
transition => transition.from === state
)
// merge the loop transition with the outgoing transitions of the given state
for (const o of outgoingTransitions) {
mergedTransitions.push({
from: o.from,
to: o.to,
alphabet: `${kleeneStarredAlphabet}${o.alphabet}`,
})
transitionsWithoutLoops = difference(transitionsWithoutLoops, [o])
}
}
return {
automaton: {
...automaton,
transitions: [...transitionsWithoutLoops, ...mergedTransitions],
},
kind: RegExpStep.S,
transitions: transitionsWithLoops,
}
}
|
ed8ec509aaf2f737c7735bfa2306e046ff05c9c6
|
TypeScript
|
gevartrix/cai-chatbot-webpart
|
/src/webparts/cai-chatbot/chatbotWebpartProps.ts
| 2.859375
| 3
|
/**
* Web part's core options for the configuration's panel.
* It needs to be populated by the credentials found under the appropriate channel from the chatbot repository's "Connect" tab.
*
* @interface ChatbotWebPartOptions
* @property channel - Selected connection channel for a CAI chatbot ("Webchat" or "SAP CAI Web Client").
* @property channelId - Chatbot's channel ID.
* @property token - Chatbot's authentication token.
* @property expanderPreferences - Chatbot's expander preferences token (available only for the "SAP CAI Web Client" channel option.
*/
export interface ChatbotWebPartOptions {
channel: string;
url: string;
channelId: string;
token: string;
expanderPreferences: string;
}
|
f2b9c5d85b2f4d71289e7371eecb680fe19759c7
|
TypeScript
|
dynamic-packages/core
|
/packages/core-types/src/common/index.ts
| 2.734375
| 3
|
import { EventEmitter } from 'events';
export interface IBase extends EventEmitter {
toString(): string;
}
export interface IKeyString {
[key: string]: string;
[key: number]: string;
}
export interface IKeyValue {
[key: string]: any;
[key: number]: any;
}
export interface IFlag extends IBase {
getBitMask(): number;
getFlag(flag: number): boolean;
resetFlags(): void;
setFlag(flag: number, value: boolean): void;
}
|
4f6b756958a80532024df67966c1a359daccd556
|
TypeScript
|
barryblando/all-about-typescript
|
/functional-programming/Currying.ts
| 4
| 4
|
// https://medium.com/javascript-scene/curry-and-function-composition-2c208d774983
// Currying
function curry(func: (...args: number[]) => number) {
return function curried(...args: any[]) {
// sum(a, b, c). Three arguments, so func.length = 3, PS .length is a built-in property for function that return the # of parameters
if (args.length >= func.length) {
// Invoke func, if passed args count is the same as the original function has in its definition (func.length) or longer, then just pass and call to it.
return func.apply({}, [...args]);
} else {
// Get a partial: otherwise, func is not called yet. Instead, another wrapper pass is returned, that will re-apply curried providing previous arguments together with the new ones. Then on a new call, again, we’ll get either a new partial (if not enough arguments) or, finally, the result.
return function pass(...args2: number[]) {
return curried.apply({}, [...args, ...args2]);
// return curried.apply(this, args.concat(args2));
}
}
};
}
function sum(a: number, b: number, c: number) {
this // ?
return a + b + c;
}
// Partial Apply
let curriedSum: (...args: number[]) => any = curry(sum);
// still callable normally
curriedSum(1, 2, 3); // ?
// get the partial with curried(1) and call it with 2 other arguments
curriedSum(1)(2,3); // ?
// full curried form
curriedSum(1)(2)(3); // ?
|
898b05a57cfde2af7fb37cddd9b1c174d77a468b
|
TypeScript
|
hugsmidjan/qj
|
/src/dom/htmlLang.ts
| 3.53125
| 4
|
import closestParent from '../select/closestParent';
/**
* Finds and returns the language of an element
* – traversing up the DOM tree looking for langauge attributes.
*
* @param elm Target element - defaults to <html/>
* @param returnFull `true` returns the full language value – not just the two-character shorthand.
*
* Usage:
* ```js
* htmlLang(elm); // returns the language of elm.
* htmlLang(elm, true); // returns full language code of elm. e.g. "en-uk"
* htmlLang(); // returns the document language.
* htmlLang(true); // returns full document language code. e.g. "en-uk"
* ```
*/
function htmlLang(returnFull?: boolean): string | undefined;
function htmlLang(elm?: Node | null, returnFull?: boolean): string | undefined;
function htmlLang(elm?: Node | null | boolean, returnFull?: boolean): string | undefined {
if (typeof elm === 'boolean') {
returnFull = elm;
elm = document.documentElement;
} else if (arguments.length === 0) {
elm = document.documentElement;
}
const langElm = elm && closestParent('[lang]', elm);
const lang = langElm && (langElm as HTMLElement).lang;
return lang ? (!returnFull ? lang.substr(0, 2) : lang).toLowerCase() : undefined;
}
export default htmlLang;
|
4d195e7a4ebb162f6bae8848fb4413ded54b0cf9
|
TypeScript
|
Zhongy1/smack
|
/string-manipulators/string-manipulator-3.ts
| 3.390625
| 3
|
import { StringManipulator } from "./string-manipulator";
export class StringManipulator3 extends StringManipulator {
private tempParam1: string;
private tempParam2: number;
private nums:string = "0123456789";
constructor() {
super();
this.author = 'Jaden';
}
private DARE(str: string): string {
var txt = str;
txt.replace(/420/g, " ");
return txt;
}
private emphasize (str:string):string {
return str.replace("cow", "COW");
}
private tempHelperMethod(str: string): string {
return str;
}
public manipulateString(str: string): string {
let someVariable = this.DARE(str);
someVariable = this.emphasize(someVariable);
someVariable = someVariable.concat(" :)");
return someVariable;
}
}
|
a0fd0bae0a25dda14e1cd2b70ad34c934080dc0a
|
TypeScript
|
australis-technica/tiny-crud-controller
|
/packages/crud-controller/src/crud-controller.ts
| 2.765625
| 3
|
import { RequestHandler } from "express";
import fromBody from "./from-body";
import fromParams from "./from-params";
import { Store } from "./types";
import fromAny from "./from-any";
/** */
const noFilter: (id: any, data: any | any[]) => any = (...x) => x;
/**
* TODO: paged
*/
export default function CrudController<TStore extends Store>(store: TStore) {
//
/**
* READ/GET/LIST
*/
const find = (payload = fromParams) => {
payload = payload || fromAny;
/** */
return (transform = noFilter): RequestHandler => {
transform = transform || noFilter;
/** */
return async (req, res, next) => {
try {
const [id] = payload(req, res);
let ret: any;
if (id) {
ret = await store.findOne(id)
} else {
ret = await store.findMany()
}
return res.json(transform(id, ret));
} catch (error) {
return next(error);
}
};
};
};
/**
* DELETE/REMOVE
*/
const remove = (payload = fromAny) => {
payload = payload || fromAny;
return (transform = noFilter): RequestHandler => {
transform = transform || noFilter;
return async (req, res, next) => {
try {
const [id] = payload(req, res);
const ret = await store.remove(id);
return res.json(transform(id, ret));
} catch (error) {
return next(error);
}
};
};
};
/**
* Create, Add, Insert , NEW , PUT
*/
const add = (payload = fromBody) => {
payload = payload || fromBody;
/** */
return (transform = noFilter): RequestHandler => {
transform = transform || noFilter;
/** */
return async (req, res, next) => {
try {
const [id, data] = payload(req, res);
await store.add(id, data);
const ret = await store.findOne(id);
return res.json(transform(id, ret));
} catch (error) {
return next(error);
}
};
};
};
/**
* SET, Modify, update, POST
*/
const update = (payload = fromBody) => {
payload = payload || fromBody;
/** */
return (transform = noFilter): RequestHandler => {
transform = transform || noFilter;
/** */
return async (req, res, next) => {
try {
const [id, data] = payload(req, res);
await store.update(id, data);
const ret = await store.findOne(id);
return res.json(transform(id, ret));
} catch (error) {
return next(error);
}
};
};
};
return {
add,
find,
remove,
update,
};
}
|
eacb19b57bc2155d14aa5fa73d7ac8a52d31fcd5
|
TypeScript
|
anthowm/graphqlpetapi-frontend
|
/src/app/shared/modules/validators/mimetype-validator.ts
| 2.765625
| 3
|
import { FormControl, Validators } from '@angular/forms';
export class FileTypeValidator implements Validators {
static validateMimeType(c: FormControl): { [key: string]: any } {
const files = c.value._files;
if (c.value && files.length > 0) {
return FileTypeValidator.checkExtension(c);
} else {
return null;
}
}
private static checkExtension(c: FormControl) {
const files = c.value._files;
const isValidMimeType = files.some(element => {
const valToLower = element.name.toLowerCase();
const regex = new RegExp('(.*?)\.(jpg|png|jpeg)$');
const regexTest = regex.test(valToLower);
return regexTest === false;
});
return isValidMimeType ? { 'notSupportedFileType': true } : null;
}
}
|
a32723d736c7c71139c37f0b6a234b597e5cf3bf
|
TypeScript
|
Zdend/movie-feed
|
/src/shared/theme.ts
| 2.5625
| 3
|
import { generate } from '@ant-design/colors';
export const COLORS = {
PRIMARY: generate('#09f'),
SUCCESS: generate('#4CAF50'),
ERROR: generate('#F44336'),
WARNING: generate('#FF9800'),
INFO: generate('#2196F3'),
GREY: generate('#a5adb7'),
DARK: generate('#414141')
};
export const GRADIENTS = {
PRIMARY: 'linear-gradient(to bottom, #09f 0, #06f 100%)',
DARK: 'linear-gradient(to bottom, #444 0, #333 100%)'
};
export const SHADES = {
BLACK: '#000',
WHITE: '#fff'
};
export const SHADOWS = {
BOTTOM_MEDIUM: '0 2px 10px 0 rgba(0,0,0,0.5)'
};
export const BASE_UNIT = 4;
export const REM = BASE_UNIT * 4;
export const BORDER_RADIUS_MEDIUM = BASE_UNIT;
export enum ColorType {
PRIMARY = 'PRIMARY',
ACCENT = 'ACCENT',
SUCCESS = 'SUCCESS',
ERROR = 'ERROR',
INFO = 'INFO'
}
export enum SizeType {
REGULAR = 'REGULAR',
SMALL = 'SMALL'
}
export enum BREAKPOINT {
xs = '575px',
sm = '576px',
md = '768px',
lg = '992px',
xl = '1200px',
xxl = '1600px'
}
type BreakpointKeys = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
type BreakpointWidth = {
[key in BreakpointKeys]: number;
};
export const BREAKPOINT_WIDTH: BreakpointWidth = Object.entries(BREAKPOINT).reduce(
(result, [key, value]) => ({
...result,
[key]: +value.replace('px', '')
}),
{}
) as BreakpointWidth;
|
428225a584ab7a060e5cc36e1c04c140553a3c18
|
TypeScript
|
JoeshuTT/v-shop
|
/src/model/index.ts
| 2.8125
| 3
|
/**
* 生成昵称
*/
export function fakeNickName(options: Recordable) {
const { type } = options;
if (type === 'mobile') {
return `用户${options.mobile.slice(-4)}`;
}
return `用户${String(new Date().getMonth() + 1).padStart(2, '0')}-${String(new Date().getDate()).padStart(2, '0')}`;
}
|
076e1bb517d5582906176554778bd64f4e4627e3
|
TypeScript
|
Vuinfang/ToDoListBackEnd
|
/src/users/user.entity.ts
| 2.671875
| 3
|
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
} from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import { IsEmail, IsNotEmpty, IsNumber, IsString, Min } from 'class-validator';
@Entity()
export class User {
@ApiProperty({
required: false,
description: 'User ID',
})
@IsNumber()
@PrimaryGeneratedColumn()
u_id: number;
@ApiProperty({
description: 'Email',
})
@IsEmail()
@IsNotEmpty({ message: 'email cannot be empty' })
@IsString({ message: 'the value must be a string' })
@Column({ comment: 'Email', length: 130, unique: true })
email: string;
@IsNotEmpty({ message: 'password cannot be empty' })
@ApiProperty({
description: 'Password',
})
@Column()
password: string;
// @ApiProperty({
// required: false,
// description: 'Mobile Phone',
// })
// @Column({ comment: 'Mobile', length: 30, unique: true })
// mobile: string;
@ApiProperty({
required: false,
description: 'Avatar',
})
@Column({ default: null })
avatar: string;
// @ApiProperty({
// required: false,
// description: 'FullName',
// })
// @Column({ comment: 'fullName', length: 130, default: null })
// fullName: string;
// @Column({ default: null })
// salt: string;
// @Column({ default: false })
// is_deleted: boolean;
@ApiProperty({
required: false,
})
@CreateDateColumn()
created?: Date;
@ApiProperty({
required: false,
})
@UpdateDateColumn()
updated?: Date;
//-------------------------------------------
@ApiProperty({
required: true,
description: 'username',
})
@Column({ comment: 'username', length: 130, unique: false })
@IsNotEmpty({ message: 'username cannot be empty' })
username: string;
}
export class LoginDTO {
@ApiProperty({ description: 'Email', example: 'user1@gmail.com' })
@IsNotEmpty({ message: 'Email cannot be empty' })
readonly email: string;
@ApiProperty({ description: 'Password', example: 'Aa123456' })
@IsNotEmpty({ message: 'Password cannot be empty' })
readonly password: string;
}
export class userResponseDTO {
@ApiProperty()
readonly user: User;
@ApiProperty({ description: 'JWT token' })
readonly token: string;
}
|
382936659bff7dc870f8207e5cf5873d8de95620
|
TypeScript
|
thomasbroderick/AngularFilmCRUD
|
/src/app/film/film.component.ts
| 2.53125
| 3
|
import { Actor } from './../models/actor';
import { Film } from './../models/film';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-film',
templateUrl: './film.component.html',
styleUrls: ['./film.component.css']
})
export class FilmComponent implements OnInit {
selectedFilm = null;
newFilm: Film = new Film();
editFilm = null;
selectedActor = null;
newActor: Actor = new Actor();
addingToFilm = false;
films = [
new Film(
1,
'ACADEMY DINOSAUR',
'A Epic Drama of a Feminist And a Mad Scientist who must Battle a Teacher in The Canadian Rockies',
1993,
0.99,
86,
20.99,
'PG',
'Japanese',
[new Actor(1, 'Penelope', 'Guiness'), new Actor(10, 'Christian', 'Gable')]
)
];
actors = [new Actor(1, 'James', 'Bond'), new Actor(2, 'Austin', 'Powers')];
displayFilm(film) {
this.selectedFilm = film;
}
addFilm() {
this.newFilm.id = this.generateId();
this.films.push(this.newFilm);
this.newFilm = new Film();
}
setEditFilm() {
console.log(this.selectedFilm);
this.editFilm = Object.assign({}, this.selectedFilm);
console.log(this.editFilm);
}
generateId() {
return this.films[this.films.length - 1].id + 1;
}
generateActorId() {
return this.actors[this.actors.length - 1].id + 1;
}
updateFilm(film) {
const id = film.id - 1;
this.films[id].title = film.title;
this.films[id].description = film.description;
this.films[id].releaseYear = film.releaseYear;
this.films[id].rentalRate = film.rentalRate;
this.films[id].length = film.length;
this.films[id].replacementCost = film.replacementCost;
this.films[id].rating = film.rating;
this.films[id].language = film.language;
this.editFilm = null;
}
deleteFilm() {
const id = this.selectedFilm.id - 1;
this.films.splice(id, 1);
this.selectedFilm = null;
}
displayActor(actor) {
this.selectedActor = actor;
}
addActor() {
this.newActor.id = this.generateActorId();
this.actors.push(this.newActor);
this.newActor = new Actor();
}
deleteActor() {
const id = this.selectedActor.id - 1;
this.actors.splice(id, 1);
this.selectedActor = null;
}
nextFilmLoc() {
return this.selectedActor.films.length;
}
addActorToFilm(actor, film) {
film.actors.push(actor);
this.addingToFilm = false;
}
constructor() {}
ngOnInit() {}
}
|
64af38dae7fcd92c04e899b3ed5b25d55cb8cda7
|
TypeScript
|
alpirres/LectorQrv2
|
/src/app/services/ui.service.ts
| 2.71875
| 3
|
import { Injectable } from '@angular/core';
import { AlertController, LoadingController, ModalController, ToastController } from '@ionic/angular';
@Injectable({
providedIn: 'root'
})
export class UiService {
miLoading: any;
miToast: any;
constructor(public loading: LoadingController,
public modal: ModalController,
public toast: ToastController,
public alertController: AlertController) { }
/**
* Funcion que muetra un loading mietras se ejecuta algo internamente
* @param msg string opcional que se puede añadir al loading
*/
async showLoading(msg?: string) {
if (this.miLoading) {
console.log("Ya hay un loading activo");
return;
}
this.miLoading = await this.loading.create({
message: msg ? msg : ''
});
await this.miLoading.present();
}
/**
* Funcion que cierra el loading
*/
public hideLoad() {
this.miLoading = null;
this.loading.dismiss();
}
/**
* Funcion que muestra el toast
* @param msg string con el mensaje a mostrar
* @param dur numero con la duracion para ocultarse
* @param col string color
*/
async presentToast(msg: string, dur: number = 2000, col: string = "danger"): Promise<void> {
if (this.miToast) {
this.toast.dismiss();
}
this.miToast = await this.toast.create({
message: msg,
duration: dur,
color: col,
translucent: true,
position: "bottom",
buttons: [
{
icon: 'close',
role: 'cancel',
handler: () => {
this.hideToast();
}
}
]
});
this.miToast.present();
}
/**
* Funcion que quita el toast
*/
public hideToast() {
this.miToast = null;
this.toast.dismiss();
}
/**
* Funcion que muestra un alert con opciones
* @param header string con el nombre del titulo
* @param message string con el mensaje
* @param opcionSi sting para la opcion si
* @param opcionNo string para la opcion no
*/
async presentAlertMultipleButtons(header: string, message: string, opcionSi: string = 'Si', opcionNo: string = 'No') {
let choice: boolean;
const alert = await this.alertController.create({
header: header,
message: message,
buttons: [
{
text: opcionSi,
handler: () => {
alert.dismiss(true);
return true;
}
}, {
text: opcionNo,
handler: () => {
alert.dismiss(false);
return false;
}
}
],
});
await alert.present();
await alert.onDidDismiss().then(data => {
choice = data.data;
console.log(choice);
});
return choice;
}
/**
* Funcion que muestra un alert con una sola opcion
* @param header string con el titulo
* @param message string con el mensage
* @param opcionSi string para la opcion si que por defecto es aceptar
*/
async presentAlert(header: string, message: string, opcionSi: string = 'Aceptar') {
let sol: boolean = false;
const alert = await this.alertController.create({
header: header,
message: message,
buttons: [
{
text: opcionSi,
handler: () => {
alert.dismiss(true);
return true;
}
}
],
});
await alert.present();
return alert.onDidDismiss();
}
}
|
926e86b3d11a38d00e4f323b89c5bfe8bd8437b5
|
TypeScript
|
li2215890610/umi-study
|
/src/pages/Dashboard/Article/List/model.ts
| 2.640625
| 3
|
import { Effect, ImmerReducer } from 'umi';
import { removeNS } from '@/utils/action';
import { RootState } from '@/models/RootState';
import * as Service from './services/Article';
import * as Entity from './entities/Article';
import * as Action from './action';
export const NS = 'article';
export const articleStatus = new Map([
[Service.ArticleStatusFilter.ALL, '全部'],
[Service.ArticleStatusFilter.SUCCESS, '成功'],
[Service.ArticleStatusFilter.PENDING, '进行中'],
[Service.ArticleStatusFilter.REJECT, '失败'],
]);
export interface State {
list: Entity.Article[];
page: number;
pageSzie: number;
totalPage: number;
statusFilter: Service.ArticleStatusFilter;
keyword: '' | string;
}
export interface ArticleModelState {
namespace: string;
state: State;
effects: {
[Action.ActionTypes.Fetch]: Effect;
[Action.ActionTypes.Delete]: Effect;
[Action.ActionTypes.BatchUpDownShelfArticle]: Effect;
};
reducers: {
[Action.ActionTypes.FetchSucceeded]: ImmerReducer<
State,
ReturnType<typeof Action.fetchSucceeded>
>;
};
}
const defaultState: State = {
list: [],
page: 1,
pageSzie: 5,
totalPage: 0,
statusFilter: 0,
keyword: '',
};
const Article: ArticleModelState = {
namespace: NS,
state: defaultState,
effects: {
*[Action.ActionTypes.Fetch]({ payload }, { call, put }) {
const response = yield call(Service.fetchArticle, payload);
yield put(
removeNS(Action.fetchSucceeded({ ...payload, ...response }), NS),
);
},
*[Action.ActionTypes.Delete]({ payload }, { call, put, select }) {
yield call(Service.deleteArticle, payload);
const state: RootState['article'] = (yield select()).article;
console.log(state, '1___11');
// const state: RootState = yield select();
// const listState = state[NS];
yield put(
removeNS(
Action.fetch({
pageNum: 1,
pageSize: 5,
statusFilter: state.statusFilter,
}),
NS,
),
);
},
*[Action.ActionTypes.BatchUpDownShelfArticle](
{ payload },
{ call, put, select },
) {
yield call(Service.batchUpDownShelfArticle, payload);
const state: RootState['article'] = (yield select())[NS];
console.log(state, '1___11');
yield put(
removeNS(
Action.fetch({
pageNum: 1,
pageSize: 5,
statusFilter: state.statusFilter,
}),
NS,
),
);
},
},
reducers: {
[Action.ActionTypes.FetchSucceeded]: (_, { payload }) => {
console.log(payload, '____payload_____');
return {
page: payload.page,
list: payload.list,
pageSize: payload.pageSize,
totalPage: payload.totalPage,
statusFilter: payload.statusFilter,
};
},
},
};
export default Article;
|
b623da89af4c9f443d0a907dc08c102c79ec0662
|
TypeScript
|
jicjjang/next-with-redux-observable-app
|
/store/user/reducers.ts
| 2.84375
| 3
|
import { createReducer } from "typesafe-actions";
import produce from 'immer';
import { fetchUserAction, UserActions } from 'store/user/actions';
export interface UserState {
nextUserId: number,
character: {
name?: string,
id?: string,
username?: string,
email?: string,
phone?: string,
website?: string
},
isFetchedOnServer: boolean,
error: any,
}
const initState: UserState = {
nextUserId: 1,
character: {},
isFetchedOnServer: false,
error: null,
}
const userReducer = createReducer<UserState, UserActions>(initState)
.handleAction(fetchUserAction.success, (state, action) => produce(state, draft => {
draft.character = action.payload.response;
draft.nextUserId = state.nextUserId + 1;
}))
.handleAction(fetchUserAction.failure, (state, action) => produce(state, draft => {
draft.isFetchedOnServer = action.payload.isServer;
draft.error = action.payload.error;
}));
export default userReducer;
|
abe629635f19caa24216e441fb589e2dc64755e1
|
TypeScript
|
MyAeroCode/PS-TypeScript-Programmers
|
/lessons/67259/solution.ts
| 3.578125
| 4
|
type Dir = "↑" | "↓" | "←" | "→";
type Delta = { dy: number; dx: number; dir: Dir; forbidden: Dir };
export function solution(board: number[][]): number {
const N = board.length;
const delta: Delta[] = [
{ dy: +1, dx: 0, dir: "↓", forbidden: "↑" },
{ dy: -1, dx: 0, dir: "↑", forbidden: "↓" },
{ dy: 0, dx: -1, dir: "←", forbidden: "→" },
{ dy: 0, dx: +1, dir: "→", forbidden: "←" },
];
const minCost = new Map<string, number>();
class State {
constructor(
readonly y: number,
readonly x: number,
readonly prevDir: Dir,
readonly cost: number,
) {}
getKey() {
return [this.y, this.x, this.prevDir].join();
}
isVaild() {
return !(
this.y < 0 ||
this.x < 0 ||
N <= this.y ||
N <= this.x ||
board[this.y][this.x] === 1 ||
(minCost.has(this.getKey()) && minCost.get(this.getKey())! <= this.cost)
);
}
regist() {
minCost.set(this.getKey(), this.cost);
}
}
//
// BFS
const queue: State[] = [new State(0, 0, "↓", 0), new State(0, 0, "→", 0)];
while (queue.length) {
const thisState = queue.shift()!;
if (thisState.isVaild()) {
thisState.regist();
const { y, x, prevDir, cost } = thisState;
for (const d of delta) {
if (d.forbidden === thisState.prevDir) continue;
const { dy, dx } = d;
const needCost = prevDir === d.dir ? 100 : 600;
const nextState = new State(y + dy, x + dx, d.dir, cost + needCost);
if (nextState.isVaild()) {
queue.push(nextState);
}
}
}
}
//
// (N-1, N-1)에 도달한 상태 중 최솟값을 반환한다.
return Math.min(
...(delta
.map((d) => minCost.get([N - 1, N - 1, d.dir].join()))
.filter((cost) => cost !== undefined) as number[]),
);
}
|
d2d1ccd30bad51f8bde855b85a763f664cc47e42
|
TypeScript
|
frenchbench/frenchbench-app
|
/src/hooks/usePermissions.ts
| 2.8125
| 3
|
// see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/permissions
import { useEffect, useState } from 'react';
export const STATUS_PROMPT = 'prompt';
export const STATUS_GRANTED = 'granted';
export const STATUS_DENIED = 'denied';
export const PERM_NAME_GEOLOCATION = 'geolocation';
export function usePermissions(name) {
const [permissionObj, setPermissionObj] = useState({
granted: false,
denied: false,
prompt: false,
error: null,
});
useEffect(() => {
try {
navigator.permissions.query({ name })
.then(result => {
permissionObj.prompt = (result.state === STATUS_PROMPT);
permissionObj.granted = (result.state === STATUS_GRANTED);
permissionObj.denied = (result.state === STATUS_DENIED);
setPermissionObj(permissionObj);
});
} catch (err) {
permissionObj.error = err;
setPermissionObj(permissionObj);
}
}, [ name ]);
return permissionObj;
}
|
ca0046d4e4e88ec168557fc0454aea9ab626b531
|
TypeScript
|
arabsorkhi/Onion
|
/Onion.Web/Assets/src/utils/auth/unauthorized.ts
| 2.640625
| 3
|
import {addResponseErrorHandler, setDefaultHeaders} from '../rest';
import {authHeader, refreshToken, dataStore} from './index';
export const handleHttpUnauthorized = () => {
addResponseErrorHandler((rest, error) => {
if (error.response.status !== 401) return;
// 401 is Unauthorized error which means that this request failed.
// What we need to do is send a refresh request, then resend the same
// request that failed but with the new access token.
// We can do this automatically using axios interceptors.
return refreshToken()
.then(token => {
// Update currUser with new access_token
// Set default headers to have new authorization token
dataStore.add(token);
setDefaultHeaders(authHeader());
// Get the original request that failed due to 401 and
// resend it with the new access token.
return new Promise((resolve, reject) => {
rest.request(error.config)
.then(response => resolve(response))
.catch(innerError => reject([error, innerError]));
});
}, error => {
// Just logout if anything goes wrong.
dataStore.remove();
return Promise.reject(error);
});
});
}
|
8c932e1933b93ee2dc789601ccf5e896506e9a96
|
TypeScript
|
renatoclt/OFE_REPO_DESKTOP
|
/1002.OFE_DESKTOP/src/app/facturacion-electronica/general/models/configuracionDocumento/idioma.ts
| 2.578125
| 3
|
export class Idioma {
idIdioma: number;
descripcionCorta: string;
descripcionLarga: string;
constructor(idIdioma: number,
descripcionCorta: string,
descripcionLarga: string) {
this.idIdioma = idIdioma;
this.descripcionCorta = descripcionCorta;
this.descripcionLarga = descripcionLarga;
}
}
export const IDIOMA_ES = new Idioma(1,'ES','Español');
export const IDIOMA_EN = new Idioma(2,'EN','Inglés');
|
98bc0f5f486e1a0726862df9e68265088367ac7a
|
TypeScript
|
djr-taureau/pomodoist-2
|
/src/app/tasks/actions/pomo.ts
| 2.703125
| 3
|
import { Action } from '@ngrx/store';
import { Pomo } from '../models/pomo';
export enum PomoActionTypes {
Load = '[Pomo] Load',
LoadSuccess = '[Pomo] Load Success',
LoadFail = '[Pomo] Load Fail',
Select = '[Pomo] Select',
}
export class Load implements Action {
readonly type = PomoActionTypes.Load;
constructor(public payload: Pomo) {}
}
export class LoadSuccess implements Action {
readonly type = PomoActionTypes.LoadSuccess;
constructor(public payload: Pomo[]) {}
}
export class LoadFail implements Action {
readonly type = PomoActionTypes.LoadSuccess;
constructor(public payload: any) {}
}
export class Select implements Action {
readonly type = PomoActionTypes.Select;
constructor(public payload: string) {}
}
export type PomoActions =
| Load
| LoadSuccess
| LoadFail
| Select;
|
d3f50e987fdb688c308e862e237ba8cf90244bf9
|
TypeScript
|
LeonBaudouin/Abyss
|
/src/front/Scroll/OnePageScroll.ts
| 2.59375
| 3
|
import { SwipeHandler } from "./SwipeHandler";
import {GetWindowHeight } from "../Utils/UtilsFunctions";
import { addWheelListener } from "../Utils/AddWheelListener.js";
import Easing from "../../threejs/Math/Easing";
import { Point } from "../Influencets/CustomTypes/Point";
type ScrollCallback = (i: number) => void;
export class OnePageScroll {
bodyClassList: DOMTokenList = document.body.classList;
container: HTMLElement = document.querySelector(".container");
currentSlideIndex : number = 0;
isScrolling: boolean = false;
slideNumber: number;
swipeHandler: SwipeHandler;
scrollAmount: number
cooldown: number;
scrollCallbacks: ScrollCallback[]
constructor(slideNumber: number, coolDown: number, scrollAmount: number, scrollCallbacks: ScrollCallback[] = []) {
this.cooldown = coolDown;
this.scrollAmount = scrollAmount;
this.slideNumber = slideNumber;
this.scrollCallbacks = scrollCallbacks;
this.bodyClassList.add("scroll-index-0");
this.InitEvent()
}
private swipeCondition({x, y}: Point): boolean {
let yFraction = Math.abs(y / GetWindowHeight());
let xFraction = Math.abs(x / window.innerWidth);
return yFraction > 0.05 && xFraction < 0.35;
}
private InitEvent(): void {
this.swipeHandler = new SwipeHandler(
(p) => {this.DirectionScroll(p.y);},
(p) => this.swipeCondition(p)
);
addWheelListener( this.container, (e : WheelEvent) => {
let distance : number;
e.preventDefault();
if(e.deltaMode === 1) {
distance = e.deltaY * 50;
} else {
distance = e.deltaY;
}
if(Math.abs(distance) > 80 ) {
this.DirectionScroll(distance);
}
})
// document.addEventListener("scroll", (e) => {
// ExitFullScreen();
// })
this.container.addEventListener("touchmove", (e) => {
e.preventDefault();
})
}
private DirectionScroll(direction: number) {
if(direction > 0 && this.currentSlideIndex < this.slideNumber - 1) {
this.Next();
} else if(direction < 0 && this.currentSlideIndex > 0) {
this.Previous();
}
}
public Next(): void {
if(this.CanScroll) {
this.MoveTo(this.currentSlideIndex + 1);
}
}
public Previous(): void {
if(this.CanScroll) {
this.MoveTo(this.currentSlideIndex - 1);
}
}
public MoveTo(destination: number) {
this.Timeout();
let currentScroll = this.scrollAmount * this.currentSlideIndex;
let animationDistance = this.scrollAmount * destination - currentScroll;
this.scrollCallbacks.forEach(func => func(destination))
this.AnimationScroll(currentScroll, 0, animationDistance, 40);
this.bodyClassList.remove("scroll-index-" + this.currentSlideIndex);
this.currentSlideIndex = destination;
this.bodyClassList.add("scroll-index-" + this.currentSlideIndex);
}
private Timeout(): void {
this.isScrolling = true;
setTimeout(
(() => this.isScrolling = false),
this.cooldown
);
}
private AnimationScroll(currentScroll: number, currentTime: number, scrollDistance: number, animationDuration: number) {
if(animationDuration > currentTime) {
currentTime++;
let scrollAmount = Easing.easeInOutQuad(currentTime, 0, scrollDistance, animationDuration);
window.scroll(0, currentScroll + scrollAmount);
window.requestAnimationFrame( () => this.AnimationScroll(currentScroll, currentTime, scrollDistance, animationDuration) );
}
}
get CanScroll(): boolean {
return !this.isScrolling;
}
}
|
78465561aa5f34798b7222b27c31b10db9f317b6
|
TypeScript
|
huytd/subreddit-monitor
|
/src/utils.ts
| 3.203125
| 3
|
export type Nullable<T> = T | null;
export type Errorable<T> = [Nullable<T>, Nullable<Error>];
/**
* Sanitize the string for using as name, remove all
* special characters.
*/
export const sanitizeString = (input: string): string => {
const matched = input.match(/[a-zA-Z0-9_]/g);
if (matched) {
return matched.join("");
}
return "";
};
/**
* Fetch HTML source of an URL
*/
export const getHTML = async (url: string): Promise<string> => {
const res = await fetch(url);
return await res.text();
};
|
b160491dff43db9ffc5c44748e2327bdc0b5f05f
|
TypeScript
|
einari/JavaScript.Fundamentals
|
/Source/concepts/for_ConceptAs/when_creating_concept/as_something.ts
| 2.921875
| 3
|
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import { some_concept, some_base } from '../given/some_concept';
import { ConceptAs, conceptFrom } from '../../ConceptAs';
class another_something extends ConceptAs<some_base, 'another_something'> {
constructor(base: some_base) {
super(base, 'another_something');
}
}
describe('when creating concept as something', () => {
const value = new some_base('x', 42);
const concept = new some_concept(value);
it('should be a concept', () => ConceptAs.isConcept(concept).should.be.true);
it('should have the correct value', () => concept.value.should.equal(value));
it('should equal the value', () => concept.equals(value).should.be.true);
it('should equal itself', () => concept.equals(concept).should.be.true);
it('should equal the same concept with the same value', () => concept.equals(conceptFrom(some_concept,value)).should.be.true);
it('should not equal the same concept with another value', () => concept.equals(conceptFrom(some_concept, new some_base('some other value', 1))).should.be.false);
it('should not equal to another concept with the same something', () => concept.equals(conceptFrom(another_something, value)).should.be.false);
it('should not equal to another concept with another something', () => concept.equals(conceptFrom(another_something, new some_base('some other value', 1))).should.be.false);
});
|
29fc3366df24946cec072371792436aa7cefd96a
|
TypeScript
|
Senth/accounting
|
/packages/backend/src/adapters/repository/FiscalYearGetAllRepositoryAdapter.ts
| 2.515625
| 3
|
import { BaseAdapter } from './BaseAdapter'
import { Id } from '../../app/core/definitions/Id'
import { FiscalYear } from '../../app/core/entities/FiscalYear'
export class FiscalYearGetAllRepositoryAdapter extends BaseAdapter {
/**
* Get all the user's fiscal years
* @param userId the user id to get the fiscal years from
* @return all the user's fiscal years
*/
getFiscalYears(userId: Id): Promise<FiscalYear[]> {
return BaseAdapter.dbGateway.getFiscalYears(userId)
}
}
|
c58720465cbefb76ec5698fa6b18d4dd0f4d5a50
|
TypeScript
|
opensumi/core
|
/packages/markers/src/browser/markers-filter.model.ts
| 2.609375
| 3
|
import {
IMarker,
MarkerSeverity,
IFilter,
matchesFuzzy,
matchesFuzzy2,
matchesPrefix,
strings,
URI,
getEmptyExpression,
IExpression,
splitGlobAware,
} from '@opensumi/ide-core-browser';
import {
IFilterOptions,
IRenderableMarker,
IRenderableMarkerModel,
MarkerItemBuilder,
MarkerModelBuilder,
ResourceGlobMatcher,
} from '../common';
import Messages from './messages';
/**
* marker 过滤选项
* - 过滤严重程度
* - 过滤文案
*/
export class FilterOptions implements IFilterOptions {
static readonly _filter: IFilter = matchesFuzzy2;
static readonly _messageFilter: IFilter = matchesFuzzy;
readonly filterErrors: boolean = false;
readonly filterWarnings: boolean = false;
readonly filterInfos: boolean = false;
readonly textFilter: string = '';
readonly excludesMatcher: ResourceGlobMatcher;
readonly includesMatcher: ResourceGlobMatcher;
constructor(readonly filter: string = '', filesExclude: { root: URI; expression: IExpression }[] | IExpression = []) {
filter = filter.trim();
const filesExcludeByRoot = Array.isArray(filesExclude) ? filesExclude : [];
const excludesExpression: IExpression = Array.isArray(filesExclude) ? getEmptyExpression() : filesExclude;
const includeExpression: IExpression = getEmptyExpression();
if (filter) {
const filters = splitGlobAware(filter, ',')
.map((s) => s.trim())
.filter((s) => !!s.length);
for (const f of filters) {
this.filterErrors = this.filterErrors || this.matches(f, Messages.markerPanelFilterErrors());
this.filterWarnings = this.filterWarnings || this.matches(f, Messages.markerPanelFilterWarnings());
this.filterInfos = this.filterInfos || this.matches(f, Messages.markerPanelFilterInfos());
if (strings.startsWith(f, '!')) {
this.setPattern(excludesExpression, strings.ltrim(f, '!'));
} else {
this.setPattern(includeExpression, f);
this.textFilter += ` ${f}`;
}
}
}
this.excludesMatcher = new ResourceGlobMatcher(excludesExpression, filesExcludeByRoot);
this.includesMatcher = new ResourceGlobMatcher(includeExpression, []);
this.textFilter = this.textFilter.trim();
}
private setPattern(expression: IExpression, pattern: string) {
if (pattern[0] === '.') {
pattern = '*' + pattern; // convert ".js" to "*.js"
}
expression[`**/${pattern}/**`] = true;
expression[`**/${pattern}`] = true;
}
private matches(prefix: string, word: string): boolean {
const result = matchesPrefix(prefix, word);
return !!(result && result.length > 0);
}
}
/**
* Marker Filter
* - 模糊匹配 marker model
* - 匹配 filename
* - 模糊匹配 marker item
* - 匹配 message
* - 匹配 srouce
* - 匹配 code
*/
export class Filter {
constructor(public options: FilterOptions) {}
public filterModel(model: IRenderableMarkerModel): IRenderableMarkerModel {
const includeMatch = this.options.includesMatcher.matches(new URI(model.resource));
const filenameMatches = model.filename ? FilterOptions._filter(this.options.textFilter, model.filename) : undefined;
const parentMatch = includeMatch || (filenameMatches && filenameMatches.length > 0);
if (parentMatch) {
return MarkerModelBuilder.buildFilterModel(
model,
this.filterMarkerItems(model.markers, false),
parentMatch,
true,
{ filenameMatches },
);
} else {
const markers = this.filterMarkerItems(model.markers, true);
return MarkerModelBuilder.buildFilterModel(model, markers, false, markers.length > 0);
}
}
private filterMarkerItems(markers: IMarker[], filterCount: boolean): IRenderableMarker[] {
if (!markers || markers.length <= 0) {
return [];
}
const result: IRenderableMarker[] = markers.map((marker) => this.filterMarkerItem(marker));
if (filterCount) {
return result.filter((model: IRenderableMarker) => model.match === true);
} else {
return result;
}
}
private filterMarkerItem(marker: IMarker): IRenderableMarker {
if (
(this.options.filterErrors && MarkerSeverity.Error === marker.severity) ||
(this.options.filterWarnings && MarkerSeverity.Warning === marker.severity) ||
(this.options.filterInfos && MarkerSeverity.Info === marker.severity) ||
!this.options.textFilter
) {
return MarkerItemBuilder.buildFilterItem(marker, true);
}
const messageMatches = marker.message ? FilterOptions._filter(this.options.textFilter, marker.message) : undefined;
const sourceMatches = marker.source ? FilterOptions._filter(this.options.textFilter, marker.source) : undefined;
const codeMatches = marker.code ? FilterOptions._filter(this.options.textFilter, marker.code) : undefined;
if (messageMatches || sourceMatches || codeMatches) {
return MarkerItemBuilder.buildFilterItem(marker, true, {
messageMatches,
sourceMatches,
codeMatches,
});
} else {
return MarkerItemBuilder.buildFilterItem(marker, false);
}
}
}
|
dbba0304ed59b7f7f63e4a3710ccb45b4dadb490
|
TypeScript
|
njirem/rdf-converter
|
/src/lib/n3.d.ts
| 2.96875
| 3
|
// Very Quick and dirty!! Do not reuse!!
declare module N3 {
export interface Triple {
subject: string,
predicate: string,
object: string,
graph?: string,
}
export interface Options {
// Options: 'N-triples', 'application/trig'
format: string;
prefixes?: Prefixes
}
interface Prefixes {
[prefix: string]: string;
}
interface N3Static {
/**
* By default, N3.Parser parses a permissive superset of Turtle, TriG, N-Triples and N-Quads.
* For strict compatibility with any of those languages, pass a format argument upon creation.
*/
Parser(options?: Options): {
parse: (ttl: string, callback: (error: any, triple: Triple, prefixes: Prefixes) => void) => void;
}
/**
* By default, N3.Writer writes Turtle (or TriG for triples with a graph property).
* To write N-Triples (or N-Quads) instead, pass a format argument upon creation:
*/
Writer(options: Options): Writer;
Util: Util;
}
interface Writer {
addTriple(subject: string, predicate: string, object: string, graph?: string): void;
addTriple(triple: Triple): void;
end(callback: (err: any, result: string) => void): void;
}
interface Util {
isLiteral(value: string): boolean;
getLiteralLanguage(value: string): string;
getLiteralValue(value: string): string;
getLiteralType(value: string): string;
createLiteral(value: string | number | boolean, type?: string): string
isBlank(resource: string): boolean // true
isIRI(resource: string): boolean // false
}
}
declare var n3: N3.N3Static;
declare module 'n3' {
export = n3;
}
|
52566a390a5bbda4b9aefa49f3b4304016961d23
|
TypeScript
|
ag-grid/ag-grid
|
/grid-packages/ag-grid-docs/documentation/doc-pages/charts-events/examples/interaction-ranges/main.ts
| 2.5625
| 3
|
import { AgCartesianChartOptions, AgChart } from "ag-charts-community"
let options: AgCartesianChartOptions = {
container: document.getElementById("myChart"),
autoSize: true,
data: [
{
quarter: "Q1",
petrol: 200,
diesel: 100,
},
{
quarter: "Q2",
petrol: 300,
diesel: 130,
},
{
quarter: "Q3",
petrol: 350,
diesel: 160,
},
{
quarter: "Q4",
petrol: 400,
diesel: 200,
},
],
series: [
{
xKey: "quarter",
yKey: "petrol",
nodeClickRange: "exact",
listeners: {
nodeClick: event =>
window.alert(`${event.yKey} - ${event.datum.petrol}`),
},
},
{
xKey: "quarter",
yKey: "diesel",
nodeClickRange: "exact",
listeners: {
nodeClick: event =>
window.alert(`${event.yKey} - ${event.datum.diesel}`),
},
},
],
axes: [
{ type: "category", position: "bottom" },
{ type: "number", position: "left" },
],
}
var chart = AgChart.create(options)
function exact() {
if (!options.series) return
for (let i = 0; i < options.series.length; i++) {
options.series[i].nodeClickRange = "exact"
}
AgChart.update(chart, options)
}
function nearest() {
if (!options.series) return
for (let i = 0; i < options.series.length; i++) {
options.series[i].nodeClickRange = "nearest"
}
AgChart.update(chart, options)
}
function distance() {
if (!options.series) return
for (let i = 0; i < options.series.length; i++) {
options.series[i].nodeClickRange = 10
}
AgChart.update(chart, options)
}
|
19d5ad4761bbeba054707616069aad791acf5087
|
TypeScript
|
future4code/Luccas-Candido
|
/semana18/Cookenu/src/endpoints/signUp.ts
| 2.859375
| 3
|
import {Request, Response} from "express"
import { insertUser } from "../data/insertUser"
import { generateToken } from "../services/authenticator"
import { generateId } from "../services/generateId"
import { hash } from "../services/hashManager"
import { User } from "../types/user"
export const signUp = async(req:Request, res:Response):Promise<void> => {
try {
const {name, email, password, role} = req.body
let message = "Usuário criado com sucesso"
if(email.indexOf("@") === -1 || !email || !password || password.length < 6) {
res.statusCode = 406
message = "Campo email ou senha inválidos"
throw new Error(message)
}
if(!name) {
res.statusCode = 406;
message = "Insira parâmetros válidos para 'name'."
throw new Error(message)
}
const id = generateId()
const cypherPassword = await hash(password)
await insertUser({id, name, email, password: cypherPassword, role})
const token:string = generateToken({id, role})
res.status(200).send({
token,
message
})
} catch (error) {
let {message} = error
if(message.includes("Duplicate")) {
message = "Usuário já existe"
}
res.status(400).send(message)
}
}
|
8901ea034f987b55e4fc1418b71760e06c3d9211
|
TypeScript
|
DmitryBogomolov/webgl-playground
|
/playground/14_draw_image/index.ts
| 2.84375
| 3
|
import type { ImageRendererRawImageData, Vec2 } from 'lib';
import { Runtime, createRenderState, ImageRenderer, color, colors, color2uint } from 'lib';
/**
* Draw image util.
*
* Shows ImageRenderer helper. It renders image on the screen.
* Location defines image location in viewport. Region defines part of the image that will be rendered.
*/
export type DESCRIPTION = never;
main();
function main(): void {
const container = document.querySelector<HTMLElement>(PLAYGROUND_ROOT)!;
const runtime = new Runtime({ element: container });
runtime.setClearColor(color(0.7, 0.7, 0.7));
runtime.setRenderState(createRenderState({
depthTest: true,
}));
const imageCells = new ImageRenderer({ runtime, tag: 'image/cells' });
imageCells.setTextureUnit(3);
const imageLetter = new ImageRenderer({ runtime, tag: 'image/f-letter' });
imageLetter.setTextureUnit(4);
const imageLeaves = new ImageRenderer({ runtime, tag: 'image/leaves' });
imageLeaves.setTextureUnit(5);
imageCells.setImageData(generateTextureData()).catch(console.error);
imageLetter.setImageData({ url: '/static/f-letter.png' }).then(
() => {
runtime.requestFrameRender();
},
console.error,
);
imageLeaves.setImageData({ url: '/static/leaves.jpg' }).then(
() => {
runtime.requestFrameRender();
},
console.error,
);
let step = 0;
const SPEED = 0.1;
runtime.frameRequested().on((delta) => {
runtime.clearBuffer('color');
step = (step + SPEED * delta / 1000) % 1;
const size = runtime.getRenderTarget().size();
render1(size, imageLeaves, step);
render2(size, imageCells, step);
render3(size, imageLetter, step);
runtime.requestFrameRender();
});
}
function render1({ y: height }: Vec2, image: ImageRenderer, step: number): void {
const size = image.imageSize();
image.setLocation({
x1: 10,
y2: 10,
});
image.render();
image.setLocation({
x1: 10,
y1: 10,
width: size.x * 0.9,
height: size.y * 0.9,
});
image.render();
const w = size.x * 0.5;
const h = size.y * 0.5;
const range = height - (10 + size.y) - (10 + size.y * 0.9) - h;
image.setLocation({
x1: 10,
y2: 10 + size.y + range * (step > 0.5 ? 1 - step : step) * 2,
width: w,
height: h,
});
image.render();
}
function render2({ x: width }: Vec2, image: ImageRenderer, step: number): void {
const size = image.imageSize();
image.setLocation({
x2: 10,
y2: 10,
width: size.x,
height: size.y,
});
image.render();
image.setLocation({
y2: 10,
x1: 300,
width: size.x * 0.9,
height: size.y * 0.9,
});
image.render();
const w = size.x * 0.75;
const h = size.y * 0.75;
const range = width - (10 + size.x) - (300 + size.x * 0.9) - w;
image.setLocation({
y2: 10,
x1: 300 + size.x * 0.9 + range * (step > 0.5 ? 1 - step : step) * 2,
width: w,
height: h,
});
image.render();
}
function render3(_: Vec2, image: ImageRenderer, step: number): void {
const size = image.imageSize();
image.setRegion({});
image.setLocation({
x2: 10,
y1: 10,
});
image.render();
image.setLocation({
x2: 10 + size.x + 60,
y1: 10 + size.y * 0.1,
width: size.x * 0.8,
height: size.y * 0.8,
rotation: step * Math.PI * 2,
});
image.render();
image.setLocation({
x2: 10 + size.x + 60 + size.x * 0.8 + 60,
y1: 10 + 35,
});
image.setRegion({
y1: 35,
y2: 45,
rotation: step * Math.PI * 2,
});
image.render();
}
function generateTextureData(): ImageRendererRawImageData {
const SIZE = 8 * 24;
const arr = new Uint32Array(SIZE * SIZE);
for (let i = 0; i < SIZE; ++i) {
const ti = (i / SIZE * 8) | 0;
for (let j = 0; j < SIZE; ++j) {
const tj = (j / SIZE * 8) | 0;
let c;
if ((ti + tj) % 2) {
c = colors.CYAN;
} else {
c = colors.MAGENTA;
}
arr[i * SIZE + j] = color2uint(c);
}
}
return { data: new Uint8Array(arr.buffer), size: { x: SIZE, y: SIZE } };
}
|
763d7fa65e25056edb4e3adb6dbd302a5e089d8b
|
TypeScript
|
mmgoodnow/snooker-tracker
|
/src/app/services/user.service.client.ts
| 2.578125
| 3
|
import {
LOGIN_URL,
LOGOUT_URL,
PROFILE_URL,
USER_URL,
REGISTER_URL,
} from "../constants/urls";
import { User } from "../models/user.model.client";
export class UserServiceClient {
findAllUsers() {
return fetch(USER_URL).then(response => response.json());
}
findUserById(userId: string) {
return fetch(USER_URL + userId).then(response => response.json());
}
login(username, password) {
return fetch(LOGIN_URL, {
method: "post",
body: JSON.stringify({ username, password }),
credentials: "include",
headers: {
"content-type": "application/json",
},
});
}
logout() {
return fetch(LOGOUT_URL, {
method: "post",
credentials: "include",
});
}
profile() {
return fetch(PROFILE_URL, {
credentials: "include", // include, same-origin, *omit
}).then(response => response.json());
}
register(user) {
return fetch(REGISTER_URL, {
method: "post",
body: JSON.stringify(user),
credentials: "include", // include, same-origin, *omit
headers: {
"content-type": "application/json",
},
});
}
updateUser(user: User) {
return fetch(PROFILE_URL, {
method: "put",
body: JSON.stringify(user),
credentials: "include", // include, same-origin, *omit
headers: {
"content-type": "application/json",
},
});
}
deleteCurrentUser() {
return fetch(PROFILE_URL, {
method: "delete",
credentials: "include", // include, same-origin, *omit
headers: {
"content-type": "application/json",
},
});
}
createUser(user: User) {
return fetch(USER_URL, {
method: "post",
body: JSON.stringify(user),
credentials: "include", // include, same-origin, *omit
headers: {
"content-type": "application/json",
},
});
}
deleteUser(id: string) {
return fetch(USER_URL + id, {
method: "delete",
});
}
}
|
53a7c18b4e67d7fd24fe88dd3049ecc957611b6f
|
TypeScript
|
schmaluk/indigo
|
/src/models/cube.ts
| 2.515625
| 3
|
import {Model} from "./model";
import {Type, plainToConstructor} from "constructor-utils";
import {JsonMember,JsonObject} from "typedjson/src/typed-json";
@JsonObject
export class Cube implements Serializable<Cube>{
deserialize(input:Object):Cube {
this.name = input.name;
this.model = new Model().deserialize(input.model);
return this;
}
constructor(){}
@JsonMember
id:number;
@JsonMember
name: string;
@JsonMember
model: Model;
}
|
a88ad6b702ae18126c7c8be78939c6f1490a6116
|
TypeScript
|
entipic/domain
|
/src/entities/unknown-name-helper.ts
| 2.8125
| 3
|
import { clearText, atonic, md5, unixTime } from "../helpers";
import ms = require("ms");
import { UnknownName } from "./unknown-name";
export type UnknownNameBuildParams = {
name: string;
lang: string;
country?: string;
refIP: string;
refHost?: string;
};
export class UnknownNameHelper {
static createUniqueName(name: string) {
name = atonic(name.trim().toLowerCase());
name = clearText(name);
return name;
}
static createId({
name,
lang,
country
}: {
name: string;
lang: string;
country?: string;
}) {
const uniqueName = UnknownNameHelper.createUniqueName(name);
return md5([lang, country || "_", uniqueName].join("|"));
}
static expiresAt(date?: Date) {
date = date || new Date();
return unixTime(new Date(date.getTime() + ms("7d")));
}
static build(params: UnknownNameBuildParams) {
const name = params.name.trim();
const lang = params.lang.trim().toLowerCase();
const date = new Date();
const createdAt = date.toISOString();
const expiresAt = UnknownNameHelper.expiresAt(date);
const uniqueName = UnknownNameHelper.createUniqueName(name);
const id = UnknownNameHelper.createId(params);
const refIP = params.refIP.trim();
const item: UnknownName = {
id,
name,
lang,
uniqueName,
createdAt,
expiresAt,
refIP
};
if (params.country) {
item.country = params.country.trim();
}
if (params.refHost) {
item.refHost = params.refHost.trim();
}
return item;
}
}
|
f0734263845f46a7c175a859ae7dd2d46effea0e
|
TypeScript
|
firecrackerz/swift-to-js
|
/builtins/floats.ts
| 2.625
| 3
|
import { wrapped } from "../functions";
import { withPossibleRepresentations, FunctionMap, PossibleRepresentation, ReifiedType } from "../reified";
import { addVariable, lookup, uniqueName, DeclarationFlags, Scope } from "../scope";
import { lookupForMap } from "../utils";
import { binary, call, callable, conditional, expr, expressionLiteralValue, literal, member, read, statements, unary } from "../values";
import { applyDefaultConformances, binaryBuiltin, updateBuiltin } from "./common";
import { identifier, returnStatement } from "@babel/types";
export function buildFloatingType(globalScope: Scope): ReifiedType {
const reifiedType: ReifiedType = {
functions: lookupForMap({
"init(_:)": wrapped((scope, arg) => arg(0, "value"), "(Self) -> Self"),
"init(_builtinIntegerLiteral:)": wrapped((scope, arg) => arg(0, "value"), "(Self) -> Self"),
"init(_builtinFloatLiteral:)": wrapped((scope, arg) => arg(0, "value"), "(Self) -> Self"),
"+": wrapped((scope, arg, type) => binary("+", arg(0, "lhs"), arg(1, "rhs"), scope), "(Self, Self) -> Self"),
"-": wrapped((scope, arg, type, argTypes) => {
if (argTypes.length === 1) {
return unary("-", arg(0, "value"), scope);
}
return binary("-", arg(0, "lhs"), arg(1, "rhs"), scope);
}, "(Self, Self) -> Self"),
"*": wrapped((scope, arg, type) => binary("*", arg(0, "lhs"), arg(1, "rhs"), scope), "(Self, Self) -> Self"),
"/": wrapped((scope, arg, type) => binary("/", arg(0, "lhs"), arg(1, "rhs"), scope), "(Self, Self) -> Self"),
"%": wrapped(binaryBuiltin("%", 0), "(Self, Self) -> Self"),
"<": wrapped(binaryBuiltin("<", 0), "(Self, Self) -> Bool"),
">": wrapped(binaryBuiltin(">", 0), "(Self, Self) -> Bool"),
"<=": wrapped(binaryBuiltin("<=", 0), "(Self, Self) -> Bool"),
">=": wrapped(binaryBuiltin(">=", 0), "(Self, Self) -> Bool"),
"&": wrapped(binaryBuiltin("&", 0), "(Self, Self) -> Self"),
"|": wrapped(binaryBuiltin("|", 0), "(Self, Self) -> Self"),
"^": wrapped(binaryBuiltin("^", 0), "(Self, Self) -> Self"),
"+=": wrapped(updateBuiltin("+", 0), "(inout Self, Self) -> Void"),
"-=": wrapped(updateBuiltin("-", 0), "(inout Self, Self) -> Void"),
"*=": wrapped(updateBuiltin("*", 0), "(inout Self, Self) -> Void"),
"/=": wrapped(updateBuiltin("/", 0), "(inout Self, Self) -> Void"),
"hashValue": wrapped((scope, arg) => {
// TODO: Find a good hash strategy for floating point types
return binary("|", arg(0, "float"), literal(0), scope);
}, "(Self) -> Int"),
} as FunctionMap),
conformances: withPossibleRepresentations(applyDefaultConformances({
Equatable: {
functions: {
"==": wrapped(binaryBuiltin("===", 0), "(Self, Self) -> Bool"),
"!=": wrapped(binaryBuiltin("!==", 0), "(Self, Self) -> Bool"),
},
requirements: [],
},
SignedNumeric: {
functions: {
"-": wrapped((scope, arg) => unary("-", arg(0, "value"), scope), "(Self) -> Self"),
},
requirements: [],
},
FloatingPoint: {
functions: {
"==": wrapped(binaryBuiltin("===", 0), "(Self, Self) -> Bool"),
"!=": wrapped(binaryBuiltin("!==", 0), "(Self, Self) -> Bool"),
"squareRoot()": (scope, arg, type) => {
return callable(() => call(member("Math", "sqrt", scope), [arg(1, "value")], ["Double"], scope), "() -> Self");
},
},
requirements: [],
},
LosslessStringConvertible: {
functions: {
"init(_:)": wrapped((scope, arg) => {
const input = read(arg(0, "description"), scope);
const value = expressionLiteralValue(input);
if (typeof value === "string") {
const convertedValue = Number(value);
return literal(isNaN(convertedValue) ? null : convertedValue);
}
const result = uniqueName(scope, "number");
return statements([
addVariable(scope, result, "Int", call(expr(identifier("Number")), [
expr(input),
], ["String"], scope), DeclarationFlags.Const),
returnStatement(
read(conditional(
binary("===",
lookup(result, scope),
lookup(result, scope),
scope,
),
literal(null),
lookup(result, scope),
scope,
), scope),
),
]);
}, "(String) -> Self?"),
},
requirements: [],
},
}, globalScope), PossibleRepresentation.Number),
defaultValue() {
return literal(0);
},
innerTypes: {
},
};
return reifiedType;
}
|
e1282064db4b8edde8ed32e1c720d2df7f0f6624
|
TypeScript
|
pvtri96/pvtri96.github.io
|
/src/hooks/useDarkMode.ts
| 2.703125
| 3
|
import { useState, useEffect } from "react";
import useMedia from "hooks/useMedia";
export const useDarkMode = (): ReturnType<typeof useState<string>> => {
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
if (theme === "light") {
window.localStorage.setItem("theme", "dark");
setTheme("dark");
} else {
window.localStorage.setItem("theme", "light");
setTheme("light");
}
};
const prefersDarkMode = useMedia(["(prefers-color-scheme: dark)"], [true], false);
useEffect(() => {
const localTheme = window.localStorage.getItem("theme");
if (localTheme) {
window.localStorage.setItem("theme", localTheme);
setTheme(localTheme);
} else if (prefersDarkMode) {
setTheme("dark");
} else {
setTheme("light");
}
}, [prefersDarkMode]);
return [theme, toggleTheme];
};
|
fa7f03042bd2b5dc39f0d84910e4f1dd07e4807f
|
TypeScript
|
sajitron/climedo
|
/src/data/identity/identity.schema.ts
| 2.71875
| 3
|
import { SchemaTypes } from 'mongoose';
import bcrypt from 'bcrypt';
import { trimmedString, SchemaFactory } from '../base';
import { Identity } from './identity.model';
import env from '@app/common/config/env';
const IdentitySchema = SchemaFactory({
password: { ...trimmedString, required: true, select: false },
email: { ...trimmedString, unique: true, sparse: true },
first_name: { ...trimmedString, index: true, required: true },
last_name: { ...trimmedString, index: true },
dob: { type: SchemaTypes.Date },
last_login: { type: SchemaTypes.Date },
role: { ...trimmedString, enum: ['user', 'admin'] },
token: { ...trimmedString, default: null, select: false }
});
/**
* Mongoose Pre-save hook used to hash passwords for new identities
*/
IdentitySchema.pre('save', async function () {
const identity = <Identity>this;
if (!identity.isNew) return;
const hash = await bcrypt.hash(identity.password, env.salt_rounds);
identity.password = hash;
});
/**
* Document method used to check if a plain text password is the same as a hashed password
* @param plainText Plain text to be hashed and set as the paswword
*/
IdentitySchema.method('isPasswordValid', async function (plainText: string) {
const identity = <Identity>this;
const result = await bcrypt.compare(plainText, identity.password);
return result;
});
/**
* Document method used to change an identity's password.
* @param plainText Plain text to be hashed and set as the paswword
*/
IdentitySchema.method('updatePassword', async function (plainText: string) {
const identity = <Identity>this;
const hash = await bcrypt.hash(plainText, env.salt_rounds);
identity.password = hash;
return await identity.save();
});
export default IdentitySchema;
|
b6da21510288209055a8f61a616b17069e157857
|
TypeScript
|
fukurosan/Jhaystack
|
/src/ThreadPlanner/ThreadPlannerMain.ts
| 3.203125
| 3
|
import { ObjectLiteral } from "../Utility/JsonUtility"
/**
* Interface for workers that adopts the browser standard
*/
export interface IThreaderWorker {
onmessage: (result: { data: any }) => void
onerror: (...args: any[]) => any
postMessage: (...args: any[]) => any
terminate: () => void
}
/**
* Interface for a promise that is stored for later resolution
*/
export interface IThreaderPromise {
resolve: (resolution: any) => void
reject: (reason: any) => void
}
/**
* A type for a function with x arguments that result in a value of type x
*/
export interface IThreaderFunction {
(...args: any[]): any
_jhaystack?: {
dependencies?: ObjectLiteral
dependencyString?: string
}
}
export interface IThreaderThreadMetaData {
freeThreads: IThreaderWorker[]
pendingTasks: number
dependencyString: string
terminationTimeout: ReturnType<typeof setTimeout> | undefined
}
/**
* Main Thread Planner Class.
* The threadplanner will serialize functions into strings and create worker objects that can execute these.
* Worker objects are reused between executions, but will terminate after x milliseconds of being idle.
* The threadplanner will try to determine the optimal amount of threads that can be started on the host, and will run only that many threads concurrently.
*/
export class ThreadPlanner {
/** A list of queued jobs. The first item is the promise that is waiting for the resolution of the thread. The second is the function to execute, and the third is a list of arguments. */
private threadQueue: [IThreaderPromise, IThreaderFunction, any[]][]
/** Currently running number of threads */
private numberOfRunningThreads: number
/** Maximum allowed number of threads (determined in extending classes) */
protected maxThreads: number
/** A map between functions and information about how many tasks are currently pending, a timeout object used to keep track of worker idle time for auto-termination, worker dependencies, as well as free worker threads. */
private metaData: WeakMap<IThreaderFunction, IThreaderThreadMetaData>
/** Maximum idle time before workers are terminated (in ms) */
private MAXIMUM_IDLE_TIME_MS = 10000 //10 seconds
/** All registered functions */
private registeredFns: IThreaderFunction[] = []
constructor() {
this.threadQueue = []
this.numberOfRunningThreads = 0
this.maxThreads = -1
this.metaData = new WeakMap()
}
setMaxThreadCount(maxThreadCount: number) {
this.maxThreads = maxThreadCount
}
setMaxIdleTime(maxIdleTime: number) {
this.MAXIMUM_IDLE_TIME_MS = maxIdleTime
}
getMaxThreadCount() {
return this.maxThreads
}
getMaxIdleTime() {
return this.MAXIMUM_IDLE_TIME_MS
}
getNumberOfQueuedJobs() {
return this.threadQueue.length
}
getNumberOfRunningJobs() {
return this.numberOfRunningThreads
}
hasNext() {
return !!this.threadQueue.length
}
createInlineWorker(fn: IThreaderFunction, dependencyString: string): IThreaderWorker {
return this.createInlineWorker(fn, dependencyString) //This is just for the TS-compiler to calm down. The real implementation can be found in extending classes
}
/**
* Terminates all workers for a given function
* @param fn - Function for which workers should be terminated
*/
terminate(fn: IThreaderFunction) {
if (this.metaData.has(fn)) {
const meta = this.metaData.get(fn)!
if (meta.terminationTimeout) {
clearTimeout(meta.terminationTimeout)
}
meta.freeThreads.forEach(worker => {
worker.terminate()
})
this.metaData.delete(fn)
}
this.threadQueue.filter(thread => thread[1] === fn).forEach(thread => thread[0].reject("Thread was terminated."))
this.threadQueue = this.threadQueue.filter(thread => thread[1] !== fn)
}
/**
* Recursively computes a dependency string for a given function
* @param obj - Object to compute dependency string for
* @param result - Should never be set externally! Recursively updated dependency string
*/
getDependencyString(obj: any, result = "") {
if (obj._jhaystack && obj._jhaystack.dependencyString) {
result += `${obj._jhaystack.dependencyString}
`
}
if (obj._jhaystack && obj._jhaystack.dependencies) {
const dependencies = obj._jhaystack.dependencies
Object.keys(dependencies).forEach(key => {
const dependency = dependencies[key]
result += `var ${key} = ${dependency.toString ? dependency.toString() : dependency}
`
result = this.getDependencyString(dependency, result)
})
}
return result
}
/**
* Retrieves meta data for a function from the threadplanner. If no meta data exists then it will be created by this function.
*/
getMetaData(fn: IThreaderFunction): IThreaderThreadMetaData {
if (!this.metaData.has(fn)) {
this.metaData.set(fn, {
pendingTasks: 0,
terminationTimeout: undefined,
dependencyString: this.getDependencyString(fn),
freeThreads: []
})
this.registeredFns.push(fn)
}
return this.metaData.get(fn)!
}
/**
* Warms up threads for a given function for later use.
*/
warmup(fn: IThreaderFunction, number?: number) {
const metaData = this.getMetaData(fn)
const threads = metaData.freeThreads
const loops = number ? number : Math.max(0, this.maxThreads - threads.length)
for (let i = 0; i < loops; i++) {
threads.push(this.createInlineWorker(fn, metaData.dependencyString))
}
}
/**
* Terminates all threads in the thread planner.
*/
terminateAllThreads() {
let fn
while ((fn = this.registeredFns.pop())) {
this.terminate(fn)
}
}
/**
* Queues a function in the thread planner (and starts a thread execution loop if possible).
* @param fn - Function to run
* @param args - Arguments for the function
*/
async run(fn: IThreaderFunction, ...args: any[]) {
const metaData = this.getMetaData(fn)
if (metaData.terminationTimeout) {
clearTimeout(metaData.terminationTimeout)
delete metaData.terminationTimeout
}
metaData.pendingTasks++
// eslint-disable-next-line @typescript-eslint/no-empty-function
let resolve: IThreaderFunction = () => {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
let reject: IThreaderFunction = () => {}
const result = new Promise((outerResolve: (resolution: any) => void, outerReject: (reason: any) => void) => {
resolve = outerResolve
reject = outerReject
})
this.threadQueue.push([{ resolve, reject }, fn, [...args]])
if (this.numberOfRunningThreads !== this.maxThreads) {
//There should never be more execution loops than max thread count.
this.executeQueueLoop()
}
return result
}
/**
* Executes threads one by one until the queue is empty.
* @param fn - Function to execute
* @param args - Arguments for the function to be executed
*/
async executeQueueLoop() {
while (this.hasNext()) {
const nextItem = this.threadQueue.shift()!
const resolve = nextItem[0].resolve
const reject = nextItem[0].reject
const fn = nextItem[1]
const args = nextItem[2]
const threads = this.metaData.get(fn)!.freeThreads
if (!threads.length) {
threads!.push(this.createInlineWorker(fn, this.metaData.get(fn)!.dependencyString))
}
const thread = threads!.splice(0, 1)[0]
this.numberOfRunningThreads++
try {
await this.executeWorker(thread, ...args)
.then(executionResult => {
this.handleThreadCompleted(fn, thread)
resolve(executionResult)
})
.catch(error => {
this.handleThreadCompleted(fn, thread)
reject(error)
})
} catch (e) {
console.error(e)
}
this.numberOfRunningThreads--
}
}
/**
* Executes a worker and returns a promise with the result
* @param worker - Worker to be executed
* @param args - arguments for the worker
*/
executeWorker(worker: IThreaderWorker, ...args: any[]) {
return new Promise((resolve, reject) => {
worker.onmessage = result => {
resolve(result.data)
}
worker.onerror = reject
worker.postMessage(args)
})
}
/**
* Handles when a worker completes an operation
* @param fn - Function that completed
* @param thread - Worker that completed
*/
handleThreadCompleted(fn: IThreaderFunction, thread: IThreaderWorker) {
const metaData = this.metaData.get(fn)
if (!metaData) {
//A termination command must have been executed
return
}
metaData.freeThreads.push(thread)
metaData.pendingTasks--
if (!metaData.pendingTasks) {
if (this.MAXIMUM_IDLE_TIME_MS) {
metaData.terminationTimeout = setTimeout(() => {
this.terminate(fn)
this.registeredFns = this.registeredFns.filter(registeredFn => registeredFn !== fn)
}, this.MAXIMUM_IDLE_TIME_MS)
}
}
}
}
|
e78ed606012e707b5f596cca7d98806d4bc6940b
|
TypeScript
|
JohnCSimon/typescript-express-starter
|
/src/mongo.ts
| 2.859375
| 3
|
import { UpVote } from './dto/votes';
import * as mongodb from 'mongodb';
// import * as url from 'url';
var server = new mongodb.Server('localhost', 27017);
var db = new mongodb.Db('mydb', server, { w: 1 });
db.open(function () { });
// function createRecord(record: UpVoteDTO) {
// try {
// console.log("go!");
// var images_collection = db.collection('votes').insertOne(record);
// var xx = images_collection;
// console.log(xx);
// // console.log("error");
// // console.log(error);
// }
// catch (x) {
// console.log('catch');
// console.log(x);
// }
// console.log('done');
// }
interface Named {
name: string;
}
class Person {
name: string;
}
let p: Named;
// OK, because of structural typing
p = new Person();
async function createRecord(record: UpVote) {
try {
console.log("go!");
var vote_collection = await db.collection('books');
var result = await vote_collection.insert(record);
console.log(result.result);
console.log(vote_collection);
// console.log(xx);
// console.log("error");
// console.log(error);
}
catch (x) {
console.log('catch');
console.log(x);
}
console.log('done');
}
async function getRecord() {
console.log("go!");
var error, images_collection = await db.collection('votes');
console.log(images_collection);
console.log("error");
console.log(error);
}
async function upVote(voteId: number) {
console.log("go!");
var error, images_collection = await db.collection('votes');
voteId++;
console.log(images_collection);
console.log("error");
console.log(error);
}
async function downVote(record: number) {
record++;
console.log("go!");
var error, images_collection = await db.collection('books');
console.log(images_collection);
console.log("error");
console.log(error);
}
export {
createRecord,
getRecord,
upVote,
downVote
}
|
3a7a84a5a6e9ad971dde52f5035ba82881589758
|
TypeScript
|
yiqingfeng/node-ts-start
|
/src/utils/fs.ts
| 3.203125
| 3
|
/**
* @description 文件相关操作
*/
import * as utils from '../../types/utils'; // 引入声明
import fs from 'fs';
import path from 'path';
type resData<T> = utils.resData<T>;
/**
* @description 检查指定目录是否存在
* @param oPath 指定目录
*/
export function checkDir(oPath: string): boolean {
return fs.existsSync(oPath);
}
/**
* @description 指定路径是否为目录
* @param oPath
*/
function isDir(oPath: string): boolean {
const isExists = checkDir(oPath);
let isDirectory = false;
// 同步版本
if (!isExists) {
return isDirectory;
}
try {
const stats = fs.statSync(oPath);
isDirectory = stats.isDirectory();
} catch (err) {
}
return isDirectory;
}
/**
* @description 删除指定文件夹
* @param oPath 目标文件夹的路径
*/
export function deleteDir(oPath: string): resData<string> {
const hasPathExist: boolean = checkDir(oPath);
const res: resData<string> = {
errCode: 0,
data: '',
};
if (hasPathExist) {
try {
const files: string[] = fs.readdirSync(oPath);
files.forEach(file => {
const curPath: string = path.resolve(oPath, file);
if (isDir(curPath)) {
deleteDir(curPath);
} else {
fs.unlinkSync(curPath); // 删除该文件
}
});
fs.rmdirSync(oPath); // 清除当前文件夹
} catch (err) {
console.log(err);
res.errCode = -1;
}
} else {
res.errCode = 500;
}
return res;
}
/**
* @description 创建指定文件夹
*/
export function mkdir(oPath: string): resData<string> {
const res = {
errCode: 0,
data: '',
};
if (isDir(oPath)) {
return res;
}
try {
fs.mkdirSync(oPath);
} catch (err) {
res.errCode = -1;
res.data = err.toString();
}
return res;
}
|
e494715762df175e343a78fa1d83983db0a26a44
|
TypeScript
|
themojilla/query-machine
|
/src/services/createRequests.ts
| 2.625
| 3
|
import { AxiosInstance, AxiosRequestConfig } from 'axios'
import { ICreateRequests, TSend } from '../types'
export const createRequests = <T>(
axios: AxiosInstance,
send: TSend<T>
): ICreateRequests => {
const onGet = (url: string, config?: AxiosRequestConfig) => {
const request = () => axios.get<T>(url, config)
send('REQUEST', { request })
}
const onDelete = (url: string, config?: AxiosRequestConfig) => {
const request = () => axios.delete<T>(url, config)
send('REQUEST', { request })
}
const onOptions = (url: string, config?: AxiosRequestConfig) => {
const request = () => axios.options<T>(url, config)
send('REQUEST', { request })
}
const onHead = (url: string, config?: AxiosRequestConfig) => {
const request = () => axios.head<T>(url, config)
send('REQUEST', { request })
}
const onPatch = <D>(url: string, data: D, config?: AxiosRequestConfig) => {
const request = () => axios.patch<T>(url, data, config)
send('REQUEST', { request })
}
const onPost = <D>(url: string, data: D, config?: AxiosRequestConfig) => {
const request = () => axios.post<T>(url, data, config)
send('REQUEST', { request })
}
const onPut = <D>(url: string, data: D, config?: AxiosRequestConfig) => {
const request = () => axios.put<T>(url, data, config)
send('REQUEST', { request })
}
return { onGet, onDelete, onOptions, onHead, onPatch, onPost, onPut }
}
|
555de4b1b0e78709f888ca703e0b45ec8d9fa1ee
|
TypeScript
|
soroushchehresa/cli-corona
|
/src/utils/table.ts
| 2.75
| 3
|
import cli from 'cli-ux';
import chalk from 'chalk';
import TableCLI from 'cli-table';
type ColItem = string[];
export default class Table {
static async draw({ data }: {data: object}): Promise<void> {
const cols = this.renderColumns(data);
const table = new TableCLI({
head: [
chalk.blue.bold('Title'),
chalk.blue.bold('Count'),
],
colWidths: [30, 20],
chars: {
'top': '═', 'top-mid': '╤', 'top-left': '╔', 'top-right': '╗'
, 'bottom': '═', 'bottom-mid': '╧', 'bottom-left': '╚', 'bottom-right': '╝'
, 'left': '║', 'left-mid': '╟', 'mid': '─', 'mid-mid': '┼'
, 'right': '║', 'right-mid': '╢', 'middle': '│',
},
});
table.push(...cols);
console.log(table.toString());
cli.action.stop('Done');
}
private static renderColumns(data: any): ColItem[] {
let cols: ColItem[] = [];
Object.keys(data).forEach((item: string) => {
if ((typeof data[item] === ('number' || 'string')) && (item !== 'updated')) {
cols = [...cols, [chalk.cyanBright.bold(item), chalk.green.bold(this.formatNumber(data[item]))]];
}
});
return cols;
}
private static formatNumber(number: number): string {
return Number((number).toFixed(1)).toLocaleString();
}
}
|
da338d50b6f4f2167327c63e4e3092d223a309be
|
TypeScript
|
GregoryPevnev/albums-front
|
/src/store/actions/albumActions.ts
| 2.578125
| 3
|
import Bundle from "../bundle";
import { Actions } from "./types";
import { SortBy, AlbumsQueryResult } from "../../application/loaders";
import { AlbumData, UpdateAlbum } from "../../application/operations";
import Album from "../../application/models/Album";
import Track from "../../application/models/Track";
import AlbumItem from "../../application/models/AlbumItem";
import Review from "../../application/models/Review";
import { AlbumInfo } from "../../application/models/AlbumItem";
// Types
export interface AlbumsLoadingAction {
type: Actions.AlbumsLoading;
}
export interface AlbumsErrorAction {
type: Actions.AlbumsError;
payload: string;
}
export interface AlbumsSuccessAction {
type: Actions.AlbumsSuccess;
payload: AlbumsQueryResult;
}
export interface MyAlbumsLoadingAction {
type: Actions.MyAlbumsLoading;
}
export interface MyAlbumsErrorAction {
type: Actions.MyAlbumsError;
payload: string;
}
export interface MyAlbumsSuccessAction {
type: Actions.MyAlbumsSuccess;
payload: AlbumItem[];
}
export interface DetailsLoadingAction {
type: Actions.DetailsLoading;
}
export interface DetailsErrorAction {
type: Actions.DetailsError;
payload: string;
}
export interface DetailsSuccessAction {
type: Actions.DetailsSuccess;
payload: Album;
}
export interface TracksLoadingAction {
type: Actions.TracksLoading;
}
export interface TracksErrorAction {
type: Actions.TracksError;
payload: string;
}
export interface TracksSuccessAction {
type: Actions.TracksSuccess;
payload: Track[];
}
export interface ReviewsLoadingAction {
type: Actions.ReviewsLoading;
}
export interface ReviewsErrorAction {
type: Actions.ReviewsError;
payload: string;
}
export interface ReviewsSuccessAction {
type: Actions.ReviewsSuccess;
payload: Review[];
}
export interface UpdateDetailsAction {
type: Actions.UpdateDetails;
payload: Album;
}
// Actions
export const loadAlbums = (page: number, sort: SortBy) => async (
dispatch: Function,
_: any,
{ albums: { loadAlbums } }: Bundle
) => {
dispatch({ type: Actions.AlbumsLoading });
try {
const result = await loadAlbums({ page, sort });
dispatch({ type: Actions.AlbumsSuccess, payload: result });
} catch (e) {
dispatch({ type: Actions.AlbumsError, payload: e.type });
}
};
export const loadMyAlbums = () => async (dispatch: Function, _: any, { albums: { loadMyAlbums } }: Bundle) => {
dispatch({ type: Actions.MyAlbumsLoading });
try {
const result = await loadMyAlbums();
dispatch({ type: Actions.MyAlbumsSuccess, payload: result });
} catch (e) {
dispatch({ type: Actions.MyAlbumsError, payload: e.type });
}
};
export const viewAlbum = (id: string) => (dispatch: Function, _: any, { view }: Bundle) => {
const { tracks, details, reviews } = view(id);
dispatch({ type: Actions.ReviewsLoading });
dispatch({ type: Actions.TracksLoading });
dispatch({ type: Actions.DetailsLoading });
return Promise.all([
tracks
.then(data => dispatch({ type: Actions.TracksSuccess, payload: data }))
.catch(error => dispatch({ type: Actions.TracksError, payload: error })),
details
.then(data => dispatch({ type: Actions.DetailsSuccess, payload: data }))
.catch(error => dispatch({ type: Actions.DetailsError, payload: error })),
reviews
.then(data => dispatch({ type: Actions.ReviewsSuccess, payload: data }))
.catch(error => dispatch({ type: Actions.ReviewsError, payload: error }))
]);
};
// No Additional actions -> Just reload
export const createAlbum = (data: AlbumData) => (__: Function, _: any, { albums: { createAlbum } }: Bundle) =>
createAlbum(data);
export const deleteAlbum = (id: string) => (dispatch: Function, _: any, { albums: { deleteAlbum } }: Bundle) =>
deleteAlbum(id).then(() => dispatch({ type: Actions.DeleteAlbum, payload: id }));
export const updateAlbum = (id: string, data: AlbumData) => async (
dispatch: Function,
_: any,
{ albums: { updateAlbum } }: Bundle
) => updateAlbum(id, data).then(album => dispatch({ type: Actions.UpdateDetails, payload: album }));
|
886d654a0d5e38ae5ebfb24f7f8f2c627b5ea753
|
TypeScript
|
scottohara/loot
|
/src/transactions/controllers/flag.ts
| 2.546875
| 3
|
import type {
Transaction,
TransactionFlag,
TransactionFlagType
} from "~/transactions/types";
import type TransactionModel from "~/transactions/models/transaction";
export default class TransactionFlagController {
public errorMessage: string | null = null;
public flagType: TransactionFlagType;
public flag: TransactionFlag;
public readonly flagged: boolean;
public constructor(private readonly $uibModalInstance: angular.ui.bootstrap.IModalInstanceService,
private readonly transactionModel: TransactionModel,
private readonly transaction: Transaction) {
this.flagType = transaction.flag_type ?? "followup";
this.flag = "(no memo)" === String(transaction.flag) ? "" : transaction.flag ?? "";
this.flagged = Boolean(transaction.flag);
}
// Save and close the modal
public save(): void {
this.errorMessage = null;
this.transaction.flag_type = this.flagType;
this.transaction.flag = "" === this.flag ? "(no memo)" : this.flag;
this.transactionModel.flag(this.transaction).then((): void => this.$uibModalInstance.close(this.transaction), (error: angular.IHttpResponse<string>): string => (this.errorMessage = error.data));
}
// Delete and close the modal
public deleteFlag(): void {
this.errorMessage = null;
this.transactionModel.unflag(Number(this.transaction.id)).then((): void => {
this.transaction.flag_type = null;
this.transaction.flag = null;
this.$uibModalInstance.close(this.transaction);
}, (error: angular.IHttpResponse<string>): string => (this.errorMessage = error.data));
}
// Dismiss the modal without deleting
public cancel(): void {
this.$uibModalInstance.dismiss();
}
}
TransactionFlagController.$inject = ["$uibModalInstance", "transactionModel", "transaction"];
|
d6a3e5f040a4944b58db003fd29cca94f3e043c2
|
TypeScript
|
internetErik/dnd-campaign-manager-angular-old
|
/lib/collections/battles.ts
| 2.734375
| 3
|
import {simpleRoll} from '../dice';
export var Battles = new Mongo.Collection('battles');
Meteor.methods({
insertBattle: function(battle) {
if (battle) {
battle.createDate = Date.now();
battle.complete = false;
battle.combatPhase = -1;
return Battles.insert(battle);
}
},
updateBattle: function(_id, battle) {
//if everyone has submitted their action, we roll for their initiative
if (battle.combatPhase === 0 &&
battle.combatants.every((c) => c.actionSubmitted || c.roundsOccupied > 0 )) {
//see if we need to advance to 1
//the sorting is too much to do on the server. Should sort on the client
battle.combatants = battle.combatants
.map((c) => {
c.initiative = (c.roundsOccupied > 0) ?
0 : simpleRoll(100) + (c.bonus || 0);
return c;
})
.sort((a:any, b:any) => {
if (a.initiative > b.initiative)
return -1;
else if (a.initiative < b.initiative)
return 1;
else
return 0;
});
battle.combatPhase = 1;
}
return Battles.update({ _id: _id }, battle);
},
finishBattle: function(_id) {
Battles.update({ _id: _id }, { $set: { complete: true } });
},
removeBattle: function(_id) {
Battles.remove({ _id: _id });
}
});
|