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
|
|---|---|---|---|---|---|---|
c16fc9f94a0ebd07a0a06db1a6e1e19d6b8dbf9a
|
TypeScript
|
LunarFuror/phantasmal-world
|
/src/core/observable/Disposer.test.ts
| 3.359375
| 3
|
import { Disposer } from "./Disposer";
import { Disposable } from "./Disposable";
test("calling add or add_all should increase length correctly", () => {
const disposer = new Disposer();
expect(disposer.length).toBe(0);
disposer.add(dummy());
expect(disposer.length).toBe(1);
disposer.add_all(dummy(), dummy());
expect(disposer.length).toBe(3);
disposer.add(dummy());
expect(disposer.length).toBe(4);
disposer.add_all(dummy(), dummy());
expect(disposer.length).toBe(6);
});
test("length should be 0 after calling dispose", () => {
const disposer = new Disposer();
disposer.add_all(dummy(), dummy(), dummy());
expect(disposer.length).toBe(3);
disposer.dispose();
expect(disposer.length).toBe(0);
});
test("contained disposables should be disposed when calling dispose", () => {
let dispose_calls = 0;
function disposable(): Disposable {
return {
dispose(): void {
dispose_calls++;
},
};
}
const disposer = new Disposer();
disposer.add_all(disposable(), disposable(), disposable());
expect(dispose_calls).toBe(0);
disposer.dispose();
expect(dispose_calls).toBe(3);
});
function dummy(): Disposable {
return {
dispose(): void {
// Do nothing.
},
};
}
|
2f2f1d31a5545427f9532032995f834be7fe4e58
|
TypeScript
|
HdrHistogram/HdrHistogramJS
|
/src/PercentileIterator.ts
| 3.375
| 3
|
import JsHistogram from "./JsHistogram";
import JsHistogramIterator from "./JsHistogramIterator";
const { pow, floor, log2 } = Math;
/**
* Used for iterating through histogram values according to percentile levels. The iteration is
* performed in steps that start at 0% and reduce their distance to 100% according to the
* <i>percentileTicksPerHalfDistance</i> parameter, ultimately reaching 100% when all recorded histogram
* values are exhausted.
*/
class PercentileIterator extends JsHistogramIterator {
percentileTicksPerHalfDistance: number;
percentileLevelToIterateTo: number;
percentileLevelToIterateFrom: number;
reachedLastRecordedValue: boolean;
/**
* @param histogram The histogram this iterator will operate on
* @param percentileTicksPerHalfDistance The number of equal-sized iteration steps per half-distance to 100%.
*/
public constructor(
histogram: JsHistogram,
percentileTicksPerHalfDistance: number
) {
super();
this.percentileTicksPerHalfDistance = 0;
this.percentileLevelToIterateTo = 0;
this.percentileLevelToIterateFrom = 0;
this.reachedLastRecordedValue = false;
this.doReset(histogram, percentileTicksPerHalfDistance);
}
/**
* Reset iterator for re-use in a fresh iteration over the same histogram data set.
*
* @param percentileTicksPerHalfDistance The number of iteration steps per half-distance to 100%.
*/
reset(percentileTicksPerHalfDistance: number) {
this.doReset(this.histogram, percentileTicksPerHalfDistance);
}
private doReset(
histogram: JsHistogram,
percentileTicksPerHalfDistance: number
) {
super.resetIterator(histogram);
this.percentileTicksPerHalfDistance = percentileTicksPerHalfDistance;
this.percentileLevelToIterateTo = 0;
this.percentileLevelToIterateFrom = 0;
this.reachedLastRecordedValue = false;
}
public hasNext(): boolean {
if (super.hasNext()) return true;
if (!this.reachedLastRecordedValue && this.arrayTotalCount > 0) {
this.percentileLevelToIterateTo = 100;
this.reachedLastRecordedValue = true;
return true;
}
return false;
}
incrementIterationLevel() {
this.percentileLevelToIterateFrom = this.percentileLevelToIterateTo;
// The choice to maintain fixed-sized "ticks" in each half-distance to 100% [starting
// from 0%], as opposed to a "tick" size that varies with each interval, was made to
// make the steps easily comprehensible and readable to humans. The resulting percentile
// steps are much easier to browse through in a percentile distribution output, for example.
//
// We calculate the number of equal-sized "ticks" that the 0-100 range will be divided
// by at the current scale. The scale is detemined by the percentile level we are
// iterating to. The following math determines the tick size for the current scale,
// and maintain a fixed tick size for the remaining "half the distance to 100%"
// [from either 0% or from the previous half-distance]. When that half-distance is
// crossed, the scale changes and the tick size is effectively cut in half.
// percentileTicksPerHalfDistance = 5
// percentileReportingTicks = 10,
const percentileReportingTicks =
this.percentileTicksPerHalfDistance *
pow(2, floor(log2(100 / (100 - this.percentileLevelToIterateTo))) + 1);
this.percentileLevelToIterateTo += 100 / percentileReportingTicks;
}
reachedIterationLevel(): boolean {
if (this.countAtThisValue === 0) {
return false;
}
const currentPercentile =
(100 * this.totalCountToCurrentIndex) / this.arrayTotalCount;
return currentPercentile >= this.percentileLevelToIterateTo;
}
getPercentileIteratedTo(): number {
return this.percentileLevelToIterateTo;
}
getPercentileIteratedFrom(): number {
return this.percentileLevelToIterateFrom;
}
}
export default PercentileIterator;
|
356b6dacc2ae17ba3b1fd2e19266ef07893b2eaa
|
TypeScript
|
Howard86/github-search
|
/src/server/cache/memory.ts
| 2.78125
| 3
|
import LRUCache, { Options } from 'lru-cache';
import { AbstractCache } from './model';
export default class MemoryCache<K, V> extends AbstractCache<K, V> {
private readonly lruCache: LRUCache<K, V>;
constructor(options: Options<K, V>) {
super();
this.lruCache = new LRUCache(options);
}
async get(key: K): Promise<V | undefined> {
return this.lruCache.get(key);
}
async set(key: K, value: V): Promise<void> {
this.lruCache.set(key, value);
}
}
|
6bfcaa8b0ba66c672452fc4c029d2361b439d85f
|
TypeScript
|
AM-Solutions23/bigcash
|
/src/config/core/config/writers/wr.entities.ts
| 2.8125
| 3
|
export default class Entities{
private entity:string;
private entity_options:string;
constructor(fragments){
this.entity_options = fragments.entity_options;
this.entity = fragments.entity;
}
public EntitiesData(){
let data:String = `import {Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn} from "typeorm";
@Entity()
export class ${this.entity} {
@PrimaryGeneratedColumn()
id: number;
`;
if(this.entity_options){
this.entity_options.split(',').forEach(option =>{
data+=`
@Column()
${option};
`
});
}else{
data+=`
@Column()
column1:string;
@Column()
column2:string;
`
}
data += `
@CreateDateColumn({ type: "timestamp", default: () => "CURRENT_TIMESTAMP(6)" })
created_at: Date;
@UpdateDateColumn({ type: "timestamp", default: () => "CURRENT_TIMESTAMP(6)", onUpdate: "CURRENT_TIMESTAMP(6)" })
updated_at: Date;
} `;
return data;
}
}
|
882ba5f627e0e452565645aeb6238dc9a51d1ea5
|
TypeScript
|
PeculiarVentures/xmldsigjs
|
/src/pki/x509.ts
| 2.53125
| 3
|
import * as Asn1Js from "asn1js";
import { Certificate, CryptoEngineAlgorithmParams } from "pkijs";
import { ECDSA } from "../algorithms";
import { Application } from "../application";
export type DigestAlgorithm = string | "SHA-1" | "SHA-256" | "SHA-384" | "SHA-512";
/**
* List of OIDs
* Source: https://msdn.microsoft.com/ru-ru/library/windows/desktop/aa386991(v=vs.85).aspx
*/
const OID: { [key: string]: { short?: string, long?: string; }; } = {
"2.5.4.3": {
short: "CN",
long: "CommonName",
},
"2.5.4.6": {
short: "C",
long: "Country",
},
"2.5.4.5": {
long: "DeviceSerialNumber",
},
"0.9.2342.19200300.100.1.25": {
short: "DC",
long: "DomainComponent",
},
"1.2.840.113549.1.9.1": {
short: "E",
long: "EMail",
},
"2.5.4.42": {
short: "G",
long: "GivenName",
},
"2.5.4.43": {
short: "I",
long: "Initials",
},
"2.5.4.7": {
short: "L",
long: "Locality",
},
"2.5.4.10": {
short: "O",
long: "Organization",
},
"2.5.4.11": {
short: "OU",
long: "OrganizationUnit",
},
"2.5.4.8": {
short: "ST",
long: "State",
},
"2.5.4.9": {
short: "Street",
long: "StreetAddress",
},
"2.5.4.4": {
short: "SN",
long: "SurName",
},
"2.5.4.12": {
short: "T",
long: "Title",
},
"1.2.840.113549.1.9.8": {
long: "UnstructuredAddress",
},
"1.2.840.113549.1.9.2": {
long: "UnstructuredName",
},
};
/**
* Represents an <X509Certificate> element.
*/
export class X509Certificate {
protected raw: Uint8Array;
protected simpl: Certificate;
protected publicKey: CryptoKey | null = null;
constructor(rawData?: BufferSource) {
if (rawData) {
const buf = new Uint8Array(rawData as ArrayBuffer);
this.LoadRaw(buf);
this.raw = buf;
}
}
/**
* Gets a serial number of the certificate in BIG INTEGER string format
*/
public get SerialNumber(): string {
return this.simpl.serialNumber.valueBlock.toString();
}
/**
* Gets a issuer name of the certificate
*/
public get Issuer(): string {
return this.NameToString(this.simpl.issuer);
}
/**
* Gets a subject name of the certificate
*/
public get Subject(): string {
return this.NameToString(this.simpl.subject);
}
/**
* Returns a thumbprint of the certificate
* @param {DigestAlgorithm="SHA-1"} algName Digest algorithm name
* @returns Promise<ArrayBuffer>
*/
public async Thumbprint(algName: DigestAlgorithm = "SHA-1") {
return Application.crypto.subtle.digest(algName, this.raw);
}
/**
* Gets the public key from the X509Certificate
*/
public get PublicKey(): CryptoKey | null {
return this.publicKey;
}
/**
* Returns DER raw of X509Certificate
*/
public GetRaw(): Uint8Array {
return this.raw;
}
/**
* Returns public key from X509Certificate
* @param {Algorithm} algorithm
* @returns Promise<CryptoKey>
*/
public async exportKey(algorithm?: Algorithm | EcKeyImportParams | RsaHashedImportParams) {
if (algorithm) {
const alg = {
algorithm,
usages: ["verify"],
};
if (alg.algorithm.name.toUpperCase() === ECDSA) {
const json = this.simpl.subjectPublicKeyInfo.toJSON();
if ("crv" in json && json.crv) {
// Set named curve
(alg.algorithm as any).namedCurve = json.crv;
} else {
throw new Error("Cannot get Curved name from the ECDSA public key");
}
}
if (this.isHashedAlgorithm(alg.algorithm)) {
if (typeof alg.algorithm.hash === "string") {
alg.algorithm.hash = { name: alg.algorithm.hash };
}
}
const key = await this.simpl.getPublicKey({ algorithm: alg as CryptoEngineAlgorithmParams });
this.publicKey = key;
return key;
}
if (this.simpl.subjectPublicKeyInfo.algorithm.algorithmId === "1.2.840.113549.1.1.1") {
// Use default hash algorithm for RSA keys. Otherwise it throws an exception for unsupported mechanism (eg md5WithRSAEncryption)
this.publicKey = await this.simpl.getPublicKey({ algorithm: { algorithm: { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } }, usages: ["verify"] } });
} else {
this.publicKey = await this.simpl.getPublicKey();
}
return this.publicKey;
}
//#region Protected methods
/**
* Converts X500Name to string
* @param {RDN} name X500Name
* @param {string} splitter Splitter char. Default ','
* @returns string Formatted string
* Example:
* > C=Some name, O=Some organization name, C=RU
*/
protected NameToString(name: any, splitter: string = ","): string {
const res: string[] = [];
name.typesAndValues.forEach((typeAndValue: any) => {
const type = typeAndValue.type;
const oid = OID[type.toString()];
const name2 = oid ? oid.short : null;
res.push(`${name2 ? name2 : type}=${typeAndValue.value.valueBlock.value}`);
});
return res.join(splitter + " ");
}
/**
* Loads X509Certificate from DER data
* @param {Uint8Array} rawData
*/
protected LoadRaw(rawData: BufferSource) {
this.raw = new Uint8Array(rawData as ArrayBuffer);
const asn1 = Asn1Js.fromBER(this.raw.buffer);
this.simpl = new Certificate({ schema: asn1.result });
}
//#endregion
private isHashedAlgorithm(alg: Algorithm): alg is RsaHashedImportParams {
return !!(alg)["hash"];
}
}
|
d0ab58829480bf20b1c48ba338be27482ffd0d7d
|
TypeScript
|
vitordelfino/pokedex
|
/src/store/modules/typeahead/types.ts
| 2.609375
| 3
|
export interface TypeaheadState {
pokemons: string[];
search: string[];
}
export const TypeaheadTypes = {
SEARCH_POKEMONS: '@@typeahead::SEARCH_POKEMON',
SEARCH_POKEMONS_SUCCESS: '@@typeahead::SEARCH_POKEMON_SUCCESS',
SEARCH_POKEMONS_ERROR: '@@typeahead::SEARCH_POKEMON_ERROR',
FILTER_NAMES: '@@typeahead::FILTER_NAMES',
FILTER_NAMES_SUCCESS: '@@typeahead::FILTER_NAMES_SUCCESS',
};
interface TypeaheadActions {
type:
| typeof TypeaheadTypes.SEARCH_POKEMONS
| typeof TypeaheadTypes.SEARCH_POKEMONS_SUCCESS
| typeof TypeaheadTypes.SEARCH_POKEMONS_ERROR
| typeof TypeaheadTypes.FILTER_NAMES
| typeof TypeaheadTypes.FILTER_NAMES_SUCCESS;
payload: string[] | string;
}
export type TypeaheadActionTypes = TypeaheadActions;
|
08d8841109c77b4cc3baa0b4461607ae086a2c08
|
TypeScript
|
SarathLUN/metronic_v8.0.25_react
|
/demo1/src/_metronic/assets/ts/components/_SwapperComponent.ts
| 2.8125
| 3
|
import {
getAttributeValueByBreakpoint,
stringSnakeToCamel,
getObjectPropertyValueByKey,
EventHandlerUtil,
throttle,
} from '../_utils/index'
export class SwapperStore {
static store: Map<string, SwapperComponent> = new Map()
public static set(instanceId: string, drawerComponentObj: SwapperComponent): void {
if (SwapperStore.has(instanceId)) {
return
}
SwapperStore.store.set(instanceId, drawerComponentObj)
}
public static get(instanceId: string): SwapperComponent | undefined {
if (!SwapperStore.has(instanceId)) {
return
}
return SwapperStore.store.get(instanceId)
}
public static remove(instanceId: string): void {
if (!SwapperStore.has(instanceId)) {
return
}
SwapperStore.store.delete(instanceId)
}
public static has(instanceId: string): boolean {
return SwapperStore.store.has(instanceId)
}
public static getAllInstances() {
return SwapperStore.store
}
}
export interface ISwapperOptions {
mode: string
}
export interface ISwapperQueries {
componentName: string
instanseQuery: string
attrQuery: string
}
const defaultSwapperOptions: ISwapperOptions = {
mode: 'append',
}
const defaultSwapperQueires: ISwapperQueries = {
componentName: 'swapper',
instanseQuery: '[data-kt-swapper="true"]',
attrQuery: 'data-kt-swapper-',
}
class SwapperComponent {
element: HTMLElement
options: ISwapperOptions
queries: ISwapperQueries
constructor(_element: HTMLElement, _options: ISwapperOptions, _queries: ISwapperQueries) {
this.element = _element
this.options = Object.assign(defaultSwapperOptions, _options)
this.queries = _queries
// Initial update
this.update()
SwapperStore.set(this.element.id, this)
}
private getOption(name: string) {
const attr = this.element.getAttribute(`${this.queries.attrQuery}${name}`)
if (attr) {
let value = getAttributeValueByBreakpoint(attr)
if (attr != null && String(value) === 'true') {
return true
} else if (value !== null && String(value) === 'false') {
return false
}
return value
} else {
const optionName = stringSnakeToCamel(name)
const option = getObjectPropertyValueByKey(this.options, optionName)
if (option) {
return getAttributeValueByBreakpoint(option)
} else {
return null
}
}
}
///////////////////////
// ** Public API ** //
///////////////////////
public update = () => {
const parentSelector = this.getOption('parent')?.toString()
const mode = this.getOption('mode')
const parentElement = parentSelector ? document.querySelector(parentSelector) : null
if (parentElement && this.element.parentNode !== parentElement) {
if (mode === 'prepend') {
parentElement.prepend(this.element)
} else if (mode === 'append') {
parentElement.append(this.element)
}
}
}
// Event API
public on = (name: string, handler: Function) => {
return EventHandlerUtil.on(this.element, name, handler)
}
public one = (name: string, handler: Function) => {
return EventHandlerUtil.one(this.element, name, handler)
}
public off = (name: string) => {
return EventHandlerUtil.off(this.element, name)
}
public trigger = (name: string, event: Event) => {
return EventHandlerUtil.trigger(this.element, name, event)
}
// Static methods
public static getInstance = (
el: HTMLElement,
componentName: string = defaultSwapperQueires.componentName
): SwapperComponent | null => {
const place = SwapperStore.get(el.id)
if (place) {
return place as SwapperComponent
}
return null
}
public static createInstances = (
selector: string = defaultSwapperQueires.instanseQuery,
options: ISwapperOptions = defaultSwapperOptions,
queries: ISwapperQueries = defaultSwapperQueires
) => {
const elements = document.body.querySelectorAll(selector)
elements.forEach((el) => {
const item = el as HTMLElement
let place = SwapperComponent.getInstance(item)
if (!place) {
place = new SwapperComponent(item, options, queries)
}
})
}
public static createInsance = (
selector: string = defaultSwapperQueires.instanseQuery,
options: ISwapperOptions = defaultSwapperOptions,
queries: ISwapperQueries = defaultSwapperQueires
): SwapperComponent | undefined => {
const element = document.body.querySelector(selector)
if (!element) {
return
}
const item = element as HTMLElement
let place = SwapperComponent.getInstance(item)
if (!place) {
place = new SwapperComponent(item, options, queries)
}
return place
}
public static bootstrap = (selector: string = defaultSwapperQueires.instanseQuery) => {
SwapperComponent.createInstances(selector)
}
public static reinitialization = (selector: string = defaultSwapperQueires.instanseQuery) => {
SwapperComponent.createInstances(selector)
}
}
// Window resize handler
window.addEventListener('resize', function () {
let timer
throttle(
timer,
() => {
// Locate and update Offcanvas instances on window resize
const elements = document.querySelectorAll(defaultSwapperQueires.instanseQuery)
elements.forEach((el) => {
const place = SwapperComponent.getInstance(el as HTMLElement)
if (place) {
place.update()
}
})
},
200
)
})
export {SwapperComponent, defaultSwapperOptions, defaultSwapperQueires}
|
4eba0b6621b80c4dd1869fa30f38b3efb8355443
|
TypeScript
|
LCluber/Indium.js
|
/src/ts/zones/left.ts
| 2.578125
| 3
|
import { Zone } from './zone';
import { IZone } from '../interfaces';
import { Vector2 } from '@lcluber/type6js';
export class Left extends Zone implements IZone {
private limit: number;
constructor(limit: number) {
super();
this.limit = limit;
}
public contains(touchPosition: Vector2): boolean {
let elementWidth = this.htmlElement!.offsetWidth;
let limit = this.limit * elementWidth;
if (touchPosition.x <= limit) {
return true;
}
return false;
}
}
|
bff868ea26464b13315fabf9f311feffde6181d7
|
TypeScript
|
Dewscntd/AccuWeatherNgrx
|
/src/app/features/weather/store/reducers/location.reducer.ts
| 2.5625
| 3
|
import { createReducer, on, Action } from '@ngrx/store';
import * as fromLocationActions from '../actions/location.actions';
export interface LocationKeyState {
locationKey: string;
locationName: string;
error: Error;
}
const initialState: LocationKeyState = {
locationKey: null,
locationName: null,
error: null,
};
const scoreboardReducer = createReducer(
initialState,
on(fromLocationActions.GetCityKeyFromGeolocationApiStart, state => ({...state})),
on(fromLocationActions.GetCityKeyFromGeolocationApiFail, (state, {error}) => ({...state, error })),
on(fromLocationActions.GetCityKeyFromGeolocationApiSuccess, (state, action) => {
return {
...state,
locationKey: action.locationData.locationKey,
locationName: action.locationData.locationName
};
}),
on(fromLocationActions.GetCityKeyFromAutocompleteApiStart, state => ({...state})),
on(fromLocationActions.GetCityKeyFromAutocompleteApiSuccess, (state, {locationData}) => {
return {
...state,
locationKey: locationData.locationKey,
locationName: locationData.locationName
};
}),
on(fromLocationActions.GetCityKeyFromAutocompleteApiFail, (state, { error }) => ({...state, error}))
);
export function reducer(state: LocationKeyState | undefined, action: Action) {
return scoreboardReducer(state, action);
}
export const getLocationKey = (state: LocationKeyState) => state.locationKey;
export const getLocationName = (state: LocationKeyState) => state.locationName;
export const getWeatherLoadingError = (state: LocationKeyState) => state.error;
|
d50af900e397167b50740eb504f5d5a0816f4efc
|
TypeScript
|
yardenGoldy/hw_1
|
/backend/services/errors/unAuthorizedError.ts
| 2.53125
| 3
|
import { IStatus } from './status';
export class UnAuthorizedError extends Error implements IStatus {
statusCode: number;
constructor(message?: string) {
super(message || "Authentication credentials not valid.");
this.statusCode = 401;
}
}
|
60480754795a5799df057e43acf6afb78b8f8d0f
|
TypeScript
|
gabolauro/angular-rocks
|
/src/app/pipes/breakline.pipe.ts
| 2.671875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'breakline'
})
export class BreaklinePipe implements PipeTransform {
transform(text: string): string {
let parrafos = text.split('</br>');
let textoTodo = ''
for (var i = 0; i < parrafos.length; i++) {
textoTodo+=parrafos[i]+"\n\r"
}
[i]
return textoTodo;
}
}
|
d0667b498af5dc8ddf6dee90279e16128a26acea
|
TypeScript
|
youknowme786/fivee
|
/src/fivee.ts
| 2.734375
| 3
|
import { BaseData, FiveeOptions, APIResource } from './structures'
import axios, { AxiosResponse } from 'axios'
import { NotFoundError } from './errors'
import { AbilityScoresManager, ClassesManager, RacesManager, ConditionsManager } from './managers'
const defaultOptions: FiveeOptions = {
baseURL: 'https://www.dnd5eapi.co'
}
export function fivee (options: FiveeOptions = {}): Fivee {
return new Fivee(options)
}
export class Fivee {
public options: FiveeOptions
public races: RacesManager
public abilityScores: AbilityScoresManager
public classes: ClassesManager
public conditions: ConditionsManager
constructor(options: FiveeOptions = {}) {
this.options = Object.assign(defaultOptions, options)
this.abilityScores = new AbilityScoresManager(this)
this.classes = new ClassesManager(this)
this.conditions = new ConditionsManager(this)
this.races = new RacesManager(this)
}
private extractReferenceURL(reference: string | APIResource): string {
return typeof reference === 'string' ? reference : reference.url
}
async getResource(reference: string | APIResource): Promise<AxiosResponse> {
const resourceURL = this.extractReferenceURL(reference),
baseURL = this.options.baseURL
return axios.get(baseURL + resourceURL)
}
async resolveResource<T extends BaseData>(reference: string | APIResource): Promise<T> {
return new Promise<T>((resolve, reject) => {
this.getResource(reference)
.then(res => {
resolve(res.data)
})
.catch(err => {
if (err.response) {
if (err.response.status === 404)
err = new NotFoundError(this, this.extractReferenceURL(reference))
}
reject(err)
})
})
}
async resolveResources<T extends BaseData>(references: Array<string | APIResource>): Promise<T[]> {
return new Promise<T[]>((resolve, reject) => {
let resolved = 0;
const resources: T[] = []
references.forEach((reference, index) => {
this.resolveResource<T>(reference)
.then(res => {
resources[index] = res
if (++resolved === references.length) resolve(resources)
})
.catch(reject)
})
})
}
async resolveCollection(reference: string | APIResource): Promise<APIResource[]> {
return new Promise<APIResource[]>((resolve, reject) => {
const url = this.options.baseURL + this.extractReferenceURL(reference)
axios.get(url)
.then(res => {
if (Array.isArray(res.data)) resolve(res.data)
else if ('results' in res.data) resolve(res.data.results)
})
.catch(reject)
})
}
}
|
b75598a6fb3c3e0336008a0d2ab97a3c90fa0836
|
TypeScript
|
ubl-chj/mirador-monorepo
|
/packages/mirador-core/src/selectors/windows.ts
| 2.6875
| 3
|
import {ICompanionWindow, IWindow} from 'mirador-core-model';
import {createSelector} from 'reselect'
import {getManifestTitle} from './manifests';
/** */
export const getWindow = (state: any, { windowId}: {windowId: string, position?: string}) => {
return state.windows && state.windows[windowId];
}
/** Return position of thumbnail navigation in a certain window.
* @param {object} state
* @param {String} windowId
* @param {String}
*/
export const getThumbnailNavigationPosition = createSelector(
[getWindow, (state: any) => state.companionWindows],
(window: any, companionWindows: ICompanionWindow) => window
&& companionWindows[window.thumbnailNavigationId]
&& companionWindows[window.thumbnailNavigationId].position,
);
/** Return type of view in a certain window.
* @param {object} state
* @param {object} props
* @param {string} props.manifestId
* @param {string} props.windowId
* @param {String}
*/
export const getWindowViewType = createSelector(
getWindow,
(window: IWindow) => window && window.view,
);
/**
* Return compantion window ids from a window
* @param {String} windowId
* @return {Array}
*/
export const getCompanionWindowIds = createSelector(
getWindow,
(window: IWindow) => (window && window.companionWindowIds) || [],
);
/**
* Return companion windows of a window
* @param {String} windowId
* @return {Array}
*/
export const getCompanionWindowsOfWindow = createSelector(
[getCompanionWindowIds, (state: any) => state.companionWindows],
(companionWindowIds: [], companionWindows: ICompanionWindow) => companionWindowIds.map(id => companionWindows[id]),
);
/**
* Return the companion window string from state in a given windowId and position
* @param {object} state
* @param {String} windowId
* @param {String} position
* @return {String}
*/
export const getCompanionWindowForPosition = createSelector(
[getCompanionWindowsOfWindow, (state) => state.config.companionWindows.defaultPosition],
(companionWindows: any, position) => companionWindows.find(cw => cw.position === position),
);
|
9137fcd2c749cc422f6b76bb028e58f6b1effd00
|
TypeScript
|
Reynals/discord-bot-ts
|
/src/classes/bot.ts
| 2.765625
| 3
|
import { ApplicationCommandOption, Client, ClientOptions } from "discord.js";
import { Collection } from 'discord.js';
import { promises, readdirSync } from 'fs';
import { join } from 'path';
class bot extends Client {
// Defining the custom properties
commands: Collection<string, Command> = new Collection();
categoires: Array<string> = readdirSync(join(__dirname, '../commands'));
extension: string = "ts";
// array of owner's Discord IDs
// Make sure to at least remove my ID from the array ( it is just a placeholder )
owners: string[] = ["441943765855240192"];
constructor(options: ClientOptions) {
super(options);
// Changing the properties according to the NODE_ENV mode
if (join(__dirname, '../commands').includes("build\\")) {
this.extension = "js";
}
this.setCommands();
this.handleEvents();
}
async setCommands() {
const categories = await promises.readdir(join(__dirname, `../commands`));
categories.forEach(async cat => {
// Reading the directories which are inside command directory
const commands = (await promises.readdir(join(__dirname, `../commands/${cat}`))).filter(file => file.endsWith(this.extension));
for (let i = 0; i < commands.length; i++) {
const file = commands[i];
// Getting the command
const command: Command = require(`../commands/${cat}/${file}`)?.default || {};
// Throwing the error if the file do not have a command
if (!command.name || typeof (command.run) !== "function") throw new SyntaxError("A command should have `data` property and a `execute` method");
// Setting the command
this.commands.set(command.name, command);
}
})
}
async handleEvents() {
// Getting all the events listed in "/events" folder
const events = await promises.readdir(join(__dirname, `../events`));
for (let i = 0; i < events.length; i++) {
const event = require(`../events/${events[i]}`)?.default || {};
if (!event || typeof (event) !== "function") return; // Not a valid event file
this.on(events[i].split(".")[0], (...args) => event(this, ...args))
}
}
}
export default bot;
interface Command {
name: string,
description: string,
category: string,
slash: boolean,
args?: string,
aliases?: Array<string>,
timeout?: number,
options: ApplicationCommandOption[],
run: Function
}
|
38622f83ad77b00575ace254736b592b1100c39c
|
TypeScript
|
HTMLProgrammer2001/messangerClient
|
/src/utils/helpers/secondsToTime.test.ts
| 2.75
| 3
|
import secondsToTime from './secondsToTime';
describe('Test seconds to time function', () => {
const vals: [number, string][] = [
[0, '03:00AM'],
[(3600 + 183) * 1000, '04:03AM'],
[(3600 * 11 + 300) * 1000, '02:05PM']
];
it('Test', () => {
for(let [time, str] of vals)
expect(secondsToTime(time)).toBe(str);
});
});
|
051aaf79a6a3e84eee2318d589b582c896974c7e
|
TypeScript
|
saijeevanballa/chat-socket.io
|
/chat-be/src/utils/authenticate.ts
| 2.5625
| 3
|
import { jwt_Verify } from "./modules/jwt";
import APIError from "./custom-error";
import { userSchema } from "../users/model";
// USER AUTHENTICATION
export default async function authenticate(req: any, res: any, next: any) {
try {
if (!req.headers.authorization) throw new Error("Missing Token.")
let token: any = await jwt_Verify(req.headers.authorization.substring(7))
if (!token) next(new APIError("Invalid Token", 400));
const user: any = await userSchema.findOne({ _id: token.user }).exec();
if (!user) next(new APIError("Invalid Action", 400));
res.user = user;
res.userId = user.id
return next();
} catch (err) {
return next(new APIError('Unauthorized', 401));
};
};
// USER AUTHENTICATION
export async function authenticateWithToken(authorization) {
try {
let token: any = await jwt_Verify(authorization.substring(7))
if (!token) throw new APIError("Invalid Token", 400);
const user: any = await userSchema.findOne({ _id: token.user }).exec();
if (!user) throw new APIError("Invalid Action", 400);
return user;
} catch (err) {
throw err
};
};
|
55976c6ac27bfcb1dbb480879effa3be298122eb
|
TypeScript
|
volunux/Student-Support-and-Thesis-Management-System
|
/src/app/shared/misc/dynamic-form-validators.ts
| 2.578125
| 3
|
import { FormGroup } from '@angular/forms';
import { dynamicDataValidator } from '../services/dynamic-control-validator';
export class DynamicFormValidators {
public static createPermanent(entry , datas : { [key : string] : any } , form : FormGroup) : void {
if (datas != null) {
for (let $prop in datas) {
let propVal = $prop.toLowerCase().split(' ').join(' ');
entry.permanentData[propVal] = datas[$prop];
form.get(propVal) ? form.get(propVal).setValidators([...entry.permanentProps[propVal] , dynamicDataValidator(entry.getMyData(propVal) , $prop)]) : null;
form.get(propVal) ? form.get(propVal).updateValueAndValidity() : null;
}
form.updateValueAndValidity(); }
}
public static removeControls(controls : string[] , form : FormGroup) : void {
if (controls != null && controls.length > 0) {
controls.forEach((control) => { let ctrl = form.get(control);
return ctrl ? form.removeControl(control) : null; }); }
}
public static removeAsyncValidators(controls : string[] , form : FormGroup) : void {
if (controls != null && controls.length > 0) {
controls.forEach((control) => {
if (form.get(control)) {
form.get(control).clearAsyncValidators();
form.get(control).updateValueAndValidity(); } });
form.updateValueAndValidity(); }
}
}
|
078311041873a8573856f862fa210eefac3099ca
|
TypeScript
|
rzvpopescu/typy
|
/lib/Bindings/PropertyBindings/ValueBinder.ts
| 2.53125
| 3
|
import {PropertyBinder} from './PropertyBinder';
import {ExpressionsHelper} from '../ExpressionsHelper';
import {ObserverEngine} from '../../Observer/Observer';
export class ValueBinder extends PropertyBinder {
protected BINDING_ATTRIBUTE = "value.bind";
elementBind(element: HTMLElement, viewModel: any, expression: string): void {
this.handleSpecificElementBind(element,viewModel,expression);
ObserverEngine.observeExpression(expression, viewModel, (value: any, oldValue: any) => {
(<HTMLInputElement>element).value = value;
});
}
handleSpecificElementBind(element:HTMLElement,viewModel:any,expression:string):void{
let elementType = (<HTMLInputElement>element).type;
switch (elementType) {
case 'select-one':
this.handleSelectElement(<HTMLSelectElement>element,viewModel,expression);
break;
case 'text':
case 'number':
this.handleTextInputElement(<HTMLInputElement>element,viewModel,expression);
default:
break;
}
}
handleSelectElement(element:HTMLSelectElement,viewModel:any,expression:string):void{
element.addEventListener('change',(ev)=>{
let selectedOptions = element.selectedOptions;
let value = (<HTMLOptionElement> selectedOptions[0]).value;
super.setExpressionValue(expression,viewModel,value);
});
}
handleTextInputElement(element:HTMLInputElement,viewModel:any,expression:string):void{
(<HTMLInputElement>element).addEventListener('input', (ev) => {
let value = (<HTMLInputElement>element).value;
super.setExpressionValue(expression,viewModel,value);
});
}
}
|
0052765cc3bebe940a6a04394dcea0a1a987b65c
|
TypeScript
|
Dead-Crumb-Trail/node-backend
|
/src/services/hash.ts
| 2.671875
| 3
|
import { Service } from 'typedi';
import crypto from 'crypto';
import { HashResult } from '../models/internal';
import { logger } from '../util/logger';
@Service()
export class HashingService {
constructor() {}
async withSalt(value: string): Promise<HashResult> {
const salt = crypto.randomBytes(16).toString('hex');
logger.debug(`Hashing ${value} with ${salt}`);
const key = await this.createHash(value, salt);
return new HashResult(key.toString('hex'), salt);
}
private async createHash(value: string, salt: string): Promise<Buffer> {
return new Promise((resolve, reject) => {
crypto.scrypt(value, salt, 64, (err, key) => {
if (err) reject(err);
resolve(key);
});
});
}
async verify(hash: HashResult, value: string): Promise<boolean> {
const aKey = Buffer.from(hash.cipher, 'hex');
const key = await this.createHash(value, hash.salt);
return crypto.timingSafeEqual(key, aKey);
}
}
|
5a4306e173998efcb6af279224593a8cdd4b076d
|
TypeScript
|
jwworth/conway
|
/src/app_helper.ts
| 2.859375
| 3
|
import { chunk } from 'lodash';
const PURPLES = [
'#e6e6fa',
'#d8bfd8',
'#dda0dd',
'#ee82ee',
'#da70d6',
'#ff00ff',
'#ff00ff',
'#ba55d3',
'#9370db',
'#8a2be2',
'#9400d3',
'#9932cc',
'#8b008b',
'#800080',
'#4b0082',
];
export const randomColor = (): string =>
PURPLES[Math.floor(Math.random() * PURPLES.length)];
export const randomWorld = (
sideLength: number,
randomness: number
): number[][] => {
const world = [];
for (let i = 0; i < sideLength ** 2; i++) {
const sentience = Number(Math.random() < randomness);
world.push(sentience);
}
return chunk(world, sideLength);
};
|
e265077f56b2c8791b505de28e9ba2f083d3870f
|
TypeScript
|
gabrielgraciani/next-reactmon-backend
|
/src/modules/cities/services/ListCitiesService.ts
| 2.734375
| 3
|
import { getCustomRepository } from 'typeorm';
import CitiesRepository from '../repositories/CitiesRepository';
import City from '../models/City';
interface Request {
offset: number;
limit: number;
}
interface Response {
data: City[];
total_records: number;
}
class ListCitiesService {
public async execute({ offset = 0, limit }: Request): Promise<Response> {
const citiesRepository = getCustomRepository(CitiesRepository);
const cities = await citiesRepository.findAndCount({
skip: offset,
take: limit,
order: {
created_at: 'DESC',
},
});
const [citiesResult, citiesCount] = cities;
return { data: citiesResult, total_records: citiesCount };
}
}
export default ListCitiesService;
|
014d72d55a81bef2a77cc1a5358d343a147540b4
|
TypeScript
|
issaafalkattan/zira-ui
|
/src/utils/statusUtils.ts
| 2.59375
| 3
|
import { TicketStatus } from '../types/index';
export const getTagColor = (status: TicketStatus): string => {
switch (status) {
case "OPEN":
return "magenta";
case "PENDING":
return "cyan";
case "CLOSED":
return "green";
default:
return "red";
}
};
|
5f1356709fdbdf43bb1e2a1af5e3fe1f234f517c
|
TypeScript
|
LukaGrdinic/Angular-Modular-Forms
|
/src/app/custom-validators.ts
| 2.71875
| 3
|
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export class CustomValidators {
static minDate(minDate: Date): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const isControlOk: boolean = control.value ? new Date(control.value) > minDate : true;
if (!isControlOk) {
return {
minDate: true,
};
}
return null;
};
}
}
|
037a2a631c0127e8bfb2bbdf71f9c9a4b4545f0e
|
TypeScript
|
gitter-badger/alloy
|
/source/config/Properties.ts
| 3.234375
| 3
|
import { ramda as R } from "../../vendor/npm";
/**
* Defines Alloy configuration properties and provides basic utilities for
* working with them.
*
* @author Joel Ong ([email protected])
*/
export default class Properties {
// Available properties.
public static BUILD_DIRECTORY: string = "out";
public static EXCLUDE: string = "exclude";
public static SOURCES: string = "src";
// Property type information.
public static LIST_PROPERTIES: string[] = [
Properties.EXCLUDE,
Properties.SOURCES
];
public static STRING_PROPERTIES: string[] = [
Properties.BUILD_DIRECTORY
];
/**
* Returns true if the given value is a valid Alloy configuration property.
*/
public static isValid(property: string): boolean {
return Properties.isList(property) || Properties.isString(property);
}
/**
* Returns true if the given property is a valid Alloy configuration property
* whose value is a string.
*/
public static isString(property: string): boolean {
return R.contains(property, Properties.STRING_PROPERTIES);
}
/**
* Returns true if the given property is a valid Alloy configuration property
* whose value is a list of strings.
*/
public static isList(property: string): boolean {
return R.contains(property, Properties.LIST_PROPERTIES);
}
/**
* Checks if the given string is a valid Alloy configuration property,
* otherwise throws an error.
* @param value Optional value on which to perform type validation.
*/
public static validate(property: string, value?: any): void {
if (!Properties.isValid(property)) {
throw new Error(`"${property}" is not a valid configuration property.`);
}
if (value === undefined) {
return;
}
if (Properties.isString(property)) {
Properties.validateString(property, value);
} else if (Properties.isList(property)) {
Properties.validateList(property, value);
}
}
/**
* Checks if the given property is a valid Alloy configuration property
* whose value is a string, otherwise throws an error.
* @param value Optional value on which to perform type validation.
*/
public static validateString(property: string, value?: any): void {
Properties.validate(property);
if (!Properties.isString(property)) {
throw new Error(
`"${property}" is not a valid string configuration property.`);
}
if (value !== undefined && typeof value !== "string") {
throw new Error(
`"${value}" is not a valid string value for property "${property}".`);
}
}
/**
* Checks if the given property is a valid Alloy configuration property
* whose value is a list of strings, otherwise throws an error.
* @param value Optional value on which to perform type validation.
*/
public static validateList(property: string, value?: any): void {
Properties.validate(property);
if (!Properties.isList(property)) {
throw new Error(
`"${property}" is not a valid list configuration property.`);
}
if (value === undefined) {
return;
}
let listErr = new Error(`'${value}' is not a valid list of strings for`
+ ` property "${property}."`);
let parsedValue = value;
if (typeof value === "string") {
try {
parsedValue = JSON.parse(value);
} catch (e) {
throw listErr;
}
}
if (typeof parsedValue !== "object" || !Array.isArray(parsedValue)) {
throw listErr;
}
for (let elem of parsedValue) {
if (typeof elem !== "string") {
throw new Error(
`"${elem}" is not a valid string for property "${property}".`);
}
}
}
}
|
af58106a42da8451b0311865f5818fd1282d081b
|
TypeScript
|
typedninja/flowable
|
/src/lib/utils.ts
| 2.6875
| 3
|
export function restack (error: Error, ignore: Function = restack): Error {
if (error.stack !== undefined) {
const stackObj = { stack: '' }
Error.captureStackTrace(stackObj, ignore)
const stackLines = stackObj.stack.split('\n')
stackLines.shift()
const newStack = stackLines.join('\n')
error.stack = error.stack + '\n' + newStack
}
return error
}
|
9da0b16785674b06413c6b2dadd8517d76ca254f
|
TypeScript
|
afroradiohead/yumi-interview
|
/src/app.service.ts
| 2.640625
| 3
|
import {Injectable} from '@nestjs/common';
import {EntityManager} from 'typeorm';
import {Order} from './models/order.entity';
import * as moment from 'moment';
import {get} from 'lodash';
interface IFindOrdersProps {
user_id: number | string;
delivery_date?: string;
per?: number | string;
page?: number | string;
sort?: 'delivery_date' | 'id';
direction?: 'ASC' | 'DESC';
}
@Injectable()
export class AppService {
constructor(
private readonly entityManager: EntityManager,
) {}
async findOrders(props: IFindOrdersProps): Promise<any> {
const allowedSortMap = {
delivery_date: 'o.delivery_date',
id : 'o.id',
};
const allowedDirectionMap = {
DESC: 'DESC',
ASC: 'ASC',
};
const deliveryDateMoment = moment(props.delivery_date || null);
const per = Math.floor(+props.per) || 4;
const page = Math.max(Math.floor(+props.page), 1) || 1;
const sort = get(allowedSortMap, props.sort, allowedSortMap.id);
const direction = get(allowedDirectionMap, (props.direction || '').toUpperCase(), allowedDirectionMap.ASC);
let orderQuery = this.entityManager.createQueryBuilder(Order, 'o')
.leftJoinAndSelect('o.attributes', 'order_attributes')
.leftJoinAndSelect('order_attributes.meal', 'meals')
.where('o.user_id = :user_id', { user_id: props.user_id })
.take(per)
.skip((page - 1) * per)
.orderBy(sort, direction);
if (deliveryDateMoment.isValid()){
orderQuery = orderQuery.andWhere(
'o.delivery_date = :delivery_date',
{delivery_date: deliveryDateMoment.format('YYYY-MM-DD')},
);
}
const orders = await orderQuery.getMany();
return orders.map(order => {
const meals = order.attributes.map(attribute => ({
id: attribute.meal.id,
quantity: attribute.quantity,
name: attribute.meal.name,
description: attribute.meal.description,
image_url: attribute.meal.image_url,
}));
return {
id: order.id,
delivery_date: moment(order.delivery_date).format('YYYY-MM-DD'),
meal_count: meals.reduce((acc, meal) => acc + meal.quantity, 0),
meals,
};
});
}
}
|
b8419e5e7e82e824e791db7cc88b6392779b4528
|
TypeScript
|
ficsit/data-landing
|
/interfaces/structs/FExponentialFogSettings.ts
| 2.640625
| 3
|
import { float } from '../native/primitive';
import { LinearColor } from '../native/structs';
export interface FExponentialFogSettings {
/**
* The ZValue of the fog
*/
FogHeight: float;
/**
* Density of the fog
*/
FogDensity: float;
FogInscatteringColor: LinearColor;
/**
* Distance at which InscatteringColorCubemap should be used directly for the Inscattering Color.
*/
FullyDirectionalInscatteringColorDistance: float;
/**
* Distance at which only the average color of InscatteringColorCubemap should be used as Inscattering Color.
*/
NonDirectionalInscatteringColorDistance: float;
DirectionalInscatteringExponent: float;
DirectionalInscatteringStartDistance: float;
DirectionalInscatteringColor: LinearColor;
FogHeightFalloff: float;
FogMaxOpacity: float;
/**
* Distance from the camera that the fog will start, in world units.
*/
StartDistance: float;
/**
* Scene elements past this distance will not have fog applied. This is useful for excluding skyboxes which already have fog baked in.
*/
FogCutoffDistance: float;
}
|
f9ef18b66f4b678969b7425626d88bba4918f715
|
TypeScript
|
Portia-Nelly-Mashaba/ToDoList-Typescript
|
/index.ts
| 2.546875
| 3
|
// Import stylesheets
import './style.css';
// Write TypeScript code!
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = `<h1>TypeScript Starter</h1>`;
let ToDoList = [
{taskName: "MarkRegister", taskDate: "2020/08/17", taskStatus: "Done"},
{taskName: "DoHouseChores", taskDate: "2020/08/17", taskStatus: "ToDo"},
{taskName: "EnrollUdemy", taskDate: "2020/08/19", taskStatus: "ToDo"},
{taskName: "BookCodeMeeting", taskDate: "2020/08/20", taskStatus: "Pending"},
{taskName: "StudyTypescript", taskDate: "2020/08/17", taskStatus: "Pending"},
{taskName: "Shopping", taskDate: "2020/08/21", taskStatus: "ToDo"},
{taskName: "StartGym", taskDate: "2020/08/20", taskStatus: "Pending"},
{taskName: "CookSupper", taskDate: "2020/08/17", taskStatus: "Done"},
{taskName: "AttendBusinessSeminar", taskDate: "2020/08/18", taskStatus: "ToDo"},
{taskName: "StudyAngular", taskDate: "2020/08/31", taskStatus: "ToDo"}
];
//Log console before change
console.log("Before update: ", ToDoList[4]);
//Update Status
ToDoList[4].taskStatus = "Done";
//Log console after change
console.log("After update: ", ToDoList[4]);
|
84ad25ea266257fa771680790cae6a0a7dfd71fc
|
TypeScript
|
Eriickson/PROYECTO-INTEGRADOR-I-PROYECTO-FINAL-SERVER
|
/src/gcp/makePrivateFile.ts
| 2.546875
| 3
|
import bucket from "./bucketMain";
interface IMakeFilePrivateArgs {
destination: string;
metadata: Record<string, string>;
}
export default async function makeFilePrivate({ destination, metadata }: IMakeFilePrivateArgs) {
// Seteamos la metadata al archivo y luego lo hacemos privado
await bucket.file(destination).setMetadata({ metadata });
await bucket.file(destination).makePrivate();
}
|
20598d369cb1cfba01ca8732ed5e9c19863717bd
|
TypeScript
|
RoelVB/pnpjs
|
/packages/graph/onedrive/users.ts
| 2.609375
| 3
|
import { addProp } from "@pnp/queryable";
import { _User } from "../users/types.js";
import { IDrive, Drive, IDrives, Drives, _Drive, DriveItem, IDriveItem } from "./types.js";
declare module "../users/types" {
interface _User {
readonly drive: IDrive;
readonly drives: IDrives;
}
interface IUser {
readonly drive: IDrive;
readonly drives: IDrives;
}
}
addProp(_User, "drive", Drive);
addProp(_User, "drives", Drives);
declare module "./types" {
interface _Drive {
special(specialFolder: SpecialFolder): IDriveItem;
}
interface IDrive {
special(specialFolder: SpecialFolder): IDriveItem;
}
}
/**
* Get special folder (as drive) for a user.
*/
_Drive.prototype.special = function special(specialFolder: SpecialFolder): IDriveItem {
return DriveItem(this, `special/${specialFolder}`);
};
export enum SpecialFolder {
"Documents" = "documents",
"Photos" = "photos",
"CameraRoll" = "cameraroll",
"AppRoot" = "approot",
"Music" = "music",
}
|
c8303c53a2b3cd6f4931dba69c26c96289b724f0
|
TypeScript
|
JoshRosenstein/styleaux
|
/packages/styleaux-styles-base/src/mdn/scroll-snap/scrollMarginLeft.ts
| 2.859375
| 3
|
import { Config } from '../../types';
import { style, styler, GetValue } from '@styleaux/core';
import { ScrollMarginLeftProperty } from '@styleaux/csstype';
const SCROLLMARGINLEFT = 'scrollMarginLeft';
export interface ScrollMarginLeftProps<T = ScrollMarginLeftProperty> {
/**
* The `scroll-margin-left` property defines the left margin of the scroll snap area that is used for snapping this box to the snapport. The scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
*
* **Initial value**: `0`
*
* | Chrome | Firefox | Safari | Edge | IE |
* | :----: | :-----: | :----: | :--: | :-: |
* | **69** | No | **11** | No | No |
*
* @see https://developer.mozilla.org/docs/Web/CSS/scroll-margin-left
*/
[SCROLLMARGINLEFT]: T;
}
export const createScrollMarginLeft = <
T = ScrollMarginLeftProperty,
Media = never,
Theme = never
>(
config: Config<ScrollMarginLeftProps<T>, Theme> = {},
) =>
style<ScrollMarginLeftProps<T>, Theme, Media>({
cssProp: SCROLLMARGINLEFT,
prop: SCROLLMARGINLEFT,
...config,
});
export const createScrollMarginLeftRule = <
T = ScrollMarginLeftProperty,
P = unknown
>(
transformer?: GetValue<T, P>,
) => styler<T, P>({ cssProp: SCROLLMARGINLEFT, getValue: transformer });
export const scrollMarginLeft = createScrollMarginLeft();
export const scrollMarginLeftRule = createScrollMarginLeftRule();
|
dbbd72b0fc48a7879f5c425975380d95d6b833ab
|
TypeScript
|
yasoonOfficial/adf-builder-javascript
|
/dist/nodes/index.d.ts
| 2.921875
| 3
|
export interface Typed {
type: string;
[key: string]: any;
}
export interface JSONable {
toJSON: () => Typed;
}
export declare class ContentNode<T extends JSONable> {
private readonly type;
private readonly minLength;
private content;
constructor(type: string, minLength?: number);
toJSON(): {
type: string;
content: Typed[];
};
add<U extends T>(node: U): U;
readonly length: number;
getItem(index: number): T;
}
export declare abstract class TopLevelNode implements JSONable {
abstract toJSON(): Typed;
}
export declare abstract class InlineNode implements JSONable {
abstract toJSON(): Typed;
}
|
def406d8a28f74b029d3432365fbe9b8db6e209b
|
TypeScript
|
karinariv/libraryAPI
|
/repositories/bookRepository.ts
| 2.640625
| 3
|
import { DeleteResult, getRepository, Repository } from "typeorm";
import { Book } from "../models/books";
export default class BookRepository {
private repository_: Repository<Book>;
constructor () {
}
private get repository(): Repository<Book> {
if(!this.repository_){
this.repository_ = getRepository(Book);
}
return this.repository_;
}
async registerBook(title: string, releaseYear: string, category: string, currentReader_id: number){
let book = new Book();
book.title = title;
book.releaseYear = releaseYear;
book.category = category;
book.currentReader_id = currentReader_id;
return await this.repository.save(book);
}
async showAllBooks(): Promise<Book[]>{
return await this.repository.find();
}
async showOneBook(book_id: string): Promise<Book>{
return await this.repository.findOne(book_id);
}
async updateBook(book_id: string, title: string, releaseYear: string, category: string, currentReader_id: number): Promise<Book>{
let newProd = await this.repository.findOne(book_id);
newProd.title = title;
newProd.releaseYear = releaseYear;
newProd.category = category;
newProd.currentReader_id = currentReader_id;
return await this.repository.save(newProd);
}
async deleteBook(book_id: string): Promise<DeleteResult>{
return await this.repository.delete(book_id);
}
}
|
cbd63ee8022735e505ecc32850f9d9062d6a76d5
|
TypeScript
|
e-cloud/ngxs-store
|
/packages/store/src/operators/of-action.ts
| 2.890625
| 3
|
import { OperatorFunction, Observable, MonoTypeOperatorFunction } from 'rxjs';
import { map, filter } from 'rxjs/operators';
import { getActionTypeFromInstanceOrClass, getActionTypeFromClass } from '../utils/utils';
import { ActionContext, ActionStatus } from '../actions-stream';
import { ActionType, IAction } from '../symbols';
export function ofAction<T>(allowedType: ActionType<T>): OperatorFunction<any, T>;
export function ofAction<T>(...allowedTypes: ActionType<T>[]): OperatorFunction<any, T>;
/**
* RxJS operator for selecting out specific actions.
*
* This will grab actions that have just been dispatched as well as actions that have completed
*/
export function ofAction<T>(...allowedTypes: ActionType<T>[]) {
return ofActionOperator(allowedTypes);
}
/**
* RxJS operator for selecting out specific actions.
*
* This will ONLY grab actions that have just been dispatched
*/
export function ofActionDispatched<T>(...allowedTypes: ActionType<T>[]) {
return ofActionOperator(allowedTypes, ActionStatus.Dispatched);
}
/**
* RxJS operator for selecting out specific actions.
*
* This will ONLY grab actions that have just been successfully completed
*/
export function ofActionSuccessful<T>(...allowedTypes: ActionType<T>[]) {
return ofActionOperator(allowedTypes, ActionStatus.Successful);
}
/**
* RxJS operator for selecting out specific actions.
*
* This will ONLY grab actions that have just been canceled
*/
export function ofActionCanceled<T>(...allowedTypes: ActionType<T>[]) {
return ofActionOperator(allowedTypes, ActionStatus.Canceled);
}
/**
* RxJS operator for selecting out specific actions.
*
* This will ONLY grab actions that have just thrown an error
*/
export function ofActionErrored<T>(...allowedTypes: ActionType<T>[]) {
return ofActionOperator(allowedTypes, ActionStatus.Errored);
}
function ofActionOperator<T>(allowedTypes: ActionType<T>[], status?: ActionStatus) {
const allowedMap = createAllowedMap(allowedTypes);
return function(actions: Observable<ActionContext<T>>) {
return actions.pipe(
filterStatus(allowedMap, status),
mapAction<T>()
);
};
}
function filterStatus(allowedTypes: Record<string, boolean>, status?: ActionStatus) {
return filter((ctx: ActionContext<IAction>) => {
const actionType = getActionTypeFromInstanceOrClass(ctx.action!)!;
const type = allowedTypes[actionType];
return status ? type && ctx.status === status : type;
}) as MonoTypeOperatorFunction<any>;
}
function mapAction<T>() {
return map((ctx: ActionContext<T>) => ctx.action!);
}
function createAllowedMap<T>(types: ActionType<T>[]) {
return types.reduce(
(acc, klass) => {
acc[getActionTypeFromInstanceOrClass(klass)!] = true;
return acc;
},
<Record<string, boolean>>{}
);
}
|
1423217f3935e7912829bb54fcd5f99e550111d9
|
TypeScript
|
coolba73/InsightStudioAlways
|
/src/app/myapp/common/shapeobject/SelectBox.ts
| 2.78125
| 3
|
import { BaseObject } from "./BaseObject";
export class SelectBox extends BaseObject{
x1 : number;
x2 : number;
y1 : number;
y2 : number;
//________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
constructor(){
super();
this.Type = SelectBox.name;
}
//________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
Draw(ctx:CanvasRenderingContext2D){
let width = Math.abs(this.x1 - this.x2);
let hegith = Math.abs(this.y1 - this.y2);
let x = Math.min(this.x1, this.x2);
let y = Math.min(this.y1, this.y2);
ctx.beginPath();
ctx.setLineDash([1,1]);
ctx.rect(x,y, width, hegith);
ctx.lineWidth = 1;
ctx.strokeStyle = 'gray';
//ctx.fill();
ctx.stroke();
}
}//class
|
94a81e1ffdf703aedf988f14d4762f46dc817cf8
|
TypeScript
|
Str4thus/p5-Columbus-App
|
/src/app/services/socket/socket.service.ts
| 2.59375
| 3
|
import { Injectable, Inject } from '@angular/core';
import { SocketConfiguration, defaultSocketConfiguration } from 'src/columbus/data-models/socket/SocketConfiguration';
import { ModuleDataService } from '../module-data/module-data.service';
import { CommandService } from '../command/command.service';
import { ColumbusCommand } from 'src/columbus/data-models/command/ColumbusCommand';
import { OpCode, ColumbusModuleType } from 'src/columbus/data-models/Enums';
import { ColumbusModule } from 'src/columbus/data-models/modules/ColumbusModule';
import { Utils } from 'src/columbus/util/Utils';
@Injectable({
providedIn: 'root'
})
/**
* Manages the communication with the web socket on Columbus.
*/
export class SocketService {
_socketConfiguration: SocketConfiguration;
_socket: WebSocket | any = null; /** Can either be a real WebSocket or a mock instance. */
_isConnected: boolean = false;
cameraURL;
constructor(private commandService: CommandService, private moduleDataService: ModuleDataService, @Inject("MockSocket") mockSocket) {
this._initSocket(defaultSocketConfiguration, mockSocket); // mockSocket can be null, thus the socket is not mocked
this.commandService.subscribeToQueue(() => this._queueUpdateCallback());
}
/**
* Callback that gets invoked when the socket connection is established.
* @param event event data
*/
_onOpenCallback(event) {
this._isConnected = true;
}
/**
* Callback that gets invoked when the web socket sends a message to us. It handles the different operation codes and extracts the data correctly.
* Throws an error, if the provided operation code has no mapping in the corresponding enum.
* @param event event data
*/
_onMessageCallback(event) {
let data = JSON.parse(event.data);
let opCode = data["op"];
console.log("-----");
console.log("Received command: ");
console.log(data);
console.log("-----");
switch (opCode) {
case OpCode.DISPATCH: // d: {affected_module: "cam", updates: {"vrot": 90, "hrot": 30}}
let affectedModule = data["d"]["t"];
let changesToApply = data["d"]["p"];
this._handleDispatch(affectedModule as ColumbusModuleType, changesToApply);
break;
case OpCode.STATE_UPDATE: // d: {"cam": true", "lidar": false", "engine": true}
let changedModules = data["d"];
this._handleStateUpdate(changedModules);
break;
case OpCode.HEARTBEAT:
this._handleHeartbeat();
break;
default:
throw new Error("Invalid OpCode!");
}
}
/**
* Callback that gets invoked when the socket connection runs into an error. Throws the error that occured.
* @param event event data
*/
_onErrorCallback(event) {
console.log(event);
}
/**
* Callback that gets invoked when the socket connection closes. That happens either due to an error or on purpose. It disconnects all modules that are being
* managed in the ModuleDataService.
* @param event event data
*/
_onCloseCallback(event) {
this._isConnected = false;
this.moduleDataService.clearModules();
}
/**
* Callback that gets invoked when a new command is being push onto the command stack in CommandService. It automatically tries to send the command via the socket
* connection.
*/
_queueUpdateCallback() {
let command = this.commandService.getNextCommandInQueue();
if (command) {
this.sendCommand(command);
}
}
/**
* Initializes the web socket instance based on the provided socket configuration. If the mockSocket parameter is NOT null, the mock instance gets used instead.
* @param configuarion configuration data
* @param mockSocket mock socket to use (can be null)
*/
_initSocket(configuarion: SocketConfiguration, mockSocket) {
this._socketConfiguration = configuarion;
this._socket = mockSocket ? mockSocket : new WebSocket(this._socketConfiguration.url); // Allow to use a mock socket object for testing purposes
this.cameraURL = "http://" + this._socketConfiguration._host + ":" + this._socketConfiguration._port + "/cam"
this._socket.onopen = e => this._onOpenCallback(e);
this._socket.onmessage = e => this._onMessageCallback(e);
this._socket.onerror = e => this._onErrorCallback(e);
this._socket.onclose = e => this._onCloseCallback(e);
}
/**
* Handles a received DISPATCH command. Simply notifies the ModuleDataService with the provided data from the command.
* @param affectedModule module that gets updated
* @param changesToApply changes to apply
*/
_handleDispatch(affectedModule: ColumbusModuleType, changesToApply: {}) {
this.moduleDataService.applyChangesToModuleState(affectedModule, changesToApply);
}
/**
* Handles a received STATE_UPDATE command. (Dis)connnects modules based on the provided data from the command. Prevents duplicate addition / removal.
* @param updatedModules module that gets (dis)connected
*/
_handleStateUpdate(updatedModules: {}) {
for (let moduleType of Object.keys(updatedModules)) {
if (Utils.isPartOfEnum(ColumbusModuleType, moduleType)) {
if (updatedModules[moduleType] && !this.moduleDataService.isModuleConnected(moduleType as ColumbusModuleType)) {
this.moduleDataService.addModule(new ColumbusModule(moduleType as ColumbusModuleType));
}
if (!updatedModules[moduleType] && this.moduleDataService.isModuleConnected(moduleType as ColumbusModuleType)) {
this.moduleDataService.removeModule(moduleType as ColumbusModuleType);
}
}
}
}
/**
* Handles a received HEARTBEAT command. Sends a HEARTBEAT_ACK command back to the web socket.
*/
_handleHeartbeat() {
let heartbeatAckCommand = new ColumbusCommand(OpCode.HEARTBEAT_ACK);
this.sendCommand(heartbeatAckCommand);
}
/**
* Sends a command to the web socket. It prevents sending the command, if the socket connection is not active.
* @param command command to send
*/
sendCommand(command: ColumbusCommand) {
console.log("-----");
console.log("Sending command: ");
console.log(command);
console.log("-----");
if (this._isConnected) {
this._socket.send(command.serialize());
}
}
/**
* Reinitializes the web socket. Used to change the socket configuration while the app is running.
* @param configuarion configuration data
*/
reinit(configuarion: SocketConfiguration) {
this._socket.close();
this._initSocket(configuarion, null);
}
}
|
ab88115bc13ff61fca872c666e42cf3bfe52ddb8
|
TypeScript
|
urbit/urbit
|
/pkg/interface/src/logic/lib/useStatelessAsyncClickable.ts
| 2.96875
| 3
|
import { MouseEvent, useCallback, useEffect, useState } from 'react';
export type AsyncClickableState = 'waiting' | 'error' | 'loading' | 'success';
export function useStatelessAsyncClickable(
onClick: (e: MouseEvent) => Promise<void>,
name: string
) {
const [state, setState] = useState<AsyncClickableState>('waiting');
const handleClick = useCallback(
async (e: MouseEvent) => {
try {
setState('loading');
await onClick(e);
setState('success');
} catch (e) {
console.error(e);
setState('error');
} finally {
setTimeout(() => {
setState('waiting');
}, 3000);
}
},
[onClick, setState]
);
// When name changes, reset button
useEffect(() => {
setState('waiting');
}, [name]);
return { buttonState: state, onClick: handleClick };
}
|
7f24d091fd511d8a37e7699305d021307b7993e4
|
TypeScript
|
davidthorn/html5-graph
|
/src/GraphObject.ts
| 2.84375
| 3
|
import { GridObject, GridMargin, GridPoint, GridIncrementColor, GridAxisOption } from './graph.module'
import { GridAxis } from './graph';
export class GraphObject {
context: any
frame: GridObject
incremetColor: GridIncrementColor = GridIncrementColor.increment
separatorColor: GridIncrementColor = GridIncrementColor.seperator
constructor(context: any, frame: GridObject) {
this.context = context;
this.frame = frame;
}
getColor(isModulus: boolean): GridIncrementColor {
return isModulus ? this.incremetColor : this.separatorColor;
}
redraw(frame: GridObject): void {
this.frame = frame;
}
draw() {
this.context.fillStyle = 'white';
this.context.fillRect(0, 0, this.frame.centerXPos * 2, this.frame.centerYPos * 2);
this.drawXAxis(this.frame.x_axis_length, this.frame.x_increments);
this.drawYAxis(this.frame.y_axis_length, this.frame.y_increments);
}
drawYAxis(numberOfIncrements: number, increments: number = 1) {
this.line(this.frame.centerXPos, this.frame.margin.y, this.frame.centerXPos, this.frame.height + this.frame.margin.y); /// vertical line y axis
let space = ((this.frame.height / 2)) / numberOfIncrements;
this.drawAxisIncrement(GridAxisOption.y, numberOfIncrements, increments, this.frame.centerYPos, space, false)
this.drawAxisIncrement(GridAxisOption.y, numberOfIncrements, increments, this.frame.centerYPos, -space, true)
}
drawXAxis(numberOfIncrements: number, increments = 1) {
this.line(this.frame.margin.x, this.frame.centerYPos, this.frame.width + this.frame.margin.x, this.frame.centerYPos); /// horizontal line x axis
let space = ((this.frame.width / 2) ) / numberOfIncrements;
this.drawAxisIncrement(GridAxisOption.x, numberOfIncrements, increments, this.frame.centerXPos, space, false)
this.drawAxisIncrement(GridAxisOption.x, numberOfIncrements, increments, this.frame.centerXPos, -space, true)
}
drawAxisIncrement(gridAxis: GridAxisOption, pieces: number, increments: number, centerPos: number, linePosition: number, isNegative: boolean) {
for (let x = 1; x <= pieces; x++) {
let line = (linePosition * x); // same
let isModulus = this.isIncrementModulus(x, increments); // same
let color = this.getColor(isModulus);
switch (gridAxis) {
case GridAxisOption.x:
this.addLabel(isModulus, centerPos + line, this.frame.centerYPos + 25, String(isNegative ? -x : x));
this.line(centerPos + line, this.frame.centerYPos + 0, centerPos + line, this.frame.centerYPos + 5, color);
break;
case GridAxisOption.y:
/// the isNegative needs to be negated because minus is positive and positive is minus
this.addLabel(isModulus, this.frame.centerXPos - 30, centerPos + line + 5, String(!isNegative ? -x : x));
this.line(this.frame.centerXPos - 5, centerPos + line, this.frame.centerXPos + 5, centerPos + line, color);
break;
default: break;
}
}
}
isIncrementModulus(increment: number, increments: number): boolean {
return increment % increments === 0;
}
addLabel(isModulus: boolean, x: number, y: number, labelText: string): void{
if (isModulus) {
this.text(x, y, labelText);
}
}
text(x: number, y: number, textString: string): void {
this.context.font = "1em Arial";
this.context.textAlign = "center";
this.context.strokeStyle = 'black';
this.context.strokeText(textString, x, y);
}
line(startX: number, startY: number, endX: number, endY: number, color = '#000000'): void {
this.context.beginPath();
this.context.strokeStyle = color;
this.context.moveTo(startX, startY);
this.context.lineTo(endX, endY);
this.context.stroke();
this.context.closePath();
}
plotPositionAt(x: number , y: number): void {
const point: GridPoint = this.frame.getPoint(x, y)
this.context.beginPath();
this.context.fillStyle = "red";
this.context.arc(point.x , point.y , 6, 0 , 2*Math.PI)
this.context.fill()
this.context.closePath();
}
drawPoints(points: GridPoint[]) {
points.forEach(point => {
this.plotPositionAt(point.x , point.y)
})
// this.drawCurve(new GridPoint(0, 0), new GridPoint(-4 , 4))
// this.drawCurve(new GridPoint(0, 0), new GridPoint(4 , 4))
// this.drawCurve(new GridPoint(0, 0), new GridPoint(-4 , -4))
// this.drawCurve(new GridPoint(0, 0), new GridPoint(4 , -4))
this.drawSquareCurve(4)
}
drawCurve(from: GridPoint , to: GridPoint) {
const fromPoint: GridPoint = this.frame.getPoint(from.x, from.y)
const midPoint: GridPoint = this.frame.getPoint(to.x, from.y)
const toPoint: GridPoint = this.frame.getPoint(to.x, to.y)
this.context.beginPath();
this.context.moveTo(fromPoint.x , fromPoint.y)
this.context.strokeStyle = 'black'
this.context.quadraticCurveTo(midPoint.x , midPoint.y , toPoint.x , toPoint.y)
this.context.stroke()
this.context.closePath();
}
drawSquareCurve(square: number) {
let absValue = Math.abs(square)
let start = this.frame.getPoint(0, 0)
let startPos = this.frame.getPoint(0, 0)
for(let x = 0; x <= absValue; x += 0.001) {
let y = square < 0 ? -(x * x) : x * x
let newPointNeg = this.frame.getPoint(-x , y)
this.line(start.x , start.y , newPointNeg.x , newPointNeg.y)
let newPointPos = this.frame.getPoint(x , y)
this.line(startPos.x , startPos.y , newPointPos.x , newPointPos.y)
start = newPointNeg
startPos = newPointPos
}
if(square < 0) return
this.drawSquareCurve(-square)
}
}
|
f202f3619811d3da268a85b5a2f277c0b65e9b5e
|
TypeScript
|
VitaliyDrapkin/SocialNetwork-Client
|
/src/redux/authReducer.ts
| 2.765625
| 3
|
import { actionsTypes } from "./actionTypes";
export const AUTHORIZATION = "AUTHORIZATION";
export const INITIALIZE = "INITIALIZE";
export const REFRESH_TOKEN = "REFRESH_TOKEN";
export const CHANGE_PROFILE_IMAGE = "CHANGE_PROFILE_IMAGE";
export interface initialStateType {
isInitialized: boolean;
isAuth: boolean;
id: string;
firstName: string;
lastName: string;
birthday: number;
gender: string;
accessToken: string;
profileImage: string;
}
let initialState: initialStateType = {
isInitialized: false,
isAuth: false,
id: "",
firstName: "",
lastName: "",
birthday: -1,
gender: "",
accessToken: "",
profileImage: "",
};
export function authReducer(
oldAppState: initialStateType = initialState,
action: actionsTypes
): initialStateType {
switch (action.type) {
case AUTHORIZATION:
return {
...oldAppState,
isAuth: true,
id: action.id,
firstName: action.firstName,
lastName: action.lastName,
birthday: action.birthday,
gender: action.gender,
accessToken: action.accessToken,
profileImage: action.profileImage,
};
case REFRESH_TOKEN:
return {
...oldAppState,
accessToken: action.accessToken,
};
case INITIALIZE:
return {
...oldAppState,
isInitialized: true,
};
case CHANGE_PROFILE_IMAGE:
return {
...oldAppState,
profileImage: action.profileImg,
};
case "DESTROY_SESSION":
return {
...oldAppState,
isInitialized: true,
};
default:
return oldAppState;
}
}
|
e4422cdabbde37c4d718a1e3db8b2cf30b546ea4
|
TypeScript
|
byte-it/backer
|
/src/BackupSource/BackupSourceFactory.ts
| 2.65625
| 3
|
import {ContainerInspectInfo} from 'dockerode';
import {singleton} from 'tsyringe';
import {BackupSourceMysql, IMysqlLabels} from './BackupSourceMysql';
import {IBackupSource} from './IBackupSource';
import {ILabels} from '../Interfaces';
/**
* BackupSourceProvider is a factory to instantiate {@link IBackupSource}s by config.
*
* @category BackupSource
*/
@singleton()
export class BackupSourceFactory {
/**
* Create a BackupSourceInstance from the labels
* @param container The container instance to create the backup source for
*
* @throws Error If no matching backup source is found
*/
public createBackupSource(container: ContainerInspectInfo, labels: ILabels | IMysqlLabels): IBackupSource {
const type = labels.type;
switch (type) {
case 'mysql':
return BackupSourceMysql.fromContainer(container, labels as IMysqlLabels);
default:
throw new Error(`Container ${!container.Name}: No backup source for '${type}' found`);
}
}
}
|
b039ecc02d8355cc44b99adc138fcb91709f2c5b
|
TypeScript
|
PurpleMyst/bombcleaner
|
/src/grid.ts
| 3
| 3
|
import { shuffle, createSquareGridTemplate } from "./utils";
import { Square } from "./square";
const MINE_DISTRIBUTION = 1 / 10;
export class Grid {
public container: HTMLElement = document.createElement("div");
public squares: Square[] = [];
constructor(public side: number) {
this.container.style.display = "inline-grid";
this.container.style.gridGap = "0";
this.container.style.gridTemplate = createSquareGridTemplate(this.side);
this.container.style.position = "absolute";
this.container.style.left = this.container.style.top = "50%";
this.container.style.transform = "translate(-50%, -50%)";
for (let y = 0; y < this.side; ++y) {
for (let x = 0; x < this.side; ++x) {
const square = new Square(x, y);
this.squares.push(square);
this.container.appendChild(square.image);
square.image.addEventListener("contextmenu", e => e.preventDefault());
square.image.addEventListener("mousedown", event => {
if (event.buttons & 2) this.flagSquare(x, y);
else this.revealSquare(x, y);
});
}
}
const nonMineSquares = this.squares.slice();
shuffle(nonMineSquares);
for (let i = 0; i < this.squares.length * MINE_DISTRIBUTION; ++i) {
nonMineSquares.pop()!.isMine = true;
}
}
getSquare(x: number, y: number): Square {
return this.squares[y * this.side + x];
}
neighbors(x: number, y: number): Square[] {
const result = [];
for (let xc = -1; xc <= 1; ++xc) {
for (let yc = -1; yc <= 1; ++yc) {
if (xc == 0 && yc == 0) continue;
const nx = x + xc;
const ny = y + yc;
if (nx < 0 || ny < 0 || nx >= this.side || ny >= this.side) continue;
result.push(this.getSquare(nx, ny));
}
}
return result;
}
revealSquare(x: number, y: number, isChain: boolean = false) {
const square = this.getSquare(x, y);
if (square.isRevealed) return;
const neighbors = Array.from(this.neighbors(x, y));
const mineNeighbors = neighbors.filter(sq => sq.isMine).length;
square.reveal(mineNeighbors);
if (!square.isMine && (isChain || mineNeighbors == 0)) {
requestAnimationFrame(() => {
neighbors.forEach(sq => {
if (!sq.isMine) this.revealSquare(sq.x, sq.y, true);
});
});
}
}
flagSquare(x: number, y: number) {
this.getSquare(x, y).flag();
}
}
|
a5d81ef5ce018f34de372a1cce2aa1e6d9707fc4
|
TypeScript
|
mdchia/overchill
|
/game/direction.ts
| 3.078125
| 3
|
export enum Cardinal { // The four cardinal compass directions
N = 0,
E = 2,
S = 4,
W = 6,
}
export enum Diagonal { // The four diagonal directions
NE = 1,
SE = 3,
SW = 5,
NW = 7
}
export type Direction = Cardinal | Diagonal; // Full set of eight directions
|
c029955f1fb2445fe766b25022719ba7b0d7c80a
|
TypeScript
|
ramya0820/azure-service-bus-node
|
/examples/samples/partitionedQueues.ts
| 2.71875
| 3
|
// Enable partitions for the topics in the azure portal and then execute the sample.
// For partitioned queues, the topmost 16 bits of the SequenceNumber(64-bit unique integer assigned by ServiceBus for a message) reflect the partition id.
// The usual the ascending SequenceNumber characteristics is no longer guaranteed as the SequenceNumber depends on partitionKey(partitioned queues are distributed among different message brokers).
// Once you enable the partitions and execute the sample, you should be able to relate the SequenceNumbers corresponding to the same partitionKey.
// Read more on Partitioned queues and topics : https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-partitioning
import {
delay,
SendableMessageInfo,
ReceiveMode,
generateUuid,
Namespace,
ReceiveHandler,
OnError,
OnMessage,
ServiceBusMessage,
MessagingError
} from "../../lib";
import * as dotenv from "dotenv";
dotenv.config();
const str = process.env.SERVICEBUS_CONNECTION_STRING || "";
const path = process.env.QUEUE_NAME || "";
console.log(`str: ${str}`);
console.log(`path: ${path}`);
async function main(): Promise<void> {
await sendMessages();
await receiveMessages();
}
async function sendMessages(): Promise<void> {
const nsSend = Namespace.createFromConnectionString(str);
const sendClient = nsSend.createQueueClient(path);
const data = [
{ lastName: "Einstein", firstName: "Albert" },
{ lastName: "Einstein", firstName: "Elsa" },
{ lastName: "Curie", firstName: "Marie" },
{ lastName: "Curie", firstName: "Eve" },
{ lastName: "Curie", firstName: "Pierre" },
{ lastName: "Pavlov", firstName: "Ivan" },
{ lastName: "Bohr", firstName: "Niels" },
{ lastName: "Asimov", firstName: "Isaac" },
{ lastName: "Asimov", firstName: "David" },
{ lastName: "Faraday", firstName: "Michael" },
{ lastName: "Kopernikus", firstName: "Katharina" },
{ lastName: "Kopernikus", firstName: "Nikolaus" }
];
try {
for (let index = 0; index < data.length; index++) {
const element = data[index];
const message: SendableMessageInfo = {
body: `${element.firstName} ${element.lastName}`,
label: "Scientist",
timeToLive: 2 * 60 * 1000, // After 2 minutes, the message will be removed from the queue
messageId: generateUuid(),
partitionKey: data[index].lastName.substring(0, 2) // The first two letters of the lastname is the partition key
};
console.log(`Sending ${message.body}`);
await sendClient.send(message);
}
console.log("\n>>>>>>> Messages Sent !");
} catch (err) {
console.log("Error while sending", err);
}
return nsSend.close();
}
async function receiveMessages(): Promise<void> {
const nsRcv = Namespace.createFromConnectionString(str);
const receiveClient = nsRcv.createQueueClient(path, { receiveMode: ReceiveMode.peekLock });
try {
let rcvHandler: ReceiveHandler;
// retrieve messages from the queue
const onMessage: OnMessage = async (brokeredMessage: ServiceBusMessage) => {
console.log(
` \n### Received message:
messageBody - ${brokeredMessage.body ? brokeredMessage.body.toString() : undefined},
SequenceNumber - ${brokeredMessage.sequenceNumber},
partitionKey - ${brokeredMessage.partitionKey}`
);
};
const onError: OnError = (err: MessagingError | Error) => {
console.log(">>>>> Error occurred: ", err);
};
rcvHandler = receiveClient.receive(onMessage, onError);
// wait 5 seconds
await delay(5000);
console.log("Stopping the receiver");
await rcvHandler.stop();
console.log("Closing the client");
} catch (err) {
console.log("Error while receiving: ", err);
}
return nsRcv.close();
}
main()
.then(() => {
console.log("\n>>>> Done!!!!");
})
.catch((err) => {
console.log("error: ", err);
});
|
883a337dad3ac62654d1e8ae12a50edb44a59407
|
TypeScript
|
anthonyec/rect
|
/src/createPoint.ts
| 2.859375
| 3
|
import { Point } from "./types";
/** Create a representation of a point */
export default function createPoint(x: number, y: number): Point {
return { x, y };
}
|
2edb34c8ca34f16c0c695addd28eeddfbd560af5
|
TypeScript
|
RyanDur/Developing-at-the-Disco
|
/src/app/data/method/index.ts
| 2.65625
| 3
|
import {Params} from './types';
import {HttpRequest} from '../types';
import {has} from '../../../lib/util/helpers';
const createParams = (params: Params = {}) =>
Object.keys(params)
.map(param => `${param}=${params[param]}`)
.join('&');
const createPath = (endpoint: string[], params?: string) =>
[endpoint.join('/'), params]
.filter(has)
.join('?');
const info = {
headers: {
Accept: 'application/json;charset=UTF-8',
'Content-Type': 'application/json'
}
};
export const get = (params: Params, ...endpoint: string[]): HttpRequest => ({
path: createPath(endpoint, createParams(params)),
request: {
...info,
method: 'GET'
}
});
export const post = (body: any, ...endpoint: string[]): HttpRequest => ({
path: createPath(endpoint),
request: {
...info,
method: 'POST',
body: JSON.stringify(body)
}
});
export const patch = (body: any, ...endpoint: string[]): HttpRequest => ({
path: createPath(endpoint),
request: {
...info,
method: 'PATCH',
body: JSON.stringify(body)
}
});
|
6986e96f087dc99bc7cb03e222dc6cf01c6754ce
|
TypeScript
|
Azure/autorest.typescript
|
/packages/typespec-ts/test/integration/arrayItemTypes.spec.ts
| 2.90625
| 3
|
import ArrayItemTypesClientFactory, {
ArrayItemTypesClient
} from "./generated/arrays/itemTypes/src/index.js";
import { assert } from "chai";
import { matrix } from "../util/matrix.js";
interface TypeDetail {
type: string;
defaultValue: any;
convertedToFn?: (_: any) => any;
}
const testedTypes: TypeDetail[] = [
{
type: "int32",
defaultValue: [1, 2]
},
{
type: "int64",
defaultValue: [Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER]
},
{
type: "boolean",
defaultValue: [true, false]
},
{
type: "string",
defaultValue: ["hello", ""]
},
{
type: "float32",
defaultValue: [42.42]
},
{
type: "datetime",
defaultValue: ["2022-08-26T18:38:00Z"]
},
{
type: "duration",
defaultValue: ["P123DT22H14M12.011S"]
},
{
type: "unknown",
defaultValue: [1, "hello", null]
},
{
type: "model",
defaultValue: [{ property: "hello" }, { property: "world" }]
},
{
type: "nullable-float",
defaultValue: [1.2, null, 3.0]
}
];
describe("Array Item-Types Client", () => {
let client: ArrayItemTypesClient;
beforeEach(() => {
client = ArrayItemTypesClientFactory({
allowInsecureConnection: true
});
});
matrix([testedTypes], async (params: TypeDetail) => {
it(`should get a ${params.type} value`, async () => {
try {
const result = await client
.path(`/type/array/${params.type}` as any)
.get();
assert.strictEqual(result.status, "200");
assert.deepEqual(result.body, params.defaultValue);
} catch (err) {
assert.fail(err as string);
}
});
it(`should put a ${params.type} value`, async () => {
try {
let property;
if (params.convertedToFn) {
property = params.convertedToFn(params.defaultValue);
} else {
property = params.defaultValue;
}
const result = await client
.path(`/type/array/${params.type}` as any)
.put({
body: property
});
assert.strictEqual(result.status, "204");
} catch (err) {
assert.fail(err as string);
}
});
});
});
|
6568830e4697688d5727c589d5fd83a54d248388
|
TypeScript
|
AsierLarranaga/angular-menu-component
|
/as_modules/as_class_manager.ts
| 2.703125
| 3
|
export class as_class_manager {
as_removeAllElementsByClass(as_className) {
const as_elements = document.getElementsByClassName(as_className);
for (let i=0; i<as_elements.length; i++) {
if (as_elements[i].classList.contains(as_className)) {
as_elements[i].classList.remove(as_className);
}
}
}
as_showSecondElementByClass(as_firstElement, as_secondElement, as_sharedClassName, as_newClassName) {
if (as_secondElement.classList.contains(as_sharedClassName)) {
as_firstElement.classList.add(as_newClassName);
} else {
as_firstElement.classList.remove(as_newClassName);
}
}
as_toggleElementClass(as_element, as_oldClassName, as_newClassName) {
if (as_element.classList.contains(as_oldClassName)) {
as_element.classList.remove(as_oldClassName);
}
as_element.classList.add(as_newClassName);
}
as_toggleElementsClass(as_elements, as_oldClassName, as_newClassName) {
for (let i=0; i<as_elements.length; i++) {
if (as_elements[i].classList.contains(as_oldClassName)) {
as_elements[i].classList.remove(as_oldClassName);
}
as_elements[i].classList.add(as_newClassName);
}
}
as_toggleAllElementsClass(as_sharedClassName, as_oldClassName, as_newClassName) {
const as_elements = document.getElementsByClassName(as_sharedClassName);
for (let i=0; i<as_elements.length; i++) {
if (as_elements[i].classList.contains(as_oldClassName)) {
as_elements[i].classList.remove(as_oldClassName);
}
as_elements[i].classList.add(as_newClassName);
}
}
as_showElementsWhenScroll(as_sharedClassName, as_oldClassName, as_newClassName) {
const as_elements = document.getElementsByClassName(as_sharedClassName);
window.addEventListener('scroll', function() {
for (let i=0; i<as_elements.length; i++) {
if (window.pageYOffset >= as_elements[i].scrollTop) {
as_elements[i].classList.remove(as_oldClassName);
as_elements[i].classList.add(as_newClassName);
} else if (window.pageYOffset <= as_elements[i].scrollTop) {
as_elements[i].classList.remove(as_newClassName);
as_elements[i].classList.add(as_oldClassName);
}
}
});
}
}
|
eb745af97bd636eaec38cf6b675228083596866a
|
TypeScript
|
elix/elix
|
/src/base/FilterListBox.d.ts
| 2.578125
| 3
|
// Elix is a JavaScript project, but we define TypeScript declarations so we can
// confirm our code is type safe, and to support TypeScript users.
import ListBox from "./ListBox.js";
export default class FilterListBox extends ListBox {
filter: string;
itemMatchesFilter(item: ListItemElement, filter: string): boolean;
}
|
416ead27ffeb05bc7cf8c96e61c333a8eddbf5a1
|
TypeScript
|
tchambard/f-streams
|
/test/unit/binary-test.ts
| 2.875
| 3
|
import { assert } from 'chai';
import { setup } from 'f-mocha';
import { run, wait } from 'f-promise';
import { binaryReader, binaryWriter, bufferReader, bufferWriter, cutter } from '../..';
setup();
const { equal } = assert;
const TESTBUF = Buffer.from([1, 4, 9, 16, 25, 36, 49, 64, 81, 100]);
function eqbuf(b1: Buffer | undefined, b2: Buffer, msg: string) {
if (!b1) throw new Error('unexpected EOF');
equal(b1.toString('hex'), b2.toString('hex'), msg);
}
describe(module.id, () => {
it('roundtrip', () => {
[1, 4, 11, 1000].forEach(function (size) {
const dst = bufferWriter();
const writer = binaryWriter(dst, {
bufSize: size,
});
writer.write(TESTBUF);
writer.writeInt8(1);
writer.writeUInt8(254);
writer.writeInt16(2);
writer.writeInt32(3);
writer.writeFloat(0.5);
writer.writeDouble(0.125);
writer.writeInt8(5);
writer.write();
const result = dst.toBuffer();
const src = bufferReader(result).transform<Buffer>(cutter(5));
const reader = binaryReader(src);
eqbuf(reader.read(7), TESTBUF.slice(0, 7), 'read 7 (size=' + size + ')');
reader.unread(3);
eqbuf(reader.peek(5), TESTBUF.slice(4, 9), 'unread 3 then peek 5');
eqbuf(reader.read(6), TESTBUF.slice(4), 'read 6');
equal(reader.readInt8(), 1, 'int8 roundtrip');
equal(reader.readUInt8(), 254, 'uint8 roundtrip');
equal(reader.peekInt16(), 2, 'int16 roundtrip (peek)');
equal(reader.readInt16(), 2, 'int16 roundtrip');
equal(reader.readInt32(), 3, 'int32 roundtrip');
equal(reader.readFloat(), 0.5, 'float roundtrip');
equal(reader.peekDouble(), 0.125, 'double roundtrip (peek)');
equal(reader.readDouble(), 0.125, 'double roundtrip');
reader.unreadDouble();
equal(reader.readDouble(), 0.125, 'double roundtrip (after unread)');
equal(reader.readInt8(), 5, 'int8 roundtrip again');
equal(reader.read(), undefined, 'EOF roundtrip');
});
});
});
|
c3dd40665d9fd3d8249c11c37f38d1d070e69bbf
|
TypeScript
|
codxse/ts-noob
|
/design-pattren/sorting/src/index.ts
| 3.03125
| 3
|
import { NumbersCollection } from "./NumbersCollection";
import { CharactersColletion } from "./CharactersCollection";
import { LinkedList } from "./LinkedList";
const numberCollection: NumbersCollection = new NumbersCollection([10, 3, -5, 0]);
console.log(numberCollection.collection);
numberCollection.sort();
console.log(numberCollection.collection);
const charactersCollection: CharactersColletion = new CharactersColletion("nadiar");
console.log(charactersCollection.collection);
charactersCollection.sort();
console.log(charactersCollection.collection);
const linkedList: LinkedList = new LinkedList();
linkedList.add(500);
linkedList.add(-10);
linkedList.add(501);
linkedList.add(8);
linkedList.add(13);
linkedList.sort();
linkedList.print();
|
21abe4f3a761ca00df3e1470aa24c4050b8627c3
|
TypeScript
|
koluch/own-proxy
|
/entry-points/common/observables/activeTab.ts
| 2.5625
| 3
|
import { Subscribable } from "light-observable";
import { Tab } from "../browser";
import { createSubject } from "light-observable/observable";
export function create(): Subscribable<Tab> {
const [stream, sink] = createSubject<Tab>();
function update(): void {
browser.tabs
.query({ currentWindow: true, active: true })
.then(tabs => {
if (tabs.length > 0) {
sink.next(tabs[0]);
} else {
sink.error("There are no tabs in current window");
}
})
.catch(e => {
sink.error(sink.error(e.message));
});
}
browser.tabs.onActivated.addListener(update);
browser.tabs.onUpdated.addListener((tabId, changeInfo, tabInfo) => {
if (tabInfo.active && changeInfo.url) {
update();
}
});
update();
return stream;
}
export const DEFAULT: Subscribable<Tab> = create();
|
9f7a5a73576a6e4a5fa8026f29d32029eba2cb22
|
TypeScript
|
cyg720/slykApp
|
/src/pages/fund-simulation/chart.ts
| 2.59375
| 3
|
import {FundSimulationDetailsHospitalVo} from "./vo/FundSimulationDetailsHospital";
import {FundSimulationDetailsAgeVo} from "./vo/FundSimulationDetailsAge";
import {FundSimulationDetailsHospLevelVo} from "./vo/FundSimulationDetailsHospLevel";
declare let c3;
/**
* 医院仿真情况
* @param c3
* @param data
* @param el
*/
export function hospitalChartSim(data:FundSimulationDetailsHospitalVo,el,color){
let name = data.name;
let sjz = data.sjz;
let fzz = data.fzz;
setTimeout(()=>{
c3.generate({
bindto: el,
data: {
x:"x",
columns: [
["x",...name],
['实际值', ...sjz],
['仿真值', ...fzz]
],
type: 'bar'
},padding: {
right: 20,
left: 40,
},
axis: {
x: {
type: 'category',
}
},
legend: {
show: false
},
bar: {
width: {
ratio: 0.2
}
},color: {
pattern: color
},
tooltip: {
format: {
value: function (value, ratio, id) {
return value+"万";
}
}
}
});
},100);
}
/**
* 年龄段 图表分析
* @param data
* @param el
*/
export function ageChartSim(data:FundSimulationDetailsAgeVo,el,color){
let name = data.ageName;
let sjz = data.sjz;
let fzz = data.fzz;
setTimeout(()=>{
c3.generate({
bindto: el,
data: {
x:"x",
columns: [
["x",...name],
['实际值', ...sjz],
['仿真值', ...fzz]
],
type: 'bar'
},padding: {
right: 20,
left: 40,
},
axis: {
x: {
type: 'category',
}
},
legend: {
show: false
},color: {
pattern: color
},
bar: {
width: {
ratio: 0.2
}
},
tooltip: {
format: {
value: function (value, ratio, id) {
return value+"万";
}
}
}
});
},100);
}
/**
* 医院等级 图表
* @param data
* @param el
*/
export function hospLevelChartSim(data:FundSimulationDetailsHospLevelVo,el,color){
let name = data.hospLevelName;
let sjz = data.sjz;
let fzz = data.fzz;
let lbh = data.lbh;
setTimeout(()=>{
c3.generate({
bindto: el,
data: {
x:"x",
columns: [
["x",...name],
['实际值', ...sjz],
['仿真值', ...fzz],
['量变化', ...lbh]
],
type: 'bar'
},
color: {
pattern: color
},padding: {
right: 20,
left: 40,
},
axis: {
x: {
type: 'category',
}
},
legend: {
show: false
},
bar: {
width: {
ratio: 0.3
}
},
tooltip: {
format: {
value: function (value, ratio, id) {
return value+"万";
}
}
}
});
},100);
}
|
da9dabecf0b997181ddcb4841ab95aa57e41eab6
|
TypeScript
|
green-fox-academy/egedurukan
|
/week02/day01/compare-lenght.ts
| 3.265625
| 3
|
'use strict'
let firstList: number[]= [1, 2, 3]
let secondList: number[]= [4, 5]
if(secondList.length > firstList.length){
console.log("p2 is longer")
}else{console.log("p2 is shorter")}
|
c5e20bbef4834f07564b5f08ad5104b5ed2de9ad
|
TypeScript
|
mohamadarbash-eng/rating-system
|
/src/app/store/movies-list.reducer.ts
| 2.703125
| 3
|
import { Action, createReducer, on } from '@ngrx/store';
import { MoviesListAction } from './movies-list.action';
export interface InitialState {
itemId: string,
rating: number
}
export const initialState: InitialState = {
itemId: null,
rating: null
};
const reducer = createReducer(
initialState,
on(MoviesListAction, (state, { itemId, rating }) => ({ itemId, rating }))
);
export function moviesListReducer(state: InitialState | undefined, action: Action) {
return reducer(state, action);
}
|
ff03adc4da937bf4efca71eba7f909f1d1e436d7
|
TypeScript
|
tanepiper/npm-lint
|
/rules/properties.ts
| 2.625
| 3
|
import propertyName from './subrules/properties-name';
import propertyVersion from './subrules/properties-version';
import propertyPrivate from './subrules/properties-version';
import * as types from '../src/types';
export default {
name: 'Properties Rules',
description: 'Handles the checking of properties within a package.json file',
key: 'properties',
processor: async (context: types.IContextObject): Promise<void> => {
const rules: { required?: string[]; private?: boolean } = context.rules.properties;
if (!rules) {
return;
}
(rules.required || []).forEach((property: string): void => {
if (!context.package[property]) {
context.errors.insert({
message: `${'package.json'.yellow} must have property "${property.yellow}"`
});
}
if (property === 'name') {
propertyName.processor(context);
} else if (property === 'version') {
propertyVersion.processor(context);
}
});
if (typeof rules.private !== 'undefined' && rules.private === true) {
propertyPrivate.processor(context);
}
}
};
|
7c903816eb6b5e9e68844070530cffd2621fde50
|
TypeScript
|
7PH/ENSEEIHT-STDL-Mini-Java
|
/tests/test.ts
| 3.28125
| 3
|
import {TAM} from "./TAM";
const SLOW_TEST_MS: number = 2000;
/* ###############################################
* ## GRAMMAR TESTS ##
* ###############################################
*/
describe('# Grammar tests', function () {
this.slow(SLOW_TEST_MS);
/* ********************* */
describe('# Global declarations', function() {
it('-> class, interfaces w/ generic types', function (done: () => any) {
const s: string = `
class abc { }
class abc<T> { }
class abc<A, B> { }
final class abc { }
abstract class abc { }
interface abc1 { }
interface abc2 extends abc1 { }
interface abc3 extends abc2<T> { }
interface abc4 extends abc3<F<D<P>>> { }
interface abc<T1 extends abc1 & abc2, T2> extends abc2<T2> { }
`;
if (! TAM.parse(TAM.storeCodeInTmp(s)).grammarCheck)
throw new Error("Grammar check should have passed");
done();
});
});
/* ********************* */
describe('# Inner class declarations', function() {
it('-> methods definitions', function (done: () => any) {
const s: string = `
class Circle {
public Circle bar;
public int bar;
public Circle() { }
public Circle foo() { }
public int foo() { }
public static int foo() { }
public static Circle foo() { }
private static final int foo() { }
private static final Integer foo() { }
private final int foo() { }
private final Integer foo() { }
}`;
if (! TAM.parse(TAM.storeCodeInTmp(s)).grammarCheck)
throw new Error("Grammar check should have passed");
done();
});
it('-> methods parameters', function (done: () => any) {
const s: string = `
class Circle<T> {
public Circle foo() { }
public Circle foo(int a) { }
public Circle foo(int a, int b) { }
public Circle foo(Circle a, Point b) { }
public Circle foo(Circle<T> a, Point b) { }
}`;
if (! TAM.parse(TAM.storeCodeInTmp(s)).grammarCheck)
throw new Error("Grammar check should have passed");
done();
});
});
/* ********************* */
describe('# Inner interface declarations', function() {
it('-> public methods with different return types and generic types', function (done: () => any) {
const s: string = `
interface Map<TK, TV> {
TV get(TK key);
void add(TK key, TV value);
}`;
if (! TAM.parse(TAM.storeCodeInTmp(s)).grammarCheck)
throw new Error("Grammar check should have passed");
done();
});
});
});
/* ###############################################
* ## RESOLVE/CHECKTYPE TESTS - PART I ##
* ###############################################
*/
describe('# Resolve/Checktype simple tests', function () {
this.slow(SLOW_TEST_MS);
/* ********************* */
describe('# About class', function() {
it('-> one class', function(done: () => any) {
TAM.ensureResult(
`class abc {}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> two classes', function(done: () => any) {
TAM.ensureResult(
`class abc {} class foo {}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> duplicate class', function(done: () => any) {
TAM.ensureResult(
`class abc {} class abc {}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> class declaration with inner attributes', function(done: () => any) {
TAM.ensureResult(
`class Point {
private int x;
private int y;
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class declaration with inner methods', function(done: () => any) {
TAM.ensureResult(`
class Point {
public int x() {}
private int y() {}
}`,
{
resolve: true,
checkType: false
});
done();
});
});
/* ********************* */
describe('# About interface', function() {
it('-> one interface', function(done: () => any) {
TAM.ensureResult(
`interface abc {}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> two interfaces', function(done: () => any) {
TAM.ensureResult(
`interface abc {} interface foo {}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> duplicate interface', function(done: () => any) {
TAM.ensureResult(
`interface abc {} interface abc {}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> interface declaration with inner methods', function(done: () => any) {
TAM.ensureResult(`
interface abc {
int fun();
}`,
{
resolve: true,
checkType: true
});
done();
});
});
/* ********************* */
describe('# About implementation', function() {
it('-> interface implementation', function(done: () => any) {
TAM.ensureResult(`
interface abc {}
class issou implements abc {}
`,{
resolve: true,
checkType: true
});
done();
});
it('-> unexisting interface implementation', function(done: () => any) {
TAM.ensureResult(
`class issou implements abc {}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> self reference', function(done: () => any) {
TAM.ensureResult(
`class abc implements abc {}`,
{
resolve: true,
checkType: false
});
done();
});
it('-> class implementing a class', function(done: () => any) {
TAM.ensureResult(`
class foo {}
class bar implements foo {}
`,{
resolve: true,
checkType: false
});
done();
});
});
/* ********************* */
describe('# About extension', function() {
it('-> class extension', function(done: () => any) {
TAM.ensureResult(`
class abc {}
class issou extends abc {}
`,{
resolve: true,
checkType: true
});
done();
});
it('-> unexisting class extension', function(done: () => any) {
TAM.ensureResult(
`class issou extends abc {}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> self reference', function(done: () => any) {
TAM.ensureResult(
`class abc extends abc {}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> class extending an interface', function(done: () => any) {
TAM.ensureResult(`
interface foo {}
class bar extends foo {}
`,{
resolve: false,
checkType: true
});
done();
});
it('-> interface extending an interface', function(done: () => any) {
TAM.ensureResult(`
interface foo {}
interface bar extends foo {}
`,{
resolve: true,
checkType: true
});
done();
});
it('-> interface extending a class', function(done: () => any) {
TAM.ensureResult(`
class foo {}
interface bar extends foo {}
`,{
resolve: true,
checkType: false
});
done();
});
it('-> extending final class', function(done: () => any) {
TAM.ensureResult(`
final class foo {}
class bar extends foo {}
`,{
resolve: true,
checkType: false
});
done();
});
});
/* ********************* */
describe('# About overloading', function() {
it('-> method overloading in class', function(done: () => any) {
TAM.ensureResult(`
class abc {
public void fun() {}
public void fun(String param) {}
public void fun(String param, int param2) {}
public void fun(int param, String param2) {}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> method overloading in interfaces', function(done: () => any) {
TAM.ensureResult(`
interface abc {
int fun();
int fun(String param);
int fun(String param, int param2);
int fun(int param, String param2);
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> bad overloading', function(done: () => any) {
TAM.ensureResult(`
class abc {
public void fun() {}
public void fun() {}
}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> bad overloading II', function(done: () => any) {
TAM.ensureResult(`
class abc {
public void fun(String foo) {}
public void fun(String bar) {}
}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> bad overloading III', function(done: () => any) {
TAM.ensureResult(`
interface abc {
int fun(String foo);
String fun(String bar);
}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> bad overloading IV', function(done: () => any) {
TAM.ensureResult(`
class abc {
public void fun(String foo) {}
private void fun(String bar) {}
}`,
{
resolve: false,
checkType: true
});
done();
});
});
/* ********************* */
describe('# About abstraction', function() {
it('-> abstract class ', function(done: () => any) {
TAM.ensureResult(
`abstract class foo { } `,
{
resolve: true,
checkType: true
});
done();
});
it('-> abstract class w/ abstract method', function(done: () => any) {
TAM.ensureResult(`
abstract class foo {
public abstract void issou();
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> abstract class w/ extented one', function(done: () => any) {
TAM.ensureResult(`
abstract class foo {}
class foo2 extends foo {}
`,{
resolve: true,
checkType: true
});
done();
});
it('-> abstract class w/ extented one w/ unimplemented method', function(done: () => any) {
TAM.ensureResult(`
abstract class foo {
public abstract void issou();
}
class foo2 extends foo {
}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> abstract class w/ extented one w/ implemented method', function(done: () => any) {
TAM.ensureResult(
`abstract class foo {
public abstract void issou();
}
class foo2 extends foo {
public void issou() {}
}`,
{
resolve: true,
checkType: true
});
done();
});
});
});
/* ###############################################
* ## RESOLVE/CHECKTYPE TESTS - PART II ##
* ###############################################
*/
describe('# Resolve / CheckType medium tests', function () {
this.slow(SLOW_TEST_MS);
/* ********************* */
describe('# About object', function() {
it('-> class w/ attribute assignment', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
public Point() {
this.x = 1;
this.y = 2;
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ attribute assignment w/ parameter use', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
public Point(int p1, int p2) {
this.x = p1;
this.y = p2;
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ bad named constructor', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
}
class ColoredPoint extends Point {
private String color;
public Segment(int x, int y, String color) {
this.x = x;
this.y = y;
this.color = color;
}
}`,
{
resolve: false
});
done();
});
});
/* ********************* */
describe('# About method', function() {
it('-> correct typed method body', function(done: () => any) {
TAM.ensureResult(`
class Random {
public int getRandom() {
return 5;
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> correct void method body', function(done: () => any) {
TAM.ensureResult(`
class Random {
public void getRandom() {}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> uncorrect typed method body', function(done: () => any) {
TAM.ensureResult(`
class Random {
public int getRandom() {
return "d";
}
}`,
{
resolve: true,
checkType: false
});
done();
});
it('-> uncorrect void method body', function(done: () => any) {
TAM.ensureResult(`
class Random {
public void getRandom() {
return "d";
}
}`,
{
resolve: true,
checkType: false
});
done();
});
it('-> public static void main', function(done: () => any) {
TAM.ensureResult(`
class Random {
public static void main(String args[]) {}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> correct method body w/ attribute use ', function(done: () => any) {
TAM.ensureResult(`
class Random {
private int x;
public int getRandom() {
return this.x;
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> uncorrect method body w/ attribute use ', function(done: () => any) {
TAM.ensureResult(`
class Random {
private String x;
public int getRandom() {
return this.x;
}
}`,
{
resolve: true,
checkType: false
});
done();
});
it('-> method call in inner class', function(done: () => any) {
TAM.ensureResult(`
class Random {
private int fooBar;
public void foo () {
int b = this.bar();
}
public int bar() {
return this.fooBar;
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> method call in a different class', function(done: () => any) {
TAM.ensureResult(`
class Random {
private int x;
public Random(int y) {
this.x = y;
}
public int getRandom() {
return 5;
}
}
class Main {
public static void main (String args[]) {
Random random = new Random(6);
int value = random.getRandom();
System.out.println(value);
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> method call in a different class w/ use of result', function(done: () => any) {
TAM.ensureResult(`
class Random {
private int x;
public Random(int y) {
this.x = y;
}
public int getRandom() {
return 5;
}
}
class Main {
public static void main (String args[]) {
Random r = new Random(6);
int x = r.getRandom();
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> method call in a different class w/ bad use of result', function(done: () => any) {
TAM.ensureResult(`
class Random {
private int x;
public Random(int y) {
this.x = y;
}
public int getRandom() {
return 5;
}
}
class Main {
public static void main (String args[]) {
Random r = new Random(6);
String x = r.getRandom();
}
}`,
{
resolve: true,
checkType: false
});
done();
});
});
/* ********************* */
describe('# About using instantiation', function() {
it('-> class w/ custom attribute types', function(done: () => any) {
TAM.ensureResult(`
class Point {}
class Segment {
private Point p1;
private Point p2;
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ attribute assignment w/ parameter use', function(done: () => any) {
TAM.ensureResult(`
class Point {}
class Segment {
private Point p1;
private Point p2;
public Segment(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ instantiation of existing object', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
public Point() { }
}
class Segment {
private Point p1;
private Point p2;
public Segment() {
this.p1 = new Point();
this.p2 = new Point();
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ instantiation of unexisting object', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
public Point() { }
}
class Segment {
private Point p1;
private Point p2;
public Segment() {
this.p1 = new ColoredPoint();
this.p2 = new ColoredPoint();
}
}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> class w/ object instantiation w/out constructor', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
}
class Segment {
private Point p1;
private Point p2;
public Segment() {
this.p1 = new Point();
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ real constructor', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
public Point(int a, int b) {
this.x = a;
this.y = b;
}
}
class Segment {
private Point p1;
private Point p2;
public Segment(int a, int b, int c, int d) {
this.p1 = new Point(a, b);
this.p2 = new Point(c, d);
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ instantiation of our type w/ bad type parameter', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
public Point(int a, int b) {
this.x = a;
this.y = b;
}
}
class Segment {
private Point p1;
private Point p2;
public Segment(int a, int b, int c, int d) {
this.p1 = new Point(a, b);
this.p2 = new Point(c, "d");
}
}`,
{
resolve: true,
checkType: false // "d" is String != int
});
done();
});
});
/* ********************* */
describe('# About extension', function() {
it('-> class w/ superclass attribute use', function(done: () => any) {
TAM.ensureResult(`
class Point {
public int x;
public int y;
}
class ColoredPoint extends Point {
private String color;
public ColoredPoint (String color) {
this.x = 1;
this.y = 2;
this.color = color;
}
}`,
{
resolve: true,
checkType: true
});
done();
});
});
/* ********************* */
describe('# About implementation', function() {
it('-> simple implementation', function(done: () => any) {
TAM.ensureResult(`
class Point {}
interface Cercle {
Point getCenter();
}
class CercleImpl implements Cercle {
private Point center;
public Point getCenter() {
return this.center;
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> simple implementation w/ missing methods', function(done: () => any) {
TAM.ensureResult(`
class Point {}
interface Cercle {
Point getCenter();
}
class CercleImpl implements Cercle {
private Point center;
}`,
{
resolve: true,
checkType: false
});
done();
});
});
});
/* ###############################################
* ## RESOLVE/CHECKTYPE TESTS - PART III ##
* ###############################################
*/
describe('# Resolve / CheckType hard tests', function () {
this.slow(SLOW_TEST_MS);
/* ********************* */
describe('# About modifier', function() {
it('-> class w/ constant', function(done: () => any) {
TAM.ensureResult(`
class Color {
public static final String ROUGE = "rouge";
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> this reference in static context', function(done: () => any) {
TAM.ensureResult(`
class Color {
public String color;
public static void main(String args[]) {
this.color = "rouge";
}
}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> call of static method from another class', function(done: () => any) {
TAM.ensureResult(`
class ColorRed {
public static final String ROUGE = "rouge";
public static String getColor() {
return this.ROUGE;
}
}
class ColorUse {
public static void main (String args[]) {
ColorRed.getColor();
}
}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> class w/ private method use in inner class', function(done: () => any) {
TAM.ensureResult(`
class Point {
public int x;
public int y;
private int getX() {
return this.x;
}
public void translateX(int a) {
this.x = this.getX() + a;
}
}
`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ public method use in inner class', function(done: () => any) {
TAM.ensureResult(`
class Point {
public int x;
public int y;
public int getX() {
return this.x;
}
public void translateX(int a) {
this.x = this.getX() + a;
}
}
`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ superclass public attribute use', function(done: () => any) {
TAM.ensureResult(`
class Point {
public int x;
public int y;
}
class ColoredPoint extends Point {
private String color;
public ColoredPoint(int a, int b) {
this.x = a;
this.y = b;
this.color = "rouge";
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ superclass private attribute use', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
}
class ColoredPoint extends Point {
private String color;
public ColoredPoint(int a, int b, String color) {
this.x = a;
this.y = b;
this.color = color;
}
}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> class w/ superclass public method use', function(done: () => any) {
TAM.ensureResult(`
class Point {
public int x;
public int y;
public int getX() {
return this.x;
}
}
class ColoredPoint extends Point {
private String color;
public ColoredPoint(int a, int b, String color) {
this.x = a;
this.y = b;
this.color = color;
}
public void translateX(int a) {
this.x = this.getX() + a;
}
}`,
{
resolve: true,
checkType: true
});
done();
});
it('-> class w/ superclass private method use', function(done: () => any) {
TAM.ensureResult(`
class Point {
public int x;
public int y;
private int getX() {
return this.x;
}
}
class ColoredPoint extends Point {
private String color;
public ColoredPoint(int a, int b, String color) {
this.x = a;
this.y = b;
this.color = color;
}
public void translateX(int a) {
this.x = this.getX() + a;
}
}`,
{
resolve: false,
checkType: true
});
done();
});
it('-> class w/ superclass attribute use w/ global constant use', function(done: () => any) {
TAM.ensureResult(`
class Color {
public static final String ROUGE = "rouge";
}
class Point {
private int x;
private int y;
}
class ColoredPoint extends Point{
private String color;
public ColoredPoint () {
this.color = Color.ROUGE;
}
}`,
{
resolve: true,
checkType: true
});
done();
});
});
/* ********************* */
describe('# About generics', function() {
it('-> basic tests', function(done: () => any) {
TAM.ensureResult(`
class A<T> { }
class B<T1, T2> extends A<T1> { }
class C { }
class D { }
class E<T> extends B<C, D> { }`,
{
resolve: true,
checkType : true
});
done();
});
it('-> generic attribute', function(done: () => any) {
TAM.ensureResult(`
class Box<T> {
private T t;
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> generic methods', function(done: () => any) {
TAM.ensureResult(`
class Box<T> {
private T t;
public void set(T t) { this.t = t; }
public T get() { return this.t; }
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> generic with wrong checktype affectation', function(done: () => any) {
TAM.ensureResult(`
class Box<T, X> {
private T t;
public void set(X t) { this.t = t; }
}`,
{
resolve: true,
checkType : false
});
done();
});
it('-> generic type extending a class', function(done: () => any) {
TAM.ensureResult(`
class Thing { }
class Box<T extends Thing> {
private Thing t;
public void set(T t) {
this.t = t;
}
}`,
{
resolve: true,
checkType : true
});
done();
});
});
/* ********************* */
describe('# About chains', function() {
it('-> chained abstract method w/ implemented method', function(done: () => any) {
TAM.ensureResult(`
abstract class Point {
public abstract void compute();
}
abstract class PointNomme extends Point {
public abstract void compute();
}
class PointNommeColore extends PointNomme {
public void compute() {}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> chained abstract method w/ implemented method II', function(done: () => any) {
TAM.ensureResult(`
abstract class Point {
public abstract void compute();
}
abstract class PointNomme extends Point {}
class PointNommeColore extends PointNomme {
public void compute() {}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> chained abstract method w/ implemented method III', function(done: () => any) {
TAM.ensureResult(`
abstract class Point {
public abstract void compute();
}
abstract class PointNomme extends Point {
public abstract void compute();
public abstract int getX();
}
class PointNommeColore extends PointNomme {
public void compute() {}
public int getX() {
return 5;
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> chained abstract method w/ unimplemented method', function(done: () => any) {
TAM.ensureResult(`
abstract class Point {
public abstract void compute();
}
abstract class PointNomme extends Point { }
class PointNommeColore extends PointNomme {
}`,
{
resolve: false,
checkType : true
});
done();
});
it('-> chained abstract method w/ unimplemented method II', function(done: () => any) {
TAM.ensureResult(`
abstract class Point {
public abstract void compute();
}
abstract class PointNomme extends Point {
public abstract void compute();
}
class PointNommeColore extends PointNomme {
}`,
{
resolve: false,
checkType : true
});
done();
});
it('-> chained abstract method w/ unimplemented method III', function(done: () => any) {
TAM.ensureResult(`
abstract class Point {
public abstract void compute();
public abstract int getX();
}
abstract class PointNomme extends Point {
public void compute() {}
public abstract int getX();
}
class PointNommeColore extends PointNomme {
}`,
{
resolve: false,
checkType : true
});
done();
});
it('-> chained abstract method w/ far attribute use', function(done: () => any) {
TAM.ensureResult(`
abstract class Point {
public int x;
public abstract void compute();
public abstract int getX();
}
abstract class PointNomme extends Point {
}
class PointNommeColore extends PointNomme {
public void compute() { }
public int getX() {
return this.x;
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> chained method ', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void translate(int x, int y) {
this.x = this.x + x;
this.y = this.y + y;
}
}
class Segment {
private Point p1;
private Point p2;
public Point getP1() {
return this.p1;
}
public Point getP2() {
return this.p2;
}
public void translate(int tau) {
this.getP1().translate(tau, tau);
this.getP2().translate(tau, tau);
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> chained method w/ private one', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
private void translate(int x, int y) {
this.x = this.x + x;
this.y = this.y + y;
}
}
class Segment {
private Point p1;
private Point p2;
public Point getP1() {
return this.p1;
}
public Point getP2() {
return this.p2;
}
public void translate(int tau) {
this.getP1().translate(tau, tau);
this.getP2().translate(tau, tau);
}
}`,
{
resolve: false,
checkType : true
});
done();
});
it('-> chained method w/ public attribute use', function(done: () => any) {
TAM.ensureResult(`
class Point {
public int x;
public int y;
}
class Segment {
private Point p1;
private Point p2;
public void translate(int tau) {
this.p1.x = this.p1.x + tau;
this.p1.y = this.p1.y + tau;
this.p2.x = this.p2.x + tau;
this.p2.y = this.p2.y + tau;
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> chained method w/ private attribute use', function(done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
private int y;
}
class Segment {
private Point p1;
private Point p2;
public void translate(int tau) {
this.p1.x = this.p1.x + tau;
this.p1.y = this.p1.y + tau;
this.p2.x = this.p2.x + tau;
this.p2.y = this.p2.y + tau;
}
}`,
{
resolve: false,
checkType : true
});
done();
});
});
});
/* ###############################################
* ## RESOLVE/CHECKTYPE TESTS - PART IV ##
* ###############################################
*/
describe('# Resolve / CheckType final tests', function () {
this.slow(SLOW_TEST_MS);
/* ********************* */
it('-> use method interface', function(done: () => any) {
TAM.ensureResult(`
interface I1 {
int getI1();
}
interface I2 extends I1 {
int getI2();
}
class C implements I2 {
public int getI1() {
return 1;
}
public int getI2() {
return 2;
}
}
class Test {
public static void main(String args[]) {
I1 c = new C();
System.out.println(c.getI1());
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> arrays', function(done: () => any) {
TAM.ensureResult(`
class Test {
public static void main(String args[]) {
int t[] = new int[5];
t[3] = 4;
System.out.println(t[3]);
int ta[] = {1, 2, 3, 4};
ta[0] = ta[1];
System.out.println(ta[0]);
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> attribute use w/out "this"', function(done: () => any) {
TAM.ensureResult(`
class Integer {
private int in;
public Integer(int _i) {
in = _i;
}
public int get() {
return in;
}
}
class Test {
public static void main(String args[]) {
Integer i = new Integer(1);
System.out.println(i.get());
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> attribute and parameter with same names', function(done: () => any) {
TAM.ensureResult(`
class Integer {
private int in;
public Integer(int in) {
in = in;
}
public int get() {
return in;
}
}
class Test {
public static void main(String args[]) {
Integer i = new Integer(1);
System.out.println(i.get());
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> method use w/out "this"', function(done: () => any) {
TAM.ensureResult(`
class Integer {
private int in;
public int get() {
return in;
}
public void test() {
int a = get();
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> double generic example', function(done: () => any) {
TAM.ensureResult(`
class Box <T, H> {
private T t;
private H h;
public Box(T _t, H _h) {
this.t = _t;
this.h = _h;
}
public void setT(T _t) {
this.t = _t;
}
public T getT() {
return this.t;
}
}
class Integer {
public int value;
public Integer(int value) {
this.value = value;
}
}
class Test {
public static void main (String args[]) {
Integer a = new Integer(1);
Integer b = new Integer(2);
Box<Integer, Integer> box = new Box<Integer, Integer>(a, b);
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> double generic example w/ generic method use', function(done: () => any) {
TAM.ensureResult(`
class Box <T, H> {
private T t;
private H h;
public Box(T _t, H _h) {
this.t = _t;
this.h = _h;
}
public void setT(T _t) {
this.t = _t;
}
public T getT() {
return this.t;
}
}
class Integer {
public int value;
public Integer(int value) {
this.value = value;
}
}
class Test {
public static void main (String args[]) {
Integer a = new Integer(1);
Integer b = new Integer(2);
Box<Integer, Integer> box = new Box<Integer, Integer>(a, b);
box.setT(new Integer(3));
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> difficult generic', function(done: () => any) {
TAM.ensureResult(`
interface Integer {
int getInteger();
}
class IntegerImpl implements Integer {
private int i;
public IntegerImpl(int _i) {
this.i = _i;
}
public int getInteger() {
return this.i;
}
}
class Mask <T extends Integer> {
private T t;
public Mask(T _t) {
this.t = _t;
}
public T getValue() {
return this.t;
}
}
class Test {
public static void main(String args[]) {
IntegerImpl ii = new IntegerImpl(1);
Mask<Integer> i = new Mask<Integer>(ii);
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> generic w/ extends', function(done: () => any) {
TAM.ensureResult(`
class Carton { public int i; }
class Box <T extends Carton> {
private T t;
public Box() { }
}
class A extends Carton { }
class Main {
public static void main(String args[]) {
Box<A> b = new Box<A>();
}
}`,
{
resolve: true,
checkType : true
});
done();
});
it('-> generic w/ missing extends', function(done: () => any) {
TAM.ensureResult(`
class Carton { public int i; }
class Box <T extends Carton> {
private T t;
public Box() { }
}
class A { }
class Main {
public static void main(String args[]) {
Box<A> b = new Box<A>();
}
}`,
{
resolve: true,
checkType : false
});
done();
});
it('-> big generic', function(done: () => any) {
TAM.ensureResult(`
interface I1 { int getI1(); }
interface I2 { int getI2(); }
interface I3 extends I2, I1 { int getI3(); }
interface I4 extends I1, I3 { int getI4(); }
class C implements I4 {
public int getI1() { return 1; }
public int getI2() { return 2; }
public int getI3() { return 3; }
public int getI4() { return 4; }
}
class Test {
public static void main(String args[]) {
C c = new C();
System.out.println(c.getI1());
System.out.println(c.getI2());
}
}`,
{
resolve: true,
checkType : true
});
done();
});
});
/* ###############################################
* ## TAM CODE TESTS ##
* ###############################################
*/
describe('# TAM code', function() {
this.slow(4000);
describe('# public static void main()', function() {
it('-> System.out.println(-)', function(done: () => any) {
TAM.ensureResult(`
class Main {
public static void main () {
int a = 1;
int b = 2;
System.out.println(a + b);
}
}`,
{
resolve: true,
checkType : true,
output: ["3"]
});
done();
});
});
describe('# attributes', function() {
it('-> object instantiation, attribute access and assignment', function (done: () => any) {
TAM.ensureResult(`
class Integer {
public int value;
public Integer() { }
}
class Main {
public static void main() {
Integer integer = new Integer();
integer.value = 12;
System.out.println(integer.value);
}
}`,
{
resolve: true,
checkType: true,
output: ["12"]
});
done();
});
it('-> idem with multiple attributes', function (done: () => any) {
TAM.ensureResult(`
class Point {
public int x;
public int y;
public Point() { }
}
class Main {
public static void main() {
Point point = new Point();
point.x = 1;
point.y = 2;
System.out.println(point.x);
System.out.println(point.y);
}
}`,
{
resolve: true,
checkType: true,
output: ["1", "2"]
});
done();
});
it('-> attributes in superclass', function (done: () => any) {
TAM.ensureResult(`
class SemiPoint1 {
public int x;
}
class Point extends SemiPoint1 {
public int y;
public Point() { }
}
class Main {
public static void main() {
Point point = new Point();
point.x = 1;
point.y = 2;
System.out.println(point.x);
System.out.println(point.y);
}
}`,
{
resolve: true,
checkType: true,
output: ["1", "2"]
});
done();
});
it('-> attributes of type Object', function (done: () => any) {
TAM.ensureResult(`
class Integer {
public int value;
public Integer() { }
}
class Point {
public Integer x;
public Integer y;
public Point() { }
}
class Main {
public static void main() {
Point point = new Point();
point.x = new Integer();
point.x.value = 13;
point.y = new Integer();
point.y.value = 17;
System.out.println(point.x.value);
System.out.println(point.y.value);
}
}`,
{
resolve: true,
checkType: true,
output: ["13", "17"]
});
done();
});
});
describe('# methods', function() {
it('-> method call without parameter', function (done: () => any) {
TAM.ensureResult(`
class Person {
public void sayHello() {
System.out.println("Hello");
}
}
class Main {
public static void main() {
Person person = new Person();
person.sayHello();
}
}`,
{
resolve: true,
checkType: true,
output: ["\"Hello\""]
});
done();
});
it('-> method call with multiple atomic type parameters', function (done: () => any) {
TAM.ensureResult(`
class Person {
public void addForMe(int a, int b) {
System.out.println(a + b);
}
}
class Main {
public static void main() {
Person person = new Person();
person.addForMe(10, 23);
}
}`,
{
resolve: true,
checkType: true,
output: ["33"]
});
done();
});
it('-> static methods', function(done: () => any) {
TAM.ensureResult(`
class Random {
public static int get() {
return 6;
}
}
class Main {
public static void main() {
int r = Random.get();
System.out.println(r);
}
}`,
{
resolve: true,
checkType: true,
output: ["6"]
});
done();
});
it('-> static attribute access', function(done: () => any) {
TAM.ensureResult(`
class Random {
public static int SECRET = 4;
}
class Main {
public static void main() {
int r = Random.SECRET;
System.out.println(r);
}
}`,
{
resolve: true,
checkType: true,
output: ["4"]
});
done();
});
it('-> static attribute assignment', function(done: () => any) {
TAM.ensureResult(`
class Random {
public static int SECRET = 4;
}
class Main {
public static void main() {
System.out.println(Random.SECRET);
Random.SECRET = 6;
System.out.println(Random.SECRET);
}
}`,
{
resolve: true,
checkType: true,
output: ["4", "6"]
});
done();
});
it('-> \'this\' access in methods calls', function (done: () => any) {
TAM.ensureResult(`
class Point {
private int x;
public void setX(int x) { this.x = x; }
public int getX() { return x; }
}
class Main {
public static void main () {
Point point = new Point();
point.setX(21);
System.out.println(point.getX());
}
}`,
{
resolve: true,
checkType: true,
output: ["21"]
});
done();
});
it('-> class instantiation and usage (methods+attributes) in a public static void main', function(done: () => any) {
TAM.ensureResult(`
class SecretNumber {
private int number;
public SecretNumber() {
this.number = 6;
}
public int get() {
return this.number;
}
public static void main () {
SecretNumber secretNumber = new SecretNumber();
int number = secretNumber.get();
System.out.println(number);
}
}`,
{
resolve: true,
checkType: true,
output: ["6"]
});
done();
});
it('-> chained methods returning objects', function(done: () => any) {
TAM.ensureResult(`
class Integer {
private int value;
public Integer(int value) {
this.value = value;
}
public void set(int value) {
this.value = value;
}
public int get() {
return value;
}
}
class Point {
private Integer x;
private Integer y;
public Point(int x, int y) {
this.x = new Integer(x);
this.y = new Integer(y);
}
public Integer getX() { return x; }
public Integer getY() { return y; }
}
class Main {
public static void main() {
Point point = new Point(11, 22);
int x = point.getX().get();
int y = point.getY().get();
System.out.println(x);
System.out.println(y);
}
}`,
{
resolve: true,
checkType: true,
output: ["11", "22"]
});
done();
});
it('-> shared object pointer', function(done: () => any) {
TAM.ensureResult(`
class Integer {
private int value;
public Integer(int value) {
this.value = value;
}
public void set(int value) {
this.value = value;
}
public int get() {
return value;
}
}
class Point {
private Integer x;
private Integer y;
public Point(int x, int y) {
this.x = new Integer(x);
this.y = new Integer(y);
}
public Integer getX() { return x; }
public Integer getY() { return y; }
}
class Main {
public static void main() {
Point point = new Point(11, 22);
Point point2 = point;
int x = point2.getX().get();
int y = point2.getY().get();
System.out.println(x);
System.out.println(y);
}
}`,
{
resolve: true,
checkType: true,
output: ["11", "22"]
});
done();
});
});
describe('-> final complex test', function() {
it('-> complex test', function(done: () => any) {
TAM.ensureResult(`
interface Point {
int getAbscisse();
int getOrdonnee();
void setAbscisse(int x);
void setOrdonnee(int y);
}
class PointImpl implements Point {
private int x;
private int y;
public void setAbscisse(int x) {
this.x = x;
}
public int getAbscisse() {
return this.x;
}
public void setOrdonnee(int y) {
this.y = y;
}
public int getOrdonnee() {
return this.y;
}
public PointImpl (int x, int y) {
this.x = x;
this.y = y;
}
}
interface PointNomme extends Point {
String getNom();
void setNom(String nom);
}
class PointNommeImpl extends PointImpl implements PointNomme {
private String nom;
public String getNom() {
return this.nom;
}
public void setNom(String nom) {
this.nom = nom;
}
}
class Test {
public static void main () {
PointNommeImpl pn = new PointNommeImpl();
pn.setNom("Point 1");
pn.setNom("Point 2");
pn.setAbscisse(10);
System.out.println(pn.getNom());
PointImpl p1 = new PointImpl(5, 10);
System.out.println(p1.getAbscisse());
System.out.println(p1.getOrdonnee());
}
}`,
{
resolve: true,
checkType : true,
output: ["\"Point 2\"", "5", "10"]
});
done();
});
});
});
|
f022740d0da98dbc78124cb6bde724e602bf05a6
|
TypeScript
|
kondratyev-nv/vscode-python-test-adapter
|
/src/logging/defaultLogger.ts
| 2.640625
| 3
|
import { WorkspaceFolder } from 'vscode';
import { ILogger, LogLevel } from './logger';
import { ILogOutputChannel } from './logOutputChannel';
export class DefaultLogger implements ILogger {
constructor(
private readonly output: ILogOutputChannel,
private readonly workspaceFolder: WorkspaceFolder,
private readonly framework: string
) { }
public log(level: LogLevel, message: string): void {
try {
this.output.write(
`${new Date().toISOString()} ` +
`${this.levelCode(level)} ` +
`${this.framework} at '${this.workspaceFolder.name}': ` +
`${message}`
);
} catch {
/* do nothing if cannot log */
}
}
private levelCode(level: LogLevel): string {
switch (level) {
case 'crit': return 'CRIT';
case 'warn': return 'WARN';
case 'info': return 'INFO';
case 'debug': return ' DBG';
default: return '?';
}
}
}
|
7ac9bf8a39bb5812c203619c6a59380dd49f20c8
|
TypeScript
|
gatsbyjs/gatsby
|
/packages/gatsby/src/utils/merge-gatsby-config.ts
| 2.96875
| 3
|
import _ from "lodash"
import { Express } from "express"
import type { TrailingSlash } from "gatsby-page-utils"
export interface IPluginEntryWithParentDir {
resolve: string
options?: Record<string, unknown>
parentDir: string
}
// TODO export it in index.d.ts
export type PluginEntry = string | IPluginEntryWithParentDir
export interface IGatsbyConfigInput {
siteMetadata?: Record<string, unknown>
plugins?: Array<PluginEntry>
pathPrefix?: string
assetPrefix?: string
polyfill?: boolean
mapping?: Record<string, string>
proxy?: {
prefix: string
url: string
}
developMiddleware?(app: Express): void
jsxRuntime?: "classic" | "automatic"
jsxImportSource?: string
trailingSlash?: TrailingSlash
}
type ConfigKey = keyof IGatsbyConfigInput
type Metadata = IGatsbyConfigInput["siteMetadata"]
type Mapping = IGatsbyConfigInput["mapping"]
const howToMerge = {
/**
* pick a truthy value by default.
* This makes sure that if a single value is defined, that one it used.
* We prefer the "right" value, because the user's config will be "on the right"
*/
byDefault: (a: ConfigKey, b: ConfigKey): ConfigKey => b || a,
siteMetadata: (objA: Metadata, objB: Metadata): Metadata =>
_.merge({}, objA, objB),
// plugins are concatenated and uniq'd, so we don't get two of the same plugin value
plugins: (
a: Array<PluginEntry> = [],
b: Array<PluginEntry> = []
): Array<PluginEntry> => a.concat(b),
mapping: (objA: Mapping, objB: Mapping): Mapping => _.merge({}, objA, objB),
} as const
/**
* Defines how a theme object is merged with the user's config
*/
export const mergeGatsbyConfig = (
a: IGatsbyConfigInput,
b: IGatsbyConfigInput
): IGatsbyConfigInput => {
// a and b are gatsby configs, If they have keys, that means there are values to merge
const allGatsbyConfigKeysWithAValue = _.uniq(
Object.keys(a).concat(Object.keys(b))
) as Array<ConfigKey>
// reduce the array of mergable keys into a single gatsby config object
const mergedConfig = allGatsbyConfigKeysWithAValue.reduce(
(config, gatsbyConfigKey) => {
// choose a merge function for the config key if there's one defined,
// otherwise use the default value merge function
const mergeFn = howToMerge[gatsbyConfigKey] || howToMerge.byDefault
return {
...config,
[gatsbyConfigKey]: mergeFn(a[gatsbyConfigKey], b[gatsbyConfigKey]),
}
},
{} as IGatsbyConfigInput
)
// return the fully merged config
return mergedConfig
}
|
f8b6005f711ab837b00a5e7c57dfa1c37e410854
|
TypeScript
|
bgwest/learning-typescript
|
/src/learning-ts/interfaces.ts
| 4
| 4
|
// interface example
function printLabel(labelledObj: { label: string, helloWorld: string }) {
console.log(labelledObj.helloWorld);
}
let myObj = {size: 10, label: "Size 10 Object", helloWorld: 'testing123'};
printLabel(myObj);
// another interface example
interface Food {
tacos: string,
pizza: string
}
function greeter(food: Food) {
return "The best place to get tacos is " + food.tacos
+ " and the best place to get pizza is " + food.pizza + ".";
}
let places = {
tacos: 'Seattle',
pizza: 'Lynnwood'
};
console.log(greeter(places));
|
faaabaf8d84bfdafbbe5626cc7f2efae457d9faa
|
TypeScript
|
ciwen91/AutoIt
|
/AutoIt.Foundation/AutoIt.Foundation.Web.Scripts/MetaData/ValLimit/ValLimitForStr.ts
| 3.015625
| 3
|
namespace MetaData {
export class ValLimitForStr extends ValLimitBase {
MinLength?: number;
MaxLength?: number;
constructor(minLength: number = null, maxLength: number = null, parttern: string = null) {
super(SimpleType.string,parttern);
this.MinLength = minLength;
this.MaxLength = maxLength;
}
ValidInner(val: string): List<string> {
var msgGroup = new List<string>();
var length = val.length;
//Ƿ
var isIn = (!IsEmpty(this.MinLength) && length >= this.MinLength) || (!IsEmpty(this.MaxLength) && length <= this.MaxLength);
//ôϢ
if (!isIn) {
if (!IsEmpty(this.MinLength) && !IsEmpty(this.MaxLength)) {
msgGroup.Set(`ȱ${this.MinLength}~${this.MaxLength}!`);
} else if (!IsEmpty(this.MinLength)) {
msgGroup.Set(`ȲС${this.MinLength}!`);
} else if (!IsEmpty(this.MaxLength)) {
msgGroup.Set(`Ȳܴ${this.MaxLength}!`);
}
}
return msgGroup;
}
}
}
|
798ad84b4a15644c1e9109cdf72471f597e70867
|
TypeScript
|
t4d-classes/bootcamp_09142020
|
/demo-app/src/reducers/calcToolReducers.ts
| 3.078125
| 3
|
import { Reducer, combineReducers } from 'redux';
import {
ADD_ACTION, SUBTRACT_ACTION, MULTIPLY_ACTION, DIVIDE_ACTION,
CalcActions, isCalcAction, isCalcHistoryAction, isCalcOpAction, isCalcValidationAction,
} from '../actions/calcToolActions';
import { CalcHistoryEntry, CalcToolState } from '../models/calcTool';
const actionToOperator = new Map<string, string>();
actionToOperator.set(ADD_ACTION, '+');
actionToOperator.set(SUBTRACT_ACTION, '-');
actionToOperator.set(MULTIPLY_ACTION, '*');
actionToOperator.set(DIVIDE_ACTION, '/');
export const historyReducer: Reducer<CalcHistoryEntry[], CalcActions> = (history = [], action) => {
if (isCalcAction(action)) {
return [];
}
if (isCalcOpAction(action)) {
return [ ...history, {
name: actionToOperator.get(action.type) || 'unknown',
value: action.payload.num,
} ];
}
if (isCalcHistoryAction(action)) {
const newHistory = [ ...history ];
newHistory.splice(action.payload.entryIndex, 1);
return newHistory;
}
return history;
};
// reducer functions must be pure fuctions...
// four qualities of a pure function
// 1. Only use data passed in via parameters
// 2. Parmeters can never be mutated
// 3. No side-effects
// 4. The only output is the return value
export const validationMessageReducer: Reducer<string, CalcActions> = (validationMessage = '', action) => {
if (isCalcValidationAction(action)) {
return action.payload.message;
}
return validationMessage;
}
// stateful logic
// newState <- reducer(currentState, action)
export const calcToolReducer: Reducer<CalcToolState, CalcActions> = combineReducers({
history: historyReducer,
validationMessage: validationMessageReducer,
});
|
ebcb24f9688ad582a22827e8c4298255c6d0bd83
|
TypeScript
|
hyemmie/dutch
|
/src/utiles/assetTokenNamePrettier.ts
| 2.6875
| 3
|
// ELYSIA_ASSET_BLUE_3_EL => AssetBlue3El
const assetTokenNamePrettier = (input: string): string => {
try {
const res = input.toLowerCase().replace('elysia_', '').split('_').map((str) => str.charAt(0).toUpperCase() + str.slice(1)).join('')
return res
} catch (e) {
alert(e)
return input
}
}
export default assetTokenNamePrettier
|
4890bd98ea2b4f85d221616a492fdc508c2efaa7
|
TypeScript
|
gititGoro/PampForkFrontEnd
|
/client/src/components/Layout/PageContent/Common/TokenImage.ts
| 2.71875
| 3
|
import imageData from '../../../../images/dataimages.json'
export interface ImageType {
BASE64: string,
name: string,
address: string
}
export const ImgSrc = (network: string) => {
const images = imageData.filter(n => n.network === network)
return (address: string): ImageType => {
if (images.length) {
const imageBlob = images[0].images
const token = imageBlob.filter(i => i.address.toLowerCase() === address.toLowerCase())
if (token.length)
return token[0]
return { name: "", BASE64: "", address: "" }
}
return { name: "", BASE64: "", address: "" }
}
}
export const RetrieveDataImages = (network: string):ImageType[] => {
const images = imageData.filter(n => n.network === network)
return images[0].images
}
|
2fe5db55135c6f8b70a94e1c3bafe7aea8831abe
|
TypeScript
|
PRX/styleguide.prx.org
|
/projects/ngx-prx-styleguide/src/lib/datepicker/calpicker.component.ts
| 2.578125
| 3
|
import { Component, AfterViewInit, OnChanges, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core';
import * as Pikaday from 'pikaday';
import { SimpleDate } from './simpledate';
// patch pikaday to show up to 12 months
// https://github.com/Pikaday/Pikaday/issues/749
const originalConfig = Pikaday.prototype.config;
Pikaday.prototype.config = function(options) {
const opts = originalConfig.apply(this, [options]);
if (options.numberOfMonths) {
opts.numberOfMonths = Math.min(options.numberOfMonths, 12);
}
return opts;
};
/**
* Multiple date-picking via a single calendar
*/
@Component({
selector: 'prx-calpicker',
template: '<input type="text" class="hidden" #textinput/><div #container></div>',
styleUrls: ['./calpicker.component.css']
})
export class CalpickerComponent implements AfterViewInit, OnChanges {
@ViewChild('textinput', { static: true }) textinput: ElementRef;
@ViewChild('container', { static: true }) container: ElementRef;
@Input() dates: SimpleDate[] = [];
@Output() datesChange = new EventEmitter<SimpleDate[]>();
@Input() months = 3;
@Input() minDate: SimpleDate;
@Input() maxDate: SimpleDate;
@Input() defaultDate: SimpleDate;
@Input() disabled = false;
private picker: Pikaday;
get options(): Pikaday.PikadayOptions {
return {
field: this.textinput.nativeElement,
container: this.container.nativeElement,
theme: this.disabled ? 'calpicker disabled' : 'calpicker',
firstDay: 0,
bound: false,
keyboardInput: false, // doesn't work with this yet
onSelect: date => (this.disabled ? null : this.onSelect(date)),
numberOfMonths: this.months,
minDate: this.minDate ? this.minDate.toLocaleDate() : null,
maxDate: this.maxDate ? this.maxDate.toLocaleDate() : null,
defaultDate: this.defaultDate ? this.defaultDate.toLocaleDate() : null,
events: this.datesInLocale()
};
}
datesInLocale() {
return this.dates.map(d => d.toLocaleDate().toDateString());
}
ngAfterViewInit() {
this.picker = new Pikaday(this.options);
}
ngOnChanges(changes: any) {
if (this.picker) {
if (
(changes.defaultDate && !changes.defaultDate.firstChange) ||
(changes.disabled && !changes.disabled.firstChange)
) {
this.picker.destroy();
this.picker = new Pikaday(this.options);
} else {
this.picker.config(this.options);
}
}
}
onSelect(date: Date) {
const selected = new SimpleDate(date, true);
// add or remove selected date
const index = this.dates.findIndex(d => d.equals(selected));
if (index > -1) {
this.dates.splice(index, 1);
} else {
this.dates.push(selected);
}
this.dates.sort();
// redraw pikaday and emit changes
this.picker.config(this.options);
this.picker.setDate(null);
this.datesChange.emit(this.dates);
}
}
|
8d2c8ca566484f10e5d1b56975501607b16bc561
|
TypeScript
|
OleksandrKyrylyuk/TypeScript-Basic-OOP-
|
/src/LinkedList.ts
| 3.515625
| 4
|
import { Sorter } from './Sorter';
class Nodes {
next: Nodes | null = null;
constructor(public value: number){}
}
export class LinkedList extends Sorter{
head: Nodes | null = null;
add(data: number): void {
const node = new Nodes(data);
if (!this.head) {
this.head = node;
return
}
let tail = this.head;
while (tail.next){
tail = tail.next;
}
tail.next = node;
}
get length(): number {
if(!this.head) return 0
let node = this.head;
let length = 1;
while (node.next){
node = node.next;
length++;
}
return length
}
at(i: number): Nodes {
if(!this.head) throw new Error('Error');
let node: Nodes | null = this.head;
let counter = 0;
while (node){
if (counter === i) return node;
counter++;
node = node.next;
}
throw new Error('Error');
}
compare (i: number, j: number): boolean {
if(!this.head) throw new Error('Error');
return this.at(i).value > this.at(j).value
}
swap(i: number, j: number):void{
const tmp = this.at(i).value;
this.at(i).value = this.at(j).value;
this.at(j).value = tmp;
}
print():void{
if(!this.head) throw new Error('Error');
let node: Nodes | null = this.head;
while(node){
console.log(node.value);
node = node.next;
}
}
}
|
0769fe7d4e355d988d66a196ff2dd590f9e828f4
|
TypeScript
|
MyCupOfTeaOo/teaness
|
/src/utils.ts
| 2.90625
| 3
|
import { ErrorsType } from './Form/typings';
/**
* 常用的moment日期格式化枚举
*/
export enum DateFormat {
sec = 'YYYY-MM-DD HH:mm:ss',
min = 'YYYY-MM-DD HH:mm',
hour = 'YYYY-MM-DD HH',
day = 'YYYY-MM-DD',
month = 'YYYY-MM',
year = 'YYYY',
}
/**
* 跳转到表单字段处,如果可以focus则自动focus
* @param fieldKey 字典id
* @param options scrollIntoView的配置透传
* @returns 是否跳转成功
*/
export const scrollToField = (
fieldKey: string,
options: boolean | ScrollIntoViewOptions = {
block: 'center',
},
) => {
try {
let inputNode = document.querySelector(
`#${fieldKey?.replace(/\.|\[|\]/g, '-')}`,
);
if (inputNode) {
(inputNode as Element & { focus?: () => {} }).focus?.();
inputNode.scrollIntoView(options);
return true;
}
inputNode = document.getElementById(`${fieldKey}`);
if (inputNode) {
(inputNode as Element & { focus?: () => {} }).focus?.();
inputNode.scrollIntoView(options);
return true;
}
let labelNode = document.querySelector(`label[for="${fieldKey}"]`);
if (labelNode) {
labelNode.scrollIntoView(options);
return true;
}
labelNode = document.querySelector(
`label[for="${fieldKey?.replace(/\.|\[|\]/g, '-')}"]`,
);
if (labelNode) {
labelNode.scrollIntoView(options);
return true;
}
} catch (err) {
console.error(err);
}
return false;
};
/**
* 根据表单错误信息跳转字段位置
* @param errs 表单校验错误信息
* @returns 是否跳转成功,没有错误算成功
*/
export function scrollByFormErrors(errs?: ErrorsType<any>) {
if (errs) {
return scrollToField(errs[Object.keys(errs)[0]]?.[0].field!);
}
return true;
}
|
bedffba81193b57d33460d86bcb778e5a5a86d7e
|
TypeScript
|
MaxV-LTTVinh/learning-react-ts
|
/src/store/account/actions.ts
| 2.6875
| 3
|
import { Dispatch } from "react"
import { userService } from "../../services";
import { AccountActionTypes, LOAD_CURRENT_LOGIN_USER_FAILURE, LOAD_CURRENT_LOGIN_USER_REQUEST, LOAD_CURRENT_LOGIN_USER_SUCCESS, LOGIN_FAIL, LOGIN_REQUEST, LOGIN_SUCCESS, LOGOUT } from "./types"
export const login = (email: string, password: string) => {
return async (dispatch: Dispatch<AccountActionTypes>) => {
dispatch({
type: LOGIN_REQUEST,
payload: {
email: email,
password: password,
},
});
dispatch({
type: LOGIN_SUCCESS,
payload: { token: '' },
});
try {
const response = await userService.login(email, password);
dispatch({
type: LOGIN_SUCCESS,
payload: response,
});
} catch (error: any) {
dispatch({
type: LOGIN_FAIL,
payload: { error: error.toString() },
});
}
}
}
export const logout = (): AccountActionTypes => {
return { type: LOGOUT };
};
export const getCurrentLoginUser = () => {
return async (dispatch: Dispatch<AccountActionTypes>) => {
dispatch({
type: LOAD_CURRENT_LOGIN_USER_REQUEST,
});
try {
const response = await userService.getCurrentLoginUser();
dispatch({
type: LOAD_CURRENT_LOGIN_USER_SUCCESS,
payload: { user: response },
});
} catch (error: any) {
dispatch({
type: LOAD_CURRENT_LOGIN_USER_FAILURE,
payload: { error: error.toString() },
});
}
};
};
|
4ea36053d326fa6f2c0715a48f8ecc34cb8c9746
|
TypeScript
|
mora50/empty-template
|
/src/hooks/useDebounce.ts
| 2.890625
| 3
|
import { useRef } from "react";
export default function useDebounce(
fn: (...args: any[]) => void,
delay: number
) {
const timeoutRef = useRef(null);
function debouncedFn(...args: any[]) {
clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => {
fn(...args);
}, delay);
}
return debouncedFn;
}
|
51c2be7ae97c10ef692d7eec59a122bb8c0a4cc7
|
TypeScript
|
speakwithalisp/csp-with-ts
|
/src/impl/processEvents.ts
| 2.625
| 3
|
import { IStream, ProcessEvents, CLOSED } from './constants';
import { isChan } from './channels';
import { makeFakeThread } from './utils';
import { IChanValue, IChan, IProcPutE, IProcTakeE, IProcSleepE } from './interfaces';
import { CSP } from './service';
import { instructionCallback } from './instructions';
import { createQ } from './processQueue';
export function put<T extends IStream, S extends IStream = T>(chan: IChan<T, S>, source: IChan<any, T> | (() => Generator<IChanValue<T>, any, any>), altFlag?: boolean): IProcPutE<T, S> {
let isDone: boolean = false;
let newSource = isChan(source) ? function* () { yield source as IChanValue<T>; } : source;
function* proc() {
try {
const push: Generator<IChanValue<T>, IChanValue<T>, any> = newSource();
let state: { value: IChanValue<T>; done?: boolean | undefined; } = push.next();
if (isChan(source)) { yield state.value; push.return(state.value); isDone = true; return; }
if (state.done) { push.return(state.value); isDone = true; return; }
while (!state.done) {
yield state.value;
state = push.next();
if (!!state.done) { break; }
}
}
finally {
isDone = true;
}
}
Object.defineProperties(proc.prototype, { isDone: { get() { return isDone; } }, channel: { get() { return chan; } }, event: { get() { return ProcessEvents.PUT; } }, altFlag: { get() { return !!altFlag; } } });
return proc() as IProcPutE<T, S>;
}
export function take<T extends IStream, S extends IStream = T>(chan: IChan<T, S>, sink?: () => Generator<undefined, any, IChanValue<S>>, altFlag?: boolean, pred?: (arg?: IChanValue<S>) => boolean): IProcTakeE<T, S> {
let isDone: boolean = false;
function* proc() {
try {
// console.log('slink', sink);
const pull: Generator<undefined, void, IChanValue<S>> | undefined = sink ? sink() : undefined;
let done = false;
let state: IChanValue<S> | undefined;
if (!!pull) { pull.next(); }
while (!done) {
state = yield;
if (state === undefined || state === CLOSED) { if (pull) { pull.return(); } isDone = true; break; }
if (pred && !pred(state)) { if (pull) { pull.return(); } isDone = true; break; }
if (pull) { done = !!pull.next(state).done; }
// else { yield state; }
}
if (!done && pull) { pull.return(); }
}
finally {
isDone = true;
}
}
Object.defineProperties(proc.prototype, { isDone: { get() { return isDone; } }, channel: { get() { return chan; } }, event: { get() { return ProcessEvents.TAKE; } }, altFlag: { get() { return !!altFlag; } } });
return proc() as IProcTakeE<T, S>;
}
export function sleep(chan: IChan<boolean>, msecs: number): IProcSleepE {
let isDone: boolean = false;
const cb = (someCb: (() => void)) => { isDone = true; someCb(); };
const ret = (someCb: (() => void)) => { setTimeout(cb, msecs, someCb); }
Object.defineProperties(ret, { isDone: { get() { return isDone; } }, channel: { get() { return chan; } }, event: { get() { return ProcessEvents.SLEEP; } } });
return ret as IProcSleepE;
}
export function putAsync<T extends IStream, S extends IStream = T>(ch: IChan<T, S>, val: T, close?: boolean, cb?: () => any | void): void {
if (!CSP().has(ch)) { CSP().set(ch, createQ<T, S>(ch)); }
// CSP().get(ch)!.addCallback(instructionCallback(ProcessEvents.PUT, ch, () => { cb && cb(); return val; }, makeFakeThread()));
const mainCB = () => { cb && cb(); return val; };
Object.defineProperty(mainCB, 'close', { get() { return !!close; } });
CSP().get(ch)!.add(instructionCallback(ProcessEvents.PUT, ch, mainCB, makeFakeThread()));
}
export function takeAsync<T extends IStream, S extends IStream = T>(ch: IChan<T, S>): Promise<IChanValue<S>> {
if (!CSP().has(ch)) { CSP().set(ch, createQ<T, S>(ch)); }
const ret: Promise<IChanValue<S>> = new Promise<IChanValue<S>>(resolve => {
// CSP().get(ch)!.addCallback(instructionCallback(ProcessEvents.TAKE, ch, resolve as ((val: T) => T), makeFakeThread()));
CSP().get<T, S>(ch)!.add(instructionCallback(ProcessEvents.TAKE, ch, resolve, makeFakeThread()));
});
return ret;
}
|
837c651e1af5fd7b50885ec8d348c5338d3cc4ea
|
TypeScript
|
polyglotm/coding-dojo
|
/coding-challange/leetcode/medium/~2022-08-11/386-lexicographical-numbers/386-lexicographical-numbers.ts
| 3.625
| 4
|
/*
386-lexicographical-numbers
leetcode/medium/386. Lexicographical Numbers
URL: https://leetcode.com/problems/lexicographical-numbers/
NOTE: Description
NOTE: Constraints
- 1 <= n <= 5 * 104
NOTE: Explanation
NOTE: Reference
*/
function lexicalOrder(n: number): number[] {
const result = [];
for (let i = 1; i < n + 1; i += 1) {
result.push(String(i));
}
result.sort((a, b) => a.localeCompare(b));
return result.map(Number);
}
let n = 13;
console.log(lexicalOrder(n));
|
fbb4483c853bbec8e66b5a8fcbf8fc42b2c375c9
|
TypeScript
|
MasashiFukuzawa/design-patterns-learned-in-typescript
|
/chap19-state/src/state/nightState.ts
| 2.703125
| 3
|
import { State } from "./state";
import { Context } from "../context/context";
import { DayState } from "./dayState";
export class NightState implements State {
private static singleton: NightState = new NightState();
private constructor() {}
static getInstance(): State {
return NightState.singleton;
}
doClock(context: Context, hour: number): void {
if (hour >= 9 && hour < 17) {
context.changeState(DayState.getInstance());
}
}
doUse(context: Context): void {
context.recordLog('Use safe (night)');
}
doAlarm(context: Context): void {
context.callSecurityCenter('Alarm (night)');
}
doPhone(context: Context): void {
context.callSecurityCenter('Normal call (night)');
}
toString(): string {
return '[night]';
}
}
|
cfaee087d046f5c1351b1e5d00135d5df2ca1084
|
TypeScript
|
jaytonbye/dicey_business_typescript
|
/app.ts
| 3.5625
| 4
|
class Die {
value: number;
constructor() {
this.value = Math.floor(Math.random() * 6) + 1;
}
roll() {
this.value = Math.floor(Math.random() * 6) + 1;
}
}
// I used ! to end the line below, I don't think this was what you were looking for :(
let generateBtn = document.getElementById("generate-die")!;
generateBtn.addEventListener("click", () => {
let die = new Die();
let div = document.createElement("div");
let divText = document.createTextNode(die.value.toString());
document.body.appendChild(div);
div.appendChild(divText);
div.className = "dice";
div.addEventListener("dblclick", () => {
div.remove();
});
});
let rollBtn = document.getElementById("roll-dice")!;
//I don't know how to handle diceArray, getting "Type 'HTMLCollectionOf<Element>' is not an array type or a string type.ts(2495)"
//I solved this error by changing the tsconfig.json file to es6 because someone on the internet said to do it. I don't understand it.
rollBtn.addEventListener("click", () => {
let diceArray = document.getElementsByClassName("dice");
for (let x of diceArray) {
x.innerHTML = (Math.floor(Math.random() * 6) + 1).toString();
}
});
let sumBtn = document.getElementById("sum-dice")!;
sumBtn.addEventListener("click", () => {
let diceArray = document.getElementsByClassName("dice");
let diceTotal = 0;
for (let x of diceArray) {
diceTotal = diceTotal + parseInt(x.innerHTML);
}
alert(diceTotal);
});
//ugh, I still don't see the point
|
a9eb7d02e03dc1c359c960d8e0125a1d2c5410aa
|
TypeScript
|
craftina/SoftUni
|
/Angular/01.Introduction-To-Angular/05.Boxes/boxes.ts
| 3.59375
| 4
|
class Box<T>{
private _boxes = [];
get count(){
return this._boxes.length;
}
public add(element): void{
this._boxes.unshift(element);
}
public remove(): void{
this._boxes.shift();
}
}
let box = new Box<Number>();
box.add(1);
box.add(2);
box.add(3);
console.log(box.count);
console.log('-----------------------');
let box2 = new Box<String>();
box2.add("Pesho");
box2.add("Gosho");
console.log(box2.count);
box2.remove();
console.log(box2.count);
|
1a89d5e098d7c5ddccd616fdb2f7eeaa46842046
|
TypeScript
|
akulyk/ts29022020
|
/old/observable.ts
| 2.625
| 3
|
import { Observable } from "rxjs";
const sequence = new Observable((subscriber) => {
console.log('Internal')
let count = 1;
const intervalID = setInterval(() => {
subscriber.next(count++);
if (count === 10) {
subscriber.complete();
clearInterval(intervalID);
}
}, 1000)
});
setTimeout(() => {
sequence.subscribe((v) => {
console.log('Sub 2', v);
}, ()=>{}, ()=>{})
}, 5000);
//
sequence.subscribe((v) => {
console.log('Sub 1', v);
}, ()=>{}, ()=>{})
|
7537694338bc885b56593a3d087701548857b8fe
|
TypeScript
|
GoofyCMS/Frontend
|
/app/shared/resources/logger.ts
| 2.625
| 3
|
import {Component} from '@angular/core';
import {Growl, Message} from 'primeng/primeng';
@Component({
template: '<p-growl [value]="messages"></p-growl>',
directives: [Growl]
})
export class Logger {
messages: Message[] = [];
/**
* Log Info message
* @method
* @param {string} title - The message to print in console and/or show in notification widget
* @param {string} message
* @param {any} data - The data object to log into console
* @param {any} source - The source object to log into console
* @param {boolean} showToast - Show toast using kendo notification widget
*/
logInfo(title: string, message: string, data: any = null, source: any = null, showToast: boolean = false): void {
this.logIt(title, message, data, source, showToast, 'info');
}
/**
* Log Error message
* @method
* @param {string} title - The message to print in console and/or show in notification widget
* @param {string} message - The message to print in console and/or show in notification widget
* @param {any} data - The data object to log into console
* @param {any} source - The source object to log into console
* @param {boolean} showToast - Show toast using kendo notification widget
*/
logError(title: string, message: string, data: any = null, source: any = null, showToast: boolean = false): void {
this.logIt(title, message, data, source, showToast, 'error');
}
/**
* Log Success message
* @method
* @param {string} title - The message to print in console and/or show in notification widget
* @param {string} message - The message to print in console and/or show in notification widget
* @param {any} data - The data object to log into console
* @param {any} source - The source object to log into console
* @param {boolean} showToast - Show toast using kendo notification widget
*/
logSuccess(title: string, message: string, data: any = null, source: any = null, showToast: boolean = false): void {
this.logIt(title, message, data, source, showToast, 'info');
}
/**
* Log Warning message
* @method
* @param {string} title - The message to print in console and/or show in notification widget
* @param {string} message - The message to print in console and/or show in notification widget
* @param {any} data - The data object to log into console
* @param {any} source - The source object to log into console
* @param {boolean} showToast - Show toast using kendo notification widget
*/
logWarning(title: string, message: string, data: any = null, source: any = null, showToast: boolean = false): void {
this.logIt(title, message, data, source, showToast, 'warn');
}
/**
* Logs the message from the public methods
* @method
* @private
* @param {string} title - The message to print in console and/or show in notification widget
* @param {string} message - The message to print in console and/or show in notification widget
* @param {any} data - The data object to log into console
* @param {any} source - The source object to log into console
* @param {boolean} showToast - Show toast using kendo notification widget
* @param {string} toastType - The type of notification to show
*/
private logIt(title: string, message: string, data: any, source: any, showToast: boolean, toastType: string): void {
if (data) {
if (window.console[toastType]) {
window.console[toastType](message, source, data);
} else {
window.console.log(message, source, data);
}
} else {
if (window.console[toastType]) {
window.console[toastType](message, source);
} else {
window.console.log(message, source);
}
}
if (showToast) {
//this.messages = [{ severity: toastType, summary: title, detail: message }];
this.messages.push({ severity: toastType, summary: title, detail: message });
}
}
}
|
0e30abf9da2f6e71f809afcf32d2851972ea802f
|
TypeScript
|
okipeterovie/hobeei
|
/src/services/NumberToWord.ts
| 3.3125
| 3
|
export class NumberToWord {
_currency: string = ""; //Naira
_decimalCurrency: string = ""; //Kobo
set currency(currencyName: string) {
this._currency = currencyName;
}
get currency(): string {
return this._currency;
}
set decimalCurrency(currencyName: string) {
this._decimalCurrency = currencyName;
}
get decimalCurrency(): string {
return this._decimalCurrency;
}
th = ['', 'Thousand', 'Million', 'Billion', 'Trillion'];
dg = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
tn = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
tw = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
toWords(amount: any): string {
amount = amount.toString();
var atemp = amount.split(".");
var s = atemp[0].split(",").join("");
s = s.toString(); s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += this.tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
}
else if (n[i] != 0) {
str += this.tw[n[i] - 2] + ' ';
sk = 1;
}
}
else if (n[i] != 0) {
str += this.dg[n[i]] + ' ';
if ((x - i) % 3 == 0) {
str += 'Hundred ';
}
sk = 1;
}
if ((x - i) % 3 == 1) {
if (sk) {
str += this.th[(x - i - 1) / 3] + ' ';
}
sk = 0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (let i = x + 1; i < y; i++) {
str += this.dg[n[i]] + ' ';
}
}
let words = str.replace(/\s+/g, ' ');
if (words.length > 0) {
words += this.currency;
}
let decimalWords = "";
if (atemp[1]) {
decimalWords = this.toWords(atemp[1]).replace(this.currency, this.decimalCurrency);
}
return decimalWords.length > 0 ? words + " and " + decimalWords : words;
}
public static getAmountInWords(amount: any, currency?: string, decimalCurrency?: string): string {
let n = new NumberToWord();
if (currency) {
n.currency = currency;
}
if (decimalCurrency) {
n.decimalCurrency = decimalCurrency;
}
return n.toWords(amount);
}
}
|
de304e2b2e1365a61cac68f7e4783d7e309075c0
|
TypeScript
|
benkolera/salty-deadlands
|
/src/CharacterSheet/DiceSet.ts
| 3.25
| 3
|
import { Chance } from "chance";
export type Sides = 4 | 6 | 8 | 10 | 12 | 20;
export type TraitResult = "bust" | number;
export type Successes = number;
export type Raises = number;
export type VsTn<A> = "bust" | "failure" | A;
export interface OpposedDraw {
type: "draw";
attackerBusted: boolean;
defenderBusted: boolean;
}
export interface OpposedWin {
type: "attacker" | "defender";
raises: Raises;
loserBusted: boolean;
}
export type OpposedResult = OpposedDraw | OpposedWin;
export function mapVsTn<A, B>(vstn: VsTn<A>, f: (a: A) => B): VsTn<B> {
if (vstn === "bust" || vstn === "failure") {
return vstn;
} else {
return f(vstn);
}
}
export function flatmapVsTn<A, B>(
vstn: VsTn<A>,
f: (a: A) => VsTn<B>,
): VsTn<B> {
if (vstn === "bust" || vstn === "failure") {
return vstn;
} else {
return f(vstn);
}
}
const traitSides: Sides[] = [4, 6, 8, 10, 12];
const damageSides: Sides[] = [4, 6, 8, 10, 12, 20];
export interface DiceSetCloneI {
num?: number;
sides?: Sides;
bonus?: number;
}
export interface ExplodingRoll {
sum: boolean;
tn?: number;
raises: boolean;
}
function toExplodingCode(e:ExplodingRoll): string {
return "!" +
(e.sum ? "" : "k") +
(e.tn !== undefined ? "t" + e.tn : "") +
(e.raises ? "s5" : "");
}
export class DiceSet {
sides: Sides;
num: number;
bonus: number;
constructor(num:number, sides:Sides, bonus: number = 0) {
this.sides = sides;
this.num = num;
this.bonus = bonus;
}
clone(args:DiceSetCloneI):DiceSet {
return new DiceSet(
args.num === undefined ? this.num : args.num,
args.sides === undefined ? this.sides : args.sides,
args.bonus === undefined ? this.bonus : args.bonus,
);
}
addBonus(bonus:number): DiceSet {
return this.clone({ bonus: this.bonus + bonus });
}
toFgCode(exploding?:ExplodingRoll): string {
return "/die " + this.toString() + (
exploding !== undefined ? toExplodingCode(exploding) : ""
);
}
toString() {
const bonusSign = this.bonus > 0 ? "+" : "";
const bonus = this.bonus !== 0 ? `${bonusSign}${ this.bonus }` : "";
return `${ this.num }d${ this.sides }${ bonus }`;
}
}
// tslint:disable-next-line:function-name
export function _rollDie(
chance: Chance.Chance,
sides: number,
total: number= 0,
rerolls: number= 10,
): number {
const res = chance.natural({ max: sides });
if (rerolls === 0 || res < sides) {
return total + res;
} else {
return _rollDie(chance, sides, total + res, rerolls - 1);
}
}
// tslint:disable-next-line:function-name
export function _bustedOrMax(results: number[]): TraitResult {
const ones = results.filter(n => n === 1).length;
if (ones > results.length - ones) {
return "bust";
} else {
return Math.max(...results);
}
}
// tslint:disable-next-line:function-name
function _stepSides(
allSides: Sides[],
timesLeft: number,
num: number,
sides: Sides,
bonus: number,
): DiceSet {
if (timesLeft === 0) {
return new DiceSet(num, sides, bonus);
} else {
const i = allSides.indexOf(sides);
if (i === allSides.length - 1) {
return _stepSides(allSides, timesLeft - 1, num, sides, bonus + 2);
} else {
return _stepSides(allSides, timesLeft - 1, num, allSides[i + 1], 0);
}
}
}
export function stepTraitType(ds: DiceSet, times: number= 1): DiceSet {
return _stepSides(traitSides, times, ds.num, ds.sides, ds.bonus);
}
export function stepDamage(ds: DiceSet, times: number= 1): DiceSet {
return _stepSides(damageSides, times, ds.num, ds.sides, ds.bonus);
}
function rollDice(chance: Chance.Chance, ds: DiceSet): number[] {
return Array.from(
{ length: ds.num },
(v, k) => _rollDie(chance, ds.sides),
);
}
export function rollDamage(chance: Chance.Chance, ds: DiceSet): number {
return rollDice(chance, ds).reduce((a, b) => a + b, 0);
}
// tslint:disable-next-line:function-name
export function _traitResult(
diceRes: number[],
bonus: number,
): TraitResult {
const out = _bustedOrMax(diceRes);
if (out !== "bust") {
return out + bonus;
} else {
return "bust";
}
}
export function rollTrait(chance: Chance.Chance, ds: DiceSet): TraitResult {
return _traitResult(rollDice(chance, ds), ds.bonus);
}
// tslint:disable-next-line:function-name
export function _successes(diff:number):Successes {
return 1 + Math.floor(diff / 5);
}
// tslint:disable-next-line:function-name
export function _successesVsTn(
res: TraitResult,
tn: number,
): VsTn<Successes> {
return mapVsTn(
_aboveTn(res, tn),
_successes,
);
}
export function successesVsTn(
chance: Chance.Chance,
ds: DiceSet,
tn: number,
): VsTn<Successes> {
return _successesVsTn(rollTrait(chance, ds), tn);
}
// tslint:disable-next-line:function-name
export function _aboveTn(res: TraitResult, tn: number): VsTn<number> {
if (res === "bust") {
return "bust";
} else if (res >= tn) {
return res - tn;
} else {
return "failure";
}
}
export function aboveTn(
chance: Chance.Chance,
ds: DiceSet,
tn: number,
): VsTn<number> {
return _aboveTn(rollTrait(chance, ds), tn);
}
// tslint:disable-next-line:function-name
export function _opposedRoll(
attackRes:VsTn<number>,
defendRes:VsTn<number>,
):OpposedResult {
const a = attackRes === "bust" || attackRes === "failure"
? -1
: attackRes;
const d = defendRes === "bust" || defendRes === "failure"
? -1
: defendRes;
if (a === d) {
return {
type: "draw",
attackerBusted: attackRes === "bust",
defenderBusted: defendRes === "bust",
};
} else {
const aRaises = a > 0 ? _successes(a) - 1 : 0;
const dRaises = d > 0 ? _successes(d) - 1 : 0;
if (a > d) {
return {
type: "attacker",
raises: Math.max(0, aRaises - dRaises),
loserBusted: defendRes === "bust",
};
} else {
return {
type: "defender",
raises: Math.max(0, dRaises - aRaises),
loserBusted: attackRes === "bust",
};
}
}
}
export const opposedRoll = (
chance: Chance.Chance,
attackerDs: DiceSet,
defenderDs: DiceSet,
): OpposedResult => {
return _opposedRoll(
aboveTn(chance, attackerDs, 5),
aboveTn(chance, defenderDs, 5),
);
};
|
1ee891d5dda34a00c09287c8ccac787488d3e29a
|
TypeScript
|
baltel/Ang5WebAPI
|
/AngularSPAWebAPI/app/shared/log-publishers.ts
| 2.75
| 3
|
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import {
Http, Response,
Headers, RequestOptions
}
from '@angular/http';
import { LogEntry } from '../services/log.service';
export abstract class LogPublisher {
location: string;
abstract log(record: LogEntry):
Observable<boolean>
abstract clear(): Observable<boolean>;
}
export class LogConsole extends LogPublisher {
log(entry: LogEntry): Observable<boolean> {
// Log to console
console.log(entry.buildLogString());
return Observable.of(true);
}
clear(): Observable<boolean> {
console.clear();
return Observable.of(true);
}
}
export class LogLocalStorage
extends LogPublisher {
constructor() {
// Must call super() from derived classes
super();
// Set location
this.location = "logging";
}
// Append log entry to local storage
log(entry: LogEntry): Observable<boolean> {
let ret: boolean = false;
let values: LogEntry[];
try {
// Get previous values from local storage
values = JSON.parse(
localStorage.getItem(this.location))
|| [];
// Add new log entry to array
values.push(entry);
// Store array into local storage
localStorage.setItem(this.location,
JSON.stringify(values));
// Set return value
ret = true;
} catch (ex) {
// Display error in console
console.log(ex);
}
return Observable.of(ret);
}
// Clear all log entries from local storage
clear(): Observable<boolean> {
localStorage.removeItem(this.location);
return Observable.of(true);
}
}
export class LogWebApi extends LogPublisher {
constructor(private http: Http) {
// Must call super() from derived classes
super();
// Set location
this.location = "/api/log";
}
// Add log entry to back end data store
log(entry: LogEntry): Observable<boolean> {
let headers = new Headers(
{ 'Content-Type': 'application/json' });
let options = new
RequestOptions({ headers: headers });
return this.http.post(this.location,
entry, options)
.map(response => response.json())
.catch(this.handleErrors);
}
// Clear all log entries from local storage
clear(): Observable<boolean> {
// TODO: Call Web API to clear all values
return Observable.of(true);
}
private handleErrors(error: any):
Observable<any> {
let errors: string[] = [];
let msg: string = "";
msg = "Status: " + error.status;
msg += " - Status Text: " + error.statusText;
if (error.json()) {
msg += " - Exception Message: " +
error.json().exceptionMessage;
}
errors.push(msg);
console.error('An error occurred', errors);
return Observable.throw(errors);
}
}
export class LogPublisherConfig {
loggerName: string;
loggerLocation: string;
isActive: boolean;
}
|
57e23578e8af441a59d09cf7d91cf199715815d2
|
TypeScript
|
nightism/react-scax
|
/src/pool/pools.ts
| 2.8125
| 3
|
import { error } from '../common/utils';
import { IPool, IPoolView, TScaxerBatchConfiguration, TScaxerDataTypeMap } from '../types';
import Pool from './Pool';
const poolViewNameObjectMap: {
[poolName: string]: IPoolView,
} = {};
/**
* Create a pool uniquely identified by a name.
* @param poolName a unique string used to identify the pool.
* @generic `N`: shape like { [key: string]: IScaxerView<A, B, C, D> }
*/
export function createPool<TScaxerDataTypes extends TScaxerDataTypeMap>
(poolName: string, scaxersConfigs: TScaxerBatchConfiguration<TScaxerDataTypes>): IPool<TScaxerDataTypes> {
if (poolViewNameObjectMap[poolName]) {
error('Repeated pool name.');
}
const newPool = new Pool<TScaxerDataTypes>(poolName, scaxersConfigs);
poolViewNameObjectMap[poolName] = newPool;
return newPool as IPool<TScaxerDataTypes>;
}
export function getPoolView(poolName: string): IPoolView {
if (!poolViewNameObjectMap[poolName]) {
error('Pool name does not exist.');
}
return poolViewNameObjectMap[poolName];
}
|
5857e0220ffb22f0e66e194e5b5c729a9a57ee00
|
TypeScript
|
KiranKaur/Racing-Car-Assignment3
|
/COMP397-MailPilot/Scripts/game.ts
| 2.609375
| 3
|
/// <reference path="typings/stats/stats.d.ts" />
/// <reference path="typings/easeljs/easeljs.d.ts" />
/// <reference path="typings/tweenjs/tweenjs.d.ts" />
/// <reference path="typings/soundjs/soundjs.d.ts" />
/// <reference path="typings/preloadjs/preloadjs.d.ts" />
/// <reference path="utility/utility.ts" />
/// <reference path="objects/gameobject.ts" />
/// <reference path="objects/road.ts" />
/// <reference path="objects/car.ts" />
/// <reference path="objects/button.ts" />
/// <reference path="objects/fuelcan.ts" />
/// <reference path="objects/stone.ts" />
/// <reference path="objects/scoreboard.ts" />
/// <reference path="managers/collision.ts" />
// Game Framework Variables
var canvas = document.getElementById("canvas");
var stage: createjs.Stage;
var stats: Stats;
var game: createjs.Container;
var assets: createjs.LoadQueue;
var manifest = [
{ id: "road", src: "assets/images/road track.png" },
{ id: "car", src: "assets/images/car7.png" },
{ id: "fuelcan", src: "assets/images/gaspump.png" },
{ id: "start", src: "assets/images/instructions.png" },
{ id: "gameover", src: "assets/images/gameover.png" },
{ id: "startbutton", src: "assets/images/startbutton.png" },
{ id: "tryagain", src: "assets/images/tryagain.png" },
{ id: "stone", src: "assets/images/stone.png" },
{ id: "yay", src: "assets/audio/fuelcansound.wav" },
{ id: "thunder", src: "assets/audio/stonesound.wav" },
{ id: "engine", src: "assets/audio/cardriving.wav" }
];
// Game Variables
var road: objects.Road;
var car: objects.Car;
var fuelcan: objects.FuelCan;
var stones: objects.Stone[] = [];
var x: number = 0;
var scoreboard: objects.ScoreBoard;
// Game Managers
var collision: managers.Collision;
var start: createjs.Bitmap;
var gameover: createjs.Bitmap;
var startbutton: objects.Button;
var tryagain: objects.Button;
// Preloader Function
function preload() {
assets = new createjs.LoadQueue();
assets.installPlugin(createjs.Sound);
// event listener triggers when assets are completely loaded
assets.on("complete", init, this);
assets.loadManifest(manifest);
//Setup statistics object
setupStats();
}
// Callback function that initializes game objects
function init() {
stage = new createjs.Stage(canvas); // reference to the stage
stage.enableMouseOver(20);
createjs.Ticker.setFPS(60); // framerate 60 fps for the game
// event listener triggers 60 times every second
createjs.Ticker.on("tick", gameLoop);
// calling main game function
main();
}
// function to setup stat counting
function setupStats() {
stats = new Stats();
stats.setMode(0); // set to fps
// align bottom-right
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '650px';
stats.domElement.style.top = '10px';
document.body.appendChild(stats.domElement);
}
// Callback function that creates our Main Game Loop - refreshed 60 fps
function gameLoop() {
stats.begin(); // Begin measuring
road.update();
car.update();
fuelcan.update();
for (var stone = 0; stone < 3; stone++) {
stones[stone].update();
collision.check(stones[stone]);
}
collision.check(fuelcan);
if (x == 1) {
scoreboard.update();
}
stage.update();
stats.end(); // end measuring
}
function startButtonClicked(event: createjs.MouseEvent) {
game.addChild(fuelcan);
game.addChild(car);
// add 3 stone objects to stage
for (var stone = 0; stone < 3; stone++) {
game.addChild(stones[stone]);
}
// game.addChild(scoreboard.lives);
// game.addChild(scoreboard.score);
//add scoreboard
game.removeChild(start);
game.removeChild(startbutton);
game.removeChild(tryagain);
game.removeChild(gameover);
x = 1;
}
function tryagainButtonClicked(event: createjs.MouseEvent) {
game.addChild(fuelcan);
game.addChild(car);
// add 3 stone objects to stage
for (var stone = 0; stone < 3; stone++) {
game.addChild(stones[stone]);
}
// game.addChild(scoreboard.lives);
// game.addChild(scoreboard.score);
//add scoreboard
game.removeChild(start);
game.removeChild(startbutton);
game.removeChild(tryagain);
game.removeChild(gameover);
x = 1;
}
// Our Main Game Function
function main() {
// instantiate game conatainer
x = 0;
game = new createjs.Container();
//add car object to stage
road = new objects.Road(assets.getResult("road"));
game.addChild(road);
//add fuelcan object to stage
fuelcan = new objects.FuelCan(assets.getResult("fuelcan"));
for (var stone = 0; stone < 3; stone++) {
stones[stone] = new objects.Stone(assets.getResult("stone"));
}
// add car object to stage
car = new objects.Car(assets.getResult("car"));
start = new createjs.Bitmap(assets.getResult("start"));
game.addChild(start);
startbutton = new objects.Button(assets.getResult("startbutton"), 440, 320);
game.addChild(startbutton);
startbutton.on("click", startButtonClicked);
gameover = new createjs.Bitmap(assets.getResult("gameover"));
tryagain = new objects.Button(assets.getResult("tryagain"), 440, 340);
tryagain.on("click", tryagainButtonClicked);
scoreboard = new objects.ScoreBoard();
//add collision manager
collision = new managers.Collision();
//add game conatiner to stage
stage.addChild(game);
console.log(game);
}
|
d42773c03bc46b7f8368e2823b502c235108a00d
|
TypeScript
|
bradmartin/nativescript-sentry
|
/src/index.d.ts
| 2.78125
| 3
|
export abstract class Sentry {
/**
* Initializes the Sentry SDK for the provided DSN key.
* @param opts [SentryOptions] - The SentryOptions for the SDK.
*/
static init(opts: InitOptions): void;
/**
* Log a message.
* @param message [string] - The message to log.
*/
static captureMessage(message: string): void;
/**
* Log an exception.
* @param exeption [Error] - The exception to log.
*/
static captureException(exeption: Error): void;
/**
* Log a breadcrumb for the current Sentry context.
* @param breadcrumb [BreadCrumb] - The breadcrumb to capture.
*/
static captureBreadcrumb(breadcrumb: BreadCrumb): void;
/**
* Set a user to the Sentry context.
* @param user [SentryUser] - The user to set with the current Sentry context.
*/
static setUser(user: UserOptions): void;
/**
* Set an object of additional Key/value pairs which generate breakdowns charts and search filters.
* @param tags [object] - Object of additional Key/value pairs.
*/
static setTags(tags: object): void;
}
export interface UserOptions {
id: string;
email?: string;
}
export interface BreadCrumb {
message: string;
category: string;
level: Level;
}
export interface InitOptions {
dsn: string;
debug?: boolean;
enableAutoPerformanceTracking?: boolean;
attachScreenshot?: boolean;
attachStacktrace?: boolean;
beforeSend?: function;
}
export enum Level {
Fatal = 'fatal',
Error = 'error',
Warning = 'warning',
Info = 'info',
Debug = 'debug'
}
|
f5869c54c55c3f7f420372229a70d8c77daa09cc
|
TypeScript
|
terzurumluoglu/ChatApplication
|
/functions/src/services/token.ts
| 2.5625
| 3
|
import { Device } from "../model/model";
// Bu metot user ın bütün device tokenlarını alır çoklanmış olanların tekilleştirir ve diğerlerinin indexlerini silinmek üzere ayırır.
export const findRepeatingElement = function (array: Device[]): any[][] {
const temp: any = {};
const deleteTokensIndexes: any[] = [];
const inUseTokens: any[] = [];
for (let i = 0; i < array.length; i++) {
if (temp[array[i].token]) {
deleteTokensIndexes.push(i);
}
temp[array[i].token] = true;
}
for (const k in temp) {
inUseTokens.push(array.find(f => f.token === k));
}
return [inUseTokens, deleteTokensIndexes];
}
|
4bea2de03a81f8fd51c39dcf7a157d07615f2479
|
TypeScript
|
ByDSA/datune
|
/packages/strings/src/parsing/utils/tokenize.ts
| 2.59375
| 3
|
import { Lexer, TokenType } from "chevrotain";
import { Options } from "lang";
import { GLOBAL_TOKENS } from "./tokens";
export type TokenizeOptions = Options & {
input: string;
langTokens: TokenType[];
};
export default function tokenize(options: TokenizeOptions) {
const { langTokens } = options;
const allTokens = [...Object.values(GLOBAL_TOKENS), ...Object.values(langTokens)];
const lexer = new Lexer(allTokens);
const result = lexer.tokenize(options.input);
if (result.errors.length > 0)
throw new Error(result.errors.map((e) => e.message).join("\n"));
return result.tokens;
}
|
c30743618add3103ab99ac598acab57e351882d3
|
TypeScript
|
duongquang1611/agora_test1
|
/src/app-redux/product/reducer.ts
| 2.75
| 3
|
import ActionType from './types';
const initialState: any = {
arrayImage: [],
category: '',
brand: '',
};
const product = (state: any = initialState, action: any) => {
switch (action.type) {
case ActionType.UPDATE_IMAGE:
return { ...state, arrayImage: action.data };
case ActionType.UPDATE_CATEGORY:
return { ...state, category: action.data };
case ActionType.UPDATE_BRAND:
return { ...state, brand: action.data };
case ActionType.DELETE_PRODUCT:
return { ...state, arrayImage: [] };
default:
return state;
}
};
export default product;
|
0186d65df3620f2a2aad066c72ff1b24e73e8b8b
|
TypeScript
|
Cotel/iToldo
|
/src/weather/types.ts
| 3.140625
| 3
|
/**
* Weather descriptions found in openweather api https://openweathermap.org/weather-conditions
*/
export type WindSpeed = number
export type Weather = 'Clear' | Clouds | Rain | 'Drizzle' | Thunderstorm | 'Mist' | 'Haze' | 'Fog'
const rain = ['Light', 'Moderate', 'Heavy', 'Very Heavy', 'Extreme'] as const
export type Rain = (typeof rain)[number]
export const isRain = (x: any): x is Rain => rain.includes(x)
const clouds = ['Overcast', 'Broken', 'Scattered', 'Few'] as const
export type Clouds = (typeof clouds)[number]
export const isClouds = (x: any): x is Clouds => clouds.includes(x)
const thunderstorm = ['With Light Rain', 'With Rain', 'With Heavy Rain', 'Light', 'Normal', 'Heavy', 'Ragged', 'With Light Drizzle', 'With Drizzle', 'With Heavy Drizzle'] as const
export type Thunderstorm = (typeof thunderstorm)[number]
export const isThunderstorm = (x: any): x is Thunderstorm => thunderstorm.includes(x)
export interface SunTimes {
sunrise: number
sunset: number
}
export const noon = ({sunrise, sunset}: SunTimes): number => (sunrise + sunset) / 2
|
24111f597fb09b95840d18c26097f4bc106caa52
|
TypeScript
|
GRPMIPSVisualizer/HardwareLogic
|
/Assembler2/src/ts/MapForInsType.ts
| 2.71875
| 3
|
export class MapForInsType {
private static map = new Map();
private constructor() {}
public static getMap(): Map<string, string> {
if (this.map.size == 0) {
let typeR: string = "R";
let typeI: string = "I";
let typeJ: string = "J";
let typeP: string = "P";
this.map.set("add", typeR);
this.map.set("addu", typeR);
this.map.set("sub", typeR);
this.map.set("subu", typeR);
this.map.set("and", typeR);
this.map.set("or", typeR);
this.map.set("nor", typeR);
this.map.set("slt", typeR);
this.map.set("sltu", typeR);
this.map.set("sll", typeR);
this.map.set("srl", typeR);
this.map.set("jr", typeR);
this.map.set("sra", typeR);
this.map.set("addi", typeI);
this.map.set("addiu", typeI);
this.map.set("andi", typeI);
this.map.set("beq", typeI);
this.map.set("bne", typeI);
this.map.set("lbu", typeI);
this.map.set("lhu", typeI);
this.map.set("llOp", typeI);
this.map.set("lui", typeI);
this.map.set("lw", typeI);
this.map.set("ori", typeI);
this.map.set("slti", typeI);
this.map.set("sltiu", typeI);
this.map.set("sb", typeI);
this.map.set("sc", typeI);
this.map.set("sh", typeI);
this.map.set("sw", typeI);
this.map.set("j", typeJ);
this.map.set("jal", typeJ);
this.map.set("abs", typeP);
this.map.set("blt", typeP);
this.map.set("bgt", typeP);
this.map.set("ble", typeP);
this.map.set("neg", typeP);
this.map.set("negu", typeP);
this.map.set("not", typeP);
this.map.set("bge", typeP);
this.map.set("li", typeP);
this.map.set("la", typeP);
this.map.set("move", typeP);
this.map.set("sge", typeP);
this.map.set("sgt", typeP);
}
return this.map;
}
}
|
d0bfc3a61e2c83ddb7c6b4941406853aac0cb008
|
TypeScript
|
mckatoo/clinica
|
/api/src/data/protocols/cache/cache-store.ts
| 2.578125
| 3
|
export interface CacheStore {
delete: (deleteKey: string) => void
insert: (insertKey: string, values: any) => void
replace: (key: string, values: any) => void
}
|
dfbb4e05e82e525aa3c840ec01a35d2b727aea42
|
TypeScript
|
intro-to-prog/frontend
|
/src/app/reducers/shopping.reducer.ts
| 2.5625
| 3
|
import { EntityState, createEntityAdapter } from '@ngrx/entity';
import { createReducer, Action, on } from '@ngrx/store';
import * as actions from '../actions/shopping.actions';
export interface ShoppingEntity {
id: string;
description: string;
}
export interface ShoppingState extends EntityState<ShoppingEntity> {
}
export const adapter = createEntityAdapter<ShoppingEntity>();
const initialState = adapter.getInitialState();
const reducerFunction = createReducer(
initialState,
on(actions.loadTheShoppingListSucceeded, (currentState, action) => adapter.setAll(action.payload, currentState)),
on(actions.temporaryShoppingItemCreated, (s, a) => adapter.addOne(a.payload, s)),
on(actions.shoppingItemCreated, (s, a) => adapter.updateOne({
id: a.temporaryId,
changes: {
id: a.payload.id
}
}, s)),
on(actions.shoppingItemDeleted, (s, a) => adapter.removeOne(a.payload.id, s)),
on(actions.shoppingItemCreationFailed, (s,a) => adapter.removeOne(a.payload.id, s))
);
export function reducer(state: ShoppingState = initialState, action: Action): ShoppingState {
return reducerFunction(state, action);
}
|
86e033ffa4c73b6e7073a2f2627e869fe1c7df19
|
TypeScript
|
nimuseel/hi-nest
|
/src/movies/movies.service.ts
| 2.71875
| 3
|
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateMovieDto } from './dto/create-movie.dto';
import { UpdateMovieDto } from './dto/update-movie.dto';
import { Movie } from './entites/Movie.entity';
@Injectable()
export class MoviesService {
private movies: Movie[] = [];
getAll(): Movie[] {
return this.movies;
}
findMovieById(id: number): Movie {
const findMovie = this.movies.find(movie => movie.id === id);
if (!findMovie) {
throw new NotFoundException(`Movie ID ${id} is Not Found`);
}
return findMovie;
}
deleteMovie(id: number) {
this.findMovieById(id);
this.movies = this.movies.filter(movie => movie.id !== id);
}
createMovie(movieData: CreateMovieDto) {
this.movies.push({
id: this.movies.length + 1,
...movieData,
});
}
updateMovie(id: number, updateData: UpdateMovieDto) {
const findMovie = this.findMovieById(id);
this.deleteMovie(id);
this.movies.push({
...findMovie,
...updateData,
});
}
}
|
af19deb0dd67f50f0bcbd194be82f416a9a5bde4
|
TypeScript
|
joni-/packages-parser
|
/util.ts
| 3.28125
| 3
|
export const isEmpty = <T>(v: string | T[]) =>
Array.isArray(v) ? v.length === 0 : v.trim().length === 0;
export const trim = (s: string) => s.trim();
// note: if there are duplicated values, keeps the last occurrence
export const uniqBy = <T>(getKey: (v: T) => string, input: T[]): T[] => {
const xs = input.reduce((acc: Record<string, T>, current) => {
const k = getKey(current);
acc[k] = current;
return acc;
}, {});
return Object.values(xs);
};
export const findDuplicates = <T>(
getKey: (v: T) => string,
input: T[]
): string[] => {
const counts = input.map(getKey).reduce<Record<string, number>>((keys, k) => {
keys[k] = (keys[k] ?? 0) + 1;
return keys;
}, {});
const duplicateKeys = Object.entries(counts)
.filter(([_, count]) => count > 1)
.map(([k, _]) => k);
return duplicateKeys;
};
|
daf2fa37b83b02cdc4245b75b020123503af1020
|
TypeScript
|
Jareechang/esbuild-examples
|
/examples/tree-shaking-annotations/src/index.ts
| 2.84375
| 3
|
import * as utils from './utils';
import getConfig from './config';
console.log(utils.add(2, 3));
// Not removed, but unused
const result1 = utils.subtract(5, 3);
// removed because of no annotation and of no reference
const result2 = /* @__PURE__ */ utils.subtract(5, 3);
// keep code even with annotation because of variable reference
const result3 = /* @__PURE__ */ utils.subtract(5, 3);
console.log(result3)
// Alternative syntax. removed due to annotation and no reference
const config = /* #__PURE__ */ getConfig();
|
e492447b1bc3abbb361ba47a66e9c2737e440421
|
TypeScript
|
folke/adventofcode
|
/src/2015/day1.ts
| 3.1875
| 3
|
import { Input, Solution } from "../util"
export const part1: Solution = (input: Input) => {
let ret = 0
for (const c of input.data) {
if (c == "(") ret++
else ret--
}
return ret
}
part1.examples = []
part1.answer = 280
export const part2: Solution = (input: Input) => {
let ret = 0
for (let i = 0; i < input.data.length; i++) {
const c = input.data[i]
if (c == "(") ret++
else ret--
if (ret == -1) return i + 1
}
return ret
}
part2.examples = [["()())", 5]]
part2.answer = 1797
|
833eef1e323b5aca08489da4f717adcd6ccda092
|
TypeScript
|
lostfictions/rot.ts
|
/src/fov/fov.ts
| 3.140625
| 3
|
import { DIRS } from "../constants";
export interface FOVOptions {
topology: 4 | 6 | 8;
}
export type LightPassesCallback = (x: number, y: number) => boolean;
export type VisibilityCallback = (
x: number,
y: number,
r: number,
visibility: number
) => void;
export abstract class FOV {
protected _lightPasses: LightPassesCallback;
protected _options: FOVOptions;
/**
* @param lightPassesCallback Does the light pass through x,y?
*/
constructor(
lightPassesCallback: LightPassesCallback,
options?: Partial<FOVOptions>
) {
this._lightPasses = lightPassesCallback;
this._options = {
topology: 8,
...options
};
}
/**
* Compute visibility for a 360-degree circle
* @param x
* @param y
* @param R Maximum visibility radius
* @param callback
*/
abstract compute(
x: number,
y: number,
R: number,
callback: VisibilityCallback
): void;
/**
* Return all neighbors in a concentric ring
* @param cx center-x
* @param cy center-y
* @param r range
*/
protected _getCircle(cx: number, cy: number, r: number): [number, number][] {
// prettier-ignore
let dirs!: ReadonlyArray<[number, number]>;
// prettier-ignore
let countFactor!: number;
// prettier-ignore
let startOffset!: [number, number];
switch (this._options.topology) {
case 4:
countFactor = 1;
startOffset = [0, 1];
dirs = [DIRS[8][7], DIRS[8][1], DIRS[8][3], DIRS[8][5]];
break;
case 6:
dirs = DIRS[6];
countFactor = 1;
startOffset = [-1, 1];
break;
case 8:
dirs = DIRS[4];
countFactor = 2;
startOffset = [-1, 1];
}
const result: [number, number][] = [];
/* starting neighbor */
let x = cx + startOffset[0] * r;
let y = cy + startOffset[1] * r;
/* circle */
for (const dir of dirs) {
for (let j = 0; j < r * countFactor; j++) {
result.push([x, y]);
x += dir[0];
y += dir[1];
}
}
return result;
}
}
|
eef9b541f54dfd8cd0f580324446b6ea99f1fdcb
|
TypeScript
|
EugeneDraitsev/simple-blog-task
|
/src/stores/feed.store.ts
| 2.8125
| 3
|
/* eslint-disable no-param-reassign */
import { action, observable } from 'mobx'
import { persist } from 'mobx-persist'
import { StoryModel } from '../models'
export class FeedStore {
@persist('list', StoryModel) @observable public feed: StoryModel[] = []
@observable public draftStories: StoryModel[] = []
constructor(feed: StoryModel[]) {
this.feed = feed
}
@action
public addStory = (item: StoryModel): void => {
this.feed.unshift(item)
this.feed = [...this.feed]
}
@action
public addDraftStory = (item: StoryModel): void => {
this.draftStories = [...this.draftStories, item]
}
@action
public addViews = (id: number): void => {
this.feed = this.feed.map((story) => {
if (story.id === id) {
story.views += 1
}
return story
})
}
@action
public editStory = (id: number, data: Partial<StoryModel>): void => {
this.feed = this.feed.map((story) => {
if (story.id === id) {
if (typeof data.text === 'string') {
story.text = data.text
}
if (typeof data.title === 'string') {
story.title = data.title
}
}
return story
})
}
@action
public deleteStory = (id: number): void => {
this.feed = this.feed.filter((story) => story.id !== id)
}
@action
public deleteDraftStory = (id: number): void => {
this.feed = this.feed.filter((story) => story.id !== id)
}
}
|
2c5938007e713fe091abc05d1d4c6ca0103a1413
|
TypeScript
|
openfl/starling
|
/samples/demo_npm/typescript/src/constants.ts
| 2.515625
| 3
|
class Constants
{
public static GameWidth:number = 320;
public static GameHeight:number = 480;
public static CenterX:number = Math.floor(Constants.GameWidth / 2);
public static CenterY:number = Math.floor(Constants.GameHeight / 2);
}
export default Constants;
|
19604fac8f94f2cff211557fddfb735224fcd254
|
TypeScript
|
PookMook/pokedex
|
/src/types/attack.ts
| 2.546875
| 3
|
import { Type } from "./type";
export type Attack = {
name: string;
type: Type;
damage: number;
};
|
9ac43428c8f2961fa3dc0997317c37971ebeed74
|
TypeScript
|
sujandev/laputa-iot-dashboard
|
/src/utils/util.ts
| 2.859375
| 3
|
import { validatenull } from './validate'
import * as CryptoJS from 'crypto-js'
import { defHttp } from '/@/utils/http/axios';
import { BasicPageParams } from '/@/api/model/baseModel';
// 表单序列化
export const serialize = (data : any) => {
const list = []
Object.keys(data).forEach(ele => {
return list.push(`${ele}=${data[ele]}`)
})
return list.join('&')
}
export const getObjType = obj => {
var toString = Object.prototype.toString
var map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object'
}
if (obj instanceof Element) {
return 'element'
}
return map[toString.call(obj)]
}
// 验证是否外部地址
export function isExternal(path: string) {
return /^(https?:|mailto:|tel:)/.test(path)
}
// 复制文本
export function copy(text: string) {
const input = document.createElement('textarea')
input.value = text
document.body.appendChild(input)
input.select()
document.execCommand('copy')
document.body.removeChild(input)
}
export const getPageParam = (params: BasicPageParams | any) => {
return { current: params?.page, size: params?.pageSize, ...params} ;
}
/**
*
* @param {校验数据源名} rule
* @param {*} value
* @param {*} callback
*/
export var validateDsName = (rule, value, callback) => {
var re = /(?=.*[a-z])(?=.*_)/;
if (value && (!(re).test(value))) {
callback(new Error('数据源名称不合法, 组名_数据源名形式'))
} else {
callback()
}
}
/**
* <img> <a> src 处理
* @returns {PromiseLike<T | never> | Promise<T | never>}
*/
export function handleImg(url, id) {
return validatenull(url) ? null : defHttp.requestData({
url: url,
method: 'get',
responseType: 'blob'
}).then((res) => { // 处理返回的文件流
// console.log(res);
const blob = res.data
const img = document.getElementById(id)
if(img !=null){
img.src = URL.createObjectURL(blob)
}
window.setTimeout(function() {
window.URL.revokeObjectURL(blob)
}, 0)
}).catch(err =>{
console.log(err);
const img = document.getElementById(id)
if(img !=null){
img.src = '/assets/images/header.jpg'
}
})
}
/**
* 对象深拷贝
*/
export const deepClone = data => {
var type = getObjType(data)
var obj
if (type === 'array') {
obj = []
} else if (type === 'object') {
obj = {}
} else {
// 不再具有下一层次
return data
}
if (type === 'array') {
for (var i = 0, len = data.length; i < len; i++) {
obj.push(deepClone(data[i]))
}
} else if (type === 'object') {
for (var key in data) {
obj[key] = deepClone(data[key])
}
}
return obj
}
/**
* 判断路由是否相等
*/
export const diff = (obj1, obj2) => {
delete obj1.close
var o1 = obj1 instanceof Object
var o2 = obj2 instanceof Object
if (!o1 || !o2) { /* 判断不是对象 */
return obj1 === obj2
}
if (Object.keys(obj1).length !== Object.keys(obj2).length) {
return false
// Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
}
for (var attr in obj1) {
var t1 = obj1[attr] instanceof Object
var t2 = obj2[attr] instanceof Object
if (t1 && t2) {
return diff(obj1[attr], obj2[attr])
} else if (obj1[attr] !== obj2[attr]) {
return false
}
}
return true
}
/**
* 设置灰度模式
*/
export const toggleGrayMode = (status) => {
if (status) {
document.body.className = document.body.className + ' grayMode'
} else {
document.body.className = document.body.className.replace(' grayMode', '')
}
}
/**
* 设置主题
*/
export const setTheme = (name) => {
document.body.className = name
}
/**
*加密处理
*/
export const encryption = (params) => {
let {
data,
type,
param,
key
} = params
const result = JSON.parse(JSON.stringify(data))
if (type === 'Base64') {
param.forEach(ele => {
result[ele] = btoa(result[ele])
})
} else {
param.forEach(ele => {
var data = result[ele]
key = CryptoJS.enc.Latin1.parse(key)
var iv = key
// 加密
var encrypted = CryptoJS.AES.encrypt(
data,
key, {
iv: iv,
mode: CryptoJS.mode.CFB,
padding: CryptoJS.pad.NoPadding
})
result[ele] = encrypted.toString()
})
}
return result
}
/**
* 递归寻找子类的父类
*/
export const findParent = (menu, id) => {
for (let i = 0; i < menu.length; i++) {
if (menu[i].children.length !== 0) {
for (let j = 0; j < menu[i].children.length; j++) {
if (menu[i].children[j].id === id) {
return menu[i]
} else {
if (menu[i].children[j].children.length !== 0) {
return findParent(menu[i].children[j].children, id)
}
}
}
}
}
}
/**
* 动态插入css
*/
export const loadStyle = url => {
const link = document.createElement('link')
link.type = 'text/css'
link.rel = 'stylesheet'
link.href = url
const head = document.getElementsByTagName('head')[0]
head.appendChild(link)
}
/**
* 判断路由是否相等
*/
export const isObjectValueEqual = (a, b) => {
let result = true
Object.keys(a).forEach(ele => {
const type = typeof (a[ele])
if (type === 'string' && a[ele] !== b[ele]) result = false
else if (type === 'object' && JSON.stringify(a[ele]) !== JSON.stringify(b[ele])) result = false
})
return result
}
/**
* 根据字典的value显示label
*/
export const findByvalue = (dic, value) => {
let result
if (validatenull(dic)) return value
if (typeof (value) === 'string' || typeof (value) === 'number' || typeof (value) === 'boolean') {
let index = 0
index = findArray(dic, value)
if (index !== -1) {
result = dic[index].label
} else {
result = value
}
} else if (value instanceof Array) {
result = []
let index = 0
value.forEach(ele => {
index = findArray(dic, ele)
if (index !== -1) {
result.push(dic[index].label)
} else {
result.push(value)
}
})
result = result.toString()
}
return result
}
/**
* 根据字典的value查找对应的index
*/
export const findArray = (dic, value) => {
for (let i = 0; i < dic.length; i++) {
if (dic[i].value === value) {
return i
}
}
return -1
}
/**
* 生成随机len位数字
*/
export const randomLenNum = (len, date) => {
let random = ''
random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len || 4)
if (date) random = random + Date.now()
return random
}
/**
* 打开小窗口
*/
export const openWindow = (url, title, w, h) => {
// Fixes dual-screen position Most browsers Firefox
const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top
const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height
const left = ((width / 2) - (w / 2)) + dualScreenLeft
const top = ((height / 2) - (h / 2)) + dualScreenTop
const newWindow = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)
// Puts focus on the newWindow
if (window.focus()) {
newWindow.focus()
}
}
export function getQueryString(url, paraName) {
const arrObj = url.split('?')
if (arrObj.length > 1) {
const arrPara = arrObj[1].split('&')
let arr
for (let i = 0; i < arrPara.length; i++) {
arr = arrPara[i].split('=')
// eslint-disable-next-line eqeqeq
if (arr != null && arr[0] == paraName) {
return arr[1]
}
}
return ''
} else {
return ''
}
}
|
85afc904a875de200639e648a0a679c090cc55e1
|
TypeScript
|
ElaheSmailpour/ToDO-Bootstrap
|
/src/models/model.ts
| 2.59375
| 3
|
export class Model {
user;
items: any[];
constructor() {
this.user = 'Toplearn-Elahe';
this.items = [
{ action: 'computer buy', done: false },
{ action: 'do work', done: false },
{ action: 'task one', done: true },
{ action: 'work second', done: false }
]
}
}
export class TodoItem {
action;
done;
constructor(action: any, done: any) {
this.action = action;
this.done = done;
}
}
|
64ae08d473e77dc7fd63a7f52eeacddf044a0965
|
TypeScript
|
patrikduch/EcommerceDDD
|
/EcommerceDDD.WebApp/ClientApp/src/app/core/models/Order.ts
| 2.625
| 3
|
export class Order {
orderId: string;
orderLines: OrderLine[] = [];
createdAt: Date;
totalPrice: number;
status: string;
}
export class OrderLine{
productId: string;
productName: string;
productPrice: number;
productQuantity: number;
currencySymbol: string;
}
|
b3920a47291609adbcbdf9055a8eb49c15c7c318
|
TypeScript
|
Dazaer/photo-items-app
|
/frontend-photo-items-app/src/models/Item.ts
| 2.796875
| 3
|
export default class Item {
public id: number = 0;
public name: string = "";
constructor(item?: Partial<Item>) {
Object.assign(this, item);
}
public static getNullSelectedItem() {
return new Item({name: "All"});
}
}
|