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
|
|---|---|---|---|---|---|---|
ef99c48209826a06f94b165239a068c9ce90a6e0
|
TypeScript
|
rhases/cep-as-promised
|
/test/unit/cep-as-promised.spec.ts
| 2.625
| 3
|
'use strict'
import { expect } from 'chai';
import '../setup';
import * as nock from 'nock';
import * as path from 'path';
import cep from '../../src/cep-as-promised'
import CepPromiseError from '../../src/errors/cep-promise'
describe('cep-promise (unit)', () => {
describe('when imported', () => {
it('should return a Function', () => {
expect(cep).to.be.a('function')
})
})
describe('when invoked', () => {
it('should return a Promise', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithFile(200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml'))
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.replyWithFile(200, path.join(__dirname, '/fixtures/cep-aberto-05010000-found.json'))
const cepPromise = cep('05010000')
expect(cepPromise.then).to.be.a('function')
expect(cepPromise.catch).to.be.a('function')
})
})
describe('when invoked without arguments', () => {
it('should reject with "validation_error"', () => {
return cep(undefined)
.catch((error) => {
return expect(error)
.to.be.an.instanceOf(CepPromiseError)
.and.containSubset({
name: 'CepPromiseError',
message: 'Erro ao inicializar a instância do CepPromise.',
type: 'validation_error',
errors: [{
message: 'Você deve chamar o construtor utilizando uma String ou um Number.',
service: 'cep_validation'
}]
})
})
})
})
describe('when invoked with a valid "05010000" String', () => {
it('should fulfill with correct address', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithFile(200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml'))
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.replyWithFile(200, path.join(__dirname, '/fixtures/cep-aberto-05010000-found.json'))
return expect(cep('05010000')).to.eventually.deep.equal({
cep: '05010000',
state: 'SP',
city: 'São Paulo',
neighborhood: 'Perdizes',
street: 'Rua Caiubi'
})
})
})
describe('when invoked with a valid 5010000 Number', () => {
it('should fulfill with correct address', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithFile(200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml'))
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.replyWithFile(200, path.join(__dirname, '/fixtures/cep-aberto-05010000-found.json'))
return expect(cep(5010000)).to.eventually.deep.equal({
cep: '05010000',
state: 'SP',
city: 'São Paulo',
neighborhood: 'Perdizes',
street: 'Rua Caiubi'
})
})
})
describe('Should succeed only with correios service', () => {
it('should fulfill with correct address', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithFile(200, path.join(__dirname, '/fixtures/response-cep-05010000-found.xml'))
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json'))
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.replyWithFile(200, path.join(__dirname, '/fixtures/cep-aberto-99999999-error.json'))
return expect(cep('5010000')).to.eventually.deep.equal({
cep: '05010000',
state: 'SP',
city: 'São Paulo',
neighborhood: 'Perdizes',
street: 'Rua Caiubi'
})
})
})
describe('Should succeed only with viacep service', () => {
it('should fulfill with correct address', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithFile(500, path.join(__dirname, '/fixtures/response-unknown-format.xml'))
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.replyWithFile(200, path.join(__dirname, '/fixtures/cep-aberto-99999999-error.json'))
return expect(cep('5010000')).to.eventually.deep.equal({
cep: '05010000',
state: 'SP',
city: 'São Paulo',
neighborhood: 'Perdizes',
street: 'Rua Caiubi'
})
})
})
describe('Should succeed only with cep aberto service', () => {
it('should fulfill with correct address', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithFile(500, path.join(__dirname, '/fixtures/response-unknown-format.xml'))
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json'))
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.replyWithFile(200, path.join(__dirname, '/fixtures/cep-aberto-05010000-found.json'))
return expect(cep('5010000')).to.eventually.deep.equal({
cep: '05010000',
state: 'SP',
city: 'São Paulo',
neighborhood: 'Perdizes',
street: 'Rua Caiubi'
})
})
})
describe('when its not possible to parse the returned XML and then succeed to one failover service', () => {
it('should fulfill with correct address', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithFile(200, path.join(__dirname, '/fixtures/response-bad-xml.xml'))
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.replyWithFile(200, path.join(__dirname, '/fixtures/cep-aberto-05010000-found.json'))
return expect(cep('5010000')).to.eventually.deep.equal({
cep: '05010000',
state: 'SP',
city: 'São Paulo',
neighborhood: 'Perdizes',
street: 'Rua Caiubi'
})
})
})
describe('when http request to Correios fails and then succeed to the failover service', () => {
it('should fulfill with correct address', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-05010000-found.json'))
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.replyWithFile(200, path.join(__dirname, '/fixtures/cep-aberto-05010000-found.json'))
return expect(cep('5010000')).to.eventually.deep.equal({
cep: '05010000',
state: 'SP',
city: 'São Paulo',
neighborhood: 'Perdizes',
street: 'Rua Caiubi'
})
})
})
describe('when invoked with an inexistent "99999999" CEP', () => {
it('should reject with "service_error"', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithFile(500, path.join(__dirname, '/fixtures/response-cep-not-found.xml'))
nock('https://viacep.com.br')
.get('/ws/99999999/json/')
.replyWithFile(200, path.join(__dirname, '/fixtures/viacep-cep-99999999-error.json'))
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=99999999')
.replyWithFile(200, path.join(__dirname, '/fixtures/cep-aberto-99999999-error.json'))
return cep('99999999')
.catch((error) => {
return expect(error)
.to.be.an.instanceOf(CepPromiseError)
.and.containSubset({
name: 'CepPromiseError',
message: 'Todos os serviços de CEP retornaram erro.',
type: 'service_error',
errors: [{
message: 'CEP NAO ENCONTRADO',
service: 'correios'
}, {
message: 'CEP não encontrado na base do ViaCEP.',
service: 'viacep'
}, {
message: 'CEP não encontrado na base do Cep Aberto.',
service: 'cepaberto'
}]
})
})
})
})
describe('when invoked with an invalid "123456789" CEP', () => {
it('should reject with "validation_error"', () => {
return cep('123456789')
.catch((error) => {
return expect(error)
.to.be.an.instanceOf(CepPromiseError)
.and.containSubset({
name: 'CepPromiseError',
message: 'CEP deve conter exatamente 8 caracteres.',
type: 'validation_error',
errors: [{
service: 'cep_validation',
message: 'CEP informado possui mais do que 8 caracteres.'
}]
})
})
})
})
describe('when http request fails both for primary and secondary service with bad response', () => {
it('should reject with "service_error"', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.reply(400, '<h2>Bad Request (400)</h2>')
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.reply(400, '<h2>Bad Request (400)</h2>')
return cep('05010000')
.catch((error) => {
return expect(error)
.to.be.an.instanceOf(CepPromiseError)
.and.containSubset({
name: 'CepPromiseError',
message: 'Todos os serviços de CEP retornaram erro.',
type: 'service_error',
errors: [{
message: 'Erro ao se conectar com o serviço dos Correios.',
service: 'correios'
}, {
message: 'Erro ao se conectar com o serviço ViaCEP.',
service: 'viacep'
}, {
message: 'Erro ao se conectar com o serviço Cep Aberto.',
service: 'cepaberto'
}]
})
})
})
})
describe('when http request has unformatted xml and alternatives services fails', () => {
it('should reject with "service_error"', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithFile(200, path.join(__dirname, '/fixtures/response-bad-xml.xml'))
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.reply(400, '<h2>Bad Request (400)</h2>')
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.reply(400, '<h2>Bad Request (400)</h2>')
return cep('05010000')
.catch((error) => {
return expect(error)
.to.be.an.instanceOf(CepPromiseError)
.and.containSubset({
name: 'CepPromiseError',
message: 'Todos os serviços de CEP retornaram erro.',
type: 'service_error',
errors: [{
message: 'Não foi possível interpretar o XML de resposta.',
service: 'correios'
}, {
message: 'Erro ao se conectar com o serviço ViaCEP.',
service: 'viacep'
}, {
message: 'Erro ao se conectar com o serviço Cep Aberto.',
service: 'cepaberto'
}]
})
})
})
})
describe('when http request fails both for primary and secondary service with error', () => {
it('should reject with "service_error"', () => {
nock('https://apps.correios.com.br')
.post('/SigepMasterJPA/AtendeClienteService/AtendeCliente')
.replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
nock('https://viacep.com.br')
.get('/ws/05010000/json/')
.replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
nock('http://www.cepaberto.com')
.get('/api/v3/cep?cep=05010000')
.replyWithError('getaddrinfo ENOTFOUND apps.correios.com.br apps.correios.com.br:443')
return cep('05010000')
.catch((error) => {
return expect(error)
.to.be.an.instanceOf(CepPromiseError)
.and.containSubset({
name: 'CepPromiseError',
message: 'Todos os serviços de CEP retornaram erro.',
type: 'service_error',
errors: [{
message: 'Erro ao se conectar com o serviço dos Correios.',
service: 'correios'
}, {
message: 'Erro ao se conectar com o serviço ViaCEP.',
service: 'viacep'
}, {
message: 'Erro ao se conectar com o serviço Cep Aberto.',
service: 'cepaberto'
}]
})
})
})
})
afterEach(() => {
nock.cleanAll()
})
})
|
0147521de8c5d50237f5c9266962bc010eb3213d
|
TypeScript
|
Joshswooft/nestjs-interface-issue
|
/src/entities/address.embeded.ts
| 2.578125
| 3
|
import { Column } from 'typeorm';
export interface IAddress {
line1: string;
line2?: string;
city: string;
state: string;
countryCode: string;
postCode: string;
}
export class AddressEmbedded implements IAddress {
@Column()
line1: string;
@Column({ nullable: true })
line2?: string;
@Column({ length: 100 })
city: string;
@Column({ length: 100 })
state: string;
@Column({ length: 3 })
countryCode: string;
@Column({ length: 10 })
postCode: string;
}
|
18e082a3ea94936f372e4cf04005d7e80ea0e761
|
TypeScript
|
bt/wepower-mvp
|
/web-frontend/src/app/shared/period.ts
| 3.1875
| 3
|
import * as moment from 'moment';
export class Period {
from : Date;
to: Date;
constructor(from?: Date, to?: Date) {
this.from = from;
this.to = to;
}
plusWeeks(weekCount : number) : Period {
const millisInWeek = 7 * 24 * 3600 * 1000;
return new Period(
moment(this.from).add(weekCount, 'week').toDate(),
moment(this.to).add(weekCount, 'week').toDate()
)
}
}
|
0bf8ea099385c71043d41f24f74feeec7599c75b
|
TypeScript
|
SidStraw/leet-codes
|
/2021-08/2021-08-19 (day32)/AGO/solution.ts
| 2.96875
| 3
|
function missingNumber(nums: number[]): number {
let result: number = 0; // store answer
for (let i = 1; i <= nums.length; i++) {
result += i;
result -= nums[i - 1];
}
return result;
};
|
5bd42c3b626036df444eb794d29c5867de00d02f
|
TypeScript
|
reduxjs/redux-toolkit
|
/packages/toolkit/src/autoBatchEnhancer.ts
| 3.015625
| 3
|
import type { StoreEnhancer } from 'redux'
export const SHOULD_AUTOBATCH = 'RTK_autoBatch'
export const prepareAutoBatched =
<T>() =>
(payload: T): { payload: T; meta: unknown } => ({
payload,
meta: { [SHOULD_AUTOBATCH]: true },
})
// TODO Remove this in 2.0
// Copied from https://github.com/feross/queue-microtask
let promise: Promise<any>
const queueMicrotaskShim =
typeof queueMicrotask === 'function'
? queueMicrotask.bind(
typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: globalThis
)
: // reuse resolved promise, and allocate it lazily
(cb: () => void) =>
(promise || (promise = Promise.resolve())).then(cb).catch((err: any) =>
setTimeout(() => {
throw err
}, 0)
)
const createQueueWithTimer = (timeout: number) => {
return (notify: () => void) => {
setTimeout(notify, timeout)
}
}
// requestAnimationFrame won't exist in SSR environments.
// Fall back to a vague approximation just to keep from erroring.
const rAF =
typeof window !== 'undefined' && window.requestAnimationFrame
? window.requestAnimationFrame
: createQueueWithTimer(10)
export type AutoBatchOptions =
| { type: 'tick' }
| { type: 'timer'; timeout: number }
| { type: 'raf' }
| { type: 'callback'; queueNotification: (notify: () => void) => void }
/**
* A Redux store enhancer that watches for "low-priority" actions, and delays
* notifying subscribers until either the queued callback executes or the
* next "standard-priority" action is dispatched.
*
* This allows dispatching multiple "low-priority" actions in a row with only
* a single subscriber notification to the UI after the sequence of actions
* is finished, thus improving UI re-render performance.
*
* Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
* This can be added to `action.meta` manually, or by using the
* `prepareAutoBatched` helper.
*
* By default, it will queue a notification for the end of the event loop tick.
* However, you can pass several other options to configure the behavior:
* - `{type: 'tick'}: queues using `queueMicrotask` (default)
* - `{type: 'timer, timeout: number}`: queues using `setTimeout`
* - `{type: 'raf'}`: queues using `requestAnimationFrame`
* - `{type: 'callback', queueNotification: (notify: () => void) => void}: lets you provide your own callback
*
*
*/
export const autoBatchEnhancer =
(options: AutoBatchOptions = { type: 'raf' }): StoreEnhancer =>
(next) =>
(...args) => {
const store = next(...args)
let notifying = true
let shouldNotifyAtEndOfTick = false
let notificationQueued = false
const listeners = new Set<() => void>()
const queueCallback =
options.type === 'tick'
? queueMicrotaskShim
: options.type === 'raf'
? rAF
: options.type === 'callback'
? options.queueNotification
: createQueueWithTimer(options.timeout)
const notifyListeners = () => {
// We're running at the end of the event loop tick.
// Run the real listener callbacks to actually update the UI.
notificationQueued = false
if (shouldNotifyAtEndOfTick) {
shouldNotifyAtEndOfTick = false
listeners.forEach((l) => l())
}
}
return Object.assign({}, store, {
// Override the base `store.subscribe` method to keep original listeners
// from running if we're delaying notifications
subscribe(listener: () => void) {
// Each wrapped listener will only call the real listener if
// the `notifying` flag is currently active when it's called.
// This lets the base store work as normal, while the actual UI
// update becomes controlled by this enhancer.
const wrappedListener: typeof listener = () => notifying && listener()
const unsubscribe = store.subscribe(wrappedListener)
listeners.add(listener)
return () => {
unsubscribe()
listeners.delete(listener)
}
},
// Override the base `store.dispatch` method so that we can check actions
// for the `shouldAutoBatch` flag and determine if batching is active
dispatch(action: any) {
try {
// If the action does _not_ have the `shouldAutoBatch` flag,
// we resume/continue normal notify-after-each-dispatch behavior
notifying = !action?.meta?.[SHOULD_AUTOBATCH]
// If a `notifyListeners` microtask was queued, you can't cancel it.
// Instead, we set a flag so that it's a no-op when it does run
shouldNotifyAtEndOfTick = !notifying
if (shouldNotifyAtEndOfTick) {
// We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue
// a microtask to notify listeners at the end of the event loop tick.
// Make sure we only enqueue this _once_ per tick.
if (!notificationQueued) {
notificationQueued = true
queueCallback(notifyListeners)
}
}
// Go ahead and process the action as usual, including reducers.
// If normal notification behavior is enabled, the store will notify
// all of its own listeners, and the wrapper callbacks above will
// see `notifying` is true and pass on to the real listener callbacks.
// If we're "batching" behavior, then the wrapped callbacks will
// bail out, causing the base store notification behavior to be no-ops.
return store.dispatch(action)
} finally {
// Assume we're back to normal behavior after each action
notifying = true
}
},
})
}
|
37fe978f20d406db5497fe7f8bdaa840b3d0a7f6
|
TypeScript
|
cdnjs/cdnjs
|
/ajax/libs/amcharts4/4.10.36/.internal/charts/elements/Candlestick.d.ts
| 3
| 3
|
/**
* Module that defines everything related to building Candlesticks.
*/
/**
* ============================================================================
* IMPORTS
* ============================================================================
* @hidden
*/
import { Column, IColumnProperties, IColumnAdapters, IColumnEvents } from "./Column";
import { Line } from "../../core/elements/Line";
/**
* ============================================================================
* REQUISITES
* ============================================================================
* @hidden
*/
/**
* Defines properties for [[Candlestick]].
*/
export interface ICandlestickProperties extends IColumnProperties {
}
/**
* Defines events for [[Candlestick]].
*/
export interface ICandlestickEvents extends IColumnEvents {
}
/**
* Defines adapters for [[Candlestick]].
*
* @see {@link Adapter}
*/
export interface ICandlestickAdapters extends IColumnAdapters, ICandlestickProperties {
}
/**
* ============================================================================
* MAIN CLASS
* ============================================================================
* @hidden
*/
/**
* Class used to creates Candlesticks.
*
* @see {@link ICandlestickEvents} for a list of available events
* @see {@link ICandlestickAdapters} for a list of available Adapters
* @todo Usage example
* @important
*/
export declare class Candlestick extends Column {
/**
* Defines available properties.
*/
_properties: ICandlestickProperties;
/**
* Defines available adapters.
*/
_adapter: ICandlestickAdapters;
/**
* Defines available events.
*/
_events: ICandlestickEvents;
/**
* Low line element
*/
lowLine: Line;
/**
* High line element
*/
highLine: Line;
/**
* Constructor
*/
constructor();
/**
* @ignore
*/
protected createAssets(): void;
/**
* Copies all parameters from another [[Candlestick]].
*
* @param source Source Candlestick
*/
copyFrom(source: this): void;
}
|
2df09b24f2bcd1505e98f8c6118c3df6ac572454
|
TypeScript
|
lucidsoftware/aichallenge
|
/lobby/src/gamefactory.ts
| 2.609375
| 3
|
import {Game} from './game';
import {PaperIO} from './games/paperio';
export class GameFactory {
static create(
name: string,
usedNames: Set<string>,
requestedPlayers?: string[],
persistent?: boolean,
): Game {
console.log('Requesting to create game named ' + name + ' with players ' + JSON.stringify(requestedPlayers));
return new PaperIO(name, usedNames, requestedPlayers, persistent);
}
}
|
84ac95103040a6121405e0f733cac804ad215fa1
|
TypeScript
|
r2-studio/robotmon-scripts
|
/scripts/framework-v1/src/page/point.ts
| 2.734375
| 3
|
export interface XY {
x: number;
y: number;
}
export interface IXYRGB {
x: number;
y: number;
r: number;
g: number;
b: number;
}
export class XYRGB {
public x: number = 0;
public y: number = 0;
public r: number = 0;
public g: number = 0;
public b: number = 0;
}
|
9fa94d465362a69a2e83b6194b9537f2684fd7ee
|
TypeScript
|
murilomontino/PRATICAS.server
|
/data/models/User.ts
| 2.703125
| 3
|
import { DataTypes, Model, Optional } from 'sequelize'
import { database } from '.'
import { Permission } from './types'
// We recommend you declare an interface for the attributes, for stricter typechecking
interface UsersAttributes {
id?: number
nome?: string
sobrenome?: string
telefone?: string
img_perfil?: string
codIbge: string
validado?: boolean
email?: string
cpf?: string
senha?: string
permissao?: Permission
ubs?: number
}
// Some fields are optional when calling UsersModel.create() or UsersModel.build()
type UsersCreationAttributes = Optional<UsersAttributes, 'id'>
// We need to declare an interface for our model that is basically what our class would be
export interface UsersInstance
extends Model<UsersAttributes, UsersCreationAttributes>,
UsersAttributes {
updatedAt: Date
dataValues: any
createdAt: Date
}
const User = (() => {
const model = database.define<UsersInstance>('usuarios', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
unique: true,
},
codIbge: {
type: DataTypes.STRING,
allowNull: false,
},
nome: {
type: DataTypes.STRING,
allowNull: false,
},
sobrenome: {
type: DataTypes.STRING,
allowNull: false,
},
telefone: {
type: DataTypes.STRING,
},
img_perfil: {
type: DataTypes.STRING,
},
validado: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
email: {
type: DataTypes.STRING,
validate: {
isEmail: true,
},
},
cpf: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
senha: {
type: DataTypes.STRING,
allowNull: false,
},
permissao: {
type: DataTypes.INTEGER,
allowNull: false,
},
})
return model
})()
export default User
|
18dc2b4a93c7f452f88b1120e62320bc9805b755
|
TypeScript
|
Mavricus/flex-cache-in-memory
|
/spec/FlexInMemoryCache.spec.ts
| 2.796875
| 3
|
import { FlexInMemoryCache } from '../src/FlexInMemoryCache';
describe('InMemoryCache', () => {
let cache: FlexInMemoryCache;
let storage: { [key: string]: { timer: NodeJS.Timer; data: unknown } };
beforeAll(() => {
jest.useFakeTimers();
});
beforeEach(() => {
storage = {};
cache = new FlexInMemoryCache(storage);
});
afterEach(() => {
jest.runAllTimers();
});
afterAll(() => {
jest.useRealTimers();
});
describe('set', () => {
it('should assign the value to the key', () => {
return cache.set('a', 123, 5000)
.then(() => expect(storage['a'].data).toBe(123));
});
it('should reject with error if cache already exists', () => {
return cache.set('a', 123, 5000)
.then(() => expect(storage['a'].data).toBe(123))
.then(() => expect(cache.set('a', 321, 5000)).rejects.toThrowError());
});
it('should re-assign the value to the key after timeout', () => {
return cache.set('a', 123, 5000)
.then(() => expect(storage['a'].data).toBe(123))
.then(() => jest.runAllTimers())
.then(() => cache.set('a', 321, 5000))
.then(() => expect(storage['a'].data).toBe(321));
});
it('should reject with error when TTL is negative', () => {
return expect(cache.set('a', 123, -5000)).rejects.toThrowError();
});
it('should reject with error when TTL is 0', () => {
return expect(cache.set('a', 123, 0)).rejects.toThrowError();
});
});
describe('delete', () => {
it('should delete data from the cache by key', () => {
return cache.set('a', 123, 5000)
.then(() => expect(storage['a'].data).toBe(123))
.then(() => cache.delete('a'))
.then(() => expect(storage['a']).toBeUndefined());
});
it('should delete data from the cache by key', () => {
return Promise.resolve(expect(storage['a']).toBeUndefined())
.then(() => expect(cache.delete('a')).resolves.toBeFalsy());
});
});
describe('get', () => {
it('should return data from the cache by key', () => {
return cache.set('a', 123, 5000)
.then(() => expect(storage['a'].data).toBe(123))
.then(() => expect(cache.get('a')).resolves.toBe(123));
});
it('should return null if there is no data by key', () => {
return Promise.resolve(expect(storage['a']).toBeUndefined())
.then(() => expect(cache.get('a')).resolves.toBeNull());
});
});
describe('setForce', () => {
it('should assign the value to the key', () => {
return cache.setForce('a', 123, 5000)
.then(() => expect(storage['a'].data).toBe(123));
});
it('should rewrite cache if already exists', () => {
return cache.setForce('a', 123, 5000)
.then(() => expect(storage['a'].data).toBe(123))
.then(() => cache.setForce('a', 321, 5000))
.then(() => expect(storage['a'].data).toBe(321));
});
it('should re-assign the value to the key after timeout', () => {
return cache.setForce('a', 123, 5000)
.then(() => expect(storage['a'].data).toBe(123))
.then(() => jest.runAllTimers())
.then(() => cache.setForce('a', 321, 5000))
.then(() => expect(storage['a'].data).toBe(321));
});
it('should reject with error when TTL is negative', () => {
return expect(cache.setForce('a', 123, -5000)).rejects.toThrowError();
});
it('should reject with error when TTL is 0', () => {
return expect(cache.setForce('a', 123, 0)).rejects.toThrowError();
});
});
describe('setForce', () => {
it('should update the cache by key', () => {
return cache.setForce('a', 123, 5000)
.then(() => expect(storage['a'].data).toBe(123))
.then(() => cache.update('a', 321, 5000))
.then(() => expect(storage['a'].data).toBe(321));
});
it('should reject wit an error if cache does not exist', () => {
return expect(cache.get('a')).resolves.toBeNull()
.then(() => expect(cache.update('a', 123, 5000)).rejects.toThrowError());
});
it('should reject with error when TTL is negative', () => {
return expect(cache.update('a', 123, -5000)).rejects.toThrowError();
});
it('should reject with error when TTL is 0', () => {
return expect(cache.update('a', 123, 0)).rejects.toThrowError();
});
});
describe('timeout', () => {
it('should delete data on timeout', () => {
return cache.set('a', 123, 5000)
.then(() => expect(cache.get('a')).resolves.toBe(123))
.then(() => jest.advanceTimersByTime(5000))
.then(() => expect(cache.get('a')).resolves.toBeNull())
});
it('should delete data on timeout of very last set', () => {
return cache.set('a', 123, 5000)
.then(() => expect(cache.get('a')).resolves.toBe(123))
.then(() => jest.advanceTimersByTime(3000))
.then(() => cache.setForce('a', 456, 5000))
.then(() => expect(cache.get('a')).resolves.toBe(456))
.then(() => jest.advanceTimersByTime(3000))
.then(() => expect(cache.get('a')).resolves.toBe(456))
.then(() => jest.advanceTimersByTime(2000))
.then(() => expect(cache.get('a')).resolves.toBeNull());
});
it('should delete data on its personal timeout', () => {
return cache.set('a', 123, 5000)
.then(() => cache.set('b', 456, 2500))
.then(() => jest.advanceTimersByTime(2000))
.then(() => expect(cache.get('a')).resolves.toBe(123))
.then(() => expect(cache.get('b')).resolves.toBe(456))
.then(() => jest.advanceTimersByTime(2000))
.then(() => expect(cache.get('a')).resolves.toBe(123))
.then(() => expect(cache.get('b')).resolves.toBeNull())
.then(() => jest.advanceTimersByTime(2000))
.then(() => expect(cache.get('a')).resolves.toBeNull())
.then(() => expect(cache.get('b')).resolves.toBeNull());
});
it('should stop timer if data was deleted', () => {
return cache.set('a', 123, 5000)
.then(() => jest.advanceTimersByTime(2000))
.then(() => cache.delete('a'))
.then(() => jest.advanceTimersByTime(2000))
.then(() => cache.set('a', 456, 5000))
.then(() => jest.advanceTimersByTime(2000))
.then(() => expect(cache.get('a')).resolves.toBe(456))
.then(() => jest.advanceTimersByTime(5000))
.then(() => expect(cache.get('a')).resolves.toBeNull());
});
it('should not delete cached data when ttl is Infinity', () => {
return cache.set('a', 123, Infinity)
.then(() => cache.set('b', 456, 2500))
.then(() => jest.runAllTimers())
.then(() => expect(cache.get('a')).resolves.toBe(123))
.then(() => expect(cache.get('b')).resolves.toBeNull());
});
it('should reset timer after update', () => {
return cache.set('a', 123, 5000)
.then(() => expect(cache.get('a')).resolves.toBe(123))
.then(() => jest.advanceTimersByTime(3000))
.then(() => cache.update('a', 321, 5000))
.then(() => expect(cache.get('a')).resolves.toBe(321))
.then(() => jest.advanceTimersByTime(3000))
.then(() => expect(cache.get('a')).resolves.toBe(321))
.then(() => jest.advanceTimersByTime(3000))
.then(() => expect(cache.get('a')).resolves.toBeNull());
});
});
});
|
947b7bb52e94d9c374b1ea821cd8cddf4dc8f9ea
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/ckeditor__ckeditor5-table/src/tableutils.d.ts
| 3.125
| 3
|
import { Plugin } from '@ckeditor/ckeditor5-core';
import { Element as ModelElement, Range as ModelRange } from '@ckeditor/ckeditor5-engine';
import Writer from '@ckeditor/ckeditor5-engine/src/model/writer';
import TableWalker from './tablewalker';
import ModelSelection from '@ckeditor/ckeditor5-engine/src/model/selection';
/**
* The table utilities plugin.
*/
export default class TableUtils extends Plugin {
static readonly pluginName: 'TableUtils';
init(): void;
/**
* Returns the table cell location as an object with table row and table column indexes.
*
* For instance, in the table below:
*
* 0 1 2 3
* +---+---+---+---+
* 0 | a | b | c |
* + + +---+
* 1 | | | d |
* +---+---+ +---+
* 2 | e | | f |
* +---+---+---+---+
*
* the method will return:
*
* const cellA = table.getNodeByPath( [ 0, 0 ] );
* editor.plugins.get( 'TableUtils' ).getCellLocation( cellA );
* // will return { row: 0, column: 0 }
*
* const cellD = table.getNodeByPath( [ 1, 0 ] );
* editor.plugins.get( 'TableUtils' ).getCellLocation( cellD );
* // will return { row: 1, column: 3 }
*/
getCellLocation(tableCell: ModelElement): { row: number; column: number } | void;
/**
* Creates an empty table with a proper structure. The table needs to be inserted into the model,
* for example, by using the {@link module:engine/model/model~Model#insertContent} function.
*
* model.change( ( writer ) => {
* // Create a table of 2 rows and 7 columns:
* const table = tableUtils.createTable( writer, { rows: 2, columns: 7 } );
*
* // Insert a table to the model at the best position taking the current selection:
* model.insertContent( table );
* }
*/
createTable(
writer: Writer,
options?: { rows?: number; columns?: number; headingRows?: number; headingColumns?: number },
): ModelElement;
/**
* Inserts rows into a table.
*
* editor.plugins.get( 'TableUtils' ).insertRows( table, { at: 1, rows: 2 } );
*
* Assuming the table on the left, the above code will transform it to the table on the right:
*
* row index
* 0 +---+---+---+ `at` = 1, +---+---+---+ 0
* | a | b | c | `rows` = 2, | a | b | c |
* 1 + +---+---+ <-- insert here + +---+---+ 1
* | | d | e | | | | |
* 2 + +---+---+ will give: + +---+---+ 2
* | | f | g | | | | |
* 3 +---+---+---+ + +---+---+ 3
* | | d | e |
* + +---+---+ 4
* + + f | g |
* +---+---+---+ 5
*/
insertRows(table: ModelElement, options?: { at?: number; rows?: number; copyStructureFromAbove?: boolean }): void;
/**
* Inserts columns into a table.
*
* editor.plugins.get( 'TableUtils' ).insertColumns( table, { at: 1, columns: 2 } );
*
* Assuming the table on the left, the above code will transform it to the table on the right:
*
* 0 1 2 3 0 1 2 3 4 5
* +---+---+---+ +---+---+---+---+---+
* | a | b | | a | b |
* + +---+ + +---+
* | | c | | | c |
* +---+---+---+ will give: +---+---+---+---+---+
* | d | e | f | | d | | | e | f |
* +---+ +---+ +---+---+---+ +---+
* | g | | h | | g | | | | h |
* +---+---+---+ +---+---+---+---+---+
* | i | | i |
* +---+---+---+ +---+---+---+---+---+
* ^---- insert here, `at` = 1, `columns` = 2
*/
insertColumns(table: ModelElement, options?: { at?: number; columns?: number }): void;
/**
* Removes rows from the given `table`.
*
* This method re-calculates the table geometry including `rowspan` attribute of table cells overlapping removed rows
* and table headings values.
*
* editor.plugins.get( 'TableUtils' ).removeRows( table, { at: 1, rows: 2 } );
*
* Executing the above code in the context of the table on the left will transform its structure as presented on the right:
*
* row index
* ┌───┬───┬───┐ `at` = 1 ┌───┬───┬───┐
* 0 │ a │ b │ c │ `rows` = 2 │ a │ b │ c │ 0
* │ ├───┼───┤ │ ├───┼───┤
* 1 │ │ d │ e │ <-- remove from here │ │ d │ g │ 1
* │ │ ├───┤ will give: ├───┼───┼───┤
* 2 │ │ │ f │ │ h │ i │ j │ 2
* │ │ ├───┤ └───┴───┴───┘
* 3 │ │ │ g │
* ├───┼───┼───┤
* 4 │ h │ i │ j │
* └───┴───┴───┘
*/
removeRows(table: ModelElement, options?: { at?: number; rows?: number }): void;
/**
* Removes columns from the given `table`.
*
* This method re-calculates the table geometry including the `colspan` attribute of table cells overlapping removed columns
* and table headings values.
*
* editor.plugins.get( 'TableUtils' ).removeColumns( table, { at: 1, columns: 2 } );
*
* Executing the above code in the context of the table on the left will transform its structure as presented on the right:
*
* 0 1 2 3 4 0 1 2
* ┌───────────────┬───┐ ┌───────┬───┐
* │ a │ b │ │ a │ b │
* │ ├───┤ │ ├───┤
* │ │ c │ │ │ c │
* ├───┬───┬───┬───┼───┤ will give: ├───┬───┼───┤
* │ d │ e │ f │ g │ h │ │ d │ g │ h │
* ├───┼───┼───┤ ├───┤ ├───┤ ├───┤
* │ i │ j │ k │ │ l │ │ i │ │ l │
* ├───┴───┴───┴───┴───┤ ├───┴───┴───┤
* │ m │ │ m │
* └───────────────────┘ └───────────┘
* ^---- remove from here, `at` = 1, `columns` = 2
*/
removeColumns(table: ModelElement, options?: { at?: number; columns?: number }): void;
/**
* Divides a table cell vertically into several ones.
*
* The cell will be visually split into more cells by updating colspans of other cells in a column
* and inserting cells (columns) after that cell.
*
* In the table below, if cell "a" is split into 3 cells:
*
* +---+---+---+
* | a | b | c |
* +---+---+---+
* | d | e | f |
* +---+---+---+
*
* it will result in the table below:
*
* +---+---+---+---+---+
* | a | | | b | c |
* +---+---+---+---+---+
* | d | e | f |
* +---+---+---+---+---+
*
* So cell "d" will get its `colspan` updated to `3` and 2 cells will be added (2 columns will be created).
*
* Splitting a cell that already has a `colspan` attribute set will distribute the cell `colspan` evenly and the remainder
* will be left to the original cell:
*
* +---+---+---+
* | a |
* +---+---+---+
* | b | c | d |
* +---+---+---+
*
* Splitting cell "a" with `colspan=3` into 2 cells will create 1 cell with a `colspan=a` and cell "a" that will have `colspan=2`:
*
* +---+---+---+
* | a | |
* +---+---+---+
* | b | c | d |
* +---+---+---+
*/
splitCellVertically(tableCell: ModelElement, numberOfCells: number): void;
/**
* Divides a table cell horizontally into several ones.
*
* The cell will be visually split into more cells by updating rowspans of other cells in the row and inserting rows with a single cell
* below.
*
* If in the table below cell "b" is split into 3 cells:
*
* +---+---+---+
* | a | b | c |
* +---+---+---+
* | d | e | f |
* +---+---+---+
*
* It will result in the table below:
*
* +---+---+---+
* | a | b | c |
* + +---+ +
* | | | |
* + +---+ +
* | | | |
* +---+---+---+
* | d | e | f |
* +---+---+---+
*
* So cells "a" and "b" will get their `rowspan` updated to `3` and 2 rows with a single cell will be added.
*
* Splitting a cell that already has a `rowspan` attribute set will distribute the cell `rowspan` evenly and the remainder
* will be left to the original cell:
*
* +---+---+---+
* | a | b | c |
* + +---+---+
* | | d | e |
* + +---+---+
* | | f | g |
* + +---+---+
* | | h | i |
* +---+---+---+
*
* Splitting cell "a" with `rowspan=4` into 3 cells will create 2 cells with a `rowspan=1` and cell "a" will have `rowspan=2`:
*
* +---+---+---+
* | a | b | c |
* + +---+---+
* | | d | e |
* +---+---+---+
* | | f | g |
* +---+---+---+
* | | h | i |
* +---+---+---+
*/
splitCellHorizontally(tableCell: ModelElement, numberOfCells?: number): void;
/**
* Returns the number of columns for a given table.
*
* editor.plugins.get( 'TableUtils' ).getColumns( table );
*/
getColumns(table: ModelElement): number;
/**
* Returns the number of rows for a given table. Any other element present in the table model is omitted.
*
* editor.plugins.get( 'TableUtils' ).getRows( table );
*/
getRows(table: ModelElement): number;
/**
* Creates an instance of the table walker.
*
* The table walker iterates internally by traversing the table from row index = 0 and column index = 0.
* It walks row by row and column by column in order to output values defined in the options.
* By default it will output only the locations that are occupied by a cell. To include also spanned rows and columns,
* pass the `includeAllSlots` option.
*/
createTableWalker(
table: ModelElement,
options?: {
row?: number;
startRow?: number;
endRow?: number;
column?: number;
startColumn?: number;
endColumn?: number;
includeAllSlots?: boolean;
},
): TableWalker;
/**
* Returns all model table cells that are fully selected (from the outside)
* within the provided model selection's ranges.
*
* To obtain the cells selected from the inside, use
* {@link #getTableCellsContainingSelection}.
*/
getSelectedTableCells(selection: ModelSelection): ModelElement[];
/**
* Returns all model table cells that the provided model selection's ranges
* {@link module:engine/model/range~Range#start} inside.
*
* To obtain the cells selected from the outside, use
* {@link #getSelectedTableCells}.
*/
getTableCellsContainingSelection(selection: ModelSelection): ModelElement[];
/**
* Returns all model table cells that are either completely selected
* by selection ranges or host selection range
* {@link module:engine/model/range~Range#start start positions} inside them.
*
* Combines {@link #getTableCellsContainingSelection} and
* {@link #getSelectedTableCells}.
*/
getSelectionAffectedTableCells(selection: ModelSelection): ModelElement[];
/**
* Returns an object with the `first` and `last` row index contained in the given `tableCells`.
*
* const selectedTableCells = getSelectedTableCells( editor.model.document.selection );
*
* const { first, last } = getRowIndexes( selectedTableCells );
*
* console.log( `Selected rows: ${ first } to ${ last }` );
*/
getRowIndexes(tableCells: ModelElement[]): { first: number; last: number };
/**
* Returns an object with the `first` and `last` column index contained in the given `tableCells`.
*
* const selectedTableCells = getSelectedTableCells( editor.model.document.selection );
*
* const { first, last } = getColumnIndexes( selectedTableCells );
*
* console.log( `Selected columns: ${ first } to ${ last }` );
*/
getColumnIndexes(tableCells: ModelElement[]): { first: number; last: number };
/**
* Checks if the selection contains cells that do not exceed rectangular selection.
*
* In a table below:
*
* ┌───┬───┬───┬───┐
* │ a │ b │ c │ d │
* ├───┴───┼───┤ │
* │ e │ f │ │
* │ ├───┼───┤
* │ │ g │ h │
* └───────┴───┴───┘
*
* Valid selections are these which create a solid rectangle (without gaps), such as:
* - a, b (two horizontal cells)
* - c, f (two vertical cells)
* - a, b, e (cell "e" spans over four cells)
* - c, d, f (cell d spans over a cell in the row below)
*
* While an invalid selection would be:
* - a, c (the unselected cell "b" creates a gap)
* - f, g, h (cell "d" spans over a cell from the row of "f" cell - thus creates a gap)
*/
isSelectionRectangular(selectedTableCells: ModelElement[]): boolean;
/**
* Returns array of sorted ranges.
*/
sortRanges(ranges: Iterable<ModelRange>): ModelRange[];
}
declare module '@ckeditor/ckeditor5-core/src/plugincollection' {
interface Plugins {
TableUtils: TableUtils;
}
}
|
8e53e2f4fb10c8cb5dc4d3a62238daa8c448d20e
|
TypeScript
|
fengkx/leetcode
|
/group-anagrams/group-anagrams.ts
| 2.796875
| 3
|
function groupAnagrams(strs: string[]): string[][] {
const cache = {};
for (let i = 0, len = strs.length; i < len; i++) {
const str = strs[i];
const normalized = str.split('').sort().join('');
if (!cache[normalized]) {
cache[normalized] = []
};
cache[normalized].push(str)
}
return Object.values(cache);
};
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('should pass', () => {
expect(groupAnagrams([''])).to.have.deep.members([['']]);
expect(groupAnagrams(
["eat", "tea", "tan", "ate", "nat", "bat"]
)).to.have.deep.members(
[["eat", "tea", "ate"],
["tan", "nat"], ["bat"]]
);
expect(groupAnagrams(
["a"]
)).to.have.deep.members(
[["a"]]
)
// Additional test cases
expect(groupAnagrams(["cab", "pug", "rat", "abc", "tar", "gup"])).to.have.deep.members(
[["cab", "abc"], ["pug", "gup"], ["rat", "tar"]]
);
expect(groupAnagrams(["hello", "olleh", "world", "dlrow"])).to.have.deep.members(
[["hello", "olleh"], ["world", "dlrow"]]
);
expect(groupAnagrams(["listen", "silent", "inlets"])).to.have.deep.members(
[["listen", "silent", "inlets"]]
);
expect(groupAnagrams(["ab", "ba", "cd", "dc", "ef", "fe"])).to.have.deep.members(
[["ab", "ba"], ["cd", "dc"], ["ef", "fe"]]
);
})
}
|
bc43d9af5d7841e9d8cc97d5c6ae669a8cb643b4
|
TypeScript
|
tett23/ckusro
|
/old/src/cli/renderers/staticRenderer/assets/modules/fileBuffers.ts
| 2.703125
| 3
|
import { FileBufferId } from '../../../../../models/FileBuffer';
import { FileBuffersState as FBState } from '../../../../../models/FileBuffersState';
export type FileBuffersState = {
fileBuffersState: FBState;
currentFileBufferId: FileBufferId;
};
const UpdateCurrentFileBufferId: 'FileBuffers/UpdateCurrentFileBufferId' =
'FileBuffers/UpdateCurrentFileBufferId';
export function updateCurrentFileBufferId(currentFileBufferId: FileBufferId) {
return {
type: UpdateCurrentFileBufferId,
payload: currentFileBufferId,
};
}
export type FileBuffersActions = ReturnType<typeof updateCurrentFileBufferId>;
export function initialState(): FileBuffersState {
return {
fileBuffersState: {
fileBuffers: [],
dependencyTable: {},
invertedDependencyTable: {},
},
currentFileBufferId: '',
};
}
export default function fileBuffersReducer(
state: FileBuffersState = initialState(),
action: FileBuffersActions,
): FileBuffersState {
switch (action.type) {
case UpdateCurrentFileBufferId:
return { ...state, currentFileBufferId: action.payload };
default:
return state;
}
}
|
6e0afb89bbc5f98f390a9601e813e14bbfe86b73
|
TypeScript
|
UpUpLiu/entitas-ts
|
/example/src/systems/PlayerInputSystem.ts
| 2.625
| 3
|
module example {
import Pool = entitas.Pool;
import Group = entitas.Group;
import Entity = entitas.Entity;
import Matcher = entitas.Matcher;
import Exception = entitas.Exception;
import TriggerOnEvent = entitas.TriggerOnEvent;
import IExecuteSystem = entitas.IExecuteSystem;
import IInitializeSystem = entitas.IInitializeSystem;
import ISetPool = entitas.ISetPool;
export class PlayerInputSystem implements IExecuteSystem, IInitializeSystem, ISetPool {
protected pool:Pool;
protected group:Group;
private static FireRate = .1;
protected shoot:boolean;
protected timeToFire:number=0;
protected mouseVector;
public execute() {
var entities = this.group.getEntities();
if (entities.length === 0) return;
var e = entities[0];
if (this.mouseVector === undefined) return;
var position:PositionComponent = e.position;
var destinationX = this.mouseVector.x;
var destinationY = this.mouseVector.y;
if (destinationX === undefined || destinationY === undefined) return;
position.x = this.mouseVector.x;
position.y = this.mouseVector.y;
if (this.shoot) {
if (this.timeToFire <= 0) {
this.pool.createBullet(position.x - 27, position.y + 2);
this.pool.createBullet(position.x + 27, position.y + 2);
this.timeToFire = PlayerInputSystem.FireRate;
}
}
if (this.timeToFire > 0) {
this.timeToFire -= bosco.delta;
if (this.timeToFire < 0) {
this.timeToFire = 0;
}
}
}
public initialize() {
document.addEventListener('touchstart', this.onTouchStart, true);
document.addEventListener('touchmove', this.onTouchMove, true);
document.addEventListener('touchend', this.onTouchEnd, true);
document.addEventListener('mousedown', this.onTouchStart, true);
document.addEventListener('mousemove', this.onTouchMove, true);
document.addEventListener('mouseup', this.onTouchEnd, true);
this.pool.createPlayer();
}
public setPool(pool:Pool) {
this.pool = pool;
this.group = pool.getGroup(Matcher.allOf(Matcher.Player));
}
protected onTouchStart = (event) => {
event = event.changedTouches ? event.changedTouches[0] : event;
this.shoot = true;
this.mouseVector = {
x: parseInt(event.clientX),
y: parseInt(event.clientY)
};
return true;
};
protected onTouchMove = (event) => {
event = event.changedTouches ? event.changedTouches[0] : event;
this.mouseVector = {
x: parseInt(event.clientX),
y: parseInt(event.clientY)
};
return true;
};
protected onTouchEnd = (event) => {
this.shoot = false;
};
}
}
|
5176d20438e43f40d7a4864bb7cb3a762ba1b95f
|
TypeScript
|
DessaureD/QuizAppReUpload
|
/src/QuizApp/wwwroot/file.ts
| 3.546875
| 4
|
class Test {
totalPoints() {
alert(`${total} points earned! Nice!`)
}
}
let finalTotal = new Test();
alert("Welcome to your first quiz my friend!");
let total = 0;
let question1 = prompt("What color is the sky? Please choose between these three options: White, Blue, or Red.");
if (question1 == "Blue") {
console.log("Question 1, Correct!");
total = total + 20
}
else if (question1 != "Blue") {
console.log("Question 1, Incorrect!");
}
let question2 = prompt("Who is the President of the United States of America? Please choose btween these three options: Mike Pence, Donald Trump or George Washington.");
if (question2 == "Donald Trump") {
console.log("Question 2, Correct!");
total = total + 20
}
else if (question2 != "Donald Trump") {
console.log("Question 2, Incorrect!");
}
let question3 = prompt("Who is the Vice President of the United States of America? Please choose btween these three options: Mike Pence, Donald Trump or George Washington.");
if (question3 == "Mike Pence") {
console.log("Question 3, Correct!");
total = total + 20
}
else if (question3 != "Mike Pence") {
console.log("Question 3, Incorrect!");
}
let question4 = prompt("Who was the first President of the United States of America? Please choose btween these three options: Mike Pence, Donald Trump or George Washington.");
if (question4 == "George Washington") {
console.log("Question 4, Correct!");
total = total + 20
}
else if (question4 != "George Washington") {
console.log("Question 4, Incorrect!");
}
let question5 = prompt("Who made Microsoft? Please choose between these three options: Bill Gates, Steve Jobs, or Barack Obama.");
if (question5 == "Bill Gates") {
console.log("Question 5, Correct!");
total = total + 20
}
else if (question5 != "Bill Gates") {
console.log("Question 5, Incorrect!");
}
finalTotal.totalPoints();
|
9c765092f6be938f6fcf4d48fc0b2d5e8b51334f
|
TypeScript
|
chaoticsparks/angular-mentoring-epam
|
/src/app/store/reducers/add-edit-course.reducer.ts
| 2.765625
| 3
|
import {AddEditCourseActions, AddEditCourseActionTypes} from '../actions/add-edit-course.actions';
import {ICourse} from '../../courses/i-course';
export interface IAddEditCourseState {
courseToSubmit: ICourse | null;
}
export const initialAddEditCourseState: IAddEditCourseState = {
courseToSubmit: null
};
export function addEditCourseReducer(state = initialAddEditCourseState, action: AddEditCourseActions): IAddEditCourseState {
switch (action.type) {
case AddEditCourseActionTypes.CreateNewCourse: {
return {
...state,
courseToSubmit: action.payload
};
}
case AddEditCourseActionTypes.FetchCourseToEditSuccess: {
return {
...state,
courseToSubmit: action.payload
};
}
default:
return state;
}
}
|
c5016e9bbe5f394b6062f2ae2f62a94fda76a489
|
TypeScript
|
rahulathi5/ng6-demo
|
/src/app/map/components/basic-map/basic-map.component.ts
| 2.546875
| 3
|
import { Component, OnInit } from '@angular/core';
import { MouseEvent } from '@agm/core';
@Component({
selector: 'app-basic-map',
templateUrl: './basic-map.component.html',
styleUrls: ['./basic-map.component.css']
})
export class BasicMapComponent {
zoom: number = 5;
lat: number = 22.160311576947638;
lng: number = 78.9860984375;
clickedMarker(m: marker, index: number) {
console.log('clicked the marker: ',m);
}
mapClicked($event: MouseEvent) {
this.markers.push({
lat: $event.coords.lat,
lng: $event.coords.lng,
draggable: false,
name:'New Marker'
});
}
markerDragEnd(m: marker, $event: MouseEvent) {
console.log('dragEnd', m, $event);
window.alert('New Location: '+ $event.coords.lat + ', ' + $event.coords.lng);
}
markers: marker[] = [
{
lat: 22.5726,
lng: 88.3639,
label: 'K',
name:'Kolkata',
draggable: false,
},
{
lat: 28.7041,
lng: 77.1025,
label: 'D',
name:'Delhi',
draggable: false
},
{
lat: 19.0760,
lng: 72.8777,
label: 'M',
name:'Mumbai',
draggable: true
}
]
}
// just an interface for type safety.
interface marker {
lat: number;
lng: number;
label?: string;
name?:String;
animation?:any;
draggable: boolean;
}
|
a6fcf8ba326cb38ceb0a5c937450dfa7ff32bdfc
|
TypeScript
|
orange4glace/epidemic-simulator
|
/src/world-impl.ts
| 2.6875
| 3
|
import { IWorld } from './world';
import { Society } from './society-impl';
import { Person } from './person-impl';
import { Entity } from './entity';
import { Vector2 } from './util';
import { Engine } from './engine';
import { SIRState } from './person';
import { SIRModel } from './sir-model';
let k = 0;
export class Statistic {
private elapsed_: number = 0;
public get elapsed() { return this.elapsed_; }
private numSuspectible_: number = 0;
public get numSuspectible() { return this.numSuspectible_; }
private numInfectious_: number = 0;
public get numInfectious() { return this.numInfectious_; }
private numRecovered_: number = 0;
public get numRecovered() { return this.numRecovered_; }
private records_: Array<[number, number, number]> = [];
public get records(): ReadonlyArray<[number, number, number]> {
return this.records_; }
constructor() {
}
public update(
numSuspectible_: number, numInfectious_: number, numRecovered_: number) {
this.numSuspectible_ = numSuspectible_;
this.numInfectious_ = numInfectious_;
this.numRecovered_ = numRecovered_;
}
public elapse(value: number): void {
this.elapsed_ = value;
}
public record() {
this.records_.push([this.numSuspectible_,
this.numInfectious_, this.numRecovered_]);
}
}
export class World extends Entity implements IWorld {
public readonly statistic = new Statistic();
private societies_: Society[] = [];
public get societies(): ReadonlyArray<Society> {
return this.societies_; }
private quarantine_: Society = null;
public get quarantine() { return this.quarantine_; }
private time_: number;
private day_: number;
public get day() { return this.day_; }
constructor() {
super();
this.time_ = 0;
this.day_ = 0;
}
public createQuarantine(x: number, y: number, w: number, h: number): Society {
this.quarantine_ = new Society(this, w, h);
this.quarantine_.transform.position = new Vector2(x, y);
this.quarantine_.quarantine = true;
this.listenSociety(this.quarantine);
return this.quarantine_;
}
public createSociety(x: number, y: number, w: number, h: number): Society {
const society = new Society(this, w, h);
society.transform.position = new Vector2(x, y);
this.societies_.push(society);
this.listenSociety(society);
return society;
}
public doUpdate(): void {
this.time_ += Engine.delta;
const nextDay = Math.floor(this.time_ / SIRModel.timeFactor);
for (let i = this.day_; i < nextDay; i ++) {
this.statistic.record();
}
if (this.day_ != nextDay) {
this.day_ = nextDay;
}
this.statistic.elapse(this.time_);
}
private listenSociety(society: Society) {
society.onDidPopulatePerson.subscribe(e => {
this.statistic.update(
this.statistic.numSuspectible + 1,
this.statistic.numInfectious,
this.statistic.numRecovered);
})
society.onDidChangePersonSIRState.subscribe(e => {
switch (e.lastState) {
case (SIRState.Suspectible):
this.statistic.update(
this.statistic.numSuspectible - 1,
this.statistic.numInfectious,
this.statistic.numRecovered);
break;
case (SIRState.Infectious):
case (SIRState.Infectious_Unknown):
this.statistic.update(
this.statistic.numSuspectible,
this.statistic.numInfectious - 1,
this.statistic.numRecovered);
break;
case (SIRState.Recovered):
this.statistic.update(
this.statistic.numSuspectible,
this.statistic.numInfectious,
this.statistic.numRecovered - 1);
break;
}
switch (e.person.state) {
case (SIRState.Suspectible):
this.statistic.update(
this.statistic.numSuspectible + 1,
this.statistic.numInfectious,
this.statistic.numRecovered);
break;
case (SIRState.Infectious):
case (SIRState.Infectious_Unknown):
this.statistic.update(
this.statistic.numSuspectible,
this.statistic.numInfectious + 1,
this.statistic.numRecovered);
break;
case (SIRState.Recovered):
this.statistic.update(
this.statistic.numSuspectible,
this.statistic.numInfectious,
this.statistic.numRecovered + 1);
break;
}
})
}
}
|
e4be12154e33fe8fb2a094982e90e2f2f55b4114
|
TypeScript
|
jas-haria/VOID_0.1
|
/angular-application/src/app/shared/models/topcard-details.model.ts
| 2.5625
| 3
|
export class TopCardDetails {
title: string;
middleValue: string;
bottomValue: string;
bottomValueSuccess: boolean;
bottomMessage: string;
icon: string;
iconBgColor: string;
constructor(title: string, icon: string, iconBgColor: string) {
this.title = title;
this.icon = icon;
this.iconBgColor = iconBgColor;
this.bottomValue = '';
this.bottomValueSuccess = false;
this.bottomMessage = '';
}
}
|
dca03465fbb69605cfa26528ab93550b96722e4f
|
TypeScript
|
lucasgmagalhaes/D3-Stuff
|
/src/app/class/circle.ts
| 2.796875
| 3
|
import * as d3 from 'd3';
export class Circle {
public static selectAllCircles() {
/*
//The line bellow search for the html element circle.
But, as i gonna use more circles in this page, i can not call the element.
I must use a class.
const circles = d3.selectAll('circle');
*/
const circles = d3.selectAll('.circleIE');
circles.style('fill', 'steelblue');
circles.attr('r', 30);
}
public static moveRandomCircles() {
const circles = d3.selectAll('.circleIEDance');
circles.data([32, 57, 112]);
circles.style('fill', 'steelblue');
circles.attr('r', function (d) { return Math.sqrt(d); });
circles.attr('cx', function (d, i) { return i * 100 + 30; });
window.setInterval(() => circles.attr('cx', function () { return Math.random() * 700; }), 500);
}
public static generateCircles() {
const svg = d3.select('.generatingSVG');
window.setInterval(() => {
svg.data([Math.random() * 12])
.enter().append('circle')
.attr('cy', 60)
.attr('cx', function (d, i) { return i * 100 + 30; })
.attr('r', function (d) { return Math.sqrt(d); });
});
}
}
|
c838adb6f4f934b93a1f72ad46260c2d6760294f
|
TypeScript
|
movibe/domain-preview-api
|
/src/index.ts
| 2.6875
| 3
|
import * as express from 'express'
import {getLinkPreview} from 'link-preview-js'
const app = express();
const port = process.env.PORT || 8080; // default port to listen
const urlPreview = async (url: string) => {
try {
const response = await getLinkPreview(url);
const domain = url.split('//')[1].split('/').shift();
return {
domain,
...response
};
} catch (e) {
console.log('error', e);
}
};
// define a route handler for the default home page
app.get('/', async (req, res) => {
const { url } = req.query;
console.log(url);
if (url) {
const response = await urlPreview(url);
return res.json(response);
}
return res.json({
error: true,
message: 'Insert url params ?url='
});
});
// start the Express server
app.listen(port, () => {
console.log(`server started at http://localhost:${port}`);
});
|
21204db7c0fe8c216c4916ed9030bf6dcc3d7582
|
TypeScript
|
benkeil/react-todo-app-clean-architecture
|
/code/applications/react/src/hooks/useObservableEffect.ts
| 2.53125
| 3
|
import { DependencyList, useEffect } from 'react';
import { Observable, Observer } from 'rxjs';
const useObservableEffect = <T>(
observable: Observable<T>,
observer: Partial<Observer<T>>,
deps: DependencyList = [],
): void => {
return useEffect(() => {
const subscription = observable.subscribe(observer);
return (): void => {
subscription.unsubscribe();
};
}, deps);
};
export default useObservableEffect;
|
59c7c124ce5ff80d4ce236ffc85b6e8aee7053b8
|
TypeScript
|
worstpractice/babbys-first-goap
|
/src/utils/sorting/toTrimmed.ts
| 2.515625
| 3
|
export const toTrimmed = <T extends string>(str: T): string => {
return str.trim();
};
|
53eec5b53f16a8847609bfadf68a90417ed5a37f
|
TypeScript
|
PatrickHaussmann/rki-covid-api
|
/src/utils.ts
| 2.921875
| 3
|
export function getStateAbbreviationById(id: number): string | null {
switch (id) {
case 1:
return "SH";
case 2:
return "HH";
case 3:
return "NI";
case 4:
return "HB";
case 5:
return "NW";
case 6:
return "HE";
case 7:
return "RP";
case 8:
return "BW";
case 9:
return "BY";
case 10:
return "SL";
case 11:
return "BE";
case 12:
return "BB";
case 13:
return "MV";
case 14:
return "SN";
case 15:
return "ST";
case 16:
return "TH";
default:
return null;
}
}
export function getStateIdByAbbreviation(abbreviation: string): number | null {
switch (abbreviation) {
case "SH":
return 1;
case "HH":
return 2;
case "NI":
return 3;
case "HB":
return 4;
case "NW":
return 5;
case "HE":
return 6;
case "RP":
return 7;
case "BW":
return 8;
case "BY":
return 9;
case "SL":
return 10;
case "BE":
return 11;
case "BB":
return 12;
case "MV":
return 13;
case "SN":
return 14;
case "ST":
return 15;
case "TH":
return 16;
default:
return null;
}
}
export function getStateAbbreviationByName(name: string): string | null {
switch (name) {
case "Baden-Württemberg":
return "BW";
case "Bayern":
return "BY";
case "Berlin":
return "BE";
case "Brandenburg":
return "BB";
case "Bremen":
return "HB";
case "Hamburg":
return "HH";
case "Hessen":
return "HE";
case "Mecklenburg-Vorpommern":
return "MV";
case "Niedersachsen":
return "NI";
case "Nordrhein-Westfalen":
return "NW";
case "Rheinland-Pfalz":
return "RP";
case "Saarland":
return "SL";
case "Sachsen":
return "SN";
case "Sachsen-Anhalt":
return "ST";
case "Schleswig-Holstein":
return "SH";
case "Thüringen":
return "TH";
default:
return null;
}
}
export function getDateBefore(days: number): string {
let offsetDate = new Date();
offsetDate.setHours(0, 0, 0, 0);
offsetDate.setDate(new Date().getDate() - days);
return offsetDate.toISOString().split("T").shift();
}
export function getDayDifference(date1: Date, date2: Date): number {
const diffTime = date1.getTime() - date2.getTime();
return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
}
export function AddDaysToDate(date: Date, days: number): Date {
return new Date(date.getTime() + 1000 * 60 * 60 * 24);
}
export function cleanupString(input: string): string {
// only keep latin characters, umlaute, ß, -
return input.replace(/[^a-zA-ZäöüÄÖÜß\-]/g, "");
}
export interface RKIErrorResponse {
code: number;
message: string;
details: string[];
}
export class RKIError extends Error {
public url?: string;
public rkiError: RKIErrorResponse;
constructor(error: RKIErrorResponse, url?: string) {
super(error.message);
this.name = "RKIError";
this.rkiError = error;
this.url = url;
}
}
|
dc3df4803ccb807e01a578b14329f2eb55e8b959
|
TypeScript
|
OpenAPITools/openapi-generator
|
/samples/client/petstore/typescript-aurelia/default/PetApi.ts
| 2.546875
| 3
|
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { autoinject } from 'aurelia-framework';
import { HttpClient } from 'aurelia-http-client';
import { Api } from './Api';
import { AuthStorage } from './AuthStorage';
import {
Pet,
ApiResponse,
} from './models';
/**
* addPet - parameters interface
*/
export interface IAddPetParams {
body: Pet;
}
/**
* deletePet - parameters interface
*/
export interface IDeletePetParams {
petId: number;
apiKey?: string;
}
/**
* findPetsByStatus - parameters interface
*/
export interface IFindPetsByStatusParams {
status: Array<'available' | 'pending' | 'sold'>;
}
/**
* findPetsByTags - parameters interface
*/
export interface IFindPetsByTagsParams {
tags: Array<string>;
}
/**
* getPetById - parameters interface
*/
export interface IGetPetByIdParams {
petId: number;
}
/**
* updatePet - parameters interface
*/
export interface IUpdatePetParams {
body: Pet;
}
/**
* updatePetWithForm - parameters interface
*/
export interface IUpdatePetWithFormParams {
petId: number;
name?: string;
status?: string;
}
/**
* uploadFile - parameters interface
*/
export interface IUploadFileParams {
petId: number;
additionalMetadata?: string;
file?: File;
}
/**
* PetApi - API class
*/
@autoinject()
export class PetApi extends Api {
/**
* Creates a new PetApi class.
*
* @param httpClient The Aurelia HTTP client to be injected.
* @param authStorage A storage for authentication data.
*/
constructor(httpClient: HttpClient, authStorage: AuthStorage) {
super(httpClient, authStorage);
}
/**
* Add a new pet to the store
* @param params.body Pet object that needs to be added to the store
*/
async addPet(params: IAddPetParams): Promise<any> {
// Verify required parameters are set
this.ensureParamIsSet('addPet', params, 'body');
// Create URL to call
const url = `${this.basePath}/pet`;
const response = await this.httpClient.createRequest(url)
// Set HTTP method
.asPost()
// Encode body parameter
.withHeader('content-type', 'application/json')
.withContent(JSON.stringify(params['body'] || {}))
// Authentication 'petstore_auth' required
// Send the request
.send();
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new Error(response.content);
}
// Extract the content
return response.content;
}
/**
* Deletes a pet
* @param params.petId Pet id to delete
* @param params.apiKey
*/
async deletePet(params: IDeletePetParams): Promise<any> {
// Verify required parameters are set
this.ensureParamIsSet('deletePet', params, 'petId');
// Create URL to call
const url = `${this.basePath}/pet/{petId}`
.replace(`{${'petId'}}`, encodeURIComponent(`${params['petId']}`));
const response = await this.httpClient.createRequest(url)
// Set HTTP method
.asDelete()
.withHeader('api_key', params['apiKey'])
// Authentication 'petstore_auth' required
// Send the request
.send();
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new Error(response.content);
}
// Extract the content
return response.content;
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
* @param params.status Status values that need to be considered for filter
*/
async findPetsByStatus(params: IFindPetsByStatusParams): Promise<Array<Pet>> {
// Verify required parameters are set
this.ensureParamIsSet('findPetsByStatus', params, 'status');
// Create URL to call
const url = `${this.basePath}/pet/findByStatus`;
const response = await this.httpClient.createRequest(url)
// Set HTTP method
.asGet()
// Set query parameters
.withParams({
'status': params['status'],
})
// Authentication 'petstore_auth' required
// Send the request
.send();
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new Error(response.content);
}
// Extract the content
return response.content;
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @param params.tags Tags to filter by
*/
async findPetsByTags(params: IFindPetsByTagsParams): Promise<Array<Pet>> {
// Verify required parameters are set
this.ensureParamIsSet('findPetsByTags', params, 'tags');
// Create URL to call
const url = `${this.basePath}/pet/findByTags`;
const response = await this.httpClient.createRequest(url)
// Set HTTP method
.asGet()
// Set query parameters
.withParams({
'tags': params['tags'],
})
// Authentication 'petstore_auth' required
// Send the request
.send();
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new Error(response.content);
}
// Extract the content
return response.content;
}
/**
* Find pet by ID
* Returns a single pet
* @param params.petId ID of pet to return
*/
async getPetById(params: IGetPetByIdParams): Promise<Pet> {
// Verify required parameters are set
this.ensureParamIsSet('getPetById', params, 'petId');
// Create URL to call
const url = `${this.basePath}/pet/{petId}`
.replace(`{${'petId'}}`, encodeURIComponent(`${params['petId']}`));
const response = await this.httpClient.createRequest(url)
// Set HTTP method
.asGet()
// Authentication 'api_key' required
.withHeader('api_key', this.authStorage.getapi_key())
// Send the request
.send();
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new Error(response.content);
}
// Extract the content
return response.content;
}
/**
* Update an existing pet
* @param params.body Pet object that needs to be added to the store
*/
async updatePet(params: IUpdatePetParams): Promise<any> {
// Verify required parameters are set
this.ensureParamIsSet('updatePet', params, 'body');
// Create URL to call
const url = `${this.basePath}/pet`;
const response = await this.httpClient.createRequest(url)
// Set HTTP method
.asPut()
// Encode body parameter
.withHeader('content-type', 'application/json')
.withContent(JSON.stringify(params['body'] || {}))
// Authentication 'petstore_auth' required
// Send the request
.send();
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new Error(response.content);
}
// Extract the content
return response.content;
}
/**
* Updates a pet in the store with form data
* @param params.petId ID of pet that needs to be updated
* @param params.name Updated name of the pet
* @param params.status Updated status of the pet
*/
async updatePetWithForm(params: IUpdatePetWithFormParams): Promise<any> {
// Verify required parameters are set
this.ensureParamIsSet('updatePetWithForm', params, 'petId');
// Create URL to call
const url = `${this.basePath}/pet/{petId}`
.replace(`{${'petId'}}`, encodeURIComponent(`${params['petId']}`));
const response = await this.httpClient.createRequest(url)
// Set HTTP method
.asPost()
// Encode form parameters
.withHeader('content-type', 'application/x-www-form-urlencoded')
.withContent(this.queryString({
'name': params['name'],
'status': params['status'],
}))
// Authentication 'petstore_auth' required
// Send the request
.send();
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new Error(response.content);
}
// Extract the content
return response.content;
}
/**
* uploads an image
* @param params.petId ID of pet to update
* @param params.additionalMetadata Additional data to pass to server
* @param params.file file to upload
*/
async uploadFile(params: IUploadFileParams): Promise<ApiResponse> {
// Verify required parameters are set
this.ensureParamIsSet('uploadFile', params, 'petId');
// Create URL to call
const url = `${this.basePath}/pet/{petId}/uploadImage`
.replace(`{${'petId'}}`, encodeURIComponent(`${params['petId']}`));
const response = await this.httpClient.createRequest(url)
// Set HTTP method
.asPost()
// Encode form parameters
.withHeader('content-type', 'application/x-www-form-urlencoded')
.withContent(this.queryString({
'additionalMetadata': params['additionalMetadata'],
'file': params['file'],
}))
// Authentication 'petstore_auth' required
// Send the request
.send();
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new Error(response.content);
}
// Extract the content
return response.content;
}
}
|
7e0b090b7bdd950cc9723965c0df5c6ad0db584c
|
TypeScript
|
omarqazidev/Data-Security-and-Encryption-Assignment
|
/src/index.ts
| 2.890625
| 3
|
import { Hasher } from './algorithms/Hasher';
import { PrimeNumber, PrimitiveRoot, DiffieHellman, RSA } from './algorithms';
// console.clear();
// console.log('================================================================================');
// console.log('\t\t\t Diffie Hellman');
// console.log('================================================================================\n');
// const randomPrimeNumber = PrimeNumber.getRandomPrimeNumber(100);
// const randomPrimitiveRoot = PrimitiveRoot.getRandomPrimitiveRoot(randomPrimeNumber);
// const aliceDiffieHellman = new DiffieHellman(randomPrimeNumber, randomPrimitiveRoot);
// const bobDiffieHellman = new DiffieHellman(randomPrimeNumber, randomPrimitiveRoot);
// const alicePublicKey = aliceDiffieHellman.getPublicKey();
// const bobPublicKey = bobDiffieHellman.getPublicKey();
// const aliceSecretKey = aliceDiffieHellman.generateSharedKey(bobPublicKey);
// const bobSecretKey = bobDiffieHellman.generateSharedKey(alicePublicKey);
// console.log(
// 'Both Alice and Bob have the same private/shared key:\t',
// aliceDiffieHellman.doesPrivateKeysMatch(bobDiffieHellman.getPrivateKey())
// );
// console.log('\n');
// console.table({ aliceDiffieHellman, bobDiffieHellman });
// console.log(
// '\n\n================================================================================\n'
// );
console.clear();
console.log('================================================================================');
console.log('\t\t\t RSA (Rivest–Shamir–Adleman)');
console.log('================================================================================\n');
const aliceRSA = new RSA(100);
const bobRSA = new RSA(100);
const aliceRSAPublicKey = aliceRSA.getPublicKey();
const bobRSAPublicKey = bobRSA.getPublicKey();
const plaintText = 31;
console.log('Plain Text:\t', plaintText);
const encryptedData = bobRSA.encrypt(plaintText, aliceRSAPublicKey.key, aliceRSAPublicKey.n);
console.log('Encrypted Text:\t', encryptedData);
let decryptedData = aliceRSA.decrypt(encryptedData);
console.log('Decrypted Text:\t', decryptedData);
console.log('\n');
console.table({ aliceRSA, bobRSA });
console.log(
'\n\n================================================================================\n'
);
// console.clear();
// console.log('======================================================================');
// console.log('\t\t MD5 (Message Digest 5)');
// console.log('======================================================================\n');
// const stringToHash = 'Omar Qazi';
// console.log('Orignal Text:\t\t', stringToHash);
// const sha1Hash = Hasher.textToMd5(stringToHash);
// console.log('Hashed with MD5:\t', sha1Hash);
// console.log('\n======================================================================\n');
//console.log('Hashed with MD5:\t', Hasher.textToMd5(stringToHash));
// console.clear();
// console.log('================================================================================');
// console.log('\t\t\t SHA-1 (Secure Hashing Algorithm 1)');
// console.log('================================================================================\n');
// const stringToHash = 'Omar Qazi';
// const sha1Hash = Hasher.textToMd5(stringToHash);
// console.log('Hashed with MD5:\t', sha1Hash);
// console.log(
// '\n\n================================================================================\n'
// );
|
7db9734e0ef5d590b26e829e065228a6b89be28b
|
TypeScript
|
connext/indra
|
/modules/utils/src/typedEmitter.ts
| 2.984375
| 3
|
import { IBasicEventEmitter, EventName, EventPayload } from "@connext/types";
import { Evt, to, Ctx } from "evt";
// Disable max handlers warnings
Evt.setDefaultMaxHandlers(0);
export class TypedEmitter implements IBasicEventEmitter {
private evt: Evt<[EventName, EventPayload[EventName]]>;
constructor() {
this.evt = Evt.create<[EventName, EventPayload[EventName]]>();
}
// Attaches a callback to a specified event, with an optional filter.
// Callbacks registered using this handler should be removed intenitionally
public attach<T extends EventName>(
event: T,
callback: (payload: EventPayload[T]) => void | Promise<void>,
filter?: (payload: EventPayload[T]) => boolean,
): void {
if (filter) {
// Evt package allows filtering if all events on EVT
// are filtered against, so convert the function
const eventFilter = ([emittedEvent, emittedPayload]) => {
return event === emittedEvent && filter(emittedPayload);
};
const eventCallback = ([_, emittedPayload]) => {
return callback(emittedPayload);
};
this.evt.attach(eventFilter, eventCallback);
return;
}
this.evt.$attach(to(event), callback);
}
// Attaches a callback to a specified event, with an optional filter
// Callbacks registered using this handler DO NOT have to be
// removed.
public attachOnce<T extends EventName>(
event: T,
callback: (payload: EventPayload[T]) => void | Promise<void>,
filter?: (payload: EventPayload[T]) => boolean,
): void {
if (filter) {
// Evt package allows filtering if all events on EVT
// are filtered against, so convert the function
const eventFilter = ([emittedEvent, emittedPayload]) => {
return event === emittedEvent && filter(emittedPayload);
};
const eventCallback = ([_, emittedPayload]) => {
return callback(emittedPayload);
};
this.evt.attachOnce(eventFilter, eventCallback);
return;
}
this.evt.$attachOnce(to(event), callback);
}
// Emits an event with a given payload
public post<T extends EventName>(event: T, payload: EventPayload[T]): void {
this.evt.post([event, payload]);
}
// Detaches all listners, or all in context if specified
public detach(ctx?: Ctx<[EventName, EventPayload[EventName]]>): void {
this.evt.detach(ctx);
}
// Creates a new void context for easy listener detachment
public createContext(): Ctx<[EventName, EventPayload[EventName]]> {
return Evt.newCtx<[EventName, EventPayload[EventName]]>();
}
// Returns a promise once matching event is emitted
public async waitFor<T extends EventName>(
event: T,
timeout: number, // time in MS before rejecting
filter?: (payload: EventPayload[T]) => boolean,
): Promise<EventPayload[T]> {
const eventFilter = ([emittedEvent, emittedPayload]) => {
if (filter) {
return event === emittedEvent && filter(emittedPayload);
}
return event === emittedEvent;
};
const [_, payload] = await this.evt.waitFor(eventFilter, timeout);
return payload as EventPayload[T];
}
}
|
3baffb6d30d24adfe2bfe961e67fed785f77df6b
|
TypeScript
|
typeorm/typeorm
|
/test/github-issues/6471/entity/SomeEntity.ts
| 2.859375
| 3
|
import { Column, Unique, PrimaryGeneratedColumn } from "../../../../src"
import { Entity } from "../../../../src"
export enum CreationMechanism {
SOURCE_A = "SOURCE_A",
SOURCE_B = "SOURCE_B",
SOURCE_C = "SOURCE_C",
SOURCE_D = "SOURCE_D",
}
@Entity({ name: "some_entity" })
@Unique(["field1", "field2"])
export class SomeEntity {
@PrimaryGeneratedColumn()
id: number
@Column()
field1: string
@Column()
field2: string
@Column({
type: "enum",
enumName: "creation_mechanism_enum",
enum: CreationMechanism,
})
creationMechanism: CreationMechanism
@Column({ nullable: false, default: () => "now()" })
createdAt: Date
}
|
73fd4b5a70d95cf2f257599dbddc09f74902f3e8
|
TypeScript
|
myprojectsfile/socket
|
/src/app/socket.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
@Injectable()
export class SocketService {
private url = 'http://localhost:3000';
public socket;
constructor() {
this.socket = io(this.url);
}
on(eventName, callback) {
this.socket.on(eventName, () => {
callback();
})
}
emit(eventName,data,callback?){
this.socket.emit(eventName,data,()=>{
if(callback) callback();
})
}
}
|
a0641fa1c1925ad7ac78554d6f1403b542feb8d8
|
TypeScript
|
dev00rob/newTP
|
/bankAccount.ts
| 3.375
| 3
|
class BankAccount {
owner: string;
balance: number;
transactions: number[];
constructor(o: string, b: number, t: number[]){
this.owner = o;
this.balance = b;
this.transactions = t;
}
getBalance():number{
return this.balance;
}
transact(n: number):number{
this.transactions.push(n);
this.balance += n;
return this.balance;
}
withdraw(n: number):number{
return this.transact(-n);
}
deposit(n: number):number{
return this.transact(n);
}
totalTransactions():number{
return this.transactions.length;
}
}
let rothschild = new BankAccount("Sir MoneyBanks", 0, []);
console.log(rothschild.getBalance());
console.log(rothschild.deposit(500));
console.log(rothschild.withdraw(300));
console.log(rothschild.deposit(67890));
console.log(rothschild);
console.log("Number of transactions: ", rothschild.totalTransactions());
// this is a test
|
b3301d5871413b760f454c46720742f51ac413ba
|
TypeScript
|
downplay/create-rogue-app
|
/games/hero/src/mechanics/canMove.ts
| 2.84375
| 3
|
import { text, Vector, add, length } from "@hero/text";
import { GameState } from "../engine/game";
import { EntityState } from "../engine/entity";
import { LifeState } from "./hasLife";
import { StatsState } from "./hasStats";
// TODO: Putting all the interactions in `move` seems like the wrong way around; as this
// becomes too unwieldy consider a more extensible way to handle entity interactions. Really
// we should check what's on the tile before we decide to move, and then call the appropriate
// action instead (move, attack, open, etc.) - then different actions would trigger different
// numbers of turns.
// const [isDead] = hasDeath();
// const combat = useCombat();
export const canMove = text`
move: ($delta)
$void(
$position=${(
actor: GameState & EntityState & LifeState & StatsState & { delta: Vector }
): Vector => {
const { position, isDead, engine, delta } = actor;
// TODO: Should never be called in either of these cirumstance
if (isDead || !position) {
return position;
}
const next = add(position, delta);
const cell = engine.map.getCell(next);
// TODO: check cell contents, maybe trigger interaction
return next;
}}
$waitForTurn(${({ delta, derived: { speed } = { speed: 1 } }) =>
length(delta) / speed})
$onMoved($position)
)
onMoved:~
{0}
`;
// TODO: Reimplement interact and combat
// if (cell.tiles.find((tile) => tile.entity?.getFlag(FLAG_SOLID))) {
// // TODO: animate bumping wall (how? - need to send some state to tile)
// return;
// }
// // TODO: needs to become a more sophisticated faction check
// // TODO: and we should really just have a findEntity method on the cell ...
// if (actor.getFlag(FLAG_PLAYER)) {
// const monsterTile = cell.tiles.find(
// (tile) => tile.entity?.getFlag(FLAG_MONSTER) && !getDeath(tile.entity)
// );
// if (monsterTile) {
// // IT'S COMBAT TIME
// combat(monsterTile.entity as EntityContext);
// return;
// }
// }
// if (actor.getFlag(FLAG_MONSTER)) {
// const playerTile = cell.tiles.find(
// (tile) => tile.entity?.getFlag(FLAG_PLAYER) && !getDeath(tile.entity)
// );
// if (playerTile) {
// // IT'S COMBAT TIME
// combat(playerTile.entity as EntityContext);
// return;
// }
// }
|
3d4d3f3f9fb8cf0767a744787f5ca8ef448558a9
|
TypeScript
|
nestdotland/hatcher
|
/lib/utilities/box.ts
| 2.671875
| 3
|
import { colors, Table } from "../../deps.ts";
const characters = {
top: "─",
topMid: "┬",
topLeft: "╭",
topRight: "╮",
bottom: "─",
bottomMid: "┴",
bottomLeft: "╰",
bottomRight: "╯",
left: "│",
leftMid: "├",
mid: "─",
midMid: "┼",
right: "│",
rightMid: "┤",
middle: "│",
};
for (const char in characters) {
characters[char as keyof typeof characters] = colors.yellow(
characters[char as keyof typeof characters],
);
}
export function box(text: string) {
new Table()
.header([])
.body([[`\n${text}\n `]])
.indent(3)
.padding(4)
.border(true)
.chars(characters)
.render();
}
|
327c57e7cd342485c27e0d6f36bc5ce8b2633018
|
TypeScript
|
olist/olist-orders-frontend
|
/src/home/classes/Search.ts
| 2.828125
| 3
|
export interface ISearch {
value: string;
}
class Search implements ISearch {
public value = '';
constructor(newValue: string) {
this.value = newValue;
}
}
export default Search;
|
45c6a7b36df39769426b29e677fbdcf1f0f7ce5a
|
TypeScript
|
andreluizsgf/Scheduler-api-typescript
|
/src/controllers/RuleController.ts
| 2.546875
| 3
|
/* eslint-disable max-len */
import * as express from 'express';
import Rule from '../models/Rule.model';
import Interval from '../models/Interval.model';
import * as scheduler from '../helpers/SchedulerHelper';
import * as file from '../helpers/FileHelper';
import moment from 'moment';
import {DATABASE_JSON} from '../paths.consts';
export const index = (req: express.Request, res: express.Response) => {
try {
file.readJson(DATABASE_JSON)
.then((rulesJson) => {
const rules = Array.from(rulesJson.values());
return res.status(200).json({
message: 'Listing all rules.',
status: true,
rules: rules,
});
});
} catch (error) {
res.status(400).send(JSON.stringify({'error': error}));
}
};
export const store = (req: express.Request, res: express.Response) => {
try {
file.readJson(DATABASE_JSON)
.then((rulesJson) => {
const date: string = req.body.date;
const intervals: Interval[] = req.body.intervals;
const errors: Rule[] = [];
if (date) {
const day = +moment(date, 'DD-MM-YYYY').format('d');
intervals.forEach((interval) => {
const id = scheduler.getNewId(rulesJson);
const rule: Rule = {date: date, day: day, interval: interval};
if (scheduler.checkConflictsByDate(rule, rulesJson) && scheduler.checkConflictsByDay(rule, rulesJson)) {
rulesJson.set(id, rule);
} else {
errors.push(rule);
}
});
} else {
const days: number[] = req.body.days || [0, 1, 2, 3, 4, 5, 6];
days.forEach((day) => {
intervals.forEach((interval) => {
const id = scheduler.getNewId(rulesJson);
const rule: Rule = {day: day, interval: interval};
if (scheduler.checkConflictsByDay(rule, rulesJson)) {
rulesJson.set(id, rule);
} else {
errors.push(rule);
}
});
});
}
file.writeJson(rulesJson, DATABASE_JSON)
.then(() => {
if (!errors.length) {
return res.status(201).json({
message: 'Rules successfully created.',
status: true,
});
} else {
return res.status(200).json({
message: 'Rules successfully created.',
status: true,
conflicts: errors,
});
}
});
});
} catch (error) {
return res.status(400).json({
message: 'Problems creating rules.',
status: false,
error: error.message,
});
}
};
export const availableHours = (req: express.Request, res: express.Response) => {
try {
const firstDate: any = req.query.firstDay;
const lastDate: any = req.query.lastDay;
if (!firstDate || !lastDate) {
return res.status(500).json({
message: 'Problems listing available hours.',
status: false,
error: 'Please inform valid firstDate and lastDate values.',
});
}
file.readJson(DATABASE_JSON)
.then((rulesJson) => {
const dates = scheduler.generateDatesWithinRange(firstDate, lastDate);
const availableHours = scheduler.getAvailableHours(dates, rulesJson);
return res.status(200).json({
message: 'All available hours.',
status: true,
hours: availableHours,
});
});
} catch (error) {
return res.status(400).json({
message: 'Problems listing available hours.',
status: false,
error: error.message,
});
}
};
export const destroy = (req: express.Request, res: express.Response) => {
const id = +req.params.id;
file.readJson(DATABASE_JSON)
.then((rulesJson) => {
try {
const rule = rulesJson.get(id);
if (rulesJson.delete(id)) {
file.writeJson(rulesJson, DATABASE_JSON);
return res.status(200).json({
message: 'Rule successfully deleted.',
status: true,
rule: rule,
});
} else {
return res.status(500).json({
message: 'Rule not found. Enter a valid ID.',
status: false,
});
}
} catch (error) {
return res.status(400).json({
message: 'Problems deleting rule.',
status: false,
error: error.message,
});
}
});
};
|
5f7e351f5762c88182d40a7dc2c7cb0a219e1abf
|
TypeScript
|
DavidTurnbough/FoodAlert
|
/src/providers/item-data-service.ts
| 2.921875
| 3
|
import { Injectable } from '@angular/core';
import { File } from '@ionic-native/file';
@Injectable()
export class ItemDataServiceProvider {
itemsObject: any;
path: string;
fileReady = false;
constructor(private file: File)
{
this.path = this.file.externalDataDirectory; //Define the path
this.checkItemFile(); //Check if the json exists create one if it doesn't
}
//
isReady(): Promise<boolean>
{
return new Promise<boolean>(resolve => {
setTimeout(() => {
resolve(this.fileReady);
},1000);
});
}
//Used to pass the json object read to the provider
setData(data: any)
{
this.itemsObject = data;
}
//Passes object to calendar
getData(item: number)
{
return this.itemsObject.Food[item];
}
getAllData()
{
return this.itemsObject.Food;
}
//
getFoodNum()
{
return this.itemsObject.Food.length;
}
//Push a new object to the internal list then immediately saves it to the json
//Expects it is already in proper format
addFood(foodOb: any)
{
this.itemsObject.Food.push(foodOb);
this.saveData();
}
//Overwrites json with current productList contents
saveData()
{
var jsonText = JSON.stringify(this.itemsObject);
this.file.writeFile(this.path,'items.json',jsonText,{replace: true});
}
//Returns true if the file already exists
checkItemFile()
{
this.file.checkFile(this.path,'items.json').then(exists => {
//This means the file exists and we can load in the data
this.readItemFileText();
this.fileReady = true;
}).catch(err => {
//This means the file doesn't exist and we call to create one
this.createItemFile();
this.itemsObject = {'Food':[]} //Initialize the items object to be empty
this.saveData(); //save empty structure to file
this.fileReady = true;
})
}
//Loads in the json file
readItemFileText()
{
this.file.readAsText(this.path,'items.json').then(text => {
var json = JSON.parse(text);
this.setData(json);
}).catch( err => {
console.log(err);
});
}
//Creates a blank item.json file, won't overwrite
createItemFile()
{
this.file.createFile(this.path,'items.json',false).then(file =>{
}).catch(err => {
console.log(err);
});
}
printToConsole()
{
for(var i = 0; i < this.itemsObject.Food.length; ++i)
{
console.log(this.itemsObject.Food[i]);
}
}
removeItem(foodOb: any)
{
for(let i = 0; i < this.itemsObject.Food.length; i++)
{
if(this.itemsObject.Food[i].name == foodOb.name && this.itemsObject.Food[i].date == foodOb.date)
{
this.itemsObject.Food.splice(i,1);
break;
}
}
this.saveData();
}
}
|
bbc5934284e8a30afbb6575588ef2bfe4e52fa53
|
TypeScript
|
NiluK/api
|
/packages/types/src/codec/createType.spec.ts
| 2.9375
| 3
|
// Copyright 2017-2018 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { TypeDefInfo, typeSplit, getTypeClass, getTypeDef } from './createType';
describe('typeSplit', () => {
it('splits simple types into an array', () => {
expect(
typeSplit('Text, u32, u64')
).toEqual(['Text', 'u32', 'u64']);
});
it('splits nested combinations', () => {
expect(
typeSplit('Text, (u32), Vec<u64>')
).toEqual(['Text', '(u32)', 'Vec<u64>']);
});
it('keeps nested tuples together', () => {
expect(
typeSplit('Text, (u32, u128), Vec<u64>')
).toEqual(['Text', '(u32, u128)', 'Vec<u64>']);
});
it('keeps nested vector tuples together', () => {
expect(
typeSplit('Text, (u32, u128), Vec<(u64, u32)>')
).toEqual(['Text', '(u32, u128)', 'Vec<(u64, u32)>']);
});
it('allows for deep nesting', () => {
expect(
typeSplit('Text, (u32, (u128, u8)), Vec<(u64, (u32, u32))>')
).toEqual(['Text', '(u32, (u128, u8))', 'Vec<(u64, (u32, u32))>']);
});
it('checks for unclosed vec', () => {
expect(
() => typeSplit('Text, Vec<u64')
).toThrow(/Invalid Compact\/Vector/);
});
it('checks for unclosed tuple', () => {
expect(
() => typeSplit('Text, (u64, u32')
).toThrow(/Invalid Tuple/);
});
});
describe('getTypeValue', () => {
it('does not allow invalid tuples, end )', () => {
expect(
() => getTypeDef('(u64, u32')
).toThrow(/Expected '\(' closing with '\)'/);
});
it('does not allow invalid vectors, end >', () => {
expect(
() => getTypeDef('Vec<u64')
).toThrow(/Expected 'Vec<' closing with '>'/);
});
it('returns a type structure', () => {
expect(
getTypeDef('(u32, Compact<u32>, Vec<u64>, (Text, Vec<(Bool, u128)>))')
).toEqual({
info: TypeDefInfo.Tuple,
type: '(u32, Compact<u32>, Vec<u64>, (Text, Vec<(Bool, u128)>))',
sub: [
{
info: TypeDefInfo.Plain,
type: 'u32'
},
{
info: TypeDefInfo.Compact,
type: 'Compact<u32>',
sub: {
info: TypeDefInfo.Plain,
type: 'u32'
}
},
{
info: TypeDefInfo.Vector,
type: 'Vec<u64>',
sub: {
info: TypeDefInfo.Plain,
type: 'u64'
}
},
{
info: TypeDefInfo.Tuple,
type: '(Text, Vec<(Bool, u128)>)',
sub: [
{
info: TypeDefInfo.Plain,
type: 'Text'
},
{
info: TypeDefInfo.Vector,
type: 'Vec<(Bool, u128)>',
sub: {
info: TypeDefInfo.Tuple,
type: '(Bool, u128)',
sub: [
{
info: TypeDefInfo.Plain,
type: 'Bool'
},
{
info: TypeDefInfo.Plain,
type: 'u128'
}
]
}
}
]
}
]
});
});
it('returns a type structure (actual)', () => {
expect(
getTypeDef('Vec<(PropIndex, Proposal, AccountId)>')
).toEqual({
info: TypeDefInfo.Vector,
type: 'Vec<(PropIndex, Proposal, AccountId)>',
sub: {
info: TypeDefInfo.Tuple,
type: '(PropIndex, Proposal, AccountId)',
sub: [
{
info: TypeDefInfo.Plain,
type: 'PropIndex'
},
{
info: TypeDefInfo.Plain,
type: 'Proposal'
},
{
info: TypeDefInfo.Plain,
type: 'AccountId'
}
]
}
});
});
});
describe('getTypeClass', () => {
it('does not allow invalid types', () => {
expect(
() => getTypeClass('SomethingInvalid' as any)
).toThrow(/determine type/);
});
});
|
b183ee062a5bfb910c2a079c95308c90fccbcd29
|
TypeScript
|
MiggieNRG/vscode-gitblame
|
/test/suite/is-url.test.ts
| 2.890625
| 3
|
import * as assert from 'assert';
import { isUrl } from '../../src/util/is-url';
suite('Is URL', (): void => {
test('Valid', (): void => {
assert.strictEqual(isUrl("http://github.com/"), true);
assert.strictEqual(isUrl("https://microsoft.com/"), true);
assert.strictEqual(isUrl("https://vscode.co.uk/"), true);
assert.strictEqual(isUrl("https://example.com/some-path"), true);
assert.strictEqual(isUrl("https://example.com/some-path.ext"), true);
assert.strictEqual(isUrl("https://host:8080/some-path.ext"), true);
assert.strictEqual(isUrl("https://user:pass@host:8080/path.ext"), true);
});
test('Invalid', (): void => {
assert.strictEqual(isUrl("ftp://github.com/"), false);
assert.strictEqual(isUrl("http:github.com"), false);
assert.strictEqual(isUrl("http:github.com/some-path"), false);
assert.strictEqual(isUrl("%"), false);
assert.strictEqual(isUrl("/file.ext"), false);
assert.strictEqual(isUrl("protocol:user@/file.ext"), false);
assert.strictEqual(isUrl("http://"), false);
assert.strictEqual(isUrl("This is not an URL"), false);
assert.strictEqual(isUrl("http://🐆.com/"), false);
});
});
|
da202fbb6f6cab743d0093b390eefc238eb424e3
|
TypeScript
|
mickeeri/egghead-redux-obs
|
/src/epics/testing.ts
| 2.515625
| 3
|
import fetch from 'node-fetch';
import { forkJoin, from } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
const topStories = `https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty`;
const storyUrl = (id: string) =>
`https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`;
const getData = (url: string) => {
return fetch(url).then(r => {
return r.ok ? r.json() : Promise.reject(`${r.statusText} ${r.status}`);
});
};
const result = from(getData(topStories)).pipe(
map(ids => ids.slice(0, 5)),
map(ids => ids.map(storyUrl)),
map(urls => urls.map((url: string) => from(getData(url)))),
mergeMap(reqs => forkJoin(reqs)),
);
result.subscribe(stories => {
if (stories.length) {
// tslint:disable-next-line:no-console
console.log(stories[0]);
}
});
|
e7604de933c65a772a81fa10a2a449049055294e
|
TypeScript
|
nm-hoang/sakila-frontend
|
/src/stores/reducers/customer.Reducers.ts
| 2.796875
| 3
|
import * as TYPES from '../constants/customer.Constants'
interface InitialStateI {
requesting?: boolean,
success?: boolean,
obj_data?: any,
list_data?: any,
message?: any
}
const initialState: InitialStateI = {
requesting: false,
success: false
}
const customerReducers = (state: InitialStateI = initialState, payload: any) => {
switch (payload.type) {
// getlist
case TYPES.GETLIST_CUSTOMER_REQUEST:
return {
...state,
requesting: true,
};
case TYPES.GETLIST_CUSTOMER_SUCCESS:
return {
...state,
requesting: false,
success: true,
list_data: payload.data,
};
case TYPES.GETLIST_CUSTOMER_ERROR:
return {
...state,
requesting: false,
success: false,
message: payload.message,
};
// get by id
case TYPES.GETBYID_CUSTOMER_REQUEST:
return {
...state,
requesting: true,
obj_data: null,
};
case TYPES.GETBYID_CUSTOMER_SUCCESS:
return {
...state,
requesting: false,
success: true,
obj_data: payload.data,
};
case TYPES.GETBYID_CUSTOMER_ERROR:
return {
...state,
requesting: false,
success: false,
message: payload.message,
};
// insert
case TYPES.INSERT_CUSTOMER_REQUEST:
return {
...state,
requesting: true,
};
case TYPES.INSERT_CUSTOMER_SUCCESS:
return {
...state,
requesting: false,
success: true,
obj_data: payload.data,
};
case TYPES.INSERT_CUSTOMER_ERROR:
return {
...state,
requesting: false,
success: false,
message: payload.message,
};
// update
case TYPES.UPDATE_CUSTOMER_REQUEST:
return {
...state,
requesting: true,
};
case TYPES.UPDATE_CUSTOMER_SUCCESS:
return {
...state,
requesting: false,
success: true,
obj_data: payload.data,
};
case TYPES.UPDATE_CUSTOMER_ERROR:
return {
...state,
requesting: false,
success: false,
message: payload.message,
};
// delete
case TYPES.DELETE_CUSTOMER_REQUEST:
return {
...state,
requesting: true,
};
case TYPES.DELETE_CUSTOMER_SUCCESS:
return {
...state,
requesting: false,
success: true,
message: payload.data,
};
case TYPES.DELETE_CUSTOMER_ERROR:
return {
...state,
requesting: false,
success: false,
message: payload.message,
};
default:
return state;
}
};
export default customerReducers;
|
43840a1d1f1690f6e12dea16b25705ca0eeb7793
|
TypeScript
|
phonowell/fire-keeper
|
/test/toString.ts
| 3.46875
| 3
|
import { $ } from './index'
// interface
type ListQuestion = [
number,
string,
boolean,
number[],
{ [key: string]: number },
() => void,
Date,
Error,
Buffer,
null,
undefined,
typeof NaN,
]
// function
const a = () => {
const listQuestion: ListQuestion = [
42, // number
'Aloha', // string
true, // boolean
[1, 2, 3], // array
{ a: 1, b: 2 }, // object
() => null, // function
new Date(), // date
new Error('OK'), // error
Buffer.from('String'), // buffer
null, // null
undefined, // undefined
NaN, // NaN
]
const listAnswer = [
'42',
'Aloha',
'true',
'[1,2,3]',
'{"a":1,"b":2}',
listQuestion[5].toString(),
listQuestion[6].toString(),
listQuestion[7].toString(),
listQuestion[8].toString(),
'null',
'undefined',
'NaN',
]
for (let i = 0; i < listQuestion.length; i++) {
const question = listQuestion[i]
const answer = listAnswer[i]
if ($.toString(question) !== answer)
throw new Error(`${$.toString(question)} !== ${answer}`)
}
}
// export
export { a }
|
acd5f3e94cb94dbac4d53a15e73eb60c2eef66ec
|
TypeScript
|
Mandustas/Coordinate
|
/src/types/detectedObjectUpdate.ts
| 2.734375
| 3
|
export interface DetectedObjectState {
detectedObject: { id: number, title: string, description: string, missionId: number, isDesired: boolean };
}
export enum DetectedObjectActionTypes {
FETCH_DETECTEDOBJECT_UPDATE = 'FETCH_DETECTEDOBJECT_UPDATE',
}
interface FetchDetectedObjectAction {
type: DetectedObjectActionTypes.FETCH_DETECTEDOBJECT_UPDATE;
payload: any;
}
export type DetectedObjectAction = FetchDetectedObjectAction
|
0c1fb6664023a112e26e2e9230aed0a8d15808f9
|
TypeScript
|
Sergey-lang/Card-Learning-app
|
/src/02-Pages/06-Cards/cards-reducer.ts
| 2.515625
| 3
|
import {Dispatch} from 'redux';
import {cardsAPI} from '../../01-API/04-cards-api';
import {ThunkDispatch} from 'redux-thunk';
import {AppStoreType} from '../../00-App/store';
import {setAppStatus} from '../../00-App/app-reducer';
type ActionsType = ReturnType<typeof setCards>
| ReturnType<typeof setFilter>
| ReturnType<typeof setAppStatus>
| ReturnType<typeof setGrade>
| ReturnType<typeof createCard>
export type CardType = {
answer: string,
question: string,
cardsPack_id: string,
grade: number,
rating: number,
shots?: number,
type: string,
user_id?: string,
created?: string,
updated?: string,
__v?: 0,
_id: string,
}
export type CardsFilterType = {
packName: string
min: number
max: number
}
const initialState = {
cards: [] as CardType[],
page: 1,
pageCount: 3,
cardsTotalCount: 5,
packUserId: '',
filter: {
packName: '',
min: 0,
max: 15,
} as CardsFilterType
} as const
export type CardsInitialStateType = typeof initialState
export const cardsReducer = (state: CardsInitialStateType = initialState, actions: ActionsType): CardsInitialStateType => {
switch (actions.type) {
case 'CARDS/CARDS/SET-FILTER':
return {...state, filter: actions.payload.filter}
case 'CARDS/CARDS/SET-CARDS':
return {...state, cards: actions.cards}
case 'CARDS/CARDS/ADD-CARD':
return {...state, cards: [actions.newCard, ...state.cards]}
case 'CARDS/CARDS/SET-GRADE':
return {
...state,
cards: state.cards.map(
(card, i) => card._id === actions.payload.id
? {...card, grade: actions.payload.grade}
: card
)
}
default:
return state
}
}
export const setCards = (cards: CardType[]) => ({type: 'CARDS/CARDS/SET-CARDS', cards} as const)
export const createCard = (newCard: CardType) => ({type: 'CARDS/CARDS/ADD-CARD', newCard} as const)
export const setFilter = (filter: CardsFilterType) => ({
type: 'CARDS/CARDS/SET-FILTER', payload: {
filter
}
} as const)
export const setGrade = (grade: number, id: string) => ({
type: 'CARDS/CARDS/SET-GRADE',
payload: {
id,
grade
}
} as const)
export const getCards = (cardsPackId: string) => async (dispatch: Dispatch<ActionsType>) => {
dispatch(setAppStatus({status: 'loading', error: null}))
try {
const res = await cardsAPI.getCards(cardsPackId)
dispatch(setAppStatus({status: 'succeeded', error: null}))
dispatch(setCards(res.data.cards))
} catch (e) {
console.log(e)
}
}
export const addCard = (card: CardType) => async (dispatch: ThunkDispatch<AppStoreType, unknown, ActionsType>) => {
dispatch(setAppStatus({status: 'loading', error: null}))
try {
await cardsAPI.createCard(card)
dispatch(setAppStatus({status: 'succeeded', error: null}))
dispatch(getCards(card.cardsPack_id))
console.log(card)
} catch (e) {
console.log(e)
}
}
export const updateCard = (card: CardType) => async (dispatch: ThunkDispatch<AppStoreType, unknown, ActionsType>) => {
dispatch(setAppStatus({status: 'loading', error: null}))
try {
const res = await cardsAPI.updateCard(card)
await dispatch(setAppStatus({status: 'succeeded', error: null}))
const packId = res.data.updatedCard.cardsPack_id
dispatch(getCards(packId))
} catch (e) {
const error = e.response
? e.response.data.error
: (e.message + ', more details in the console')
console.log(error)
}
}
export const deleteCard = (id: string) => async (dispatch: ThunkDispatch<AppStoreType, unknown, ActionsType>) => {
dispatch(setAppStatus({status: 'loading', error: null}))
try {
const res = await cardsAPI.deleteCard(id)
await dispatch(setAppStatus({status: 'succeeded', error: null}))
const packId = res.data.deletedCard.cardsPack_id
dispatch(getCards(packId))
} catch (e) {
const error = e.response
? e.response.data.error
: (e.message + ', more details in the console')
console.log(error)
}
}
export const sendGrade = (grade: number, card_id: string) => async (dispatch: ThunkDispatch<AppStoreType, unknown, ActionsType>) => {
dispatch(setAppStatus({status: 'loading', error: null}))
try {
const res = await cardsAPI.sendGrade(grade, card_id)
await dispatch(setAppStatus({status: 'succeeded', error: 'Sent'}))
const cardID = res.data._id
const newGrade = res.data.grade
dispatch(setGrade(newGrade, cardID))
} catch (e) {
const error = e.response
? e.response.data.error
: (e.message + ', more details in the console')
dispatch(setAppStatus({status: 'succeeded', error: error}))
}
}
|
29adde00e698f4f0ad0a192f9b777b7a4d168719
|
TypeScript
|
def-codes/the-better-thing
|
/packages/meld/graph-it.ts
| 2.703125
| 3
|
import { getInUnsafe } from "@thi.ng/paths";
import {
Subgraph,
object_graph_to_dot_subgraph,
depth_first_walk,
graph,
empty_traversal_state,
default_traversal_spec,
} from "@def.codes/graphviz-format";
import { dot_updater } from "@def.codes/node-web-presentation";
interface Sketch {
path?: string; // supports a.b.c notation
as?: "walk" | "dot" | "graph";
}
export const make_grapher = () => {
const updater = dot_updater();
return function graph_it(thing: any, view?: Sketch | Sketch[]) {
if (!view)
view = Object.keys(thing)
.filter(key => key !== "view")
.map(path => ({ path, as: "graph" }));
const state = empty_traversal_state();
const spec = default_traversal_spec();
// const spec: LabeledSyncTraversalSpec = {
// id: x => x,
// links_from: x => [...members_of(x)].slice(0, 3),
// };
const options = { spec, state };
const to_subgraph_special = (sketch: Sketch): Subgraph => {
const value = sketch.path ? getInUnsafe(thing, sketch.path) : thing;
const interpreter = sketch.as || "graph";
if (interpreter === "walk")
return object_graph_to_dot_subgraph(
[...depth_first_walk([value])],
options
);
if (interpreter === "dot")
return object_graph_to_dot_subgraph(
// if you were to override spec, I don't think you'd want to apply it here too...
[object_graph_to_dot_subgraph([value], options)],
options
);
if (interpreter === "graph")
return object_graph_to_dot_subgraph([value], options);
};
const to_subgraph = (sketch: Sketch): Subgraph => ({
...to_subgraph_special(sketch),
id: `cluster_${
Array.isArray(sketch.path)
? sketch.path.join("_")
: sketch.path
? sketch.path.replace(".", "_")
: "anon"
}`,
attributes: {
label: sketch.path ?? "anon",
},
});
const statements = (Array.isArray(view) ? view : [view]).map(to_subgraph);
// Hold on just a little while longer...
// console.log(`graph`, graph);
// const dot = serialize_dot(graph);
// console.log(`dot`, dot);
// If you must do that ^ then just add as:`text` interpreter
const g = graph({
statements,
directed: true,
attributes: { rankdir: "LR" },
});
updater.go(g, false); // trace
};
};
|
a29db75149e42b62a7830af4b4a96a630550175d
|
TypeScript
|
gitter-badger/planktos
|
/lib/channel.ts
| 2.890625
| 3
|
import * as socketio from 'socket.io-client';
import { EventEmitter } from 'events';
const SimplePeer = require('simple-peer');
export interface Message {
type: string;
content: any;
}
/* Bi-directional communication via message passing between a
* source and destination
* Emits: message(msg: Message), connect(), error(e: any)
*/
export interface Channel extends NodeJS.EventEmitter {
getRemoteId(): string;
sendMessage(m: Message): void;
// TODO add onDisconnect
}
/* Communication to/from a server using socketio as the transport */
export class SocketioChannel extends EventEmitter implements Channel {
private socket: SocketIOClient.Socket;
constructor(masterUrl?: string) {
super();
this.socket = socketio.connect(masterUrl);
this.socket.on('message', (msg: Message) => {
console.info("SOCKETIO RECV", JSON.stringify(msg));
this.emit('message', msg);
});
this.socket.on('connect', () => {
this.emit('connect');
});
}
getRemoteId() {
return '/#' + this.socket.id;
}
sendMessage(msg: Message) {
console.info("SOCKETIO SEND", JSON.stringify(msg));
this.socket.send(msg);
}
}
/* Channel that relays it's messages through another channel */
export class RelayChannel extends EventEmitter implements Channel {
private remoteId: string;
private localId: string;
private relay: Channel;
constructor(relay: Channel, localId: string, remoteId: string) {
super();
this.localId = localId;
this.remoteId = remoteId;
this.relay = relay;
relay.on('message', (msg: Message) => {
// Only accpet messages that have the exported toId/fromId since
// there may be multiple RelayChannels using the same relay
if (msg.type === 'relay' && msg.content.toId === this.localId &&
msg.content.fromId == this.remoteId) {
this.emit('message', msg.content.msg);
}
});
this.emit('connect');
}
getRemoteId() {
return this.remoteId;
}
sendMessage(msg: Message) {
const relayMsg = {
type: 'relay',
content: {
toId: this.remoteId,
fromId: this.localId,
msg: msg
}
};
this.relay.sendMessage(relayMsg);
}
}
/* Channel that uses webrtc as it's transport */
export class WrtcChannel extends EventEmitter implements Channel {
private signaler: Channel;
private remoteId: string;
private webrtc: any; // Instance of SimplePeer
/* Initiates a webrtc channel. Before two peers can connect they
* must first exchange signaling information which is exchanged
* through the provided `signaler` channel. The initiator of the
* connection sends an 'offer' through the signaler channel. If the
* 'offer' is accpeted, an 'answer' is sent back to the initiator.
* After this, the two peers are connected
*/
constructor(signaler: Channel, remoteId: string, offer?: any) {
super();
if (!SimplePeer.WEBRTC_SUPPORT)
throw new Error("WebRTC is not supported!");
this.signaler = signaler;
this.remoteId = remoteId;
this.webrtc = new SimplePeer({
initiator: typeof(offer) === 'undefined',
trickle: false
});
if (typeof(offer) !== 'undefined')
this.webrtc.signal(offer);
this.signaler.on('message', (msg: Message) => {
if (msg.type !== 'signal') {
console.warn("Received message other than signals over signaler channel", msg);
return;
}
this.webrtc.signal(msg.content);
});
this.webrtc.on('signal', (signal: any) => {
// We received an answer or our offer is ready.
// So send the destination our signaling info
this.signaler.sendMessage({
type: 'signal',
content: signal
});
});
this.webrtc.on('connect', () => {
console.info("WEBRTC CONNECTED");
this.emit('connect');
});
this.webrtc.on('error', (e: any) => {
console.warn("WEBRTC ERROR", e);
this.emit('error', e);
});
this.webrtc.on('data', (data: string) => {
const msg: Message = JSON.parse(data);
console.info("WRTC RECV", JSON.stringify(msg));
this.emit('message', msg);
});
}
getRemoteId() {
return this.remoteId;
}
sendMessage(msg: Message) {
const str = JSON.stringify(msg);
console.info("WRTC SEND", str);
this.webrtc.send(str);
}
}
/* Brokers all the connections for a client.
* When a new potential peer is found, ChannelManager attempts
* to open a webrtc channel to that peer. First it must open
* up a relay channel that relays all the messages between the
* peers through a server so the peers can exchange signaling
* information. When the peers connect over webrtc the
* ChannelManager's 'connect' event is fired.
*
* Emits: channel-connect()
*/
export class ChannelManager extends EventEmitter {
private server: Channel;
private localId: string;
// Channels that are in the process of exhanging signaling info
private pendingChannels: {[i: string]: WrtcChannel} = {};
// Channels that have formed a connection
private connectedChannels: {[i: string]: Channel} = {};
constructor(localId: string, server: Channel) {
super();
this.localId = localId;
this.server = server;
server.on('message', (msg: Message) => this.handleServerMsg(msg));
this.findPeers();
}
getLocalId() {
return this.localId;
}
/* Asks the server for more peers and attempts to connect to them */
findPeers() {
this.server.sendMessage({ type: 'findPeers', content: {} });
}
/* Called when we received a message from the server */
private handleServerMsg(msg: Message) {
if (msg.type == 'newPeers') {
this.handlePotentialPeers(msg.content);
} else if (msg.type === 'relay') {
this.handleRelayedMsg(msg);
} else {
console.warn("Received message with unknown type", msg);
}
}
/* Watches for messages relayed over the server channel in
* order to find signaling messages and start the webrtc
* process on this side of the connection
*/
private handleRelayedMsg(msg: Message) {
const remoteId: string = msg.content.fromId;
const relayMsg: Message = msg.content.msg;
// Only signaling messages should be relayed
if (relayMsg.type !== 'signal') {
console.warn('Recieved relayed message other than signal', msg);
return;
}
if (remoteId in this.pendingChannels || remoteId in this.connectedChannels)
return;
// An offer has been received
this.initiateWrtcChannel(remoteId, relayMsg.content);
}
/* Called when potential peers have been found */
private handlePotentialPeers(peerIds: string[]) {
for (const remoteId of peerIds) {
if (remoteId in this.pendingChannels || remoteId in this.connectedChannels)
continue; // Already have this peer
this.initiateWrtcChannel(remoteId);
}
}
private initiateWrtcChannel(remoteId: string, offer?: any) {
const signaler = new RelayChannel(this.server, this.getLocalId(), remoteId);
const wrtc = new WrtcChannel(signaler, remoteId, offer);
wrtc.on('connect', () => {
this.connectedChannels[remoteId] = wrtc;
delete this.pendingChannels[remoteId];
this.emit('channel-connect', wrtc);
});
//TODO Cleanup pending peers if connection fails after timeout
this.pendingChannels[remoteId] = wrtc;
}
}
|
f5677ccba06c7de272ef3f639678f8742273a6e0
|
TypeScript
|
uber/nebula.gl
|
/modules/edit-modes/test/lib/measure-distance-mode.test.ts
| 2.859375
| 3
|
import { MeasureDistanceMode } from '../../src/lib/measure-distance-mode';
import {
createFeatureCollectionProps,
createClickEvent,
createPointerMoveEvent,
createKeyboardEvent,
} from '../test-utils';
const expectToBeCloseToArray = (actual, expected) => {
expect(actual.length).toBe(expected.length);
actual.forEach((x, index) => expect(x).toBeCloseTo(expected[index], 1));
};
describe('move without click', () => {
let mode;
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handlePointerMove(createPointerMoveEvent(), createFeatureCollectionProps());
});
it('guides are empty', () => {
const guides = mode.getGuides(createFeatureCollectionProps());
expect(guides).toEqual({ type: 'FeatureCollection', features: [] });
});
it('tooltips are empty', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps());
expect(tooltips).toEqual([]);
});
});
describe('one click', () => {
let mode;
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps());
});
it('guides are a single point', () => {
const guides = mode.getGuides(createFeatureCollectionProps());
expect(guides).toMatchSnapshot();
});
it('tooltips are 0.00', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps());
expect(tooltips[0].text).toContain('0.00');
});
});
describe('one click - centerTooltipsOnLine = true', () => {
let mode;
const props = { modeConfig: { centerTooltipsOnLine: true } };
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps(props));
});
it('tooltip is placed at [1,2]', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps(props));
expect(tooltips[0].position).toEqual([1, 2]);
});
});
describe('one click + pointer move', () => {
let mode;
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps());
mode.handlePointerMove(createPointerMoveEvent([3, 4]), createFeatureCollectionProps());
});
it('guides are two points + line string', () => {
const guides = mode.getGuides(createFeatureCollectionProps());
expect(guides).toMatchSnapshot();
});
it('tooltip contains distance', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps());
expect(tooltips).toMatchSnapshot();
});
});
describe('one click + pointer move - centerTooltipsOnLine = true', () => {
let mode;
const props = { modeConfig: { centerTooltipsOnLine: true } };
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps(props));
mode.handlePointerMove(createPointerMoveEvent([1, 4]), createFeatureCollectionProps(props));
});
it('tooltips are on center of their respective line', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps(props));
expect(tooltips[0].position).toEqual([1, 3]);
});
});
describe('two clicks', () => {
let mode;
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps());
mode.handleClick(createClickEvent([3, 4]), createFeatureCollectionProps());
});
it('guides are two points + line string', () => {
const guides = mode.getGuides(createFeatureCollectionProps());
expect(guides).toMatchSnapshot();
});
it('tooltip contains distance', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps());
expect(tooltips).toMatchSnapshot();
});
it('can measure kilometers', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps());
expect(tooltips[0].text).toContain('kilometers');
});
it('can measure miles', () => {
const tooltips = mode.getTooltips(
createFeatureCollectionProps({ modeConfig: { turfOptions: { units: 'miles' } } })
);
expect(tooltips[tooltips.length - 1].text).toContain('miles');
});
it('can format distance', () => {
const tooltips = mode.getTooltips(
createFeatureCollectionProps({ modeConfig: { formatTooltip: String } })
);
expect(tooltips[tooltips.length - 1].text).toEqual('314.28368918020476');
});
});
describe('two clicks - centerTooltipsOnLine = true', () => {
let mode;
const props = { modeConfig: { centerTooltipsOnLine: true } };
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps(props));
mode.handleClick(createClickEvent([1, 4]), createFeatureCollectionProps(props));
});
it('tooltips are on center of their respective line', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps(props));
expect(tooltips[0].position).toEqual([1, 3]);
expect(tooltips[1].position).toEqual([1, 4]);
});
});
describe('two clicks + pointer move', () => {
let mode;
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps());
mode.handleClick(createClickEvent([3, 4]), createFeatureCollectionProps());
mode.handlePointerMove(createPointerMoveEvent([4, 5]), createFeatureCollectionProps());
});
it('ending point is clicked point not hovered point', () => {
const guides = mode.getGuides(createFeatureCollectionProps());
expect(guides.features[2].geometry.coordinates).toEqual([3, 4]);
});
it('tooltip contains distance', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps());
expect(tooltips).toMatchSnapshot();
});
});
describe('two clicks + pointer move - centerTooltipsOnLine = true', () => {
let mode;
const props = { modeConfig: { centerTooltipsOnLine: true } };
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps(props));
mode.handleClick(createClickEvent([1, 4]), createFeatureCollectionProps(props));
mode.handlePointerMove(createPointerMoveEvent([5, 4]), createFeatureCollectionProps(props));
});
it('tooltips are on center of their respective line', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps(props));
expect(tooltips[0].position).toEqual([1, 3]);
expectToBeCloseToArray(tooltips[1].position, [3, 4]);
});
});
describe('three clicks + pointer move', () => {
let mode;
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps());
mode.handleClick(createClickEvent([3, 4]), createFeatureCollectionProps());
mode.handleClick(createClickEvent([4, 5]), createFeatureCollectionProps());
mode.handlePointerMove(createPointerMoveEvent([6, 7]), createFeatureCollectionProps());
});
it('first feature is a tentative line that contains 4 points', () => {
const guides = mode.getGuides(createFeatureCollectionProps());
expect(guides.features[0].properties.guideType).toEqual('tentative');
expect(guides.features[0].geometry.type).toEqual('LineString');
expect(guides.features[0].geometry.coordinates.length).toEqual(4);
expect(guides.features[0].geometry.coordinates[3]).toEqual([6, 7]);
});
it('Second feature is a editHandle point with coordinates [1,2]', () => {
const guides = mode.getGuides(createFeatureCollectionProps());
expect(guides.features[1].properties.guideType).toEqual('editHandle');
expect(guides.features[1].geometry.type).toEqual('Point');
expect(guides.features[1].geometry.coordinates).toEqual([1, 2]);
});
it('tooltip contains distance', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps());
expect(tooltips).toMatchSnapshot();
});
});
describe('three clicks + pointer move - centerTooltipsOnLine = true', () => {
let mode;
const props = { modeConfig: { centerTooltipsOnLine: true } };
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps(props));
mode.handleClick(createClickEvent([1, 4]), createFeatureCollectionProps(props));
mode.handleClick(createClickEvent([5, 4]), createFeatureCollectionProps(props));
mode.handlePointerMove(createPointerMoveEvent([11, 8]), createFeatureCollectionProps(props));
});
it('tooltips are on center of their respective line', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps(props));
expect(tooltips[0].position).toEqual([1, 3]);
expectToBeCloseToArray(tooltips[1].position, [3, 4]);
expectToBeCloseToArray(tooltips[2].position, [8, 6]);
});
});
describe('three clicks + pointer move + press Escape', () => {
let mode;
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps());
mode.handleClick(createClickEvent([3, 4]), createFeatureCollectionProps());
mode.handleClick(createClickEvent([4, 5]), createFeatureCollectionProps());
mode.handlePointerMove(createPointerMoveEvent([6, 7]), createFeatureCollectionProps());
mode.handleKeyUp(createKeyboardEvent('Escape'), createFeatureCollectionProps());
});
it('first feature is a tentative line that contains 3 points', () => {
const guides = mode.getGuides(createFeatureCollectionProps());
expect(guides.features[0].properties.guideType).toEqual('tentative');
expect(guides.features[0].geometry.type).toEqual('LineString');
expect(guides.features[0].geometry.coordinates.length).toEqual(3);
expect(guides.features[0].geometry.coordinates[2]).toEqual([4, 5]);
});
it('tooltip contains distance', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps());
expect(tooltips).toMatchSnapshot();
});
});
describe('three clicks + pointer move + press Enter', () => {
let mode;
beforeEach(() => {
mode = new MeasureDistanceMode();
mode.handleClick(createClickEvent([1, 2]), createFeatureCollectionProps());
mode.handleClick(createClickEvent([3, 4]), createFeatureCollectionProps());
mode.handleClick(createClickEvent([4, 5]), createFeatureCollectionProps());
mode.handlePointerMove(createPointerMoveEvent([6, 7]), createFeatureCollectionProps());
mode.handleKeyUp(createKeyboardEvent('Enter'), createFeatureCollectionProps());
});
it('first feature is a tentative line that contains 3 points', () => {
const guides = mode.getGuides(createFeatureCollectionProps());
expect(guides.features[0].properties.guideType).toEqual('tentative');
expect(guides.features[0].geometry.type).toEqual('LineString');
expect(guides.features[0].geometry.coordinates.length).toEqual(4);
expect(guides.features[0].geometry.coordinates[3]).toEqual([6, 7]);
});
it('tooltip contains distance', () => {
const tooltips = mode.getTooltips(createFeatureCollectionProps());
expect(tooltips).toMatchSnapshot();
});
});
|
4481785219e4e5e8c927e67bb06a9c83387cbfbb
|
TypeScript
|
remorses/play-xml
|
/src/time.ts
| 3.46875
| 3
|
import { isUndefined } from "lodash"
export type TimeObject =
| number
| {
isBpm?: boolean
isFps?: boolean
seconds: number
timeString: string
toString: () => string
}
export function Beats(n: number, bpm: number = 120): TimeObject {
return {
isBpm: true,
timeString: `${Math.floor(60 * n * 1000)}/${bpm * 1000}s`,
seconds: (60 / bpm) * n,
toString() {
return `Beats(${n}, bpm=${bpm})`
},
}
}
export function Fps(n: number, fps: number = 25): TimeObject {
return {
isFps: true,
timeString: `${Math.floor(n * 1000)}/${fps * 1000}s`,
seconds: (1 / fps) * n,
toString() {
return `Fps(${n}, fps=${fps})`
},
}
}
export function formatDuration(
n: TimeObject,
denominator = DEFAULT_DENOMINATOR,
): string {
if (isUndefined(n)) {
return
}
if (typeof n === 'string') {
return n
}
if (typeof n === 'number') {
if (n % 1 === 0) {
return `${n}s`
}
return `${Math.floor(n * denominator)}/${denominator}s`
}
if (n.timeString) {
return n.timeString
}
throw new Error(`${n} is not a valid time object`)
}
const DEFAULT_DENOMINATOR = 30000
|
d8a5b7a73afe3a58d1fa633d9eb1ee4766ae3d2e
|
TypeScript
|
hudhudhud/lhkj
|
/new_admin/src/api/modules/OrderCreditGoodsDetailResponse.ts
| 2.65625
| 3
|
import Pager from "../base/Pager";
/**
* 作者没有写注释!!!
*/
export default class OrderCreditGoodsDetailResponse {
/**
* 积分类型id
*/
public creditTypeId!: number;
/**
* 积分类型名称
*/
public creditTypeName!: string;
/**
* 兑换比
*/
public exchangeRate!: number;
/**
* 积分过期时间
*/
public expiredTime!: string;
/**
* 商品积分价值
*/
public goodCreditValue!: number;
/**
* 商品id
*/
public goodId!: string;
/**
* 商品名称
*/
public goodName!: string;
/**
* 商品数量
*/
public goodNum!: number;
/**
* 订单号
*/
public orderCode!: string;
/**
* 总积分值
*/
public totalAmount!: number;
constructor(options?:any){
if(options&&options['creditTypeId']){
this.creditTypeId=options['creditTypeId'];
}
else{
this.creditTypeId=undefined
}
if(options&&options['creditTypeName']){
this.creditTypeName=options['creditTypeName'];
}
else{
this.creditTypeName=undefined
}
if(options&&options['exchangeRate']){
this.exchangeRate=options['exchangeRate'];
}
else{
this.exchangeRate=undefined
}
if(options&&options['expiredTime']){
this.expiredTime=options['expiredTime'];
}
else{
this.expiredTime=undefined
}
if(options&&options['goodCreditValue']){
this.goodCreditValue=options['goodCreditValue'];
}
else{
this.goodCreditValue=undefined
}
if(options&&options['goodId']){
this.goodId=options['goodId'];
}
else{
this.goodId=undefined
}
if(options&&options['goodName']){
this.goodName=options['goodName'];
}
else{
this.goodName=undefined
}
if(options&&options['goodNum']){
this.goodNum=options['goodNum'];
}
else{
this.goodNum=undefined
}
if(options&&options['orderCode']){
this.orderCode=options['orderCode'];
}
else{
this.orderCode=undefined
}
if(options&&options['totalAmount']){
this.totalAmount=options['totalAmount'];
}
else{
this.totalAmount=undefined
}
}
}
|
2f7ed917cb44b314d95ec42204926b02b5d9bb29
|
TypeScript
|
42LeetCoDong/Top-Interview-Questions_Easy
|
/09. Others/05. Valid Parentheses/Valid-Parentheses_hjeon.ts
| 3.421875
| 3
|
function isValid(s: string): boolean {
let stack: string[] = [];
for (let c of s) {
if (/\(|\[|\{/.test(c)) stack.push(c);
else {
let earlierOne: number = (stack.pop() || '').charCodeAt(0);
let cCode: number = c.charCodeAt(0);
if (c === ')') cCode -= 1;
else cCode -= 2;
if (earlierOne !== cCode) return (false);
}
}
if (stack.length) return (false);
else return (true);
};
console.log(isValid('({})'));
|
33c1a0c815f211834087526efd543eb75a6c06cf
|
TypeScript
|
inesscw/primera-app
|
/src/app/contador/contador.component.ts
| 2.625
| 3
|
import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-contador',
templateUrl: './contador.component.html',
styleUrls: ['./contador.component.scss']
})
export class ContadorComponent implements OnInit, OnChanges {
@Input() contador: number;
contadorBackup: number;
contadorRef;
constructor() {
}
/**
* Voy a detectar el cambio en el parametro de entrar contdor
* cuando eso pase quiero iniciar un contador sobre ese valor
* que decrezca el numero en 1 cada segundo
* @param changes
*/
ngOnChanges(changes: SimpleChanges): void {
if (changes.contador) {
this.contadorBackup = changes.contador.currentValue;
clearInterval(this.contadorRef);
this.comenzarContador();
}
}
ngOnInit(): void {
}
reiniciar(): void {
clearInterval(this.contadorRef);
this.contador = this.contadorBackup;
this.comenzarContador();
}
private comenzarContador() {
this.contadorRef = setInterval(() => {
this.contador--;
if (this.contador === 0) {
alert('El contador ha terminado');
clearInterval(this.contadorRef);
}
}, 1000);
}
}
|
06a10dbdb932ffb189810cd30455cfd868057774
|
TypeScript
|
recruit-tech/redux-pluto
|
/src/server/services/__tests__/utils.formatPathname.test.ts
| 2.671875
| 3
|
import assert from "assert";
import { formatPathname } from "../utils";
test("utils: formatPathname", () => {
const testCases = [
{ pathname: "", params: [], expected: "" },
{ pathname: "?", params: ["foo"], expected: "foo" },
{ pathname: "/", params: [], expected: "/" },
{ pathname: "/foo", params: [], expected: "/foo" },
{ pathname: "/foo/?", params: ["bar"], expected: "/foo/bar" },
{ pathname: "/foo/?/baz", params: ["bar"], expected: "/foo/bar/baz" },
{ pathname: "/foo/?", params: [null], expected: "/foo/null" },
{ pathname: "/foo/?", params: [123], expected: "/foo/123" },
{ pathname: "/foo/?", params: ["."], expected: "/foo/%2E" },
{ pathname: "/foo/?", params: [".."], expected: "/foo/%2E%2E" },
{ pathname: "/foo/?", params: ["..."], expected: "/foo/..." },
{
pathname: "/foo/?",
params: ["!@#$%^&*()_+=-`~¥\\][{}|';:\"/.,<>?"],
expected:
"/foo/!%40%23%24%25%5E%26*()_%2B%3D-%60~%C2%A5%5C%5D%5B%7B%7D%7C'%3B%3A%22%2F.%2C%3C%3E%3F",
},
{
pathname: "/foo/?/bar/?/baz/?/hoge/?/fuga/?/",
params: ["piyo?", null, 123, "..", {}],
expected:
"/foo/piyo%3F/bar/null/baz/123/hoge/%2E%2E/fuga/%5Bobject%20Object%5D/",
},
{ pathname: "/?", params: [], expected: "/!(MISSING)" },
{ pathname: "/", params: ["foo"], expected: "/" },
{ pathname: "/?", params: ["foo", 123, "..", "!@#$"], expected: "/foo" },
{
pathname: "/?/?/?/?",
params: ["foo"],
expected: "/foo/!(MISSING)/!(MISSING)/!(MISSING)",
},
{ pathname: "/?", params: [""], expected: "/!(EMPTY)" },
{ pathname: "/foo/?/bar", params: [""], expected: "/foo/!(EMPTY)/bar" },
{
pathname: "/foo/?/bar/?",
params: [[], []],
expected: "/foo/!(EMPTY)/bar/!(EMPTY)",
},
{
pathname: "/?/?/?/?",
params: ["", "foo", "bar", "baz"],
expected: "/!(EMPTY)/foo/bar/baz",
},
];
testCases.forEach(testCase => {
let actual = formatPathname(testCase.pathname, testCase.params);
assert.strictEqual(actual, testCase.expected);
});
});
|
2cc07eed849260424eccd263a9b3d6c259d7cd5a
|
TypeScript
|
freeman1995/react-beitzim
|
/src/react-beitzim/masonry-virtualization-hooks.ts
| 2.671875
| 3
|
import { ItemSizeGetter } from "react-beitzim/types";
import { useEffect, useState } from "react";
import { flatten, range, last } from "lodash/fp";
type MasonryItemOffset = {
itemId: string;
itemIndex: number;
offset: number;
columnIndex: number;
};
export function useItemOffsets<ItemType>(
items: ItemType[],
width: number,
itemWidth: number,
itemHeight: ItemSizeGetter<ItemType>,
getItemId: (item: ItemType) => string
) {
const columnCount = Math.floor(width / itemWidth);
const [itemOffsets, setItemOffsets] = useState<MasonryItemOffset[][]>(
range(0, columnCount).map(() => [])
);
const [itemsSnapshotSignature, setItemsSnapshotSignature] = useState(Math.random().toString(32));
useEffect(() => {
setItemsSnapshotSignature(Math.random().toString(32));
let nextItemOffsets: MasonryItemOffset[][] = range(0, columnCount).map(() => []);
let itemOffsetsDidChange = items.length !== flatten(itemOffsets).length;
items.forEach((item, itemIndex) => {
const currentColumnHeights = nextItemOffsets.map((columnItemOffsets) => {
const columnLastItemOffset = last(columnItemOffsets);
return columnLastItemOffset
? columnLastItemOffset.offset + itemHeight(items[columnLastItemOffset.itemIndex])
: 0;
});
const lowestColumnHeight = Math.min(...currentColumnHeights);
const currentColumnIndex = currentColumnHeights.indexOf(lowestColumnHeight);
const currentRowIndex = nextItemOffsets[currentColumnIndex].length;
const { itemIndex: columnPrevRowItemIndex, offset: columnPrevRowItemOffset } =
nextItemOffsets[currentColumnIndex][currentRowIndex - 1] || {};
const columnPrevRowItem = items[columnPrevRowItemIndex];
const itemId = getItemId(item);
nextItemOffsets[currentColumnIndex].push({
itemId,
itemIndex,
offset: columnPrevRowItem ? columnPrevRowItemOffset + itemHeight(columnPrevRowItem) : 0,
columnIndex: currentColumnIndex,
});
if (
nextItemOffsets[currentColumnIndex]?.[currentRowIndex] !==
itemOffsets[currentColumnIndex]?.[currentRowIndex]
) {
itemOffsetsDidChange = true;
}
});
if (itemOffsetsDidChange) {
setItemOffsets(nextItemOffsets);
}
}, [items, width, itemWidth]);
return {
itemOffsets,
itemsSnapshotSignature,
};
}
|
22ecc407b8fb462fe20f4bd8f65d6774f94938bd
|
TypeScript
|
guicostaarantes/cashbook-server
|
/src/modules/transactions/services/counterparts/UpdateCounterpartService.ts
| 2.671875
| 3
|
import 'reflect-metadata';
import { inject, injectable } from 'tsyringe';
import AppError from '../../../../shared/errors/AppError';
import ICounterpart from '../../entities/counterparts/ICounterpart';
import { ICounterpartsRepository } from '../../repositories/counterparts/ICounterpartsRepository';
interface IServiceRequest {
counterpartId: string;
name?: string;
}
@injectable()
class UpdateCounterpartService {
constructor(
@inject('CounterpartsRepository')
private counterpartsRepository: ICounterpartsRepository,
) {}
public async execute({
counterpartId,
...changingFields
}: IServiceRequest): Promise<ICounterpart> {
const counterpart = await this.counterpartsRepository.findById(
counterpartId,
[],
);
const validFields = Object.keys(changingFields).every(field =>
['name'].includes(field),
);
if (!validFields) {
throw new AppError('Bad request', 400);
}
const { name } = changingFields;
const findByName =
name && (await this.counterpartsRepository.findByName(name, ['id']));
if (findByName && findByName.id !== counterpartId) {
throw new AppError(
'There is another counterpart with the same name.',
400,
);
}
const newCounterpart = { ...counterpart, ...changingFields };
await this.counterpartsRepository.update(newCounterpart);
return newCounterpart;
}
}
export default UpdateCounterpartService;
|
d412e8eddb789d7fd50e765574551da4312dcbda
|
TypeScript
|
sketchthat/acx
|
/examples/private/trades.ts
| 2.890625
| 3
|
// Import Keys
import * as fs from 'fs';
const keys = JSON.parse(fs.readFileSync('./examples/keys.json', 'utf8'));
// Start Example
import { ACX } from '../../src';
const acx = new ACX(keys.accessKey, keys.secret);
/**
* Get Trades
*
* Market: BTCAUD
*/
acx.private().trades('btcaud')
.then(trades => {
console.log(trades);
});
/**
* Get Trades
*
* Market: BTCAUD
* Limit: 5
* Timestamp: An Hour Ago (Variable)
* From: 1 (Start Order Number)
* To: 8935296 (End Order Number)
* Order By: ASC
*/
const timeInSeconds = Math.floor(Date.now() / 1000);
const anHourInSeconds = 3600;
acx.private().trades('btcaud', 5, timeInSeconds - anHourInSeconds, 1, 8935296, 'asc')
.then(trades => {
console.log(trades);
});
|
7749f90108b36e8414b2c9ac3c91effa72d153a6
|
TypeScript
|
samyue/tote
|
/src/app/shared/pipes/tote-dividend.pipe.ts
| 2.53125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { Dividend } from '../../tote-bet/models/dividend.model';
import { ProductType } from '../../tote-bet/models/product-type.const';
import { CurrencyPipe } from '@angular/common';
@Pipe({
name: 'toteDividend',
})
export class ToteDividendPipe implements PipeTransform {
constructor(private currencyPipe: CurrencyPipe){}
readonly productMap = {
W: 'Win',
P: 'Place',
E: 'Exacta'
}
transform(value: Dividend): string {
if (!value) {
return '';
}
let productDisplayName: string = this.productMap[value.product];
let winningSelections: string;
if (value.product == ProductType.W || value.product == ProductType.P ) {
winningSelections = `${value.winningSelections[0]}`;
} else if (value.product == ProductType.E) {
winningSelections = `${value.winningSelections[0]},${value.winningSelections[1]}`;
}
let dividend: string = this.currencyPipe.transform(value.dividend, 'USD', true);
return `${productDisplayName}:${winningSelections}:${dividend}`;
}
}
|
d8efccb983ce9235faf93815e456eb1257d56d3c
|
TypeScript
|
reimagined/resolve-cloud-common
|
/s3/uploadS3Object.ts
| 2.53125
| 3
|
import S3, { Body as S3ObjectBody } from 'aws-sdk/clients/s3'
import { retry, Options, getLog, Log } from '../utils'
async function uploadS3Object(
params: {
Region: string
BucketName: string
FileKey: string
Body: S3ObjectBody
ContentType?: string
Metadata?: Record<string, string>
},
log: Log = getLog('UPLOAD-S3-OBJECT')
): Promise<void> {
const { Region, BucketName, FileKey, Body, ContentType, Metadata } = params
const s3 = new S3({ region: Region })
try {
log.debug(`Upload the S3 object "${FileKey}" to "${BucketName}"`)
const upload = retry(
s3,
s3.upload,
Options.Defaults.override({ log, maxAttempts: 1, silent: true })
)
await upload({
Bucket: BucketName,
Key: FileKey,
Body,
ContentType,
Metadata
})
} catch (error) {
log.debug(`Failed to upload the S3 object "${FileKey}" to "${BucketName}"`)
throw error
}
log.debug(`The S3 object "${FileKey}" has been uploaded to "${BucketName}"`)
}
export default uploadS3Object
|
1b4e66b412ee5da19488e2a99f391d03b49998f1
|
TypeScript
|
gabmarini/ng-cacheable
|
/src/decorators/cacheable.decorator.ts
| 2.546875
| 3
|
import {ICacheBusterMetadataInterface, ICachedMetadataInterface} from '../interfaces/Icacheable-metadata.interface';
import {CacheService} from '../services/cache.service';
import {cacheResultOperator, Defaults} from '../constants/defaults.constant';
import {isObservable, throwError} from 'rxjs';
import {catchError, tap} from 'rxjs/operators';
import {CacheInsertion} from '../interfaces/cache-insertion.interface';
export function Cached(metadata?: ICachedMetadataInterface): MethodDecorator {
const cacheService: CacheService = CacheService.getInstance();
function cacheResult(cacheInsertion: CacheInsertion) {
if (isObservable(cacheInsertion.result)) {
cacheInsertion.result = cacheInsertion.result.pipe(
catchError(err => throwError(err)),
cacheResultOperator(cacheInsertion),
);
} else {
if (!!cacheInsertion.result) {
cacheService.insertCacheResult(cacheInsertion);
}
}
return cacheInsertion.result;
}
return function (target: Function, method: string, descriptor: PropertyDescriptor) {
if (!metadata.cacheTTL) {
metadata.cacheTTL = Defaults.defaultTTL;
}
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const hasCacheHit = cacheService.canBeCacheHit(method, args);
let result;
if (hasCacheHit) {
result = cacheService.getCacheHit(method, args);
} else {
result = originalMethod.apply(this, args);
const cacheInsertion: CacheInsertion = {
args: args,
bustingKey: metadata.cacheBustingKey,
method: method,
result: result,
ttl: metadata.cacheTTL,
cacheKey: CacheService.buildHashedKey(method, args)
};
result = cacheResult(cacheInsertion);
}
return result;
};
return descriptor;
};
}
export function CacheBuster(metadata?: ICacheBusterMetadataInterface): MethodDecorator {
function bustCacheResult(key: string) {
CacheService.getInstance().deleteCacheHit(key);
}
return function (target: Function, key: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const result = originalMethod.apply(this, args);
bustCacheResult(metadata.cacheBusterFor);
return result;
};
return descriptor;
};
}
|
e80480f46b27c30681ebdad24737f65870f964ee
|
TypeScript
|
andreslt67/Barbermanager-web
|
/src/app/interfaces/resena.ts
| 2.578125
| 3
|
/**
* Interfaz para parsear json Resena
*/
export interface Resena {
idresena: number,
fecha: Date,
peluquero: string,
contenido: string,
valoracion: number
}
/**
* Interfaz para parsear json ResenaPelu
*/
export interface ResenaPelu {
idresena: number,
fecha: Date,
cliente: string,
contenido: string,
valoracion: number
}
|
bab3eb063462b19a125253a28f51dfcf8506edea
|
TypeScript
|
zz8023wanjin-moyuxin/hello-wrold
|
/src/policyContext/CashContext.ts
| 3.015625
| 3
|
import {CashSuper} from "@/Utils/cash/CashSuper";
import {CashRebates} from "@/Utils/cash/CashRebates";
import {CashReturn} from "@/Utils/cash/CashReturn";
import {CashNormal} from "@/Utils/cash/CashNormal";
export enum DiscountType {
FIVE_DISCOUNT = '打五折',
SEVEN_DISCOUNT = '打七折',
NINE_DISCOUNT = '打九折',
THREE_AGAINST_ONE = '满300返100',
SEVEN_AGAINST_THREE = '满700返300'
}
export class CashContext {
cs: CashSuper;
constructor(standard: string){
switch (standard) {
case DiscountType.FIVE_DISCOUNT:
this.cs = new CashRebates(0.5);
break;
case DiscountType.SEVEN_DISCOUNT:
this.cs = new CashRebates(0.7);
break;
case DiscountType.NINE_DISCOUNT:
this.cs = new CashRebates(0.9);
break;
case DiscountType.THREE_AGAINST_ONE:
this.cs = new CashReturn(300, 100);
break;
case DiscountType.SEVEN_AGAINST_THREE:
this.cs = new CashReturn(700, 300);
break;
default:
this.cs = new CashNormal();
break;
}
}
getResult(money: number){
return this.cs.acceptCash(money);
}
}
|
f3fd32f143ef4ba702124625a41d25dd59acddb8
|
TypeScript
|
blake256/avaxcast
|
/frontend/src/reducers/marketFilter.ts
| 3.171875
| 3
|
import { Market } from "common/enums";
/**
* Reducer for the {@link Market} filter
* @param state - Current state
* @param action - Action to be carried out
* @returns The chosen {@link Market} to filter by
*/
function marketFilterReducer(state = Market.ALL, action: Action): Market {
switch (action.type) {
case "AVAX":
return Market.AVAX;
case "BTC":
return Market.BTC;
case "ETH":
return Market.ETH;
case "LINK":
return Market.LINK;
case "ALL":
return Market.ALL;
default:
return state;
}
}
export default marketFilterReducer;
|
25eb83d7fde85dcb07cbed641607196fbb15746f
|
TypeScript
|
Quione/aula3
|
/app.ts
| 3.46875
| 3
|
class Hero{
constructor(public codenome:string, public identidadeSecreta:string){}
//metodo (função)
getIdentidade():void{
console.log(`A identidade secreta do(a) ${this.codenome} é ${this.identidadeSecreta}`);
}
}
interface Habilidade{
superPoder?:string;
pericia?:string;
poder:number;
}
class Batman extends Hero implements Habilidade{
superPoder?:string;
pericia?:string;
poder:number;
constructor(public arquiRival:string){
super(`Batman`,`Bruce Wayen`);
this.superPoder = "Não possui";
this.pericia = "artes marciais,armas,tecnologia,investigação";
this.poder = 50;
}
getArquiRival():string{
return `O(a) arque rival do ${this.codenome} é ${this.arquiRival}`;
}
getPericia(){
return `A(s) pericia(s) do(a) ${this.codenome} é(são) ${this.pericia}`;
}
}
let darkKinight = new Batman('Coringa');
darkKinight.getIdentidade();
console.log(darkKinight.getArquiRival());
console.log(darkKinight.getPericia());
|
03a375294e60aedea313f2dc5ff1d08569fcc383
|
TypeScript
|
cydran/cydran
|
/src/component/ElementOperationsImpl.ts
| 2.9375
| 3
|
import ElementOperations from "component/ElementOperations";
import { requireNotNull } from "util/Utils";
class ElementOperationsImpl<E extends HTMLElement> implements ElementOperations<E> {
private element: E;
constructor(element: E) {
this.element = requireNotNull(element, "element");
}
public get(): E {
return this.element;
}
public focus(): void {
setTimeout(() => {
this.element.focus();
}, 1);
}
public blur(): void {
setTimeout(() => {
this.element.blur();
}, 1);
}
}
export default ElementOperationsImpl;
|
eeab97bb1642ae269e35efc57181c42b743d6b7a
|
TypeScript
|
sojulover/Tetris-with-Angular2
|
/tetris_multi/src/app/tetris/game.ts
| 2.71875
| 3
|
export class Game
{
mode: number = 0; // game mode(SINGLE: 0, MULTI: 1)
level: number = 0; // game level(easy: 0, normal: 1, hard: 2)
map: any = null; // root element
flag: boolean = false; // game flag: true=live, false=die.
isReady: boolean = false; // game ready flag
nextBlock: any = null; // next block
currentBlock: any = null; // current block
blockIndex: number = 0; // block index
position: any = {col: 0, row: 0}; // current block position.
score: number = 0;
isCombo: boolean = false; // combo flag
combo: number = 0; // combo count
maxCombo: number = 0; // max combo
isGameEnded = true;
scoreInterval: any =
{
id: 0,
term: 2000
};
autoDownInterval: any =
{
id: 0,
term: 1000
};
hurdleInterval: any =
{
id: 0,
term: 15000
};
createBlock(): any
{
var block = BLOCK_FORMS[Math.floor(Math.random() * BLOCK_FORMS.length)];
var form = block.form;
var properties = {blockIndex: this.blockIndex++, color: block.color};
var result = [];
for(var idx in form)
{
result.push(form[idx].map(function(col)
{
if(col != 0)
return properties;
else
return null;
}));
}
if(this.currentBlock != null)
{
this.position.col = 4;
this.position.row = 0 - this.currentBlock.length;
}
return result;
}
isMovable(block: any, row: number, col: number): boolean
{
var startIdx = 0;
var rowIdx = row;
var colIdx = col;
// out of range - return false.
if(col < 0)
return false;
if((col + block[0].length) > this.map.colSize)
return false;
if((row + block.length) > this.map.rowSize)
return false;
if(row + block.length == 0)
{
this.position.row = row;
this.position.col = col;
return true;
}
// if there is a part of block over the map, change startIdx from 0 to that value.
if(row < 0)
startIdx = Math.abs(row);
for(var i = startIdx; i < block.length; i++)
{
for(var j = 0; j < block[0].length; j++)
{
if(block[i][j] != null && this.map.form[i + rowIdx][j + colIdx] != null)
return false;
}
}
this.position.row = row;
this.position.col = col;
return true;
}
buildBlock(): boolean
{
var startIdx = 0;
var position = this.position;
var block = this.currentBlock;
// build block
if(this.position.row < 0)
startIdx = Math.abs(this.position.row);
for(var i = startIdx; i < block.length; i++)
{
var mapRow = this.map.form[i + position.row];
for(var j = 0; j < block[0].length; j++)
{
if(block[i][j] != null)
{
mapRow[j + position.col] = block[i][j];
}
}
}
if(this.position.row < 0)
{
this.gameOver();
return false;
}
// Calculate combo and score.
this.currentBlock = this.nextBlock;
this.nextBlock = this.createBlock();
this.isCombo = false;
for(var i = 0; i < this.map.rowSize; i++)
{
var isBreak = true;
for(var j = 0; j < this.map.colSize; j++)
{
if(this.map.form[i][j] == null)
{
isBreak = false;
break;
}
}
if(isBreak == true)
{
this.isCombo = true;
this.score += 100;
var tempRowArray = [];
var tempRow = document.createElement('div');
tempRow.classList.add('row');
for(var idx = 0; idx < this.map.colSize; idx++)
{
tempRowArray.push(null);
var tempCol = document.createElement('div');
tempCol.classList.add('col');
tempRow.appendChild(tempCol);
}
this.map.form.splice(i, 1);
this.map.form.unshift(tempRowArray);
document.getElementById(this.map.target).removeChild(document.getElementById(this.map.target).children[i]);
document.getElementById(this.map.target).insertBefore(tempRow, document.getElementById(this.map.target).children[0]);
}
}
// If the combo larger than 1, add bonus score.
if(this.isCombo && ++this.combo > 1)
{
if(this.combo > this.maxCombo)
this.maxCombo = this.combo;
this.score += Math.round(this.combo * (100 * (1 + (this.combo / 10))));
document.getElementById('score').innerText = (this.score + '').replace(/(\d)(?=(?:\d{3})+(?!\d))/g,'$1,');
document.getElementById('combo').innerText = this.combo + '';
}
else if(!this.isCombo)
{
// Init combo
this.combo = 0;
}
}
downBlock(): void
{
if(!this.isMovable(this.currentBlock, this.position.row + 1, this.position.col))
{
this.buildBlock();
}
}
putBlock(): void
{
while(true)
{
if(!this.isMovable(this.currentBlock, this.position.row + 1, this.position.col))
{
this.buildBlock();
break;
}
}
}
swapBlock(): void
{
var tempBlock = this.currentBlock;
this.currentBlock = this.nextBlock;
this.nextBlock = tempBlock;
}
turnBlock(block: any): any
{
var turnedBlock = [];
for(var i = 0; i < block[0].length; i++)
{
var tempRow = [];
for(var j = block.length - 1; j > -1; j--)
{
tempRow.push(block[j][i]);
}
turnedBlock.push(tempRow);
}
return turnedBlock;
}
halfTurnBlock(block: any)
{
var turnedBlock = [];
for(var i = block[0].length - 1; i > - 1; i--)
{
var tempRow = [];
for(var j = 0; j < block.length; j++)
{
tempRow.push(block[j][i]);
}
turnedBlock.push(tempRow);
}
return turnedBlock;
}
gameOver(): void
{
this.flag = false;
}
printMap(): void
{
var text = '';
for(var rowIdx = 0; rowIdx < this.map.rowSize; rowIdx++)
{
var targetRow = this.map.form[rowIdx];
for(var colIdx = 0; colIdx < this.map.colSize; colIdx++)
{
var target = targetRow[colIdx] != null ? "*" : " ";
text += target;
}
text += "\r\n";
}
console.log(text);
}
}
var BLOCK_FORMS =
[
{
form:
[
[ 0, 1 ],
[ 1, 1 ],
[ 1, 0 ]
],
color: '#ff0000'
},
{
form:
[
[ 1, 1 ],
[ 0, 1 ],
[ 0, 1 ]
],
color: '#ff9436'
},
{
form:
[
[ 1, 1 ],
[ 1, 1 ]
],
color: '#ffe400'
},
{
form:
[
[ 1, 0 ],
[ 1, 1 ],
[ 0, 1 ]
],
color: '#32cd32'
},
{
form:
[
[ 1 ],
[ 1 ],
[ 1 ],
[ 1 ]
],
color: '#0000ff'
},
{
form:
[
[ 1, 1 ],
[ 1, 0 ],
[ 1, 0 ]
],
color: '#000080'
},
{
form:
[
[ 1, 0 ],
[ 1, 1 ],
[ 1, 0 ]
],
color: '#800080'
}
];
|
2d4033a47e7b70b823968950bcb8d2274c720aa4
|
TypeScript
|
borlaym/game-engine
|
/dist/GameCamera.d.ts
| 2.53125
| 3
|
import { Camera, Vector3 } from 'three';
export default class GameCamera {
readonly camera: Camera;
constructor(camera?: Camera);
/**
* Intersect the plane at 0 height to get the point the camera is currently pointing at
*/
readonly lookingAt: Vector3;
rotateLeft(): void;
rotateRight(): void;
update(dt: number): void;
readonly position: Vector3;
private rotate;
}
|
8477955d14c19059acbe52ed5fefe933bc29ed67
|
TypeScript
|
davisb10/serilogger
|
/test/helpers.ts
| 2.796875
| 3
|
import {Sink} from '../src/sink';
import {PipelineStage} from '../src/pipeline';
import {ConsoleProxy} from '../src/consoleSink';
import {LogEvent} from "../src/logEvent";
export class ConcreteSink implements Sink {
emit(events: LogEvent[]) {
}
flush(): Promise<any> {
return Promise.resolve();
}
}
export class ConcretePipelineStage implements PipelineStage {
emit(events: LogEvent[]) {
return events;
}
flush(): Promise<any> {
return Promise.resolve();
}
}
export class ConcreteConsoleProxy implements ConsoleProxy {
error(message?: any, ...properties: any[]) {
}
warn(message?: any, ...properties: any[]) {
}
info(message?: any, ...properties: any[]) {
}
debug(message?: any, ...properties: any[]) {
}
log(message?: any, ...properties: any[]) {
}
}
export class ConcreteStorage {
length: number = 0;
getItem(key: string): string {
return this[key] || null;
}
setItem(key: string, data: string) {
if (!this.getItem(key)) {
++this.length;
}
this[key] = data;
}
removeItem(key: string) {
this[key] = null;
delete this[key];
--this.length;
}
}
|
6dc92afc3e24aab6a2bcd653d88f43db6a87e5ed
|
TypeScript
|
objuan/petrorov
|
/app/deck/ClientApp/src/app/common/ping-timer.ts
| 3.078125
| 3
|
import { Injectable, EventEmitter, OnDestroy } from "@angular/core";
export class PingTimer implements OnDestroy {
//private pingRequest: Request;
private pingInterval: number = 10 ;
private pingHandle: any;
/*
* An event emitted when the service is pinging.
*/
public onPing: EventEmitter<any> = new EventEmitter;
/*
* An event emitted when the service has pinged an HTTP endpoint and received a response.
*/
public onPingResponse: EventEmitter<Response> = new EventEmitter;
/*
* Initializes a new instance of PingTimer
*/
constructor(private handle: any, pingInterval: number) {
this.interval( pingInterval);
}
/*
* Sets the interval (in seconds) at which the ping operation will occur when start() is called.
* @param seconds - The ping interval in seconds.
* @return The current interval value.
*/
interval(seconds?: number): number {
if (!isNaN(seconds) && seconds > 0) {
this.pingInterval = seconds;
} else if (!isNaN(seconds) && seconds <= 0) {
throw new Error('Interval value must be greater than zero.');
}
return this.pingInterval;
}
/*
* Immediately performs the ping operation. If a request has been set, an HTTP
* request will be made and the response will be emitted via the
* onPingResponse event.
*/
ping(): void {
this.onPing.emit(null);
//if (this.pingRequest) {
this.handle();
// //this.http.request(this.pingRequest).subscribe((response: Response) => {
// // this.onPingResponse.emit(response);
// //});
//}
}
delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
force(delayTime) {
(async () => {
// Do something before delay
console.log('before delay')
await this.delay(delayTime);
this.ping();
// Do something after
console.log('after delay')
})();
}
/*
* Starts pinging on an interval.
*/
start(): void {
this.stop();
this.pingHandle = setInterval(() => { this.ping(); }, this.pingInterval * 1000);
}
/*
* Stops pinging on an interval.
*/
stop(): void {
if (this.pingHandle) {
clearInterval(this.pingHandle);
this.pingHandle = null;
}
}
/*
* Performs any cleanup tasks when Angular destroys the instance.
*/
ngOnDestroy(): void { this.stop(); }
/*
* Returns whether or not the service will ping automatically at the specified interval.
* @return True if the service will ping at the specified interval; otherwise, false.
*/
isRunning(): boolean { return !!this.pingHandle; }
}
|
c9af64c71815bd3a64516661d957ac70120a778e
|
TypeScript
|
themikelester/SketchBase
|
/src/base/CameraTypes.ts
| 2.890625
| 3
|
//----------------------------------------------------------------------------------------------------------------------
// Notes: Basic camera types. Create and push them onto the camera stack via the CameraSystem.
//
// Author: Mike Lester
// Date C: 2020/12/07
//----------------------------------------------------------------------------------------------------------------------
import { vec3 } from "gl-matrix";
import { CameraNode, CameraState } from "./CameraSystem";
import { Clock } from "./Clock";
import { AxisY, saturate } from "./Math";
import { assertDefined } from "./Util";
/**
* The most basic camera. Look at a fixed position, from a fixed position.
*/
export class FixedCamera extends CameraNode {
constructor( pos: vec3, target: vec3, up: vec3 = AxisY ) {
super();
this.state.lookAtWithPos( pos, target, up );
}
initialize(): void {}
update(): void {}
}
/**
* Blend smoothly between the previous two cameras on the stack.
* Call beginFadeOut() to transition back to the older of the two cameras.
* Once fade out is complete, both this and the previous camera will be removed.
*/
export class BlendCamera extends CameraNode {
private fadeOut = false;
private inTicker = 0.0;
private outTicker = 0.0;
private target: CameraNode;
constructor( private clock: Clock, public fadeInDuration = 1000.0, public fadeOutDuration = 1000.0 ) {
super();
}
initialize(): void {
this.target = assertDefined( this.prev );
this.outTicker = 0.0;
this.inTicker = 0.0;
}
update(): void {
const child = assertDefined( this.prev );
const grandChild = assertDefined( child.prev );
if( !this.fadeOut ) { this.inTicker += this.clock.gameDt; }
else { this.outTicker += this.clock.gameDt; }
let inT = this.fadeInDuration > 0.0 ? saturate( this.inTicker / this.fadeInDuration ) : 1.0;
inT = -Math.cos( inT * Math.PI ) * 0.5 + 0.5;
this.state = CameraState.lerp( this.state, grandChild.state, child.state, inT, true );
let outT = this.fadeOutDuration > 0.0 ? saturate( this.outTicker / this.fadeOutDuration ) : 1.0;
outT = this.fadeOut ? ( -Math.cos( outT * Math.PI ) * 0.5 + 0.5 ) : 0.0;
this.state = CameraState.lerp( this.state, this.state, grandChild.state, outT, true );
if( outT >= 1.0 ) {
this.deactivate();
this.target.deactivate();
}
}
beginFadeOut(): void { this.fadeOut = true; }
skipFadeOut(): void { this.fadeOut = true; this.fadeOutDuration = 0; }
}
|
ad5ca40870a6a4dbf70422c7616437b9fe948956
|
TypeScript
|
akanosenritu/sk-frontend
|
/utils/assign/assign.ts
| 3.125
| 3
|
export const detectNumberOfPeopleDiscrepancies = (
required: {
male: number,
female: number,
unspecified: number
},
current: {
male: number,
female: number
}
) => {
// positive number means there is a vacancy for the slot
// negative number means the slot is overflowing.
const result: {[gender in Gender]: number} = {
male: 0,
female: 0,
unspecified: 0,
}
// calculate male
// whether male slots are filled
if (required.male > current.male) result.male = required.male - current.male
let maleOverFlow = Math.max(0, current.male - required.male)
// calculate female
// whether female slots are filled
if (required.female > current.female) result.female = required.female - current.female
let femaleOverFlow = Math.max(0, current.female - required.female)
// calculate unspecified
// whether unspecified slots are filled
if (required.unspecified >= maleOverFlow + femaleOverFlow) {
result.unspecified = required.unspecified - (maleOverFlow + femaleOverFlow)
return result
}
let remainingUnspecified = required.unspecified
while (remainingUnspecified > 0) {
if (maleOverFlow > 0) {
maleOverFlow -= 1
remainingUnspecified -= 1
} else {
break
}
}
while (remainingUnspecified > 0) {
if (femaleOverFlow > 0) {
femaleOverFlow -= 1
remainingUnspecified -= 1
} else {
break
}
}
if (maleOverFlow) result.male = -1 * maleOverFlow
if (femaleOverFlow) result.female = -1 * femaleOverFlow
result.unspecified =
(required.male + required.female + required.unspecified) -
(current.male + current.female) -
(result.male + result.female)
return result
}
|
2184f14d1e4a779cb3b5a3649ccd429d4f42a615
|
TypeScript
|
hugomatheus/udemy-nestjs-zero-to-hero
|
/src/tasks/entities/task.entity.ts
| 2.546875
| 3
|
import {
Column,
CreateDateColumn,
Entity,
PrimaryColumn,
UpdateDateColumn,
} from 'typeorm';
import { TaskStatus } from '../task-status.enum';
import { v4 as uuid } from 'uuid';
@Entity('tasks')
export class Task {
@PrimaryColumn()
id: string;
@Column()
title: string;
@Column()
description: string;
@Column()
status: TaskStatus;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
constructor() {
if (!this.id) {
this.id = uuid();
}
}
}
|
048f174b98a4fc1ef198cd874676ad8af7ca0d55
|
TypeScript
|
thomas4t/quacky-clean-fe
|
/lib/utils/localStorage.ts
| 2.890625
| 3
|
const globalWindow =
typeof window === "undefined" ? { localStorage: null } : window;
type JSONPrimitive = string | number | boolean | null;
type JSONValue = JSONPrimitive | JSONObject | JSONArray;
type JSONObject = { [member: string]: JSONValue };
interface JSONArray extends Array<JSONValue> {}
export const localStorageApi = {
getValue: (key: string): JSONValue | null => {
if (!globalWindow.localStorage) {
return null;
}
const stored = globalWindow.localStorage.getItem(key);
if (!stored) {
return null;
}
try {
return JSON.parse(stored);
} catch (e) {
console.error(e);
}
return null;
},
setValue: (key: string, value: JSONValue) => {
if (!globalWindow.localStorage) {
return;
}
let strValue = "";
try {
strValue = JSON.stringify(value);
} catch (e) {
console.error(e);
}
globalWindow.localStorage.setItem(key, strValue);
},
};
|
6f5a54539c2c00aeae0b819d082353aa8285f98c
|
TypeScript
|
WillIbbetson/rich-editor
|
/plugins/rich-editor/src/scripts/editor/index.ts
| 2.609375
| 3
|
/*
* @author Adam (charrondev) Charron <adam.c@vanillaforums.com>
* @copyright 2009-2018 Vanilla Forums Inc.
* @license https://opensource.org/licenses/GPL-2.0 GPL-2.0
*/
import Quill from "../quill/index";
import * as utility from "@dashboard/utility";
import { ensureHtmlElement } from "@dashboard/dom";
const options = {
theme: "vanilla",
};
function initializeEditor(bodybox, container) {
utility.log("Initializing Rich Editor");
const initialValue = bodybox.value;
const quill = new Quill(container, options);
bodybox.style.display = "none";
if (initialValue) {
utility.log("Setting existing content as contents of editor");
quill.setContents(JSON.parse(initialValue));
}
quill.on("text-change", () => {
bodybox.value = JSON.stringify(quill.getContents().ops);
});
bodybox.addEventListener("paste", event => {
event.stopPropagation();
event.preventDefault();
// Get pasted data via clipboard API
const clipboardData = event.clipboardData || window.clipboardData;
const pastedData = clipboardData.getData("Text");
const delta = JSON.parse(pastedData);
quill.setContents(delta);
});
}
/**
* Mount the editor into a DOM Node.
*
* @param {string|Element} containerSelector - The CSS selector or the HTML Element to render into.
*/
export function mountEditor(containerSelector) {
const container = ensureHtmlElement(containerSelector);
const bodybox = container.closest("form")!.querySelector(".BodyBox");
if (!bodybox) {
throw new Error("Could not find the BodyBox to mount editor to.");
}
const initialFormat = bodybox.getAttribute("format") || "Rich";
if (initialFormat === "Rich") {
initializeEditor(bodybox, container);
} else {
throw new Error(`Unsupported initial editor format ${initialFormat}`);
}
}
|
bf333ed31272f3588485f3058dd6cd4d9221f55f
|
TypeScript
|
Laotouy/ms
|
/packages/sponge/src/typings/org.spongepowered.api.event.server.query.QueryServerEvent.Basic.ts
| 2.875
| 3
|
declare namespace org {
namespace spongepowered {
namespace api {
namespace event {
namespace server {
namespace query {
namespace QueryServerEvent {
// @ts-ignore
interface Basic extends org.spongepowered.api.event.server.query.QueryServerEvent {
/**
* Gets the MOTD to respond with.
* <p>By default, this is the server's current MOTD</p>
*/
// @ts-ignore
getMotd(): string;
/**
* Sets the MOTD to respond with.
* <p>If setting the string causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
setMotd(motd: string): void;
/**
* Gets the GameType to respond with.
* <p>By default, this is <code>SMP</code>.
* If setting the string causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
getGameType(): string;
/**
* Sets the GameType to respond with.
* <p>If setting the string causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
setGameType(gameType: string): void;
/**
* Gets the map (world) to respond with.
* <p>By default, this is the current world on the server.</p>
*/
// @ts-ignore
getMap(): string;
/**
* Sets the map (world) to respond with.
* <p>If setting the string causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
setMap(map: string): void;
/**
* Gets the player count to respond with.
* <p>By default, this is the number of players present on the server.
* If setting the string causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
getPlayerCount(): number;
/**
* Sets the player count to respond with.
* <p>If setting the int causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
setPlayerCount(playerCount: number): void;
/**
* Gets the max player count to respond with.
* <p>By default, this is the maximum number of players allowed on the
* server.</p>
*/
// @ts-ignore
getMaxPlayerCount(): number;
/**
* Sets the max player count to respond with.
* <p>If setting the int causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
setMaxPlayerCount(maxPlayerCount: number): void;
/**
* Gets the address to respond with.
* <p>By default, this is the address the server is listening on.</p>
*/
// @ts-ignore
getAddress(): any;
/**
* Sets the address to respond with.
*/
// @ts-ignore
setAddress(address: any): void;
/**
* Gets the current size of the data to respond with.
* <p>This value is implementation-defined - it is only meaningful when
* compared with {@link #getMaxSize()}.</p>
*/
// @ts-ignore
getSize(): number;
/**
* Gets the maximum size of the data to respond with.
* <p>If the size of the data is greater than the returned value,
* it will be automatically truncated.
* This value is implementation-defined - it is only meaningful when
* compared with {@link #getSize()} ()}.</p>
*/
// @ts-ignore
getMaxSize(): number;
}
}
}
}
}
}
}
}
|
bb21b5c1e61ea1e4430f9084b3813615fcc97caf
|
TypeScript
|
Shubhamg2595/TypeScript
|
/TypeScript Notes/1. Basics/5.Delayed Initialization.ts
| 3.53125
| 4
|
//! delayed initialization : declaring a variable and then initializing it later
// // issue
// let words = ['red','green']
// let foundWord; //type: any
// for(let i=0;i<words.length;i++){
// if(words[i] === 'greem'){
// foundWord = true;
// }
// }
// solution
let words = ['red','green']
let foundWord: boolean; //type: any
for(let i=0;i<words.length;i++){
if(words[i] === 'greem'){
foundWord = true;
}
}
|
b990df15f5e219508c707ed6641407493d45c7c1
|
TypeScript
|
deepslam/feature-framework
|
/src/Models/Translations.ts
| 2.90625
| 3
|
import { Locale } from 'locale-enum';
import { IApp } from '../Interfaces';
import { TranslationItemType } from '../Types';
export type LocaleKey = keyof typeof Locale;
export default class Translations<T = TranslationItemType> {
private app?: IApp<any>;
constructor(
private readonly translations: { [key in keyof typeof Locale]?: T } = {},
) {}
static template(str: string, data: Record<string, string>): string {
let s = str;
for (const prop in data) {
s = s.replace(new RegExp('{' + prop + '}', 'g'), data[prop]);
}
return s;
}
setApp(app: IApp<any>) {
this.app = app;
}
toArray(): T[] {
if (!this.app) {
return [];
}
if (this.translations[this.app.locale as LocaleKey]) {
return Object.values(this.translations[this.app.locale as LocaleKey]!);
}
if (this.translations[this.app.fallbackLocale as LocaleKey]) {
return Object.values(
this.translations[this.app.fallbackLocale as LocaleKey]!,
);
}
return [];
}
get t(): T | null {
if (!this.app) {
return null;
}
if (this.translations[this.app.locale as LocaleKey]) {
return this.translations[this.app.locale as LocaleKey]!;
}
if (this.translations[this.app.fallbackLocale as LocaleKey]) {
return this.translations[this.app.fallbackLocale as LocaleKey]!;
}
return null;
}
}
|
99a44e6dff7c0f39948775faddfe12bd1b9cba83
|
TypeScript
|
springtype-org/st-validate
|
/src/validate/not-null.ts
| 2.515625
| 3
|
import {getParameterValidateDecorator} from "../function/get-parameter-validate-decorator";
import {validatorNameFactory} from "../function/validator-name-factory";
export const NOT_NULL = 'not-null';
// decorator @NotNull
export const NotNull = () => getParameterValidateDecorator(not_null, NOT_NULL);
export const not_null = validatorNameFactory((value: any): boolean => null !== value, NOT_NULL);
|
8240c3a93aa2f74f3916dd0faba6735ab0664c19
|
TypeScript
|
dviramontes/reddit-newsletter
|
/src/reddit.ts
| 2.5625
| 3
|
import axios from "axios";
import { ok, err } from "neverthrow";
import { Child, ChildData } from "./types";
export const fetchPosts = async (subreddit: String) => {
try {
const {
data: {
data: { children },
},
} = await axios.get(
`https://www.reddit.com/r/${subreddit}/top.json?limit=3`
);
const results = children
.map(({ data }: Child) => data)
.map(
({
ups,
title,
permalink,
thumbnail,
preview,
subreddit,
}: ChildData) => ({
ups,
title,
permalink,
thumbnail,
preview,
subreddit,
})
);
return ok(results);
} catch (error) {
return err(error);
}
};
|
1b3a8666f90acd5eaa3595476b1e7bbdde90fb84
|
TypeScript
|
HiP-App/HiP-CmsAngularApp
|
/app/feature-toggle/features/shared/feature.service.ts
| 2.65625
| 3
|
import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Feature } from './feature.model';
import { FeatureToggleApiService } from '../../../shared/api/featuretoggle-api.service';
/**
* Service which does feature toggle related api calls
*/
@Injectable()
export class FeatureService {
constructor(private featureToggleApiService: FeatureToggleApiService) {}
/**
* Get all features.
*
* @return an array containing all features
*/
public getAllFeatures() {
return this.featureToggleApiService.getUrl('/Api/Features', {})
.toPromise()
.then(
(response: Response) => Feature.extractData(response)
).catch(
(error: any) => FeatureService.handleError(error)
);
}
/**
* Get the enabled features enabled for the current user.
*
* @return the enabled feature toggles
*/
public getEnabledFeaturesForCurrentUser() {
return this.featureToggleApiService.getUrl('/Api/Features/IsEnabled', {})
.toPromise()
.then(
(response: Response) => Feature.extractData(response)
).catch(
(error: any) => FeatureService.handleError(error)
);
}
/**
* Returns whether the feature is enabled for the current user.
*
* @param featureId the feature id
* @return true if and only if the feature is enabled for the current user
*/
public isFeatureEnabledForCurrentUser(featureId: number): Promise<boolean> {
return this.featureToggleApiService.getUrl('/Api/Features/{featureId}/IsEnabled', {})
.toPromise()
.then(
(response: Response) => response.status === 200
).catch(
(response: any) => (response.status === 401 || response.status === 403) ? false : FeatureService.handleError<boolean>(response)
);
}
/**
* Creates a new feature.
*
* @param feature the feature to save
*/
public createFeature(feature: Feature) {
return this.featureToggleApiService.postUrl('/Api/Features', JSON.stringify(feature), {})
.toPromise()
.then(
(response: Response) => {
return response.status === 200;
}
).catch(
(error: any) => FeatureService.handleError(error)
);
}
/**
* Delete feature by id.
*
* @param id the feature to delete.
*/
public deleteFeature(id: number) {
return this.featureToggleApiService.deleteUrl('/Api/Features/' + id, {})
.toPromise()
.then(
(response: any) => {
return response.status === 204;
}
).catch(
(error: any) => FeatureService.handleError(error)
);
}
/**
* Enables the feature for the given group.
*
* @param featureId the id of the feature to enable.
* @param groupId the id of the group to enable for the feature for.
* @returns {Promise<void>}
*/
public enableFeatureForGroup(featureId: number, groupId: number) {
return this.featureToggleApiService.putUrl('/Api/Features/' + featureId + '/Group/' + groupId, '', {})
.toPromise()
.catch(
(error: any) => FeatureService.handleError(error)
);
}
/**
* Disables the feature for the given group.
*
* @param featureId the id of the feature to disable.
* @param groupId the id of the group to disable for the feature for.
* @returns {Promise<void>}
*/
public disableFeatureForGroup(featureId: number, groupId: number) {
return this.featureToggleApiService.deleteUrl('/Api/Features/' + featureId + '/Group/' + groupId, {})
.toPromise()
.catch(
(error: any) => FeatureService.handleError(error)
);
}
private static handleError<T>(error: any) {
let errMsg = error.message || error.status ? `${error.status} - ${error.statusText}` : 'Server error';
return Promise.reject<T>(errMsg);
}
}
|
c9b9a5578169c1affd8bdb4ed8463a252950017e
|
TypeScript
|
rg-ubbcluj-ro/lab9x-AnaSavu
|
/bikes-web/src/main/webapp/src/app/employees/shared/employee.model.ts
| 2.515625
| 3
|
export interface Employee {
id: number;
name: string;
position: string;
workedHours: number;
}
|
200d39268906d543425277227932645e07c11d8a
|
TypeScript
|
import-keshav/oppia
|
/core/templates/dev/head/expressions/ExpressionSyntaxTreeService.ts
| 2.5625
| 3
|
// Copyright 2014 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Expression syntax tree service.
*/
require('expressions/ExpressionParserService.js');
angular.module('oppia').factory('ExpressionSyntaxTreeService', [
'ExpressionParserService', 'PARAMETER_TYPES',
function(ExpressionParserService, PARAMETER_TYPES) {
// Exceptions that can be thrown from the evaluation of expressions.
const ExpressionError = function() {};
ExpressionError.prototype = new Error();
ExpressionError.prototype.constructor = ExpressionError;
var ExprUndefinedVarError = function(varname, envs) {
this.varname = varname;
this.envs = envs;
};
ExprUndefinedVarError.prototype = new ExpressionError();
ExprUndefinedVarError.prototype.constructor = ExprUndefinedVarError;
ExprUndefinedVarError.prototype.name = 'ExprUndefinedVarError';
ExprUndefinedVarError.prototype.toString = function() {
return this.name + ': ' + this.varname + ' not found in ' + this.envs;
};
var ExprWrongNumArgsError = function(args, expectedMin, expectedMax) {
this.args = args;
this.expectedMin = expectedMin;
this.expectedMax = expectedMax;
};
ExprWrongNumArgsError.prototype = new ExpressionError();
ExprWrongNumArgsError.prototype.constructor = ExprWrongNumArgsError;
ExprWrongNumArgsError.prototype.name = 'ExprWrongNumArgsError';
ExprWrongNumArgsError.prototype.toString = function() {
return this.name + ': {' + this.args + '} not in range [' +
this.expectedMin + ',' + this.expectedMax + ']';
};
var ExprWrongArgTypeError = function(arg, actualType, expectedType) {
this.arg = arg;
this.actualType = actualType;
this.expectedType = expectedType;
};
ExprWrongArgTypeError.prototype = new ExpressionError();
ExprWrongArgTypeError.prototype.constructor = ExprWrongArgTypeError;
ExprWrongArgTypeError.prototype.name = 'ExprWrongArgTypeError';
ExprWrongArgTypeError.prototype.toString = function() {
if (this.arg === null) {
return this.name + ': Type ' + this.actualType +
' does not match expected type ' + this.expectedType;
}
return this.name + ': ' + this.arg + ' has type ' + this.actualType +
' which does not match expected type ' + this.expectedType;
};
var getParamsUsedInExpression = function(expression) {
var _findParams = function(parseTree) {
var paramsFound = [];
if (parseTree instanceof Array) {
if (parseTree[0] === '#') {
paramsFound.push(parseTree[1]);
} else {
for (var i = 1; i < parseTree.length; i++) {
paramsFound = paramsFound.concat(_findParams(parseTree[i]));
}
}
}
var uniqueParams = [];
for (var i = 0; i < paramsFound.length; i++) {
if (uniqueParams.indexOf(paramsFound[i]) === -1) {
uniqueParams.push(paramsFound[i]);
}
}
return uniqueParams.sort();
};
var parsed = ExpressionParserService.parse(expression);
return _findParams(parsed);
};
// Checks if the args array has the expectedNum number of elements and
// throws an error if not. If optional expectedMax is specified, it
// verifies the number of args is in [expectedNum, expectedMax] range
// inclusive.
var verifyNumArgs = function(args, expectedNum, expectedMax = expectedNum) {
if (expectedMax === undefined) {
expectedMax = expectedNum;
}
if (args.length >= expectedNum && args.length <= expectedMax) {
return;
}
throw new ExprWrongNumArgsError(args, expectedNum, expectedMax);
};
var _verifyArgTypesMatchExpectedType = function(argTypes, expectedType) {
for (var i = 0; i < argTypes.length; i++) {
if (argTypes[i] !== expectedType) {
throw new ExprWrongArgTypeError(null, argTypes[i], expectedType);
}
}
return true;
};
var _verifyArgTypesMatch = function(argType1, argType2) {
if (argType1 !== argType2) {
throw new ExprWrongArgTypeError(null, argType1, argType2);
}
return true;
};
var applyFunctionToParseTree = function(parsed, envs, func) {
return func(parsed, envs.concat(system));
};
/**
* Looks up a variable of the given name in the env. Here the variable
* can be system or user defined functions and parameters, as well as
* system operators.
* @param {string} name The name to look up.
* @param {!Array.<!object>} envs Represents a nested name space
* environment to look up the name in. The first element is looked up
* first (i.e. has higher precedence).
* @throws {ExprUndefinedVarError} The named variable was not found in
* the given environment.
*/
const lookupEnvs = (name: string, envs: object[]) => {
for (const env of envs) {
if (env.hasOwnProperty(name)) {
return env[name];
}
}
throw new ExprUndefinedVarError(name, envs);
};
// Coerces the argument to a Number, and throws an error if the result
// is NaN.
var _coerceToNumber = function(originalValue) {
var coercedValue = (+originalValue);
if (!isNaN(coercedValue)) {
return coercedValue;
}
throw new ExprWrongArgTypeError(
originalValue, typeof originalValue, 'Number');
};
// Coerces all values in the given argument array to Number, and throws
// an error if the result is NaN.
var _coerceAllArgsToNumber = function(args) {
for (var i = 0; i < args.length; i++) {
args[i] = _coerceToNumber(args[i]);
}
return args;
};
// NOTE TO DEVELOPERS: When adding a new reserved word to this object,
// please first ensure that existing explorations do not use this
// parameter name. Also, to prevent future explorations using it,
// modify constants.INVALID_PARAMETER_NAMES accordingly.
// TODO(kashida): Document all operators input and output contracts.
// Arguments:
// args: for eval(): list of values of the evaluated sub-expression
// for getType(): list of types of the evaluated sub-expression
var system = {
'+': {
eval: function(args) {
verifyNumArgs(args, 1, 2);
var numericArgs = _coerceAllArgsToNumber(args);
return numericArgs.length === 1 ? numericArgs[0] :
numericArgs[0] + numericArgs[1];
},
getType: function(args) {
verifyNumArgs(args, 1, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.REAL;
}
},
'-': {
eval: function(args) {
verifyNumArgs(args, 1, 2);
var numericArgs = _coerceAllArgsToNumber(args);
return numericArgs.length === 1 ? -numericArgs[0] :
numericArgs[0] - numericArgs[1];
},
getType: function(args) {
verifyNumArgs(args, 1, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.REAL;
}
},
'*': {
eval: function(args) {
verifyNumArgs(args, 2);
var numericArgs = _coerceAllArgsToNumber(args);
return numericArgs[0] * numericArgs[1];
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.REAL;
}
},
'/': {
eval: function(args) {
verifyNumArgs(args, 2);
var numericArgs = _coerceAllArgsToNumber(args);
return numericArgs[0] / numericArgs[1];
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.REAL;
}
},
'%': {
eval: function(args) {
verifyNumArgs(args, 2);
var numericArgs = _coerceAllArgsToNumber(args);
return numericArgs[0] % numericArgs[1];
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.REAL;
}
},
'<=': {
eval: function(args) {
verifyNumArgs(args, 2);
var numericArgs = _coerceAllArgsToNumber(args);
return numericArgs[0] <= numericArgs[1];
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.UNICODE_STRING;
}
},
'>=': {
eval: function(args) {
verifyNumArgs(args, 2);
var numericArgs = _coerceAllArgsToNumber(args);
return numericArgs[0] >= numericArgs[1];
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.UNICODE_STRING;
}
},
'<': {
eval: function(args) {
verifyNumArgs(args, 2);
var numericArgs = _coerceAllArgsToNumber(args);
return numericArgs[0] < numericArgs[1];
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.UNICODE_STRING;
}
},
'>': {
eval: function(args) {
verifyNumArgs(args, 2);
var numericArgs = _coerceAllArgsToNumber(args);
return numericArgs[0] > numericArgs[1];
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.UNICODE_STRING;
}
},
'!': {
eval: function(args) {
verifyNumArgs(args, 1);
return !args[0];
},
getType: function(args) {
verifyNumArgs(args, 1);
_verifyArgTypesMatchExpectedType(
args, PARAMETER_TYPES.UNICODE_STRING);
return PARAMETER_TYPES.UNICODE_STRING;
}
},
'==': {
eval: function(args) {
verifyNumArgs(args, 2);
return args[0] === args[1];
},
getType: function(args) {
verifyNumArgs(args, 2);
return PARAMETER_TYPES.UNICODE_STRING;
}
},
'!=': {
eval: function(args) {
verifyNumArgs(args, 2);
return args[0] !== args[1];
},
getType: function(args) {
verifyNumArgs(args, 2);
return PARAMETER_TYPES.UNICODE_STRING;
}
},
'&&': {
eval: function(args) {
// TODO(kashida): Make this short-circuit.
verifyNumArgs(args, 2);
return Boolean(args[0] && args[1]);
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(
args, PARAMETER_TYPES.UNICODE_STRING);
return PARAMETER_TYPES.UNICODE_STRING;
}
},
'||': {
eval: function(args) {
// TODO(kashida): Make this short-circuit.
verifyNumArgs(args, 2);
return Boolean(args[0] || args[1]);
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(
args, PARAMETER_TYPES.UNICODE_STRING);
return PARAMETER_TYPES.UNICODE_STRING;
}
},
// Note that removing quotation marks from this key causes issues with
// minification (when running the deployment scripts).
/* eslint-disable quote-props */
'if': {
eval: function(args) {
// TODO(kashida): Make this short-circuit.
verifyNumArgs(args, 3);
return args[0] ? args[1] : args[2];
},
getType: function(args) {
verifyNumArgs(args, 3);
_verifyArgTypesMatchExpectedType(
[args[0]], PARAMETER_TYPES.UNICODE_STRING);
_verifyArgTypesMatch(args[1], args[2]);
return args[1];
}
},
'floor': {
eval: function(args) {
verifyNumArgs(args, 1);
var numericArgs = _coerceAllArgsToNumber(args);
return Math.floor(numericArgs[0]);
},
getType: function(args) {
verifyNumArgs(args, 1);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.REAL;
}
},
'pow': {
eval: function(args) {
verifyNumArgs(args, 2);
var numericArgs = _coerceAllArgsToNumber(args);
return Math.pow(args[0], args[1]);
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.REAL;
}
},
'log': {
eval: function(args) {
verifyNumArgs(args, 2);
var numericArgs = _coerceAllArgsToNumber(args);
var preciseAns = Math.log(numericArgs[0]) / Math.log(numericArgs[1]);
// We round answers to 9 decimal places, so that we don't run into
// issues like log(9, 3) = 2.0000000000004.
return Math.round(preciseAns * Math.pow(10, 9)) / Math.pow(10, 9);
},
getType: function(args) {
verifyNumArgs(args, 2);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.REAL;
}
},
'abs': {
eval: function(args) {
verifyNumArgs(args, 1);
var numericArgs = _coerceAllArgsToNumber(args);
return Math.abs(numericArgs[0]);
},
getType: function(args) {
verifyNumArgs(args, 1);
_verifyArgTypesMatchExpectedType(args, PARAMETER_TYPES.REAL);
return PARAMETER_TYPES.REAL;
}
}
/* eslint-enable quote-props */
};
return {
ExpressionError: ExpressionError,
ExprUndefinedVarError: ExprUndefinedVarError,
ExprWrongNumArgsError: ExprWrongNumArgsError,
ExprWrongArgTypeError: ExprWrongArgTypeError,
applyFunctionToParseTree: applyFunctionToParseTree,
getParamsUsedInExpression: getParamsUsedInExpression,
lookupEnvs: lookupEnvs
};
}
]);
|
078dfedd24ca4360e97dc29ed51001c2b320e4b9
|
TypeScript
|
vl0w/TargetShootingDatabase
|
/routes/gateways.ts
| 2.734375
| 3
|
/**
* Created by jonashansen on 29/04/15.
*/
/// <reference path="../typings/express.d.ts" />
import express = require("express");
import keys = require("./keys");
export var ERR_NO_API_KEY = "ERR: NO_APY_KEY";
export var ERR_INVALID_API_KEY = "ERR: INVALID_API_KEY";
interface Gateway {
handleRequest(req:express.Request, res:express.Response, next:Function);
}
export class GetGateway implements Gateway {
handleRequest(req:express.Request, res:express.Response, next:Function) {
console.log("GET request from " + req.host + " passed the gates");
next();
}
}
export class PutGateway implements Gateway {
private keyChecker:keys.KeyChecker;
constructor(keyChecker:keys.KeyChecker) {
this.keyChecker = keyChecker;
}
handleRequest(req:express.Request, res:express.Response, next:Function):any {
if (!req.body.api_key) {
res.status(400);
res.send(ERR_NO_API_KEY);
} else {
var apiKey = req.body.api_key;
if (!this.keyChecker.check(apiKey)) {
res.status(401);
res.send(ERR_INVALID_API_KEY);
} else {
next();
console.log("PUT request from " + req.host + " passed the gates");
}
}
}
}
export function handleGetRequest(req:express.Request, res:express.Response, next:Function):any {
if (req.method === "GET") {
var gateway = new GetGateway();
gateway.handleRequest(req, res, next);
} else {
next();
}
}
export function handlePutRequest(req:express.Request, res:express.Response, next:Function):any {
if (req.method === "PUT") {
var keyChecker = new keys.DefaultKeyChecker();
var gateway = new PutGateway(keyChecker);
gateway.handleRequest(req, res, next);
} else {
next();
}
}
|
316d8aad8f47d299e815c5a63122d47f853737a5
|
TypeScript
|
tsedbrpp/apiexpress
|
/react-typescript-app/src/Rule.ts
| 2.65625
| 3
|
import LogicSet from "./LogicSet";
import OvPair from "./OvPair";
import Outputer from "./Outputer";
import Statement from "./Statement";
import Logic from "./Logic";
import { StatementForm } from "./Statement";
import Nodes from "./Nodes";
export default class Rule {
myName: string;
ParsedOk: boolean;
Reference: string;
MyLogic: Array<LogicSet>;
Cons: Array<OvPair>;
Elses: Array<OvPair>;
Output: Outputer;
public FindLogicSet(tag: string): LogicSet | undefined {
if (!Logic.CreateNewLogic) {
let filtered = this.MyLogic.filter(
(logicSet) => logicSet.Equals(tag) && !logicSet.Seal
);
if (filtered.length == 1) {
filtered[0].Seal = true;
return filtered[0];
} else {
Logic.CreateNewLogic = false;
let aSet = new LogicSet(tag);
this.MyLogic.push(aSet);
return aSet;
}
}
}
public constructor(
aName: string,
aReference: string,
premises: Array<StatementForm>,
conclusions: Array<StatementForm>
) {
this.ParsedOk = true;
this.myName = aName;
this.Reference = aReference;
this.Cons = [];
this.MyLogic = [];
this.Elses = [];
this.Output = new Outputer();
if (!this.MakePremises(aName, premises)) this.ParsedOk = false;
if (!this.MakeConclusions(conclusions)) this.ParsedOk = false;
}
public MakePremises(aName: string, premises: Array<StatementForm>): boolean {
let logicSet: LogicSet | undefined;
Logic.ContainsPrior = false;
premises.forEach((aPremise) => {
let currentStatement = new Statement(aPremise);
if (Logic.ContainsPrior) {
let prior = Logic.GetPriorStatement(currentStatement);
Logic.setPrior(currentStatement);
// @ts-ignore
let aPair = prior.aPair;
if (aPair == undefined || null) {
throw new Error("null in makePremises");
}
// @ts-ignore
switch (prior.tag[<any>"logic"]) {
case "O":
// @ts-ignore
logicSet = this.FindLogicSet("O");
if (logicSet == null) {
throw new Error("Rules error or");
}
logicSet.Add(aPair);
break;
case "N":
// @ts-ignore
logicSet = this.FindLogicSet("N");
if (logicSet == null) {
throw new Error("Rules error not");
}
logicSet.Add(aPair);
break;
case "A":
// @ts-ignore
logicSet = this.FindLogicSet("A");
if (logicSet == null) {
throw new Error("Rules error and");
}
logicSet.Add(aPair);
break;
default:
throw new Error("Rules Default switch");
}
} else {
Logic.setPrior(currentStatement);
}
});
let lastStatement = Logic.getPrior();
let aLastPair = lastStatement.aPair;
if (aLastPair.isNull()) {
throw new Error("Rules Default switch");
}
switch (lastStatement.tag[<any> "logic"]) {
case "O":
logicSet = this.FindLogicSet("O");
// System.out.println("adding or last" + aPair.printString());
// @ts-ignore
logicSet.Add(aLastPair);
break;
case "N":
logicSet = this.FindLogicSet("N");
// System.out.println("adding not last" + aPair.printString());
// @ts-ignore
logicSet.Add(aLastPair);
break;
case "A":
logicSet = this.FindLogicSet("A");
// @ts-ignore
logicSet.Add(aLastPair);
// System.out.println("adding and last" + aPair.printString());
break;
default:
throw new Error("Rules bad tag in make premise" + lastStatement.tag);
} // end for
return true;
}
private MakeConclusions(conclusions: Array<StatementForm>): boolean {
conclusions.forEach((conclusion) => {
let aStatement = new Statement(conclusion);
let aPair = aStatement.aPair;
if (aPair.isNull()) {
throw new Error("rules make conclusion a pair= null");
}
switch (aStatement.tag[<any>"logic"]) {
case "E":
this.Elses.push(aPair);
break;
case "A":
this.Cons.push(aPair);
break;
default:
throw new Error("Rules bad tag in make conclusion " + aStatement.tag);
}
});
return true;
}
public Equals(aName: string): boolean {
return this.myName == aName;
}
public GetRuleConclusions(aName: string): Array<OvPair> {
let filtered = this.Cons.filter((ovPair) => {
ovPair.objectEquals(aName);
});
return filtered;
}
public Concludes(aName: string): boolean {
return this.Cons.some((ovPair) => ovPair.objectEquals(aName));
}
public printPairs(whatString: string, pairs: Array<OvPair>) {
let first = true;
let accum = "";
let filterPairs = pairs.filter((ovPair) => ovPair);
filterPairs.forEach((aPair) => {
if (!first || !(whatString == "And"))
accum += whatString + " " + aPair.toString();
else {
first = false;
accum += aPair.toString();
}
});
Outputer.Update(accum);
}
public Print(): string {
Outputer.Reset();
this.PrintPremises();
this.PrintConclusion();
Outputer.Update("<REFERENCE>\n" + this.Reference + "\n");
Outputer.Update("<END>\n");
return Outputer.Result;
}
public PrintPremisesString(): string {
Outputer.Reset();
this.MyLogic.forEach((logicSet) => {
Outputer.Update(logicSet.toString());
});
return Outputer.Result;
}
public PrintPremises(): void {
Outputer.Update("<RULE>\n" + this.myName + "\n");
Outputer.Update("<IF>\n");
this.MyLogic.forEach((logicSet) => {
Outputer.Update(logicSet.toString());
});
}
public PrintConclusionString(): string {
Outputer.Reset();
this.printPairs("AND", this.Cons);
if (this.Elses.length > 0) {
Outputer.Update("ELSE ");
this.printPairs("", this.Elses);
}
return Outputer.Result;
}
public PrintConclusion(): string {
Outputer.Update("<THEN>\n");
this.printPairs("AND", this.Cons);
if (this.Elses.length > 0) {
Outputer.Update("ELSE ");
this.printPairs("AND", this.Elses);
}
return Outputer.Result;
}
public FindCert(theNodes: Nodes): number {
let max = 101;
this.MyLogic.forEach((aSet) => {
let cert = aSet.FindCert(theNodes);
if (cert < max) max = cert;
});
return max;
}
public HasElse(): boolean {
return this.Elses.length != 0;
}
}
|
e9e0ef19899193c989182c79a9ec2a0b1879d8ae
|
TypeScript
|
JayKay24/coding_challenges
|
/algorithms_and_data_structures_masterclass/reverse.ts
| 3.234375
| 3
|
export const reverse = (str: string): string => {
if (str.length <= 1) return str;
return `${str[str.length - 1]}${reverse(str.slice(0, -1))}`;
};
let res = reverse("awesome");
console.log(res);
|
6d6a157ae5c29f53f938bed42242fb6276680d51
|
TypeScript
|
albizures/flashruad
|
/src/entities/word/word.entity.ts
| 2.625
| 3
|
// TODO: remove this entity
import {
Entity,
Column,
PrimaryGeneratedColumn,
Unique,
ManyToOne,
CreateDateColumn,
UpdateDateColumn,
} from 'typeorm';
import { ObjectType, Field, Int, ArgsType, InputType } from 'type-graphql';
import { Language } from '../internals';
@Entity()
@ObjectType()
@Unique(['word'])
class Word {
@Field((type) => Int)
@PrimaryGeneratedColumn()
id: number;
@Field((type) => String)
@Column('text')
word: string;
@Field((type) => Language)
@ManyToOne((type) => Language)
language: Language;
@Field((type) => Date)
@CreateDateColumn({ type: 'timestamp' })
createdAt: Date;
@Field((type) => Date)
@UpdateDateColumn({ type: 'timestamp' })
updatedAt: Date;
}
@ArgsType()
class NewWordInput {
@Field((type) => String)
word: string;
@Field((type) => Number)
language: number;
}
@ArgsType()
@InputType()
class FilterWord {
@Field((type) => String, { nullable: true })
word?: string;
@Field((type) => Number, { nullable: true })
language?: number;
}
@ArgsType()
class WordListArgs {
@Field((type) => FilterWord, { nullable: true })
filter: FilterWord;
}
export { WordListArgs, FilterWord, Word, NewWordInput };
|
b67caf12023baa9d4ff06238d5a81b462f13458d
|
TypeScript
|
chris-schmitz/binary-operations-presentation
|
/source-client/common/BrickColor.ts
| 3.515625
| 4
|
import { BrickColor as RGBBrickColor } from "./Interfaces";
export class BrickColor {
static withRandomColor(): BrickColor {
const color = new BrickColor()
color.setColorRGB({ red: BrickColor.getRandomColorValue(), green: BrickColor.getRandomColorValue(), blue: BrickColor.getRandomColorValue() })
return color
}
public static getRandomColorValue() {
return Math.floor(Math.random() * 255)
}
private color: RGBBrickColor;
constructor() {
this.color = { red: 0, green: 0, blue: 0 };
}
static fromHex(color: number) {
const brickColor = new BrickColor();
brickColor.setColorHEX(color);
return brickColor;
}
static fromRGB(color: RGBBrickColor) {
const brickColor = new BrickColor();
brickColor.setColorRGB(color);
return brickColor;
}
public asRGB() {
return this.color;
}
public asHex() {
let hex = 0;
hex |= this.color.red;
hex <<= 8;
hex |= this.color.green;
hex <<= 8;
hex |= this.color.blue;
return hex.toString(16);
}
public asPrefixedHex() {
return `#${this.asHex()}`;
}
public asCSS() {
return `rgb(${this.color.red}, ${this.color.green}, ${this.color.blue})`;
}
// TODO: refactor if you feel like it
// * go back and read about typeguarding and checking with interfaces and then come back and make
// * a single `setColor` method with a number or RGBBrickColor type, switch on the argument, and
// * call the individual setColor___ methods as needed (make those methods private)
public setColorRGB(color: RGBBrickColor) {
this.color.red = color.red;
this.color.green = color.green;
this.color.blue = color.blue;
}
public setColorHEX(color: number) {
this.color.blue = color & 0xFF;
color >>= 8;
this.color.green = color & 0xFF;
color >>= 8;
this.color.red = color & 0xFF;
}
}
|
b34bfdc48f4144d16609abbf3e4c66da7694bcf9
|
TypeScript
|
brscherer/ng-ecommerce
|
/src/app/core/functions/dynamic-sort.spec.ts
| 3.171875
| 3
|
// export function dynamicSort(property: string) {
// let sortOrder = 1;
import { dynamicSort } from './dynamic-sort';
// if (property[0] === '-') {
// sortOrder = -1;
// property = property.substr(1);
// }
// return function (a: any, b: any) {
// const result = a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0;
// return result * sortOrder;
// };
// }
describe('dynamicSort', () => {
const mock = [
{ name: 'Test D', price: 4 },
{ name: 'Test B', price: 2 },
{ name: 'Test C', price: 3 },
{ name: 'Test C', price: 3 },
{ name: 'Test A', price: 1 },
];
it('should order by name asc', () => {
const expected = [
{ name: 'Test A', price: 1 },
{ name: 'Test B', price: 2 },
{ name: 'Test C', price: 3 },
{ name: 'Test C', price: 3 },
{ name: 'Test D', price: 4 },
];
expect(mock.sort(dynamicSort('name'))).toEqual(expected);
});
it('should order by name desc', () => {
const expected = [
{ name: 'Test D', price: 4 },
{ name: 'Test C', price: 3 },
{ name: 'Test C', price: 3 },
{ name: 'Test B', price: 2 },
{ name: 'Test A', price: 1 },
];
expect(mock.sort(dynamicSort('-name'))).toEqual(expected);
});
});
|
c345475bf481780630f26c769fe0bf812dcd3066
|
TypeScript
|
PrendiProgramming/EFTClient.IPInterface.Typescript
|
/ts/index.ts
| 2.53125
| 3
|
import { tcpSocket } from "./tcp_socket";
import * as net from 'net'
import { createEFTTransactionRequest, createEFTLogonRequest, createSendKeyRequest, createSetDialogRequest, createEFTStatusRequest, createGetClientListRequest } from "./request_parser";
import { EFTTransactionRequest } from "./model/transaction";
import { EFTLogonRequest } from "./model/logon";
import { EFTSendKeyRequest } from "./model/key";
import { SetDialogRequest } from "./model/dialogue";
import { EFTStatusRequest } from "./model/status";
export type EFTClientOptions = {
hostName: string,
port: string,
onError: Function,
onResponse: Function,
onConnect: Function,
onClose: Function,
}
const defaultOptions: EFTClientOptions = {
hostName: '127.0.0.1',
port: '2011',
onResponse: () => {},
onError: () => {},
onClose: () => {},
onConnect: () => {},
}
export class EFTClientIP {
options: EFTClientOptions
connection: net.Socket
constructor(options?: Partial<EFTClientOptions>) {
let opts = {...defaultOptions, ...options}
this.options = {...opts, onClose: () => {
opts.onClose()
// Attempt to reconnect in two seconds
setTimeout(() => this.connection = tcpSocket(this.options), 2000)
}}
this.connection = tcpSocket(this.options)
this.heartbeat()
}
heartbeat() {
// Heartbeat
setInterval(() => {
if (this.connection) this.connection.write('')
}, 5000)
}
// Not required, as it will reconnect automatically in 2 seconds.
reconnect() {
this.connection.destroy()
this.connection = tcpSocket(this.options)
}
send = {
transaction: (transaction: Partial<EFTTransactionRequest>) => {
this.connection.write(createEFTTransactionRequest(transaction))
},
logon: (logon: Partial<EFTLogonRequest>) => {
this.connection.write(createEFTLogonRequest(logon))
},
key: (key: Partial<EFTSendKeyRequest>) => {
this.connection.write(createSendKeyRequest(key))
},
setDialog: (dialogue: Partial<SetDialogRequest>) => {
this.connection.write(createSetDialogRequest(dialogue))
},
status: (status: Partial<EFTStatusRequest>) => {
this.connection.write(createEFTStatusRequest(status))
},
getClientList: () => {
this.connection.write(createGetClientListRequest())
}
}
}
|
e4f4f23788f08956b4375cfb2bf0e976a39a788d
|
TypeScript
|
qlonik-forks/matechs-effect-legacy
|
/packages/core/demo/demo10.ts
| 3.0625
| 3
|
import * as A from "../src/Array"
import { pipe } from "../src/Function"
import * as T from "../src/next/Effect"
import * as Has from "../src/next/Has"
import * as L from "../src/next/Layer"
import * as S from "../src/next/Semaphore"
abstract class Console {
abstract readonly putStrLn: (s: string) => T.Sync<void>
}
abstract class Format {
abstract readonly formatString: (s: string) => T.Sync<string>
}
abstract class AppConfig<S> {
abstract readonly config: S
}
export const HasConsole = Has.has(Console)
export type HasConsole = Has.HasType<typeof HasConsole>
export const HasFormat = Has.has(Format)
export type HasFormat = Has.HasType<typeof HasFormat>
export const HasStringConfig = Has.has<AppConfig<string>>()
export type HasStringConfig = Has.HasType<typeof HasStringConfig>
export const HasNumberConfig = Has.has<AppConfig<number>>()
export type HasNumberConfig = Has.HasType<typeof HasNumberConfig>
export const Core = T.region<"core", HasStringConfig>()
export type HasCoreConfig = Has.HasType<typeof Core>
export const Second = T.region<"second", HasStringConfig>()
export type HasSecondAppConfig = Has.HasType<typeof Second>
export const Third = T.region<"third", HasNumberConfig>()
export type HasThirdConfig = Has.HasType<typeof Third>
export const putStrLn = (s: string) =>
T.accessServiceM(HasConsole)((console) => console.putStrLn(s))
export class LiveConsole extends Console {
constructor(private readonly format: Format) {
super()
}
putStrLn: (s: string) => T.Sync<void> = (s) =>
T.chain_(this.format.formatString(s), (f) =>
T.provideService(HasFormat)(this.format)(
T.effectTotal(() => {
console.log(f)
})
)
)
}
export class AugumentedConsole extends Console {
constructor(private readonly format: Format) {
super()
}
putStrLn: (s: string) => T.Sync<void> = (s) =>
T.chain_(this.format.formatString(s), (f) =>
T.provideService(HasFormat)(this.format)(
T.effectTotal(() => {
console.log("(augumented) ", f)
})
)
)
}
export const provideConsole = T.provideServiceM(HasConsole.overridable())(
T.accessService(HasFormat)((format) => new LiveConsole(format))
)
export const provideAugumentedConsole = T.provideServiceM(HasConsole.overridable())(
T.accessService(HasFormat)((format) => new AugumentedConsole(format))
)
export const complexAccess = pipe(
T.of,
T.bind("console", () => T.readService(HasConsole)),
T.bind("app", () => T.readServiceIn(HasStringConfig)(Core)),
T.bind("scoped", () => T.readServiceIn(HasStringConfig)(Second)),
T.bind("number", () => T.readServiceIn(HasNumberConfig)(Third)),
T.chain(({ app, console, number, scoped }) =>
console.putStrLn(`${app.config} - (${scoped.config}) - (${number.config})`)
)
)
export const provideFormat = T.provideServiceM(HasFormat)(
T.effectTotal(
() =>
new (class extends Format {
formatString: (s: string) => T.Sync<string> = (s) =>
T.effectTotal(() => `running: ${s}`)
})()
)
)
const program = pipe(
S.makeSemaphore(2),
T.chain((s) =>
T.foreachPar_(A.range(0, 10), (n) =>
S.withPermit(s)(T.delay(1000)(putStrLn(String(n))))
)
),
T.chain(() => complexAccess)
)
export const provideAppConfig = pipe(
L.service(HasStringConfig).fromEffect(
T.effectTotal(
() =>
new (class extends AppConfig<string> {
config = "ok"
})()
)
),
L.region(Core)
)
export const provideNumberConfig = pipe(
L.service(HasNumberConfig).fromEffect(
T.effectTotal(
() =>
new (class extends AppConfig<number> {
config = 1
})()
)
),
L.region(Third)
)
export const provideScopedAppConfig = pipe(
L.service(HasStringConfig).fromEffect(
T.effectTotal(
() =>
new (class extends AppConfig<string> {
config = "ok - scoped"
})()
)
),
L.region(Second)
)
const appLayer = L.all(provideAppConfig, provideScopedAppConfig, provideNumberConfig)
const main = pipe(
program,
provideConsole,
provideAugumentedConsole,
provideFormat,
T.provideSomeLayer(appLayer)
)
T.runMain(main)
|
29321a1126a7635ed15feccac19fb58589b4fe87
|
TypeScript
|
isuru89/vscode-nyql
|
/src/nyModel.ts
| 2.578125
| 3
|
import { Disposable } from "vscode";
export class NyConnection {
name: string;
dialect: string;
host: string;
port: number;
username: string;
password: string;
databaseName: string;
additionalOptions?: string;
autoCapitalizeTableNames?: boolean;
}
export class NySchemaInfo {
database: NyDatabase;
tables: Array<NyTable>;
columns: Map<string, Array<NyColumn>>;
}
export interface NyDatabaseImpl {
fetchDatabases(con: NyConnection) : Promise<string[]>;
reloadConnection(connectionInfo: NyConnection) : Promise<NyDatabaseImpl>;
loadSchema() : Promise<NySchemaInfo>;
validateConnection(connectionInfo: NyConnection) : boolean;
close();
}
export class NyDatabase {
name: string;
constructor(name: string) {
this.name = name;
}
}
export class NyTable {
name: string;
database: NyDatabase;
constructor(name: string, db: NyDatabase) {
this.name = name;
this.database = db;
}
}
export class NyColumn {
name: string;
tableName: string;
table: NyTable;
type: string
}
|
e440cf584a79d8ceb67a187fef3cb08875e434bb
|
TypeScript
|
isatix971/prototipo_sgt
|
/src/infrastructure/repository/persistence/profesional.ts
| 2.65625
| 3
|
import { EntityRepository, getRepository } from "typeorm";
import { ProfesionalEntity } from "../entity/profesional";
import { ProfesionalRepoContract } from "../interfaces/profesional";
import { keysToLowerCase } from "../../../application/common/utils";
import { InputProfesional } from "../../../application/resolvers/profesional.input";
import { ContactoEntity } from "../entity/contacto";
@EntityRepository(ProfesionalEntity)
export class ProfesionalRepository implements ProfesionalRepoContract {
async insertarDatosBasicosProfesiona(datos : InputProfesional): Promise<ProfesionalEntity> {
try {
const profesional = new ProfesionalEntity();
profesional.nombre = datos.nombre;
profesional.apellido = datos.apellido;
profesional.tipo_identificacion= datos.tipo_identificacion;
profesional.fecha_nacimiento= datos.fecha_nacimiento,
profesional.genero= datos.genero,
profesional.estado_civil= datos.estado_civil,
profesional.nacionalidad= datos.nacionalidad,
profesional.discapacidad= datos.discapacidad,
profesional.referido= datos.referido
const valores = [];
datos.contacto.forEach(function(item){
const contacto = new ContactoEntity();
contacto.celular = item.celular;
contacto.correo = item.correo;
contacto.fijo = item.fijo;
valores.push(contacto);
});
profesional.contact = valores;
getRepository(ProfesionalEntity).save(profesional);
return profesional;
}
catch (err) {
throw new Error(err.message);
}
}
async datosBasicosProfesiona(): Promise<ProfesionalEntity[]> {
try {
const resultado: ProfesionalEntity[] = await getRepository(ProfesionalEntity).createQueryBuilder("dato")
.getMany();
return keysToLowerCase(resultado);
}
catch (err) {
throw new Error(err.message);
}
}
}
|
8f657de80689d16433340ed703bb28614ba6d5e2
|
TypeScript
|
can-i/see-example
|
/services/ModelService.ts
| 2.71875
| 3
|
import {Injectable} from "can-i/IOC";
import _ = require("lodash");
export interface Model{
id:number
}
let collection = new Map<string,Model[]>()
let primary_key = new Map<string,number>();
export abstract class ModelService{
public name:string;
public get collection(){
return this.getCollection();
}
public get primary(){
return this.nextKey();
}
public Create(object:Model):Model{
object.id = this.nextKey();
this.collection.push(object);
return object;
}
public Find(id:number):Model[];
public Find(id:any):Model[]{
if(_.isNumber(id)){
return this.Filter({id});
}else{
return this.Filter(id);
}
}
Update(id:number,update:Object):Model[]
Update(id:Object,update:Object):Model[]{
return this.Filter(id).map(x=>{
let keys =Object.keys(update);
for(let key of keys){
x[key] = update[key];
}
return x;
})
}
Delete(id:number):number
Delete(id:Object):number{
let count:number=0;
this.Filter(id).forEach(x=>{
count++;
this.collection.splice(this.collection.indexOf(x),1);
})
return count;
}
private Filter(object:any):Model[]{
if(!object){
return []
}
let keys = Object.keys(object);
return this.collection.filter(x=>{
for(let key of keys){
if(x[key]!==object[key]){
return false
}
}
return true
})
}
private getCollection():Model[]{
if(collection.has(this.name)){
return <Model[]>collection.get(this.name)
}else{
let arr = [];
collection.set(this.name,arr);
return arr;
}
}
private getKey(){
return primary_key.get(this.name) || 1;
}
private setKey(key:number){
primary_key.set(this.name,key);
}
private nextKey(){
let key = this.getKey();
this.setKey(key+1);
return key;
}
}
|
cb05485fbd407acf909105333920a9047bb3951b
|
TypeScript
|
MerHS/sarissa
|
/src/utils/types/scoreTypes.ts
| 2.734375
| 3
|
export type Coord = [number, number];
/**
* [bottom-left Coord, [width, height]]
*/
export type Rect = [Coord, Coord];
export type Beat = [number, number];
export type NoteIndex = string;
export type SoundIndex = string;
export type LaneIndex = number;
export type TrackIndex = number;
export interface ScoreMetaData {
title: string;
artist: string; // TODO: TO BMSMetaData?
fileName?: string;
resourcePath?: string;
extra: Record<string, any>;
};
// pulse and second should be calculated when to use it.
export class NoteTime {
public beat: Beat;
public pulse: number;
public second: number;
public isFixedTime: boolean; // default: false
public constructor(pulse: number, isFixedTime: boolean = false) {
this.beat = [0, 4];
this.pulse = pulse;
this.second = 0;
this.isFixedTime = isFixedTime;
}
}
export interface NoteLayer {
index: TrackIndex;
name: string;
isLocked: boolean;
isVisible: boolean;
editableLaneIndex: LaneIndex[]; // use all if empty
};
export interface TimeSignature {
measureNo: number;
meter: Beat;
};
export interface NoteType {
index: string;
typeName: string;
BMSChannel?: number;
};
export interface EventType {
index: string;
BMSChannel?: number;
};
export interface MIDIValue {
length: number; // second scale
intensity: number; // normalized to 0-1
pitch: number; // midi scale
};
export interface SoundSprite {
fileName: string;
useWhole: boolean; // default true
interval?: [number, number]; // second scale
}
export interface SoundType {
index: SoundIndex;
midiValue?: MIDIValue;
soundSpriteIndex?: string;
};
// export interface LaneType {
// noteType: NoteType,
// };
export enum EditMode {
TIME_SELECT_MODE, SELECT_MODE, WRITE_MODE
}
export class PlayNoteProps {
public propType: 'm' | 'e' = 'm';
public laneIndex: LaneIndex; // Position X
public trackIndex: TrackIndex;
public lnPrevPart: NoteIndex | null;
public lnNextPart: NoteIndex | null;
public constructor() {
this.laneIndex = 0;
this.trackIndex = 0;
this.lnPrevPart = null;
this.lnNextPart = null;
}
}
export class MusicNoteProps extends PlayNoteProps {
public soundIndex: SoundIndex;
public noteTypeIndex: string;
public constructor() {
super();
this.soundIndex = '';
this.noteTypeIndex = '';
}
}
export class EventNoteProps extends PlayNoteProps {
public propType: 'm' | 'e' = 'e';
public eventTypeIndex: string;
public constructor() {
super();
this.eventTypeIndex = '';
}
}
export class Note {
public index: NoteIndex;
public time: NoteTime; // Y Position
public isLocked: boolean;
public constructor(index: NoteIndex, time: NoteTime) {
this.index = index;
this.time = time;
this.isLocked = false;
}
}
export class PlayNote extends Note {
public isBackground: boolean;
// DO NOT MANIPULATE IT! props are used as euclase core properties only
public props: PlayNoteProps;
// this extra value is for users
public extra: Record<string, any>;
public constructor(indexNo: number, time: NoteTime, props: PlayNoteProps) {
super(`${props.propType}${indexNo}`, time);
this.isBackground = false;
this.props = props;
this.extra = {};
}
}
export class BPMNote extends Note {
public bpm: number;
public isLocked: boolean;
public constructor(indexNo: number, pulse: number, bpm: number) {
super(`b${indexNo}`, new NoteTime(pulse));
this.bpm = bpm;
this.isLocked = false;
}
}
export class StopNote extends Note {
public duration: NoteTime;
public isLocked: boolean;
public constructor(indexNo: number, positionPulse: number, durationPulse: number) {
super(`s${indexNo}`, new NoteTime(positionPulse));
this.duration = new NoteTime(durationPulse);
this.isLocked = false;
}
}
// time is always fixed by pulse
export type ScoreNote = BPMNote | StopNote;
|
f704ee6480a9b82adacf5ec5d2a7b4b3af62336b
|
TypeScript
|
brunnre8/thelounge
|
/server/plugins/messageStorage/sqlite.ts
| 2.546875
| 3
|
import type {Database} from "sqlite3";
import log from "../../log";
import path from "path";
import fs from "fs/promises";
import Config from "../../config";
import Msg, {Message} from "../../models/msg";
import Chan, {Channel} from "../../models/chan";
import Helper from "../../helper";
import type {SearchResponse, SearchQuery, SearchableMessageStorage} from "./types";
import Network from "../../models/network";
// TODO; type
let sqlite3: any;
try {
sqlite3 = require("sqlite3");
} catch (e: any) {
Config.values.messageStorage = Config.values.messageStorage.filter((item) => item !== "sqlite");
log.error(
"Unable to load sqlite3 module. See https://github.com/mapbox/node-sqlite3/wiki/Binaries"
);
}
const currentSchemaVersion = 1520239200;
const schema = [
// Schema version #1
"CREATE TABLE IF NOT EXISTS options (name TEXT, value TEXT, CONSTRAINT name_unique UNIQUE (name))",
"CREATE TABLE IF NOT EXISTS messages (network TEXT, channel TEXT, time INTEGER, type TEXT, msg TEXT)",
"CREATE INDEX IF NOT EXISTS network_channel ON messages (network, channel)",
"CREATE INDEX IF NOT EXISTS time ON messages (time)",
];
class Deferred {
resolve!: () => void;
promise: Promise<void>;
constructor() {
this.promise = new Promise((resolve) => {
this.resolve = resolve;
});
}
}
class SqliteMessageStorage implements SearchableMessageStorage {
isEnabled: boolean;
database!: Database;
initDone: Deferred;
userName: string;
constructor(userName: string) {
this.userName = userName;
this.isEnabled = false;
this.initDone = new Deferred();
}
async _enable() {
const logsPath = Config.getUserLogsPath();
const sqlitePath = path.join(logsPath, `${this.userName}.sqlite3`);
try {
await fs.mkdir(logsPath, {recursive: true});
} catch (e) {
throw Helper.catch_to_error("Unable to create logs directory", e);
}
this.isEnabled = true;
this.database = new sqlite3.Database(sqlitePath);
try {
await this.run_migrations();
} catch (e) {
this.isEnabled = false;
throw Helper.catch_to_error("Migration failed", e);
}
}
async enable() {
try {
await this._enable();
} finally {
this.initDone.resolve(); // unblock the instance methods
}
}
async run_migrations() {
for (const stmt of schema) {
await this.serialize_run(stmt, []);
}
const version = await this.serialize_get(
"SELECT value FROM options WHERE name = 'schema_version'"
);
if (version === undefined) {
// new table
await this.serialize_run(
"INSERT INTO options (name, value) VALUES ('schema_version', ?)",
[currentSchemaVersion]
);
return;
}
const storedSchemaVersion = parseInt(version.value, 10);
if (storedSchemaVersion === currentSchemaVersion) {
return;
}
if (storedSchemaVersion > currentSchemaVersion) {
throw `sqlite messages schema version is higher than expected (${storedSchemaVersion} > ${currentSchemaVersion}). Is The Lounge out of date?`;
}
log.info(
`sqlite messages schema version is out of date (${storedSchemaVersion} < ${currentSchemaVersion}). Running migrations if any.`
);
await this.serialize_run("UPDATE options SET value = ? WHERE name = 'schema_version'", [
currentSchemaVersion,
]);
}
async close() {
if (!this.isEnabled) {
return;
}
this.isEnabled = false;
return new Promise<void>((resolve, reject) => {
this.database.close((err) => {
if (err) {
reject(`Failed to close sqlite database: ${err.message}`);
return;
}
resolve();
});
});
}
async index(network: Network, channel: Chan, msg: Msg) {
await this.initDone.promise;
if (!this.isEnabled) {
return;
}
const clonedMsg = Object.keys(msg).reduce((newMsg, prop) => {
// id is regenerated when messages are retrieved
// previews are not stored because storage is cleared on lounge restart
// type and time are stored in a separate column
if (prop !== "id" && prop !== "previews" && prop !== "type" && prop !== "time") {
newMsg[prop] = msg[prop];
}
return newMsg;
}, {});
await this.serialize_run(
"INSERT INTO messages(network, channel, time, type, msg) VALUES(?, ?, ?, ?, ?)",
[
network.uuid,
channel.name.toLowerCase(),
msg.time.getTime(),
msg.type,
JSON.stringify(clonedMsg),
]
);
}
async deleteChannel(network: Network, channel: Channel) {
await this.initDone.promise;
if (!this.isEnabled) {
return;
}
await this.serialize_run("DELETE FROM messages WHERE network = ? AND channel = ?", [
network.uuid,
channel.name.toLowerCase(),
]);
}
async getMessages(
network: Network,
channel: Channel,
nextID: () => number
): Promise<Message[]> {
await this.initDone.promise;
if (!this.isEnabled || Config.values.maxHistory === 0) {
return [];
}
// If unlimited history is specified, load 100k messages
const limit = Config.values.maxHistory < 0 ? 100000 : Config.values.maxHistory;
const rows = await this.serialize_fetchall(
"SELECT msg, type, time FROM messages WHERE network = ? AND channel = ? ORDER BY time DESC LIMIT ?",
network.uuid,
channel.name.toLowerCase(),
limit
);
return rows.reverse().map((row: any): Message => {
const msg = JSON.parse(row.msg);
msg.time = row.time;
msg.type = row.type;
const newMsg = new Msg(msg);
newMsg.id = nextID();
return newMsg;
});
}
async search(query: SearchQuery): Promise<SearchResponse> {
await this.initDone.promise;
if (!this.isEnabled) {
// this should never be hit as messageProvider is checked in client.search()
throw new Error(
"search called but sqlite provider not enabled. This is a programming error"
);
}
// Using the '@' character to escape '%' and '_' in patterns.
const escapedSearchTerm = query.searchTerm.replace(/([%_@])/g, "@$1");
let select =
'SELECT msg, type, time, network, channel FROM messages WHERE type = "message" AND json_extract(msg, "$.text") LIKE ? ESCAPE \'@\'';
const params: any[] = [`%${escapedSearchTerm}%`];
if (query.networkUuid) {
select += " AND network = ? ";
params.push(query.networkUuid);
}
if (query.channelName) {
select += " AND channel = ? ";
params.push(query.channelName.toLowerCase());
}
const maxResults = 100;
select += " ORDER BY time DESC LIMIT ? OFFSET ? ";
params.push(maxResults);
params.push(query.offset);
const rows = await this.serialize_fetchall(select, ...params);
return {
...query,
results: parseSearchRowsToMessages(query.offset, rows).reverse(),
};
}
canProvideMessages() {
return this.isEnabled;
}
private serialize_run(stmt: string, params: any[]): Promise<void> {
return new Promise((resolve, reject) => {
this.database.serialize(() => {
this.database.run(stmt, params, (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
});
}
private serialize_fetchall(stmt: string, ...params: any[]): Promise<any[]> {
return new Promise((resolve, reject) => {
this.database.serialize(() => {
this.database.all(stmt, params, (err, rows) => {
if (err) {
reject(err);
return;
}
resolve(rows);
});
});
});
}
private serialize_get(stmt: string, ...params: any[]): Promise<any> {
return new Promise((resolve, reject) => {
this.database.serialize(() => {
this.database.get(stmt, params, (err, row) => {
if (err) {
reject(err);
return;
}
resolve(row);
});
});
});
}
}
// TODO: type any
function parseSearchRowsToMessages(id: number, rows: any[]) {
const messages: Msg[] = [];
for (const row of rows) {
const msg = JSON.parse(row.msg);
msg.time = row.time;
msg.type = row.type;
msg.networkUuid = row.network;
msg.channelName = row.channel;
msg.id = id;
messages.push(new Msg(msg));
id += 1;
}
return messages;
}
export default SqliteMessageStorage;
|
0c09bc2b3b1c8608fed5caaf6f77050e83cfd7eb
|
TypeScript
|
SaeedYaghuti/kasabe-16
|
/src/accounting/models/account/dto/create-tree-account.dto.ts
| 2.578125
| 3
|
import { IsNotEmpty, IsOptional, IsInt, IsString } from 'class-validator';
export class CreateTreeAccountDto {
@IsNotEmpty()
@IsString()
title: string; // english
@IsNotEmpty()
@IsString()
titleArb: string; // Arabic
@IsNotEmpty()
@IsString()
titlePer: string; // Persian
@IsOptional()
@IsString()
description: string;
@IsOptional()
parent: CreateTreeAccountDto;
@IsOptional()
children: CreateTreeAccountDto[];
}
// parameters: { title, titleArb, titlePer, description, parentId }
// @IsOptional()
// @IsInt()
// parentId: number;
|
5679699b05155bc1391486ca374dc31b60b8306a
|
TypeScript
|
NirajBhavnani/DiscoveryLandCo
|
/src/components/PressArticles/PressArticles.ts
| 2.515625
| 3
|
interface IArticlesDataItem {
title: string;
subtitle: string;
}
import { Options, Vue } from "vue-class-component";
import PressArticlesCard from "../PressArticlesCard/PressArticlesCard.vue";
@Options({
name: "PressArticles",
components: {
PressArticlesCard,
},
data() {
return {
page: 0 as number,
articlesData: [
{
title: "10 Fairways to Tee Off on Now",
subtitle: "Vegas Magazine I September 2021",
},
{
title:
"Golf Real Estate Roars Back as Vacation Homes Boom in Pandemic",
subtitle: "Bloomberg I September 2021",
},
{
title:
"Brexit drives British millionaires to Portugal for tax and EU perks — but it’s about to get complicated",
subtitle: "Telegraph UK | August 20, 2021",
},
{
title:
"This Property Company Ups the Ante with Luxury and Sustainability",
subtitle: "Sunset Magazine | August 13, 2021",
},
{
title: "Where Sun, Sand and Splendor Are Still to Be Discovered",
subtitle: "New York Times | June 9, 2021",
},
{
title:
"Mike Meldman is one of the most influential real-estate moguls in the country thanks to his luxurious live-in resorts, which became irresistible to the rich and famous during the pandemic",
subtitle: "Business Insider | June 4, 2021",
},
{
title:
"There's a real buy-in for resort communities offering amusement and amenities",
subtitle: "Luxury Magazine | Spring/Summer 2021",
},
{
title: "This Blue Chip Caribbean Island Hopes to Dethrone St. Barts",
subtitle: "New York Post | April 5, 2021",
},
{
title: "No Longer Waiting for Retirement",
subtitle: "New York Times International Homes | March 27-28, 2021",
},
{
title: "Golf and Pickleball are Having a Love Affair",
subtitle: "New York Times | March 22, 2021",
},
{
title: "For Many, the Pandemic Has Led to the 'Discovery' of Golf",
subtitle: "New York Times | March 22, 2021",
},
] as IArticlesDataItem[],
};
},
computed: {
totalPages(): number {
return this.articlesData.length % 4;
},
desktopArticlesData(): Array<{ title: string; subtitle: string }> {
// console.log(this.articlesData.slice(this.page * 4, (this.page + 1) * 4));
return this.articlesData.slice(this.page * 4, (this.page + 1) * 4);
},
},
methods: {
nextPage(): void {
this.page = (this.page + 1) % this.totalPages;
// console.log(this.page);
},
previousPage(): void {
this.page = (this.page + this.totalPages - 1) % this.totalPages;
// console.log(this.page);
},
},
})
export default class PressArticles extends Vue {}
|
4a08b320b919391a98dd9938af89ea0ecc9e6581
|
TypeScript
|
VoicuIuliana/angular
|
/learning/src/app/heroes/heroes.component.ts
| 2.734375
| 3
|
import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
hero: Hero = {
id: 1,
name: 'Windstorm',
age: 23
};
value = '';
onEnter(value: string) {
this.value = value;
}
res = 'no result';
onEnter2(value: string) {
let x = Number(value);
x = x*x;
this.res = "Patratul lui x este " + x.toString();
}
res3 = '';
onEnter3(value: string) {
let x = Number(value);
if(x>=18){
this.res3="This is major";
}
else{
this.res3="This is minnor";
}
}
res4='';
onEnter4(value: string) {
let x= Number(value);
let count=0;
this.res4 ='';
for(let d=1; d<=x; d++){
if(x%d==0){
this.res4 =this.res4 +" "+ d;
count++;
}
}
if(count ==2){
this.res4=this.res4 + " Numarul este prim";
}
else{
this.res4=this.res4 +" Numarul nu este prim";
}
}
constructor() { }
ngOnInit() {
}
}
|
61d3b078098bd1f62c6f6da9d13830f37dfbc495
|
TypeScript
|
petebacondarwin/ts-simple-ast
|
/src/tests/compiler/literal/template/taggedTemplateExpressionTests.ts
| 2.75
| 3
|
import * as ts from "typescript";
import {expect} from "chai";
import {TaggedTemplateExpression} from "./../../../../compiler";
import {getInfoFromTextWithDescendant} from "./../../testHelpers";
function getExpression(text: string) {
return getInfoFromTextWithDescendant<TaggedTemplateExpression>(text, ts.SyntaxKind.TaggedTemplateExpression).descendant;
}
describe(nameof(TaggedTemplateExpression), () => {
const tag = "(x + 1)";
const template = "`hello world`";
const expr = `${tag}${template}`;
describe(nameof<TaggedTemplateExpression>(n => n.getTag), () => {
function doTest(text: string, expectedText: string) {
const expression = getExpression(text);
expect(expression.getTag().getText()).to.equal(expectedText);
}
it("should get the correct tag expression", () => {
doTest(expr, tag);
});
});
describe(nameof<TaggedTemplateExpression>(n => n.getTemplate), () => {
function doTest(text: string, expectedText: string) {
const expression = getExpression(text);
expect(expression.getTemplate().getText()).to.equal(expectedText);
}
it("should get the correct template expression", () => {
doTest(expr, template);
});
});
});
|
8775e67f33353da7a7b6da96ad9be8dd3514813b
|
TypeScript
|
yin0105/SpaceNextDoor-onslib
|
/src/modules/media/media.controller.ts
| 2.75
| 3
|
import { BadRequestError } from '../../exceptions';
import {
IFileDetail,
IResizeImageQueryParam,
IResizeImageResult,
IUploadImagesQueryParam,
IUploadImagesResult,
} from './interfaces/media.interface';
import { MediaService } from './media.service';
export class MediaController {
private bucketUrl: string = '';
constructor(private readonly mediaService: MediaService) {
this.bucketUrl = `${process.env.AWS_S3_BUCKET_URL}`;
}
//@UseInterceptors(FilesInterceptor('files', 10))
async uploadImages(
queryParams: IUploadImagesQueryParam,
files: any[]
): Promise<IUploadImagesResult> {
await this.mediaService.validateImageUploadQueryParams(queryParams);
const filesDetails: IFileDetail[] = files.map(file => ({
file: file.buffer,
ext: this.mediaService.getExtensionFromContentType(file.mimetype),
mimeType: file.mimetype,
})) as IFileDetail[];
try {
const uploadFileResult = await this.mediaService.upload(
filesDetails,
queryParams
);
/* eslint-disable @typescript-eslint/restrict-template-expressions */
console.log(`Uploader result: ${uploadFileResult}`);
return {
bucketUrl: this.bucketUrl,
files: uploadFileResult,
} as IUploadImagesResult;
} catch (e) {
console.error('Error occurred while uploading', e);
throw new BadRequestError('Something went wrong while uploading images!');
}
}
async resizeImage(
queryParams: IResizeImageQueryParam
): Promise<IResizeImageResult> {
await this.mediaService.validateResizeImageQueryParams(queryParams);
const { size, imageKey } = queryParams;
const sizeArray = size.split('x');
const width = parseInt(sizeArray[0], 10);
const height = parseInt(sizeArray[1], 10) || undefined;
if (!width) {
console.error(`Width param missing or malformed size param: ${size}`);
throw new BadRequestError(
'The size path param should be like 40x40, instead got width undefined'
);
}
try {
const imagePath = await this.mediaService.resize(imageKey, width, height);
console.log(`Generated new image with path: ${imagePath}`);
return {
bucketUrl: this.bucketUrl,
key: imagePath,
} as IResizeImageResult;
} catch (e) {
console.error('Error occurred while resizing and uploading', e);
throw new BadRequestError('Error occurred while resizing the image!');
}
}
}
|
6d51a08ac7dd8b10c55d04c587c27c6d965637ae
|
TypeScript
|
crystalis-randomizer/crystalis-randomizer
|
/src/js/pass/fixskippableexits.ts
| 2.96875
| 3
|
import {Rom} from '../rom';
import { UnionFind } from '../unionfind';
import { Exit } from '../rom/location';
// There's an oddity where map screens that can be fallen into (i.e.
// via a pit) can have their exits skipped over while the screen is
// shaking on impact (the game stops checking exits during that time,
// cf. ff:e8f6, where 7d7 stores the positive screen-shake timer.
// Rather than move various exits, the most elegant fix is to extend
// any exits by an extra tile, but only on screens that can be fallen
// into. (The vanilla game solves this by moving the Sabera Fortress
// entrance down a tile, but this is ugly and inconsistent).
export function fixSkippableExits(rom: Rom) {
const targets = new Set<number>(); // stores location << 8 | screen
for (const location of rom.locations) {
for (const pit of location.pits ?? []) {
targets.add(pit.dest << 8 | pit.toScreen);
}
}
for (const target of targets) {
const location = rom.locations[target >> 8];
const scr = target & 0xff;
const exitList = location.exits.filter(e => e.screen === scr);
const entranceList = location.entrances.filter(e => e.screen === scr);
const exits = new Map<number, Exit>(exitList.map(e => [e.tile, e]));
const uf = new UnionFind<number>();
for (const exit of exits.keys()) {
for (const dir of DIRS) {
if (exits.has(exit + dir)) uf.union([exit, exit + dir]);
}
}
const map = uf.map();
for (const entrance of entranceList) {
for (const dir of DIRS) {
const found = map.get(entrance.tile + dir);
for (const tile of found ?? []) {
const orig = exits.get(tile)!;
const exit = Exit.of({screen: target & 0xff, tile: tile + dir,
dest: orig.dest, entrance: orig.entrance});
location.exits.push(exit);
}
}
}
}
}
const DIRS = [1, -1, 16, -16];
|
6dc0e5406d16921a81b4d4220bf3cea7fde54960
|
TypeScript
|
nkint/umbrella
|
/packages/bench/src/index.ts
| 3.96875
| 4
|
export type TimingResult<T> = [T, number];
/**
* Calls function `fn` without args, prints elapsed time and returns
* fn's result. The optional `prefix` will be displayed with the output,
* allowing to label different measurements.
*
* @param fn
* @param prefix
*/
export const timed = <T>(fn: () => T, prefix = "") => {
const t0 = Date.now();
const res = fn();
console.log(prefix + (Date.now() - t0) + "ms");
return res;
};
/**
* Similar to `timed()`, but produces no output and instead returns
* tuple of `fn`'s result and the time measurement.
*
* @param fn
*/
export const timedResult = <T>(fn: () => T): TimingResult<T> => {
const t0 = Date.now();
const res = fn();
return [res, Date.now() - t0];
};
/**
* Executes given function `n` times, prints elapsed time to console and
* returns last result from fn. The optional `prefix` will be displayed
* with the output, allowing to label different measurements.
*
* @param fn
* @param n
*/
export const bench = <T>(fn: () => T, n = 1e6, prefix = "") => {
let res: T;
return timed(() => {
while (n-- > 0) {
res = fn();
}
return res;
}, prefix);
};
/**
* Similar to `bench()`, but produces no output and instead returns
* tuple of `fn`'s last result and the grand total time measurement.
*
* @param fn
* @param n
*/
export const benchResult = <T>(fn: () => T, n = 1e6): TimingResult<T> => {
let res: T;
return timedResult(() => {
while (n-- > 0) {
res = fn();
}
return res;
});
};
|
741c19096b3663f928703fbd5d1cd1fbcce79d78
|
TypeScript
|
aadorian/TuringVscode
|
/client/src/providers/moduleProvider.ts
| 2.71875
| 3
|
import * as vscode from 'vscode';
import { functionCompletion, moduleCompletion, variableCompletion } from './completions';
// Module autocomplete
export const moduleProvider = vscode.languages.registerCompletionItemProvider(
't',
{
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) {
const completionArray = [];
const linePrefix = document.lineAt(position).text.substr(0, position.character);
// Check which module its part of
if (linePrefix.endsWith('Config.')) {
completionArray.push(functionCompletion(
'Display',
'Config.Display returns information about the display (or displays) attached to the computer. The parameter displayCode determines what sort of information is passed back',
'Display properties'
));
completionArray.push(functionCompletion(
'Lang',
'Config.Lang returns information about the language and the limitations of the implementation that the program is currently running. The parameter langCode determines what sort of information is passed back',
'Current turing version'
));
completionArray.push(functionCompletion(
'Machine',
'Config.Machine returns information about the machine that the program is currently running on. The parameter machineCode determines what sort of information is passed back',
'Returns properties of machine'
));
}
else if(linePrefix.endsWith('Dir.')) {
completionArray.push(functionCompletion(
'Change',
'Dir.Change changes the execution directory to that specified by the parameter directoryPathName. This is the equivalent of doing a cd in UNIX',
'Changes current directory'
));
completionArray.push(functionCompletion(
'Close',
'Dir.Close is part of a series of four subprograms that help users get directory listings. Dir.Close is used to close a directory stream number opened by Dir.Open. After the directory stream number is closed, it can not be used with Dir.Get or Dir.GetLong',
'Closes current directory'
));
completionArray.push(functionCompletion(
'Create',
'Dir.Create is used to create the directory specified by the parameter directoryPathName. This is the equivalent of doing a mkdir in DOS or UNIX',
'Creates new directory'
));
completionArray.push(variableCompletion(
'Current',
'Dir.Current returns the full path name of the current execution directory. This is the equivalent of doing a pwd in UNIX',
'Returns current directory'
));
completionArray.push(functionCompletion(
'Delete',
'Dir.Delete is used to delete the directory specified by the parameter directoryPathName. This is the equivalent of doing a rmdir in DOS or UNIX. Dir.Delete will fail if it attempts delete a directory that has files in it',
'Deletes empty directory'
));
completionArray.push(functionCompletion(
'Exists',
'Dir.Exists returns true if a directory by the name of directoryPathName exists. It will return false if directoryPathName is a file',
'Checks if directory exists'
));
completionArray.push(functionCompletion(
'Get',
'Dir.Get is part of a series of four subprograms that help users get directory listings. Dir.Get is used to get the file names in the directory. Each time the function is called, it returns the next file name in the directory',
'Returns a file name'
));
completionArray.push(functionCompletion(
'GetLong',
'Dir.GetLong is part of a series of four subprograms that help users get directory listings. Dir.GetLong is used to get the names and assorted information of the files in the directory. Each time the function is called, it returns the name and information of the next file in the directory',
'Returns file details'
));
completionArray.push(functionCompletion(
'Open',
'Dir.Open is part of a series of four subprograms that help users get directory listings. Dir.Open returns a directory stream number if the directory could be opened',
'Opens directory'
));
}
else if (linePrefix.endsWith('Draw.')) {
completionArray.push(functionCompletion(
'Cls',
'The Draw.Cls (clear screen) procedure is used to blank the output window. The cursor is set to the top left (to row 1, column 1)',
'Clears the screen'
));
completionArray.push(functionCompletion(
'Dot',
'The Draw.Dot procedure is used to color the dot (pixel) at location (x, y) using the specified Color',
'Draws a dot'
));
completionArray.push(functionCompletion(
'Line',
'The Draw.Line procedure is used to draw a line on the screen from (x1, y1) to (x2, y2) using the specified Color',
'Draws a line'
));
completionArray.push(functionCompletion(
'DashedLine',
'The Draw.DashedLine procedure is used to draw a dotted or dashed line on the screen from (x1, y1) to (x2, y2) using the specified Color',
'Draws a dashed line'
));
completionArray.push(functionCompletion(
'ThickLine',
'The Draw.ThickLine procedure is used to draw a line on the screen from (x1, y1) to (x2, y2) using the specified Color',
'Draws a line of set thickness'
));
completionArray.push(functionCompletion(
'Box',
'The Draw.Box procedure is used to draw a box on the screen with bottom left and top right corners of (x1, y1) to (x2, y2) using the specified Color',
'Draws a box'
));
completionArray.push(functionCompletion(
'FillBox',
'The Draw.FillBox procedure is used to draw a filled box on the screen with bottom left and top right corners of (x1, y1) to (x2, y2) filled using the specified Color',
'Draws a filled box'
));
completionArray.push(functionCompletion(
'Oval',
'The Draw.Oval procedure is used to draw an oval whose center is at (x, y). The horizontal and vertical distances from the center to the oval are given by xRadius and yRadius',
'Draws an oval'
));
completionArray.push(functionCompletion(
'FillOval',
'The Draw.FillOval procedure is used to draw a filled oval whose center is at (x, y). The horizontal and vertical distances from the center to the oval are given by xRadius and yRadius',
'Draws a filled oval'
));
completionArray.push(functionCompletion(
'Arc',
'The Draw.Arc procedure is used to draw an arc whose center is at (x, y). This is just like drawoval, except that you must also give two angles, initialAngle and finalAngle, which determine where to start and stop drawing',
'Draws an arc'
));
completionArray.push(functionCompletion(
'FillArc',
'The Draw.FillArc procedure is used to draw a filled arc whose center is at (x, y). It then fills in the pie-shaped wedge using the specified Color',
'Draws a filled arc'
));
completionArray.push(functionCompletion(
'Polygon',
'The Draw.Polygon procedure is used to draw a polygon with n points. A line is drawn in Color from the point (x(1), y(1)) to (x(2), y(2)) to (x(3), y(3)) and so on',
'Draws a polygon'
));
completionArray.push(functionCompletion(
'FillPolygon',
'The Draw.FillPolygon procedure is used to draw a filled polygon with n points. The polygon is described by the points (x(1), y(1)) to (x(2), y(2)) to (x(3), y(3)) and so on to (x(n), y (n))',
'Draws a filled polygon'
));
completionArray.push(functionCompletion(
'MapleLeaf',
'The Draw.MapleLeaf procedure is used to draw a maple leaf on the screen bounded by a rectangle described by the bottom left and top right corners of (x1, y1) to (x2, y2) using the specified Color',
'Draws a maple leaf 🍁'
));
completionArray.push(functionCompletion(
'FillMapleLeaf',
'The Draw.FillMapleLeaf procedure is used to draw a filled maple leaf on the screen bounded by a rectangle with bottom left and top right corners of (x1, y1) to (x2, y2) and filled using the specified Color',
'Draws a maple leaf 🍁'
));
completionArray.push(functionCompletion(
'Star',
'The Draw.Star procedure is used to draw a star on the screen bounded by a rectangle described by the bottom left and top right corners of (x1, y1) to (x2, y2) using the specified Color',
'Draws a star'
));
completionArray.push(functionCompletion(
'FillStar',
'The Draw.FillStar procedure is used to draw a filled five pointed star on the screen bounded by a rectangle with bottom left and top right corners of (x1, y1) to (x2, y2) and filled using the specified Color',
'Draws a filled star'
));
completionArray.push(functionCompletion(
'Fill',
'The Draw.Fill procedure is used to color in a figure that is on the screen. Starting at (x, y), the figure is filled with fillColor to a surrounding border whose color is borderColor',
'Fills in shape'
));
completionArray.push(functionCompletion(
'Text',
'Draw.Text is used to actually draw text in a specified font. The textStr parameter contains the string to be drawn. The x and y parameters are the location of the lower left hand corner of the text to be displayed',
'Draws text'
));
}
else if (linePrefix.endsWith('Error.')) {
completionArray.push(variableCompletion(
'Last',
'Error.Last is a function that returns the error code set by the last called predefined subprogram. If there is no error, then it returns eNoError (which is 0). If there is an error, you can use Error.LastMsg to obtain a textual form of the error or Error.LastStr to obtain a string version of the error constant',
'Get last error code'
));
completionArray.push(variableCompletion(
'LastMsg',
'Error.LastMsg is a function that returns the error message set by the last called predefined subprogram. If there is no error, then it returns the empty string. If there is an error, you can use Error.Last to obtain the error code',
'Get last error'
));
completionArray.push(variableCompletion(
'LastStr',
'Error.LastStr is a function that returns the string version of the error code set by the last called predefined subprogram',
'Get last error string'
));
completionArray.push(functionCompletion(
'Msg',
'Error.Msg is a function that returns the error message related to a specified error code. If the error code is eNoError, or if there is no such error code, it returns the empty string. If there is such an error, it returns the textual message associated with that error',
'Get message from error code'
));
completionArray.push(functionCompletion(
'Str',
'Error.Str is a function that returns the error message related to a specified error code. If the error code is eNoError or if there is no such error code, it returns the empty string. If there is such an error, it returns the textual message associated with that error',
'Get string of error code'
));
completionArray.push(functionCompletion(
'Trip',
'Error.Trip is a procedure that sets the error number that is returned by Error.Last and Error.LastMsg. It does not halt the program',
'Trip an error'
));
completionArray.push(functionCompletion(
'TripMsg',
'Error.TripMsg is a procedure that sets the error number and error message that is returned by Error.Last and Error.LastMsg. It does not halt the program',
'Set error message'
));
completionArray.push(functionCompletion(
'Halt',
'Error.Halt is a procedure that immediately halts execution of the program and shows the specified error message on the line in the program that calls Error.Halt',
'Halts the program with an error'
));
}
else if (linePrefix.endsWith('File.')) {
completionArray.push(functionCompletion(
'Exists',
'File.Exists returns true if a file by the name of pathName exists. It will return false if pathName is a directory',
'Checks if file exists'
));
completionArray.push(functionCompletion(
'FullPath',
'File.FullPath returns a string representing the full absolute path name in Turing format (forward slashes) of the path that is passed to the function. The path name passed in does not have to describe an existing file or directory',
'Gets full path to file'
));
completionArray.push(functionCompletion(
'Parent',
'File.Parent returns a string representing the parent directory in Turing format (forward slashes) of the path passed as a parameter. The path name passed in does not have to describe an existing file or directory',
'Gets parent directory'
));
completionArray.push(functionCompletion(
'Status',
'File.Status is used to get assorted information about a file or directory. When the function is called with a specified pathName, it returns the information about the file in the other parameters',
'Gets file information'
));
completionArray.push(functionCompletion(
'Copy',
'File.Copy copies a file named by the srcPathName parameter to the file named by the destPathName parameter. The copy can be between different disks or file systems',
'Copies a file'
));
completionArray.push(functionCompletion(
'Rename',
'File.Copy renames a file or directory named by the srcPathName parameter to the destName parameter. The destName parameter must be a name only',
'Renames a file'
));
completionArray.push(functionCompletion(
'Delete',
'File.Delete is used to delete the file specified by the parameter filePathName. This is the equivalent of doing a del in DOS or rm in UNIX',
'Deletes a file'
));
completionArray.push(functionCompletion(
'DiskFree',
'File.DiskFree gets the number of bytes for the disk upon which pathName resides. The pathName parameter can specify either a file or a directory. If it is the empty string, then File.DiskFree returns the number of bytes of free disk space on the disk upon which the execution directory resides',
'Gets free disk space'
));
}
else if (linePrefix.endsWith('Limits.')) {
completionArray.push(variableCompletion(
'DefaultFW',
'Default fraction width used in printing using the "put" statement',
'Fraction width'
));
completionArray.push(variableCompletion(
'DefaultEW',
'Default exponent width used in printing using the "put" statement',
'Exponent width'
));
completionArray.push(variableCompletion(
'minint',
'The minimum integer in Turing',
'Smallest int'
));
completionArray.push(variableCompletion(
'maxint',
'The maximum integer in Turing',
'Largest int'
));
completionArray.push(variableCompletion(
'minnat',
'The minimum natural number in Turing',
'Smallest natural number'
));
completionArray.push(variableCompletion(
'maxnat',
'The maximum natural number in Turing',
'Largest natural number'
));
completionArray.push(variableCompletion(
'Radix',
'The "radix (usually 2)',
'The root'
));
completionArray.push(variableCompletion(
'NumDigits',
'The number of radix digits in f',
'Number of root digits'
));
completionArray.push(variableCompletion(
'MinExp',
'"minexp" (the smallest exponent allowed)',
'Smallest exponent'
));
completionArray.push(variableCompletion(
'MaxExp',
'"maxexp" (the largest exponent allowed)',
'Largest exponent'
));
completionArray.push(variableCompletion(
'Rreb',
'The relative round-off error bound',
'Rounding error'
));
}
else if (linePrefix.endsWith('Input.')) {
completionArray.push(functionCompletion(
'Pause',
'The Input.Pause procedure simply waits for a key to be pressed and then returns. It echoes the key pressed if echo mode is set. (See View.Set for setting echo mode)',
'Wait for input'
));
completionArray.push(functionCompletion(
'KeyDown',
'The Input.Keydown procedure allows a program to read which keys are currently being pressed. This procedure is different from getch in that it allows a program to detect when a user presses and releases a button. As such, it is not to be used in conjunction with getch',
'Sets parameter to key array'
));
completionArray.push(functionCompletion(
'Flush',
'The Input.Flush procedure empties the keyboard buffer. It is often used to avoid accidentally reading multiple keystrokes because the user pressed a key for too long, causing autorepeat',
'Flush keyboard buffer'
));
}
else if (linePrefix.endsWith('Math.')) {
completionArray.push(variableCompletion(
'PI',
'The constant Pi π = ~3.1415 ',
'Pi (3.1415)'
));
completionArray.push(variableCompletion(
'E',
'Eulers number e = ~2.7183 ',
'Eulers number (2.7182)'
));
completionArray.push(functionCompletion(
'Distance',
'Math.Distance is used to calculate the distance between two points. (x1, y1) is the location of the first point, and (x2, y2) is the location of the second point',
'Distance between two points'
));
completionArray.push(functionCompletion(
'DistancePointLine',
'Math.DistancePointLine is used to calculate the distance between a point and a line segment. It is often used in games to determine if a collision has occurred. (xp, yp) is the location between the point. (x1, y1) and (x2, y2) are the end points of the line segment',
'Distance between point and line segment'
));
}
else if (linePrefix.endsWith('Mouse.')) {
completionArray.push(functionCompletion(
'Where',
'The Mouse.Where procedure is used to get current information about the status of the mouse. The parameters x and y are set to the current location of the mouse cursor. If the program is running on a system using windows, the cursor may be outside the window. This means that x and y may be set to values outside of the bounds of 0 to maxx and 0 to maxy',
'Location of mouse'
));
completionArray.push(functionCompletion(
'ButtonMoved',
'The Mouse.ButtonMoved function indicates whether there is a mouse event of the appropriate type on the mouse queue. Events are either "up", "down", "updown" or "downup" events (although the "downup" and "updown" are the same event)',
'Check if user is pressing button'
));
completionArray.push(functionCompletion(
'ButtonWait',
'The Mouse.ButtonWait procedure gets information about a mouse event and removes it from the queue',
'Wait until press event'
));
completionArray.push(functionCompletion(
'ButtonChoose',
'The Mouse.ButtonChoose procedure is used to change the mode of the mouse. In Turing, the mouse can either be in "single-button mode" or in "multi-button mode". In "single-button mode" the mouse is treated as a one button mouse. A button is considered pressed when any button is pressed and released only when all buttons have been released',
'Change mouse mode'
));
}
else if (linePrefix.endsWith('Music.')) {
completionArray.push(functionCompletion(
'Play',
'The Music.Play procedure is used to sound musical notes on the computer',
'Plays note(s)'
));
completionArray.push(functionCompletion(
'PlayFile',
'The Music.PlayFile procedure is used to play a file of music. The file must be in one of the acceptable formats and the machine, must have the appropriate hardware',
'Play from file'
));
completionArray.push(functionCompletion(
'PlayFileReturn',
'The Music.PlayFileReturn procedure is used to play a file of music. The file must be in one of the acceptable formats and the machine, must have the appropriate hardware',
'Play without wait'
));
completionArray.push(functionCompletion(
'PlayFileLoop',
'The Music.PlayFileLoop procedure is used to play a file of music continuously, looping until the program is halted or the Music.PlayFileStop command is given. The file must be in one of the acceptable formats and the machine, must have the appropriate hardware',
'Loop music file'
));
completionArray.push(functionCompletion(
'PlayFileStop',
'The Music.PlayFileStop procedure is used to to stop all music files currently playing. This includes processes that are executing the Music.PlayFile procedure (they exit immediately and start executing the next statement in the process), and the Music.PlayFileReturn and Music.PlayFileLoop statements, which simply stop playing the music',
'Stop play'
));
completionArray.push(functionCompletion(
'Sound',
'The Music.Sound statement is used to cause the computer to sound a note of a given frequency for a given time. The frequency is in cycles per second (Hertz). The time duration is in milliseconds. For example, middle A on a piano is 440 Hertz, so Music.Sound(440, 1000) plays middle A for one second',
'Play frequency'
));
completionArray.push(functionCompletion(
'SoundOff',
'The Music.SoundOff procedure stops any sound or music that is currently playing or is waiting to play',
'Turns off all music'
));
}
else if (linePrefix.endsWith('Net.')) {
completionArray.push(functionCompletion(
'WaitForConnection',
'Listens for a connection at the port specified by the port parameter. When another program connects to the port, then the function returns. The address of the connecting machine is specified in the netAddr parameter and the Net.WaitForConnection returns a network stream descriptor which can be used with the put, get, read, and write statements and eof function to send and receive data to the connecting program. It is also the parameter used for the Net.CloseConnection, Net.BytesAvailable, Net.CharAvailable, Net.LineAvailable, and Net.TokenAvailable functions',
'Wait for a tcp connection'
));
completionArray.push(functionCompletion(
'OpenConnection',
'Attempts to open a connection to port specified by the port parameter on the machine specified by netAddr parameter. There must be a program listening to that port for the connection to be made. In OOT, this is done using the Net.WaitForConnection function',
'Local tcp connection'
));
completionArray.push(functionCompletion(
'OpenURLConnection',
'Attempts to open a http connection to pthe URL (Universal Resource Locator) specified by the urlAddr',
'Tcp connection by url'
));
completionArray.push(functionCompletion(
'CloseConnection',
'Closes a network connection made with Net.OpenConnection or Net.WaitForConnection. After the connection is closed, the net stream cannot be used for any purpose on either side of the connection',
'Close tcp connection'
));
completionArray.push(functionCompletion(
'BytesAvailable',
'Returns the number of bytes available for reading from the net stream specified by the netStream parameter',
'Size of byte stream'
));
completionArray.push(functionCompletion(
'CharAvailable',
'Returns true if a character is waiting to be read from the net stream specified by the netStream parameter. If Net.CharAvailable returns true, then a single character can be read from the stream without blocking',
'Char can be read'
));
completionArray.push(functionCompletion(
'LineAvailable',
'Returns true if a line of input is waiting to be read from the net stream specified by the netStream parameter. If Net.LineAvailable returns true, then a line of input can be read from the stream without blocking',
'Line can be read'
));
completionArray.push(functionCompletion(
'TokenAvailable',
'Returns true if a line of input is waiting to be read from the net stream specified by the netStream parameter. If Net.TokenAvailable returns true, then a single token (character surrounded by whitespace) can be read from the stream without blocking',
'Token can be read'
));
completionArray.push(functionCompletion(
'HostAddressFromName',
'Returns the numeric TCP/IP address of the machine whose hostname is specified by the hostName parameter',
'Get hostname'
));
completionArray.push(functionCompletion(
'HostNameFromAddress',
'Returns the TCP/IP hostname of the machine whose numeric address is specified by the hostAddr parameter',
'Get hostname from url'
));
completionArray.push(variableCompletion(
'LocalAddress',
'Returns the TCP/IP numeric address of the machine the program is running on. The numeric address is of the form xxx.yyy.zzz.www where each segment is a number from 0 to 255',
'Returns local ip address'
));
completionArray.push(variableCompletion(
'LocalName',
'Returns the TCP/IP hostname of the machine the program is running on',
'Returns local host name'
));
}
else if (linePrefix.endsWith('PC.')) {
completionArray.push(functionCompletion(
'ParallelGet',
'The PC.ParallelGet procedure is used on a PC to read the value of certain pins on the parallel port. This port corresponds to the MS-DOS device "LPT1". This procedure can be used to control robots and peripherals',
'Retrieves parallel data'
));
completionArray.push(functionCompletion(
'ParallelGet',
'The PC.ParallelGet procedure is used on a PC to set the values on the data pins on the parallel port. This port corresponds to the MS-DOS device "LPT1". This procedure can be used to control robots and peripherals',
'Sends parallel data'
));
}
else if (linePrefix.endsWith('Rand.')) {
completionArray.push(functionCompletion(
'Real',
'The Rand.Real function returns a pseudo-random number in the range zero to one. For example, if x is a real number, after x := Rand.Real, x would have a value such as 0.729548 or 0.352879',
'Random real generator'
));
completionArray.push(functionCompletion(
'Int',
'The Rand.Int statement is used to create a pseudo-random integer in the range low to high, inclusive. For example, if i is an integer, after randint(i,1, 10), i would have a value such as 7 or 2 or 10',
'Random int generator'
));
completionArray.push(functionCompletion(
'Reset',
'This is a procedure with no parameters that resets the sequences of pseudo-random numbers produced by Rand.Real and Rand.Int. This allows identical executions of the same program to produce identical results',
'Determinizes randomness'
));
completionArray.push(functionCompletion(
'Set',
'This procedure sets the seed for sequences of pseudo-random numbers produced by Rand.Real and Rand.Int. This allows identical executions of the same program to produce identical results',
'Set the random seed'
));
completionArray.push(functionCompletion(
'Next',
'The Rand.Next procedure is used when you need several sequences of pseudo-random numbers, and you need to be able to exactly repeat these sequences for a number of simulations. The Rand.Next procedure is the same as rand, except seq specifies one of ten independent and repeatable sequences of pseudo-random real numbers',
'Next predetermined number'
));
completionArray.push(functionCompletion(
'Seed',
'The Rand.Seed procedure restarts one of the sequences generated by Rand.Next. Each restart with the same seed causes Rand.Next to produce the same sequence for the given sequence',
'Resets randomness for next'
));
}
else if (linePrefix.endsWith('RGB.')) {
completionArray.push(functionCompletion(
'GetColour',
'The RGB.GetColour procedure returns the red, green and blue components to the color associated with the colorNumber parameter. The red, green and blue values are normalized to be between 0 and 1. Thus color white returns 1.0 for the redComp, greenComp and blueComp values and colour black returns 0.0 for all three',
'Get rgb of colour id'
));
completionArray.push(functionCompletion(
'SetColour',
'The RGB.SetColour function sets the red, green and blue components of the color associated with the colourNumber parameter. The red, green and blue values must normalized to be between 0 and 1',
'Set rgb of colour id'
));
completionArray.push(functionCompletion(
'AddColour',
'The RGB.AddColour function attempts to create a new colour with the red, green and blue components specified. If successful, the function returns a new color number (usually one greater than maxcolor) and maxcolor is updated by adding 1 to it. If it is unsuccessful, the function returns 1 and Error.Last and Error.LastMsg can be used to determine the cause of the problem',
'Creates new colour'
));
}
else if (linePrefix.endsWith('Stream.')) {
completionArray.push(functionCompletion(
'Flush',
'The Stream.Flush procedure is used to flush any buffered output associated with the streamNumber parameter',
'Flush file buffer'
));
completionArray.push(functionCompletion(
'FlushAll',
'The Stream.FlushAll procedure is used to flush any buffered output in any open file',
'Flush all file buffer'
));
}
else if (linePrefix.endsWith('Str.')) {
completionArray.push(functionCompletion(
'Lower',
'The Str.Lower function takes the string s and returns a string in which all the upper case letters are converted to lower case. For example, Str.Lower ("ABC123def") returns "abc123def"',
'Converts to lower case'
));
completionArray.push(functionCompletion(
'Upper',
'The Str.Upper function takes the string s and returns a string in which all the lower case letters are converted to upper case. For example, Str.Upper ("ABC123def") returns "ABC123DEF"',
'Converts to upper case'
));
completionArray.push(functionCompletion(
'Trim',
'The Str.Trim function takes the string str and returns a string in all the leading and trailing spaces (the spaces at the beginning and the end) are deleted. For example, Str.Trim (" This is a test ") returns "This is a test". If str only has spaces in it, then Str.Trim will return an empty string',
'Remove whitespace'
));
}
else if (linePrefix.endsWith('Sys.')) {
completionArray.push(functionCompletion(
'GetComputerName',
'The Sys.GetComputerName function is used to determine the name of the computer. On the PC, this is the NetBIOS name. It returns “No Name” if a name could not be determined',
'Get name of PC'
));
completionArray.push(functionCompletion(
'GetEnv',
'The Sys.GetEnv function is used to access the environment string whose name is symbol. These strings are determined by the shell (command processor) or the program that caused your program to run. See also the Sys.Nargs and Sys.FetchArg functions',
'Get turing properties'
));
completionArray.push(functionCompletion(
'GetPid',
'The Sys.GetPid function is used to determine the I.D. (number) that identifies the current operating system task (process). Beware that there are processes, activated by the fork statement, that are independent of the operating systems tasks',
'Get Process id'
));
completionArray.push(functionCompletion(
'GetUserName',
'The Sys.GetUserName function is used to determine the name of the current user. It returns “Unknown” if a name could not be determined',
'Get name of user'
));
completionArray.push(functionCompletion(
'Exec',
'The Sys.Exec function is used to execute an application or more often, open a data file with its associated application. Sys.Exec can be used to launch such programs as the Internet Browser by specifying a URL. Sys.Exec launches the application associated with file\'s suffix. (In essence, it performs the same operation as if a user double clicked on the file.)',
'Runs a file or program'
));
completionArray.push(variableCompletion(
'Nargs',
'The Sys.Nargs function is used to determine the number of arguments that have been passed to a program from the command line. For example, if the program is run from the Turing environment using',
'Number of arguments passed in'
));
completionArray.push(functionCompletion(
'FetchArg',
'The Sys.FetchArg function is used to access the i-th argument that has been passed to a program from the command line',
'Get arguments passed in'
));
}
else if (linePrefix.endsWith('Text.')) {
completionArray.push(variableCompletion(
'WhatRow',
'The Text.WhatRow function is used to determine the cursor position\'s row',
'Get current row'
));
completionArray.push(variableCompletion(
'WhatCol',
'The Text.WhatCol function is used to determine the cursor position\'s column',
'Get current column'
));
completionArray.push(variableCompletion(
'WhatColour',
'The Text.WhatColour function is used to determine the current text (foreground) colour, ie., the color used for characters that are output using put',
'Get current text colour'
));
completionArray.push(variableCompletion(
'WhatColourBack',
'The Text.WhatColourBack function is used to determine the current text background colour',
'Get current background colour'
));
completionArray.push(functionCompletion(
'Cls',
'The Text.Cls (clear screen) procedure is used to blank the screen to the text background color. The cursor is set to the top left (to row 1, column 1)',
'Clears screen'
));
completionArray.push(functionCompletion(
'Colour',
'The Text.Colour procedure is used to change the currently-active colour. This is the colour of characters that are to be put on the screen',
'Change text colour'
));
completionArray.push(functionCompletion(
'ColourBack',
'The Text.ColourBack procedure is used to change the current text background colour',
'Change background colour'
));
completionArray.push(functionCompletion(
'Locate',
'The Text.Locate procedure is used to move the cursor so that the next output from put will be at the given row and column. Row 1 is the top of the screen and column 1 is the left side of the screen',
'Move curser to position'
));
completionArray.push(functionCompletion(
'LocateXY',
'The Text.LocateXY procedure is used to move the cursor so that the next output from put will be at approximately (x, y). The exact location may be somewhat to the left of x and below y to force alignment to a character boundary',
'Move curser (pixels)'
));
}
else if (linePrefix.endsWith('Time.')) {
completionArray.push(functionCompletion(
'SecDate',
'The Time.SecDate function is used to convert the number of seconds since 00:00:00 GMT Jan 1, 1970 into a date and time string',
'Current time in seconds'
));
completionArray.push(functionCompletion(
'DateSec',
'The Time.DateSec function is used to convert a date and time string into a number, specifically, the number of seconds since 00:00:00 GMT Jan 1, 1970',
'Convert date str to seconds'
));
completionArray.push(functionCompletion(
'SecParts',
'The Time.SecParts function is used to convert a single number form of the time (the number of seconds since 00:00:00 GMT Jan 1, 1970) into a date with numeric component parts',
'Convert date to seconds'
));
completionArray.push(functionCompletion(
'PartsSec',
'The Time.PartsSec function is used to convert the numeric parts of a date (specifically the year, month, day, hour, minute and second) into the number of seconds since 00:00:00 GMT Jan 1, 1970 and the date specified by the parts',
'Convert date to seconds'
));
completionArray.push(functionCompletion(
'SecStr',
'The Time.SecStr function is used to convert the number of seconds since 00:00:00 GMT Jan 1, 1970 into a date and time string',
'Convert seconds to date str'
));
completionArray.push(functionCompletion(
'Delay',
'The Time.Delay procedure is used to cause the program to pause for a given time. The time duration is in milliseconds',
'Waits specified time (ms)'
));
completionArray.push(functionCompletion(
'DelaySinceLast',
'The Time.DelaySinceLast procedure is used to cause the program to pause for a given time since the last call to Time.DelaySinceLast. The time duration is in milliseconds',
'Time since last call'
));
completionArray.push(variableCompletion(
'Sec',
'The Time.Sec function returns the current date and time as a number. The returned integer is the time in seconds since 00:00:00 GMT (Greenwich Mean Time) January 1, 1970',
'Current time in seconds'
));
completionArray.push(variableCompletion(
'Date',
'The Time.Date function returns the current date and time as a string. The returned string in the format "dd mmm yy hh:mm:ss", where mmm is the first 3 characters of the month, e.g., "Apr". For example, if the date is Christmas 1989 at 9:02:37 in the morning, Time.Date will return "25 Dec 89 09:02:37". Twenty-four hour time is used, so eleven thirty at night the same day would return "25 Dec 89 23:30:00"',
'Current date string'
));
completionArray.push(variableCompletion(
'Elapsed',
'The Time.Elapsed function returns the amount of time since a program (process) started running. The number of milliseconds since the program started running is returned',
'Elapsed time'
));
completionArray.push(variableCompletion(
'ElapsedCPU',
'The Time.ElapsedCPU function is used on a multitasking system such as UNIX to determine the amount of time that has been used by this program (process). The number of central processor milliseconds assigned to this program is returned. This is of little use on a personal computer, where Time.ElapsedCPU returns the same value as Time.Elapsed',
'Elapsed cpu time'
));
}
else if (linePrefix.endsWith('View.')) {
completionArray.push(variableCompletion(
'maxx',
'The View.maxx function is used to determine the maximum value of x for the current graphics mode',
'Max x coordinate'
));
completionArray.push(variableCompletion(
'maxy',
'The View.maxy function is used to determine the maximum value of y for the current graphics mode',
'Max y coordinate'
));
completionArray.push(variableCompletion(
'maxcolour',
'The View.maxcolour function is used to determine the maximum colour number for the current mode of the screen',
'Max colour id'
));
completionArray.push(functionCompletion(
'Set',
'The View.Set statement is used to change the mode of the screen, as well as the way in which Turing does input and output. The parameter to View.Set is a string, such as "graphics". The string contains one or more options separated by commas, such as "text, noecho". View.Set affects the active window',
'Set View mode'
));
completionArray.push(functionCompletion(
'ClipSet',
'The View.ClipSet procedure sets the clipping region to the rectangle specified by (x1, y1) - (x2, y2). If a clipping region already exist, it is replaced by the specified rectangle',
'Set clip rectangle'
));
completionArray.push(functionCompletion(
'ClipAdd',
'The View.ClipAdd procedure adds another rectangle specified by (x1, y1) - (x2, y2) to the clipping region. This only works on systems that support complex clipping regions. If no clipping region has been specified, then the rectangle becomes the complete clipping region',
'Add clip rectangle'
));
completionArray.push(functionCompletion(
'ClipAddOval',
'The View.ClipAddOval procedure adds another oval specified by (x, y) and xradius and yradius) to the clipping region. If no clipping region has been specified, then the oval becomes the complete clipping region',
'Add clip oval'
));
completionArray.push(functionCompletion(
'ClipOff',
'The View.ClipOff procedure turns off clipping. This means that any drawing commands can appear on the entire drawing surface (the screen or the window, depending on the system)',
'Turns off clipping'
));
completionArray.push(functionCompletion(
'WhatDotColour',
'The View.WhatDotColour function is used to determine the colour number of the specified pixel',
'Colour of pixel'
));
completionArray.push(functionCompletion(
'Update',
'The View.Update procedure updates a Run window from an offscreen bitmap. It is used with the command View.Set ("offscreenonly") which prevents the Run window from being updated until the View.Update command is given',
'Update screen'
));
completionArray.push(functionCompletion(
'UpdateArea',
'The View.UpdateArea procedure updates a rectanglular area Run window, specified by (x1, y1) - (x2, y2) from the offscreen bitmap. It is used with the command View.Set ("offscreenonly") which prevents the Run window from being updated until the View.UpdateArea or View.Update command is given',
'Update rectangle'
));
}
else if (linePrefix.endsWith('Window.')) {
completionArray.push(functionCompletion(
'Open',
'The Window.Open function is used to create a window. A window ID is returned if the window is successfully created. If the window is not created then it returns 0. Error.Last and Error.LastMsg can then be used to determine the cause of the failure',
'Create new window'
));
completionArray.push(functionCompletion(
'Close',
'The Window.Close procedure closes the window specified by the windowID parameter',
'Closes specific window'
));
completionArray.push(functionCompletion(
'Select',
'The Window.Select selects the window that output is to be sent to',
'Selects window for input'
));
completionArray.push(functionCompletion(
'GetSelect',
'The Window.GetSelect function returns the window ID of the selected window. If the select window is the main (default) run window, then it returns defWinID (which is -1)',
'Gets id of selected window'
));
completionArray.push(functionCompletion(
'SetActive',
'The Window.SetActive procedure activates the window specified by the windowID parameter',
'Selects window'
));
completionArray.push(functionCompletion(
'GetActive',
'The Window.GetActive function returns the window ID of the active window. If the active window is a Turing run window, then Window.GetActive returns defWinID (which is -1) if the window is the default run window, or whatever number was returned from Window.Open for any other run window',
'Get active window id'
));
completionArray.push(functionCompletion(
'GetPosition',
'The Window.GetPosition procedure returns the location of the specified execution window on the screen in the x and y parameters. The x and y parameters specify the lower left corner of the window in screen coordinates. (0, 0) is the lower left corner of the screen',
'Get window position'
));
completionArray.push(functionCompletion(
'SetPosition',
'The Window.SetPosition procedure moves the location of the specified execution window on the screen. x and y specify the lower left corner of the window in screen coordinates. (0, 0) is the lower left corner of the screen',
'Set window position'
));
completionArray.push(functionCompletion(
'Hide',
'The Window.Hide procedure hides the specified window. This means it disappears from the user\'s screen. However, it is still possible to select and draw the window while it remains hidden. If the user activates it (using Window.GetActive) it will automatically appear',
'Hides window from user'
));
completionArray.push(functionCompletion(
'Show',
'The Window.Show procedure makes the specified window appear if it was invisible',
'Show window to user'
));
completionArray.push(functionCompletion(
'Set',
'The Window.Set procedure sets the configuration of the window specified by the windowID parameter. See View.Set for a complete list of available options. The setUpString parameter can be any combination options, separated by commas. Here is a selection of the available options',
'Set window properties'
));
completionArray.push(functionCompletion(
'Update',
'The Window.Update procedure updates a specified Run window from an offscreen bitmap. It is used with the command View.Set("offscreenonly") which prevents the Run window from being updated until the Window.Update command is given',
'Update window from offscreen'
));
}
// Complete the modules themselves
else if (!linePrefix.endsWith('.')){
completionArray.push(moduleCompletion(
'Config',
'This unit contains the predefined subprograms that deal with getting configuration information about the machine and environment on which the program is being run',
'Machine properties'
));
completionArray.push(moduleCompletion(
'Dir',
'This unit contains the predefined subprograms that deal with directories. You can use these subprograms to list the contents of directories, create directories, change directories and return the current directory',
'Manages current directory'
));
completionArray.push(moduleCompletion(
'Draw',
'This unit contains the predefined subprograms that deal with drawing pixel graphics to the screen. Most methods require view be set to "graphics"',
'Drawing to screen'
));
completionArray.push(moduleCompletion(
'Error',
'This unit contains the predefined subprograms that deal with errors returned from other predefined subprograms',
'Error Handling'
));
completionArray.push(moduleCompletion(
'File',
'This unit contains the predefined subprograms that deal with file manipulation on a whole-file basis (as opposed to manipulating the data in the file using open and close, etc.). These routines allow you to rename, copy and delete files, as well as get information about a file and get the free space on disk available for a file',
'File IO'
));
completionArray.push(moduleCompletion(
'Input',
'This unit contains the predefined procedures that deal with handling input on a character-by-character basis',
'Keyboard input'
));
completionArray.push(moduleCompletion(
'Limits',
'This unit contains constants and functions used in determining the mathematical accuracy of the language.',
'Datatype limits'
));
completionArray.push(moduleCompletion(
'Math',
'This unit contains all the mathematical routines. There are three routines that are part of the language, but are conceptually part of the Math unit',
'Mathematical operations'
));
completionArray.push(moduleCompletion(
'Mouse',
'This unit contains the predefined subprograms that deal with using the mouse in a Turing program',
'Mouse control'
));
completionArray.push(moduleCompletion(
'Music',
'This unit contains the predefined subprograms that deal with sound and music. Some of these routines have not been implemented at the time of the writing of this manual and will be implemented in future releases',
'Music control'
));
completionArray.push(moduleCompletion(
'Net',
'The Net module allows TCP/IP equipped machines to communicate. In the current implementation (WinOOT 3.0), this is available only under Win32 (Windows 95, 98, NT and later)',
'Internet communication'
));
completionArray.push(moduleCompletion(
'PC',
'This unit contains the predefined subprograms that deal with direct access to the hardware under the IBM PC architecture',
'PC interface'
));
completionArray.push(moduleCompletion(
'RGB',
'This unit contains the predefined constants for the basic colors and the subprograms to change the color palette',
'RGB Color'
));
completionArray.push(moduleCompletion(
'Stream',
'This unit contains the predefined subprograms that deal with I/O streams. The basic I/O in Turing is done with I/O statements. However, extra functions are all part of the Stream unit',
'File stream'
));
completionArray.push(moduleCompletion(
'Str',
'This unit contains the predefined constants for manipulating strings',
'String manipulation'
));
completionArray.push(moduleCompletion(
'Sys',
'This unit contains the predefined subprograms that deal with the operating system directly (getting the process id, getting run time arguments and executing commands in the operating system, etc.)',
'System information'
));
completionArray.push(moduleCompletion(
'Text',
'This unit contains the predefined subprograms that handle character (text) output on the screen (i.e. output using put)',
'Text unit'
));
completionArray.push(moduleCompletion(
'Time',
'This unit contains the predefined subprograms that handle anything to do with time, either as a date or as a timer',
'Time unit'
));
completionArray.push(moduleCompletion(
'View',
'This unit contains the predefined subprograms that deal with the current output surface, which is a window',
'View properties'
));
completionArray.push(moduleCompletion(
'Window',
'This unit contains the predefined subprograms that handle windows. There are routines to open, close, hide, show and select windows',
'Window properties'
));
// All modules
}
return completionArray;
}
}, '.'
);
|
3315a890800c1df43e8d6a6c893d6025756290e0
|
TypeScript
|
bokeh/bokeh
|
/bokehjs/test/integration/colors.ts
| 2.90625
| 3
|
import {column, display, fig, row} from "./_util"
import {ColumnDataSource, GlyphRenderer, Circle} from "@bokehjs/models"
import type {ColorNDArray} from "@bokehjs/api/glyph_api"
import type {OutputBackend} from "@bokehjs/core/enums"
import * as nd from "@bokehjs/core/util/ndarray"
import {isArrayable} from "@bokehjs/core/util/types"
import type {Value, Vector} from "@bokehjs/core/vectorization"
import type {Color, Arrayable} from "@bokehjs/core/types"
type ColorArg = Value<Color | null> | Arrayable<Color | null> | ColorNDArray
type AlphaArg = Value<number> | Arrayable<number>
describe("Color support", () => {
const N = 4
const x = [0, 1, 2, 4]
const y = [0, 1, 2, 4]
const radius = [4, 1, 2, 3]
function plot_api(color: ColorArg, alpha?: AlphaArg) {
const p = fig([120, 120], {x_range: [-6, 6], y_range: [-6, 6]})
p.circle({x, y, radius, fill_color: color, fill_alpha: alpha, line_color: null})
return p
}
function plot_glyph(color: ColorArg, alpha?: AlphaArg) {
const p = fig([120, 120], {x_range: [-6, 6], y_range: [-6, 6]})
const source = new ColumnDataSource({data: {x, y, radius}})
const fill_color: Vector<Color | null> = (() => {
if (isArrayable(color) || nd.is_NDArray(color)) {
source.data.fill_color = color
return {field: "fill_color"}
} else
return color
})()
const fill_alpha: Vector<number> | undefined = (() => {
if (isArrayable(alpha) || nd.is_NDArray(alpha)) {
source.data.fill_alpha = alpha
return {field: "fill_alpha"}
} else
return alpha
})()
const glyph = new Circle({radius: {field: "radius"}, fill_color, fill_alpha, line_color: null})
const circle = new GlyphRenderer({data_source: source, glyph})
p.add_renderers(circle)
return p
}
function plot(color: ColorArg, alpha?: AlphaArg) {
return row([plot_api(color, alpha), plot_glyph(color, alpha)], {width: 240, height: 120})
}
function plot_alpha_combinations(color: ColorArg) {
const scalar_alpha = {value: 0.5}
const vector_alpha = [0.75, 1, 0.5, 0.25]
return column([plot(color), plot(color, scalar_alpha), plot(color, vector_alpha)])
}
it("should allow arrays of named colors", async () => {
const colors = ["yellow", "red", "lime", "blue"]
await display(plot_alpha_combinations(colors))
})
it("should allow arrays of #RRGGBB colors", async () => {
const colors = ["#ffff00", "#ff0000", "#00ff00", "#0000ff"]
await display(plot_alpha_combinations(colors))
})
it("should allow arrays of #RRGGBBAA colors", async () => {
const colors = ["#ffff00ff", "#ff0000ff", "#00ff00c0", "#0000ffc0"]
await display(plot_alpha_combinations(colors))
})
it("should allow arrays of rgb(r g b) colors", async () => {
const colors = ["rgb(255 255 0)", "rgb(255 0 0)", "rgb(0 255 0)", "rgb(0 0 255)"]
await display(plot_alpha_combinations(colors))
})
it("should allow arrays of rgb(r g b / a) colors", async () => {
const colors = ["rgb(255 255 0 / 1.0)", "rgb(255 0 0 / 1.0)", "rgb(0 255 0 / 0.75)", "rgb(0 0 255 / 0.75)"]
await display(plot_alpha_combinations(colors))
})
it("should allow arrays of other CSS4 colors", async () => {
const colors = ["hsl(60deg 100% 50% / 1.0)", "hsl(0deg 100% 50% / 1.0)", "hsl(120deg 100% 50% / 0.75)", "hsl(240deg 100% 50% / 0.75)"]
await display(plot_alpha_combinations(colors))
})
it("should allow arrays of RGB tuples", async () => {
const colors: Color[] = [[255, 255, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255]]
await display(plot_alpha_combinations(colors))
})
it("should allow arrays of RGBA tuples", async () => {
const colors: Color[] = [[255, 255, 0, 1.0], [255, 0, 0, 1.0], [0, 255, 0, 0.75], [0, 0, 255, 0.75]]
await display(plot_alpha_combinations(colors))
})
it("should allow arrays of 32-bit unsigned integers", async () => {
const colors = [0xffff00ff, 0xff0000ff, 0x00ff00c0, 0x0000ffc0]
await display(plot_alpha_combinations(colors))
})
it("should allow uint32[N] arrays", async () => {
const colors = nd.ndarray([
0xffff00ff,
0xff0000ff,
0x00ff00c0,
0x0000ffc0,
], {dtype: "uint32", shape: [N]})
await display(plot_alpha_combinations(colors))
})
it("should allow uint8[N, 3] arrays", async () => {
const colors = nd.ndarray([
255, 255, 0,
255, 0, 0,
0, 255, 0,
0, 0, 255,
], {dtype: "uint8", shape: [N, 3]})
await display(plot_alpha_combinations(colors))
})
it("should allow uint8[N, 4] arrays", async () => {
const colors = nd.ndarray([
255, 255, 0, 255,
255, 0, 0, 255,
0, 255, 0, 192,
0, 0, 255, 192,
], {dtype: "uint8", shape: [N, 4]})
await display(plot_alpha_combinations(colors))
})
it("should allow float[N, 3] arrays", async () => {
const colors = nd.ndarray([
1.0, 1.0, 0.0,
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
], {dtype: "float32", shape: [N, 3]})
await display(plot_alpha_combinations(colors))
})
it("should allow float[N, 4] arrays", async () => {
const colors = nd.ndarray([
1.0, 1.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
0.0, 1.0, 0.0, 0.75,
0.0, 0.0, 1.0, 0.75,
], {dtype: "float32", shape: [N, 4]})
await display(plot_alpha_combinations(colors))
})
it("should allow object[N] arrays", async () => {
const colors = nd.ndarray([
"#ffff00ff",
"#ff0000ff",
"#00ff00c0",
"#0000ffc0",
], {dtype: "object", shape: [N]})
await display(plot_alpha_combinations(colors))
})
it("should combine alpha for line, fill and hatch on all output backends", async () => {
const x = [0, 1, 2]
const xs = [[0, 1], [1, 2], [2, 3]]
const ys = [[2, 3], [2, 3], [2, 3]]
const color = "#000080c0"
const alpha = [1.0, 0.75, 0.5]
const width = 0.9
const height = 0.9
function p(output_backend: OutputBackend) {
const p = fig([200, 250], {output_backend, title: output_backend})
p.multi_line({xs, ys, line_color: color, line_alpha: alpha, line_width: 15})
p.block({x, y: 1, width, height, fill_color: color, fill_alpha: alpha})
p.block({x, y: 0, width, height, fill_color: null, hatch_pattern: "@", hatch_color: color, hatch_alpha: alpha})
return p
}
await display(row([p("canvas"), p("svg"), p("webgl")]))
})
})
|