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
|
|---|---|---|---|---|---|---|
2bc9619b2774b11cb12baba4eeab440cef5006ac
|
TypeScript
|
MarioACo/Sueldo
|
/sueldo.ts
| 3.015625
| 3
|
class sueldo{
public nombre:string = (<HTMLInputElement>document.getElementById("nombre")).value;
public sueldom:number = parseFloat((<HTMLInputElement>document.getElementById("sueldo")).value);
public horas:number = parseInt((<HTMLInputElement>document.getElementById("horas")).value);
public hextras:number = parseInt((<HTMLInputElement>document.getElementById("hextras")).value);
public setNombre():any{
(<HTMLInputElement>document.getElementById("nombreT")).value = this.nombre;
}
public calcularSueldo():number{
let suel:number = this.sueldom * this.horas;
if(this.hextras > 0){
let suelh:number = this.sueldom * (this.hextras * 2);
suel = suel + suelh;
}
return suel;
}
public calcularImpuesto():number{
let impuesto:number = this.calcularSueldo() / 100;
impuesto = impuesto * 16;
return impuesto;
}
public calcularSueldoNeto():number{
let sueldoN:number = this.calcularSueldo() - this.calcularImpuesto();
return sueldoN;
}
public resultados(){
(<HTMLInputElement>document.getElementById("sueldoh")).value = this.calcularSueldo().toString();
(<HTMLInputElement>document.getElementById("impuesto")).value = this.calcularImpuesto().toString();
(<HTMLInputElement>document.getElementById("sueldof")).value = this.calcularSueldoNeto().toString();
}
}
function calcular(){
let objeto = new sueldo();
let nombre:string = (<HTMLInputElement>document.getElementById("nombre")).value;
let sueldom:string = (<HTMLInputElement>document.getElementById("sueldo")).value;
let horas:string = (<HTMLInputElement>document.getElementById("horas")).value;
let hextras:string = (<HTMLInputElement>document.getElementById("hextras")).value;
if(nombre==""){
alert("Debes de agregar el nombre");
return false;
}else if(sueldom == ""){
alert("Debes de agregar el sueldo");
return false;
}else if(horas == ""){
alert("Debes de agregar las horas");
return false;
}else if(hextras == ""){
alert("Debes de agregar las horas extras o en su defecto poner 0");
return false;
}else{
$('#exampleModal').modal('show');
}
objeto.setNombre();
objeto.resultados();
}
function limpiar(){
(<HTMLInputElement>document.getElementById("nombre")).value = "";
(<HTMLInputElement>document.getElementById("sueldo")).value = "";
(<HTMLInputElement>document.getElementById("horas")).value = "";
(<HTMLInputElement>document.getElementById("hextras")).value = "";
}
|
35e04611c5f832ac8a1c85c6d8ac97e39bff6b46
|
TypeScript
|
G3F4/moxy-proxy
|
/server/infrastructure/sockets-client/SocketsClient.ts
| 2.671875
| 3
|
//@ts-ignore
import * as WebSocket from 'ws';
import { ClientAction, ServerEvent } from '../../../sharedTypes';
import { logError } from '../../utils/logger';
export default class SocketsClient {
sockets: WebSocket[] = [];
clientMessageHandlers: Record<
string,
(payload: unknown) => Promise<void>
> = {};
private generateSocketId() {
return Date.now();
}
connect(socket: WebSocket, onDisconnect: (socketId: string) => void): string {
this.addSocket(socket);
socket.id = this.generateSocketId();
socket.on('message', async (message: string) => {
await this.handleClientMessage(message);
});
socket.on('close', () => {
this.deleteSocket(socket);
onDisconnect(socket.id);
});
return socket.id;
}
registerMessageHandlers(
handlers: Record<string, (payload: unknown) => Promise<void>>,
) {
this.clientMessageHandlers = handlers;
}
async sendEventToSocket(socketId: string, event: ServerEvent) {
const socket = this.getSocket(socketId);
await this.sendEvent(socket, event);
}
async broadcastEvent(event: ServerEvent) {
await Promise.all(
this.sockets.map(async (socket) => {
try {
await socket.send(JSON.stringify(event));
} catch (e) {
logError(e);
this.clearSocket(socket.id);
}
}),
);
}
private async sendEvent(
socket: WebSocket,
event: ServerEvent,
): Promise<void> {
try {
await socket.send(JSON.stringify(event));
} catch (e) {
logError(e);
}
}
private async handleClientMessage(message: string) {
const { action, payload } = this.parseClientMessage(message);
const handler = this.clientMessageHandlers[action];
await handler(payload);
}
private addSocket(socket: WebSocket) {
this.sockets.push(socket);
}
private deleteSocket(socket: WebSocket) {
this.sockets = this.sockets.filter(({ id }) => id === socket.id);
}
private clearSocket(socketId: string) {
this.sockets.filter(({ id }) => id === socketId);
}
private getSocket(socketId: string) {
return this.sockets.find(({ id }) => id === socketId);
}
private parseClientMessage(
message: string,
): { action: ClientAction; payload: unknown } {
const { action, payload } = JSON.parse(message);
return { action, payload };
}
}
|
994341c9e3ba3c900133d83b29e54186ed2d7813
|
TypeScript
|
cuatromedios/nequ
|
/backend/src/store/store.service.ts
| 2.578125
| 3
|
import {HttpException, Injectable} from '@nestjs/common'
import * as crypto from 'crypto'
import * as AWS from 'aws-sdk'
@Injectable()
export class StoreService {
async put(file): Promise<string> {
let hash = crypto.createHash('sha1')
hash.setEncoding('hex')
hash.write(file.buffer)
hash.end()
const checksum = hash.read()
let extension = file.originalname.split(/\./g).slice(-1)
extension = String(extension).toLowerCase()
const name = `${checksum}.${extension}`
const s3 = new AWS.S3({
region: process.env.S3_REGION,
accessKeyId: process.env.S3_ACCESS_KEY,
secretAccessKey: process.env.S3_SECRET,
endpoint: process.env.S3_ENDPOINT,
})
const params = {
Bucket: process.env.S3_BUCKET,
Key: name,
Body: file.buffer,
ACL: 'public-read'
}
try {
await s3.upload(params).promise()
} catch (e) {
throw new HttpException({
'message': 'file_upload_failed',
'data': e.message
}, 503)
}
return name
}
}
|
153ad4a0ebb45c053196fc75af4174040ce54fc9
|
TypeScript
|
robcrocombe/monzo-calendar-react
|
/src/monzo/auth.store.ts
| 2.609375
| 3
|
import { createContext } from 'react';
import { observable, computed, action } from 'mobx';
class AuthStore {
public readonly REDIRECT_URL = process.env.REDIRECT_URL;
@observable public CLIENT_ID = process.env.CLIENT_ID || localStorage.getItem('auth.clientId');
@observable
public CLIENT_SECRET = process.env.CLIENT_SECRET || localStorage.getItem('auth.clientSecret');
@computed
public get loginUrl(): string {
const stateToken = this.setStateToken();
return `https://auth.monzo.com/?
client_id=${this.CLIENT_ID}
&redirect_uri=${this.REDIRECT_URL}
&response_type=code
&state=${stateToken}`.replace(/\s/g, '');
}
public getToken(authCode: string): Promise<any> {
const data = this.getFormData({
grant_type: 'authorization_code',
client_id: this.CLIENT_ID,
client_secret: this.CLIENT_SECRET,
redirect_uri: this.REDIRECT_URL,
code: authCode,
});
return fetch('https://api.monzo.com/oauth2/token', {
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded; charset=utf-8',
},
body: data,
}).then(res => res.json());
}
@computed
public get hasClientVars(): boolean {
return !!(this.CLIENT_ID && this.CLIENT_SECRET);
}
@action
public setClientVars(clientId: string, clientSecret: string) {
this.CLIENT_ID = clientId;
this.CLIENT_SECRET = clientSecret;
localStorage.setItem('auth.clientId', clientId);
localStorage.setItem('auth.clientSecret', clientSecret);
}
// Generate random token
private setStateToken(): string {
const stateToken =
'id-' +
Math.random()
.toString(36)
.substr(2, 16);
localStorage.setItem('session.stateToken', stateToken);
return stateToken;
}
private getFormData(params: Dictionary<string>): URLSearchParams {
const searchParams = new URLSearchParams();
for (const prop in params) {
searchParams.set(prop, params[prop]);
}
return searchParams;
}
}
export const authStore = new AuthStore();
export const AuthStoreContext = createContext(authStore);
|
aebdb0d6cb0f013f00de68860ef12fbe6c7a93db
|
TypeScript
|
COMP30022-Russia/COMP30022_Server
|
/controllers/notification/index.ts
| 2.859375
| 3
|
import send from '../../helpers/notifications';
import {
getFirebaseTokensHelper,
replaceFirebaseToken,
removeFirebaseToken
} from './actions';
export { updateFirebaseToken, getFirebaseTokens } from './actions';
/**
* Builds an Firebase android notification message.
* @param title Title of message.
* @param body Body of message.
* @param [priority] Priority of message.
*/
export const buildAndroidNotificationMessage = (
title: string,
body: string,
priority?: string
) => {
return {
notification: {
title,
body
}
};
};
/**
* Builds a Firebase data message.
* @param type The type of the message.
* @param content Content of message.
* @param [priority] Priority of message.
*/
export const buildDataMessage = (
type: string,
content: any,
priority?: string
) => {
return {
data: {
type,
data: JSON.stringify(content)
}
};
};
/**
* Sends a message to the specified recipient.
* @param message The message to be sent.
* @param userID The ID(s) of the recipient.
*/
export const sendMessage = async (message: any, userID: number | number[]) => {
// Only send in production environment
if (process.env.NODE_ENV !== 'production') {
// Output message to console if in development environment
if (process.env.NODE_ENV === 'development') {
console.info(message);
}
return;
}
// Get token of target user(s)
let tokens: string[] = [];
if (Array.isArray(userID)) {
// More than 1 user
for (const id of userID) {
tokens.push(...(await getFirebaseTokensHelper(id)));
}
} else {
// One user only
tokens = await getFirebaseTokensHelper(userID as number);
}
// Stop if there are no tokens
if (tokens.length === 0) {
return;
}
try {
// Send the message with given tokens
const response = await send(message, tokens);
// If there are errors
if (response.failureCount !== 0) {
response.results.map(async (result, i) => {
// Replace token, if applicable
if (result.canonicalRegistrationToken) {
await replaceFirebaseToken(
tokens[i],
result.canonicalRegistrationToken
);
}
// Remove token, if applicable
if (result.error) {
if (
result.error.code ===
'messaging/registration-token-not-registered'
) {
await removeFirebaseToken(tokens[i]);
} else {
console.error(result.error);
}
}
});
}
} catch (err) {
console.error(err);
}
};
|
7a0da85a03c52dbafdf4ffc64dae22fa9a22881f
|
TypeScript
|
xiel/use-location-state
|
/src/packages/use-location-state/src/useQueryState/test/method-push.test.ts
| 2.5625
| 3
|
import { renderHook } from '@testing-library/react-hooks'
import { useQueryState } from '../../use-location-state'
import {
asyncAct,
unwrapResult,
} from 'use-location-state-test-helpers/test-helpers'
import { cleanup } from '@testing-library/react'
// reset jest mocked hash
beforeAll(() => {
window.location.hash = ''
})
afterEach(() => {
window.location.hash = ''
cleanup()
})
describe('method - push', () => {
it('method push creates new entries in history with each change', async () => {
const { result, unmount } = renderHook(
({ itemName, defaultValue }) => useQueryState(itemName, defaultValue),
{
initialProps: { itemName: 'name', defaultValue: 'Sarah' },
}
)
const name = unwrapResult(result)
expect(name.value).toEqual('Sarah')
expect(window.history.length).toEqual(1)
await asyncAct(async () => void name.setValue('Kim', { method: 'push' }))
expect(window.location.hash).toEqual('#name=Kim')
expect(name.value).toEqual('Kim')
// method push creates new entries in history with each change
expect(window.history.length).toEqual(2)
unmount()
})
})
|
e97d722be66681fbafa169f8f37e40cab1b06c4e
|
TypeScript
|
geoblink/lodash-mixins
|
/test/unit/fromPairsMap.spec.ts
| 2.640625
| 3
|
import fromPairsMap from '../../src/fromPairsMap'
import { expect, use as chaiUse } from 'chai'
import sinonChai from 'sinon-chai'
import * as sinon from 'sinon'
chaiUse(sinonChai)
describe('fromPairsMap', function () {
it('should return an object', function () {
const array = ['a', 'b', 'c']
const expectedResult = {
a: 'a',
b: 'b',
c: 'c'
}
const result = fromPairsMap(array, v => [v, v])
expect(result).to.be.deep.equal(expectedResult)
})
it('should apply map function', function () {
const mapFunction = sinon.stub().callsFake(v => [v, `the key is ${v}`])
const array = ['a', 'b', 'c']
const expectedResult = {
a: 'the key is a',
b: 'the key is b',
c: 'the key is c'
}
const result = fromPairsMap(array, mapFunction)
expect(mapFunction).to.have.property('callCount').that.is.equal(array.length)
expect(mapFunction).to.have.been.calledWith('a', 0)
expect(mapFunction).to.have.been.calledWith('b', 1)
expect(mapFunction).to.have.been.calledWith('c', 2)
expect(result).to.be.deep.equal(expectedResult)
})
})
|
3fd17f31564a495a295f6ff786cf0ae751e02402
|
TypeScript
|
Ahryman40k/typescript-fhir-types
|
/src/R4/Resource/RTTI_ClinicalImpression_Investigation.ts
| 2.9375
| 3
|
import * as t from 'io-ts';
import { RTTI_Extension, IExtension } from './RTTI_Extension';
import { RTTI_CodeableConcept, ICodeableConcept } from './RTTI_CodeableConcept';
import { RTTI_Reference, IReference } from './RTTI_Reference';
export interface IClinicalImpression_Investigation {
/**
* A name/code for the group ("set") of investigations. Typically, this will be something like "signs", "symptoms", "clinical", "diagnostic", but the list is not constrained, and others such groups such as (exposure|family|travel|nutritional) history may be used.
*/
code: ICodeableConcept;
/**
* Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces.
*/
id?: string;
/**
* May be used to represent additional information that is not part of the basic definition of the element. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension.
*/
extension?: IExtension[];
/**
* May be used to represent additional information that is not part of the basic definition of the element and that modifies the understanding of the element in which it is contained and/or the understanding of the containing element's descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.
Modifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself).
*/
modifierExtension?: IExtension[];
/**
* A record of a specific investigation that was undertaken.
*/
item?: IReference[];
}
export const RTTI_ClinicalImpression_Investigation: t.Type<
IClinicalImpression_Investigation
> = t.recursion('IClinicalImpression_Investigation', () =>
t.intersection([
t.type({
code: RTTI_CodeableConcept
}),
t.partial({
id: t.string,
extension: t.array(RTTI_Extension),
modifierExtension: t.array(RTTI_Extension),
item: t.array(RTTI_Reference)
})
])
);
|
c3ec9304a9c3e88e2038b38b917ba7683af0dee7
|
TypeScript
|
sergejmigun/ShopEngine.Frontend
|
/Frontend/Scripts/core/lib/objects/enumerable.ts
| 3.3125
| 3
|
class Enumerable<T> {
private $iterate: (func: (x: T) => any) => void;
private utils;
constructor($iterate: (func: (x: T) => any) => void, utils) {
this.$iterate = $iterate;
this.utils = utils;
}
public where(predicate: (x: T) => boolean) {
var self = this;
return new Enumerable<T>(function (onIterate) {
self.$iterate(function (item) {
if (predicate(item)) {
onIterate(item);
}
});
}, this.utils);
};
public select<TOut>(selector: (x: T, index: number) => TOut) {
var self = this;
return new Enumerable<TOut>(function (onIterate) {
var index = 0;
self.$iterate(function (item) {
onIterate(selector(item, index));
index += 1;
});
}, this.utils);
};
public selectMany<TOut>(selector: (x: T) => Array<TOut>) {
var self = this;
return new Enumerable<TOut>(function (onIterate) {
self.$iterate(function (item: T) {
var set = selector(item);
if (set) {
set.forEach(function (innerItem) {
onIterate(innerItem);
});
}
});
}, this.utils);
};
public groupBy(selector: (x: T) => any) {
var self = this;
return new Enumerable<{ key: string, items: T[] }>(function (onIterate) {
var group = {};
self.$iterate(function (item: T) {
var key = selector(item);
if (!group.hasOwnProperty(key)) {
group[key] = [];
}
group[key].push(item);
});
for (var key in group) {
onIterate({
key: key,
items: group[key]
});
}
}, this.utils);
};
public skip(skip: number) {
var self = this;
return new Enumerable<T>(function (onIterate) {
var index = 0;
self.$iterate(function (item) {
if (index >= skip) {
onIterate(item);
}
index += 1;
});
}, this.utils);
};
public take(take: number) {
var self = this;
return new Enumerable<T>(function (onIterate) {
var index = 0;
self.$iterate(function (item) {
if (index < take) {
onIterate(item);
}
index += 1;
});
}, this.utils);
};
public foreach(onIterate: (x: T, i: number) => void) {
var index = 0;
this.$iterate(function (item) {
onIterate(item, index);
index += 1;
});
};
public first(predicate?: (x: T) => boolean) {
var first: T;
this.$iterate(function (item) {
if (!predicate || predicate(item)) {
first = item;
return false;
}
});
return first;
};
public selectIndexes(predicate) {
var resultIndexes: number[] = [],
self = this,
index = 0;
this.$iterate(function (item) {
var isFunction = self.utils.objects.isFunction(predicate);
if ((isFunction && predicate(item)) || (!isFunction && predicate === item)) {
resultIndexes.push(index);
}
index += 1;
});
return resultIndexes;
};
public indexOf(predicate) {
var resultIndex = -1,
self = this,
index = 0;
this.$iterate(function (item) {
var isFunction = self.utils.objects.isFunction(predicate);
if ((isFunction && predicate(item)) || (!isFunction && predicate === item)) {
resultIndex = index;
return false;
}
index += 1;
});
return resultIndex;
};
public any(predicate: (x: T) => boolean) {
var any = false;
this.$iterate(function (item) {
if (!predicate || predicate(item)) {
any = true;
return false;
}
});
return any;
};
public all(predicate: (x: T) => boolean) {
var all = true;
this.$iterate(function (item) {
if (!predicate(item)) {
all = false;
return false;
}
});
return all;
};
public contains(targetItem) {
var contains = false;
this.$iterate(function (item) {
if (targetItem === item) {
contains = true;
return false;
}
});
return contains;
};
public count() {
var count = 0;
this.$iterate(function () {
count += 1;
});
return count;
};
public toArray() {
var arr: T[] = [];
this.$iterate(function (item) {
arr.push(item);
});
return arr;
};
public toObject<T>(propertySelector: (item: any) => INameValue<T>) {
var obj = {};
this.$iterate(function (item) {
var propInfo = propertySelector(item);
obj[propInfo.name] = propInfo.value;
});
return obj;
};
}
app.registerComponent('enumerable', 'Lib.objects', ['Utils', function (utils) {
'use strict';
return {
init: function ($iterate) {
return new Enumerable($iterate, utils);
}
};
}]);
|
4e927e535adb0b3875651e21916cc65d85ab14c7
|
TypeScript
|
cevaris/api-cli
|
/tests/index.integration.ts
| 2.875
| 3
|
import { exec } from 'child_process';
import { EOL as NEW_LINE } from 'os';
import { promisify } from 'util';
import { shuffle } from './helper';
const execPromise = promisify(exec);
describe('advice api', () => {
it('test ids are not numbers', async () => {
const response = await execPromise('./bin/advice --ids a,b,c');
expect(response.stderr).toEqual('Error: a is not a number');
});
it('test query command successfully returns ordered advice', async () => {
const response = await execPromise('./bin/advice --query mother');
const expected: string = [
'Advice(031): Never let your Mother cut your hair.',
'Advice(208): Play is the true mother of invention.'
].join(NEW_LINE);
expect(response.stdout).toEqual(expected);
});
it('test query command returns no advice for an unknown search term', async () => {
const expected = [
'Error: Failed to search for Advice containing aaa',
'{\"message\":{\"type\":\"notice\",\"text\":\"No advice slips found matching that search term.\"'
].join(NEW_LINE);
const response = await execPromise('./bin/advice --query aaa');
expect(response.stderr).toContain(expected);
});
it('test ids command successfully returns ordered advice', async () => {
const ids = shuffle([10, 30, 100]).join(',')
const response = await execPromise(`./bin/advice --ids ${ids}`);
const expected: string = [
'Advice(010): Never pay full price for a sofa at DFS.',
'Advice(030): When in doubt, just take the next small step.',
'Advice(100): Everybody makes mistakes.'
].join(NEW_LINE);
expect(response.stdout).toEqual(expected);
});
it('test ids command successfully returns with inline errors', async () => {
const ids = shuffle([1000, 2, 3]).join(',')
const response = await execPromise(`./bin/advice --ids ${ids}`);
const expected: string = [
"Advice(002): Smile and the world smiles with you. Frown and you're on your own.",
"Advice(003): Don't eat non-snow-coloured snow.",
'Advice(1000): Error: failed to hydrate 1000',
].join(NEW_LINE);
expect(response.stdout).toEqual(expected);
});
});
describe('weather api', () => {
it('test multiple weather locations successfully returns ordered data', async () => {
const response = await execPromise("./bin/weather --locations 'Paris,France:Fresno,CA,USA' --json");
const obj = JSON.parse(response.stdout);
expect(obj).toBeDefined();
expect(obj).toHaveLength(2);
[0, 1].forEach(idx => {
expect(obj[idx]).toBeDefined();
expect(obj[idx]['local_datetime']).toBeTruthy();
expect(obj[idx]['curr_temp']).toBeTruthy();
expect(obj[idx]['lat_long']).toBeTruthy();
expect(obj[idx]['visibility']).toBeTruthy();
expect(obj[idx]['wind_speed']).toBeTruthy();
expect(obj[idx]['wind_angle']).toBeTruthy();
});
expect(obj[0]['name']).toEqual('Fresno,CA,USA');
expect(obj[1]['name']).toEqual('Paris,France');
});
it('test location not found error', async () => {
const response = await execPromise("./bin/weather --locations 'B:A:Z' --json");
const expected: string = [
'Location "A" not found.',
'Location "B" not found.',
'Location "Z" not found.',
'', // leaving this in for now
].join(NEW_LINE);
expect(response.stderr).toEqual(expected);
});
it('test no location passed in', async () => {
const response = await execPromise("./bin/weather --json");
const expected: string = 'Error: invalid request, no locations found.';
expect(response.stderr).toEqual(expected);
});
});
|
deb41113137bb1634f4eb526584bf29e44450398
|
TypeScript
|
cococoquito/AdminFree-frontend
|
/AdminFree/src/app/dtos/english/serie.dto.ts
| 2.625
| 3
|
import { SeasonDTO } from "./season.dto";
/**
* DTO para mappear las series
*
* @author Carlos Andres Diaz
*/
export class SerieDTO {
/** identificador de la serie */
public id: number;
/** Es el nombre de la serie */
public name: string;
/** Es la URL de esta serie */
public url: string;
/** es la imagen a mostrar en pantalla */
public img: any;
/** son las temporadas de esta serie */
public seasons: Array<SeasonDTO>;
}
|
46cd14c746580303749e731de3cb455c1c56f819
|
TypeScript
|
dongsu8142/dongz.ml
|
/util/index.ts
| 2.546875
| 3
|
import matter from 'gray-matter'
export async function getAllPosts(){
const context = require.context('../_posts', false, /\.md$/)
const posts = []
for(const key of context.keys()){
const post = key.slice(2);
const content = await import(`../_posts/${post}`);
const meta = matter(content.default)
meta.data.date = String(meta.data.date)
posts.push({
slug: post.replace('.md',''),
title: meta.data.title,
description: meta.data.description,
date: meta.data.date
})
}
return posts;
}
export async function getPostBySlug(slug){
const fileContent = await import(`../_posts/${slug}.md`)
const meta = matter(fileContent.default)
meta.data.date = String(meta.data.date)
const categories = meta.data.categories.split(" ");
return {
title: meta.data.title,
content: meta.content,
categories,
date: meta.data.date
}
}
|
c68b897bf8ec5eafffa4c7ae228bb95edf589018
|
TypeScript
|
nori-dot-eco/ethql
|
/src/__tests__/core/block.test.ts
| 2.59375
| 3
|
import { testGraphql } from '../utils';
const { execQuery } = testGraphql();
test('block: select single block by number', async () => {
const query = `
{
block(number: 12345) {
hash
}
}
`;
const expected = { data: { block: { hash: '0x767c2bfb3bdee3f78676c1285cd757bcd5d8c272cef2eb30d9733800a78c0b6d' } } };
const result = await execQuery(query);
expect(result).toEqual(expected);
});
test('block: select single block by tag', async () => {
const query = `
{
block(tag: LATEST) {
hash
}
}
`;
const expected = { data: { block: { hash: expect.any(String) } } };
const result = await execQuery(query);
expect(result).toEqual(expected);
});
test('block: select single transaction from block by index', async () => {
const query = `
{
block(number: 5771878) {
difficulty
transactionAt(index: 22) {
hash
nonce
}
}
}`;
const expected = {
data: {
block: {
difficulty: 3351918027816898,
transactionAt: { hash: '0xb0804426b4c800f962416f0e7155d9c6be007e95d0af9820bd6cec8d95efdfd5', nonce: 156806 },
},
},
};
const result = await execQuery(query);
expect(result).toEqual(expected);
});
test('block: null response when selecting transaction by negative index', async () => {
const query = `
{
block(number: 5771878) {
difficulty
transactionAt(index: -1) {
hash
nonce
}
}
}`;
const expected = { data: { block: { difficulty: 3351918027816898, transactionAt: null } } };
const result = await execQuery(query);
expect(result).toEqual(expected);
});
test('block: null response when selecting transaction by an index that does not exist in block', async () => {
const query = `
{
block(number: 5771878) {
difficulty
transactionAt(index: 140) {
hash
nonce
}
}
}`;
const expected = { data: { block: { difficulty: 3351918027816898, transactionAt: null } } };
const result = await execQuery(query);
expect(result).toEqual(expected);
});
test('block: select single block by hash', async () => {
const query = `
{
block(hash: "0x4b3c1d7e65a507b62734feca1ee9f27a5379e318bd52ae62de7ba67dbeac66a3") {
number
}
}
`;
const expected = { data: { block: { number: 12344 } } };
const result = await execQuery(query);
expect(result).toEqual(expected);
});
test('block: error when selecting block by invalid hash', async () => {
const query = `
{
block(hash: "0x1234") {
number
}
}
`;
const result = await execQuery(query);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].message).toMatch(/^Expected type Bytes32/);
});
test('block: error when selecting block with no number, hash, or tag', async () => {
const query = `
{
block {
number
}
}
`;
const result = await execQuery(query);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].message).toMatch(/^Expected either number, hash or tag argument/);
});
test('block: error when selecting block with more than one argument', async () => {
const query = `
{
block(hash: "0x4b3c1d7e65a507b62734feca1ee9f27a5379e318bd52ae62de7ba67dbeac66a3", number: 12344) {
number
}
}
`;
const result = await execQuery(query);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].message).toMatch(/^Only one of number, hash or tag argument should be provided/);
});
test('block: all scalar fields successfully returned', async () => {
const query = `
{
block(hash: "0x4b3c1d7e65a507b62734feca1ee9f27a5379e318bd52ae62de7ba67dbeac66a3") {
number
difficulty
extraData
gasLimit
gasUsed
hash
mixHash
nonce
receiptsRoot
stateRoot
transactionsRoot
timestamp
totalDifficulty
}
}
`;
const expected = {
data: {
block: {
number: 12344,
difficulty: 735153649021,
extraData: '0x476574682f76312e302e302d30636463373634372f6c696e75782f676f312e34',
gasLimit: 5000,
gasUsed: 0,
hash: '0x4b3c1d7e65a507b62734feca1ee9f27a5379e318bd52ae62de7ba67dbeac66a3',
mixHash: '0xa479f6fc3188eccaa1e1af9c63078a8f09f66a45a8c11d96f92e110ab442b49d',
nonce: '0x5c3a45c45e16729d',
receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
stateRoot: '0x262da2fca20d165b195dbf2858d983c90d1d1f7f376da838b704e0632dd28174',
transactionsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
timestamp: '1438367018',
totalDifficulty: 3861404974593840,
},
},
};
const result = await execQuery(query);
expect(result).toEqual(expected);
});
|
c718e4f65bf98299a808b9791cd436c2d6223701
|
TypeScript
|
rwp-anonymous/HyproDoc-API-V2
|
/src/items/pipes/store-location-validation.pipe.ts
| 2.859375
| 3
|
import { PipeTransform, BadRequestException } from "@nestjs/common";
import { StoreLocations } from "../store-location.enum";
export class StoreLocationValidationPipe implements PipeTransform {
readonly allowedStoreLocation = [
StoreLocations.UGANDA,
StoreLocations.SRI_LANKA,
];
transform(value: any) {
value = value.toUpperCase();
if (!this.isStoreLocationValid(value)) {
throw new BadRequestException(`${value} is an invalid store location`)
}
return value;
}
private isStoreLocationValid(storeLocation: any) {
const idx = this.allowedStoreLocation.indexOf(storeLocation);
return idx !== -1;
}
}
|
82f630e4275527343bd8ec4b5e4b0f76ae019ead
|
TypeScript
|
VikaBondareva/hotel-api
|
/src/models/client.model.ts
| 2.625
| 3
|
import DataTypes, { Model } from 'sequelize';
import { StatusUsersArray, Validate, CountAttempt } from '../enums';
export class Client extends Model {
public clientId!: number;
public name!: string;
public surname!: string;
public phoneNumber!: string;
public email!: string;
public phoneCountryId!: number;
public status!: number;
public gender!: string;
public attemptLogin!: number;
public loginCode!: number | null;
public newEmail: string | null;
public newPhone: string | null;
public createAt!: string;
public updatedAt!: string;
public static initTable(sequelize: any) {
return Client.init(
{
clientId: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false
},
name: {
type: DataTypes.STRING(20),
allowNull: false
},
surname: {
type: DataTypes.STRING(20),
allowNull: false
},
email: {
type: DataTypes.STRING(50),
allowNull: false,
validate: {
isEmail: true
}
},
phoneNumber: {
type: DataTypes.STRING(20),
allowNull: false,
validate: {
is: Validate.phoneNumber
}
},
phoneCountryId: {
type: DataTypes.INTEGER,
allowNull: false
},
newEmail: {
type: DataTypes.STRING(50),
allowNull: true,
validate: {
isEmail: true
}
},
newPhone: {
type: DataTypes.STRING(20),
allowNull: true
},
gender: {
type: DataTypes.STRING(10),
allowNull: false,
validate: {
isIn: [['male', 'female']]
}
},
status: {
type: DataTypes.STRING(15),
allowNull: false,
validate: {
isIn: [StatusUsersArray]
}
}
},
{
indexes: [
{
unique: true,
fields: ['email', 'phoneNumber']
}
],
sequelize,
timestamps: false,
tableName: 'Clients'
}
);
}
public static associate(models: any) {
this.belongsTo(models.Countries, { as: 'country', foreignKey: 'phoneCountryId', targetKey: 'countryId' });
this.hasMany(models.Bookings, {
as: 'bookings',
sourceKey: 'clientId',
foreignKey: 'clientId'
});
}
}
|
6772ac982c4d0797606311a70772ad09ae8505bf
|
TypeScript
|
nstranquist/apps
|
/pages/api/apps/[id].ts
| 2.890625
| 3
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
import { connectToDatabase } from "../../../util/mongodb";
type Data = {
message: string
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
// Get id from the request
const { id } = req.query
console.log('id:', id)
// Query the app data from the database
const { db } = await connectToDatabase()
try {
const appData = await db
.collection("apps")
.find({ slug: id })
.limit(1)
.toArray()
if(appData.length === 0) {
res.status(404).send({
message: "App details not found"
})
}
// Return the app data
res.send(appData)
} catch (error) {
console.log('error:', error.toString())
// Return an error if the app data cannot be found
res.status(404).send({
message: "App Details not found"
})
}
}
|
78e18f73fd11b236078196639bd331f50bdd57f1
|
TypeScript
|
tonngw/leetcode
|
/typescript/0901-online-stock-span.ts
| 3.46875
| 3
|
class StockSpanner {
private stack: { price: number; spanDays: number }[];
constructor() {
this.stack = [];
}
next(price: number): number {
let span = 1;
while (
this.stack.length > 0 &&
this.stack[this.stack.length - 1].price <= price
) {
span += this.stack[this.stack.length - 1].spanDays;
this.stack.pop();
}
this.stack.push({ price, spanDays: span });
return span;
}
}
/**
* Your StockSpanner object will be instantiated and called as such:
* var obj = new StockSpanner()
* var param_1 = obj.next(price)
*/
|
96a650b2953d70178c52ac7f940d003c5edb232c
|
TypeScript
|
anton-nagornyi/math
|
/src/vectors/floats.ts
| 3.109375
| 3
|
import {INumber2, INumber3, INumber4} from "./numbers";
export abstract class AVectorData
{
abstract value: Float32Array;
}
export class Float2 extends AVectorData implements INumber2
{
value = new Float32Array(2);
get x(): number
{
return this.value[0];
}
get y(): number
{
return this.value[1];
}
set x(value: number)
{
this.value[0] = value;
}
set y(value: number)
{
this.value[1] = value;
}
}
export class Float3 extends AVectorData implements INumber3
{
value = new Float32Array(3);
get x(): number
{
return this.value[0];
}
get y(): number
{
return this.value[1];
}
get z(): number
{
return this.value[2];
}
set x(value: number)
{
this.value[0] = value;
}
set y(value: number)
{
this.value[1] = value;
}
set z(value: number)
{
this.value[2] = value;
}
}
export class Float4 extends AVectorData implements INumber4
{
value = new Float32Array(4);
get x(): number
{
return this.value[0];
}
get y(): number
{
return this.value[1];
}
get z(): number
{
return this.value[2];
}
get w(): number
{
return this.value[3];
}
set x(value: number)
{
this.value[0] = value;
}
set y(value: number)
{
this.value[1] = value;
}
set z(value: number)
{
this.value[2] = value;
}
set w(value: number)
{
this.value[3] = value;
}
}
|
4cafb775f7a3d59ff87399ee8b8c073f76b6c5ef
|
TypeScript
|
SAanajamil/bootCamp2021
|
/version-7/src/index.ts
| 3.078125
| 3
|
//Removing completed task
import { TodoItem } from "./todoItem";
import { TodoCollection } from "./todoCollection";
import * as inquirer from 'inquirer';
let todos: TodoItem[] = [
new TodoItem(1, "Buy Flowers"),
new TodoItem(2, "Get Shoes"),
new TodoItem(3, "Collect Tickets"),
new TodoItem(4, "Call Joe", true),
new TodoItem(5, "send an email", true)];
let collection: TodoCollection = new TodoCollection("Sana", todos);
let showCompleted = true;
function displayTodoList(): void {
console.log(`${collection.userName}'s Todo List `
+ `(${ collection.getItemCounts().incomplete } items to do)`);
collection.getTodoItems(true).forEach(item => item.printDetails());
collection.getTodoItems(showCompleted).forEach(item => item.printDetails());
}
enum Commands {
Toggle = "Show/Hide Completed",
Quit = "Quit"
}
function promptUser(): void {
console.clear();
displayTodoList();
inquirer.prompt({
type: "list",
name: "command",
message: "Choose option",
choices: Object.values(Commands),
//badProperty: true
}).then(answers => {
switch (answers["command"]) {
case Commands.Toggle:
showCompleted = !showCompleted;
promptUser();
break;
}
})
}
promptUser();
console.clear();
//console.log(`${collection.userName}'s Todo List`);
//let newId: number = collection.addTodo("Go for shopping");
//let todoItem: TodoItem = collection.getTodoById(newId);
//todoItem.printDetails();
console.log(`${collection.userName}'s Todo List `
+ `(${ collection.getItemCounts().incomplete } items to do)`);
collection.getTodoItems(true).forEach(item => item.printDetails());
|
5827678357757547d005afe66c659033a282370b
|
TypeScript
|
lee-dalais/pacman-game
|
/index.ts
| 2.640625
| 3
|
import * as shell from 'shell'
import { Packman } from './models/packman'
const app = new shell();
let packman;
app.configure(function() {
app.use(shell.router({shell: app}));
app.use(shell.error({shell: app}));
});
app.cmd('PLACE :x,:y,:direction', function(req, res) {
if (!packman) {
packman = new Packman(req.params.x, req.params.y, req.params.direction);
} else {
packman.place(req.params.x, req.params.y, req.params.direction);
}
res.prompt();
});
app.cmd('MOVE', function(req, res){
if (!packman) {
console.log('Please PLACE your Pacman.');
res.prompt();
return;
}
packman.move();
res.prompt();
});
app.cmd('LEFT', function(req, res) {
if (!packman) {
console.log('Please PLACE your Pacman.');
res.prompt();
return;
}
packman.left();
res.prompt();
});
app.cmd('RIGHT', function(req, res) {
if (!packman) {
console.log('Please PLACE your Pacman.');
res.prompt();
return;
}
packman.right();
res.prompt();
});
app.cmd('REPORT', function(req, res) {
if (!packman) {
console.log('Please PLACE your Pacman.');
res.prompt();
return;
}
console.log(`${packman.x},${packman.y},${packman.direction}`);
res.prompt();
});
|
b5b4fdbb2bc1fea3d1ef1ab1ce7175b143888aff
|
TypeScript
|
logscl/nicobot-persistence
|
/src/common/model/Error.ts
| 2.859375
| 3
|
import { ErrorItem } from "./ErrorItem";
export class Error {
private errors : Array<ErrorItem> = new Array();
hasError() : boolean {
return (this.errors.length == 0) ? false : true;
}
addFieldError(fieldName:string, errorMessage:string) {
this.errors.push(new ErrorItem(fieldName, errorMessage));
}
addError(error:ErrorItem) {
this.errors.push(error);
}
getErrors() { return this.errors; }
toJSON() : Array<ErrorItem> {
return this.errors;
}
}
|
c4155ab1a99685e488292430a5fa7b08dae059d4
|
TypeScript
|
ruchirathakare/Algorithms-JS
|
/nthFromEnd-LinkedListTS.ts
| 3.9375
| 4
|
class Node {
constructor(public data: number, public next: null | any = null) {}
}
class Linkedlist {
head: null | any;
constructor() {
this.head = null;
}
nthFromEnd(n: number): void {
let firstNode = this.head;
let secondNode = this.head;
for (let i = 0; i < n; i++) {
secondNode = secondNode.next;
}
while (secondNode != null) {
firstNode = firstNode.next;
secondNode = secondNode.next;
}
console.log(`${n}th node from end is ${firstNode.data}`);
}
insertFirst(data: number): void {
this.head = new Node(data, this.head);
}
}
let nodeOneTSS = new Node(88);
let listt = new Linkedlist();
listt.head = nodeOneTSS;
listt.insertFirst(3);
listt.insertFirst(4);
listt.insertFirst(5);
listt.insertFirst(7);
listt.insertFirst(9);
console.log(JSON.stringify(listt));
listt.nthFromEnd(2);
|
753e78bbeefcf6fa9d63ddf5f691fbd5d789556f
|
TypeScript
|
AmitPr/insci
|
/src/app/component/ButtonState.ts
| 2.546875
| 3
|
import { Cell, Cells, Plugin } from 'insci-notebook';
import { App } from '../App';
@Plugin
class ButtonState {
cellTypes: string[]=[];
postNotebookInit() {
Object.keys(Cells.builtins).forEach(key => {
this.cellTypes.push(key);
});
Object.keys(Cells.plugins).forEach(key => {
this.cellTypes.push(key);
});
for(const type of this.cellTypes){
const opt:HTMLOptionElement=document.createElement("option");
opt.textContent=type.charAt(0).toUpperCase()+type.slice(1);
opt.value=type;
App.instance().typeSelector.appendChild(opt);
}
App.instance().typeSelector.onchange = (e: Event) => { App.instance().notebook.newCell((e.currentTarget as HTMLSelectElement).value,App.instance().notebook.activeCell); }
}
onSelectCell(cell: Cell) {
App.instance().typeSelector.value = cell.type;
}
}
|
4ab54af82eb0bd040c2ae01a44e5cef0b3ebac3c
|
TypeScript
|
divasilevski/mrbeam
|
/utils/fem/calculate.ts
| 2.796875
| 3
|
import { CalculateOptions, Skeleton } from './types/calculate'
import { Element } from './types/element'
import { Unit } from './types/unit'
import { fragmentation } from './core/fragmentation'
import { multiply, solve } from './core/algebra'
import { createGraph } from './core/graph'
import { parse } from './core/parse'
export function buildSkeleton(elems: Element[]): Skeleton {
let counter = 0 // Общее кол-во элементов в матрице индексов
const indexMatrix = [] // Матрица индексов
const sups = new Set() // Запоминаем места с заделками
const temp = []
for (let i = 0; i < elems.length; i++) {
for (let j = 0; j < 4; j++) {
// definition vector building
const isIncludesNodeOne = ['fixed', 'simple'].includes(
elems[i].nodes[0].support || ''
)
const isIncludesNodeTwo = ['fixed', 'simple'].includes(
elems[i].nodes[1].support || ''
)
if (j === 0 && isIncludesNodeOne) sups.add(counter)
if (j === 1 && elems[i].nodes[0].support === 'fixed') sups.add(counter)
if (j === 2 && isIncludesNodeTwo) sups.add(counter)
if (j === 3 && elems[i].nodes[1].support === 'fixed') sups.add(counter)
// index matrix building
if (j === 1 && elems[i].nodes[0].support === 'hinge') counter++
temp[j] = counter
counter++
}
indexMatrix[i] = [...temp]
counter -= 2
}
return {
indexMatrix,
sups: Array.from(sups) as number[],
counter: counter + 2,
}
}
export function buildGlobalM(elems: Element[], skeleton: Skeleton) {
const { indexMatrix, sups, counter } = skeleton
const matrix = Array.from(Array(counter), () =>
Array.from(Array(counter), () => 0)
)
for (let i = 0; i < elems.length; i++) {
for (let j = 0; j < 4; j++) {
for (let k = 0; k < 4; k++) {
matrix[indexMatrix[i][j]][indexMatrix[i][k]] +=
elems[i].localMatrix[j][k]
}
}
}
// registrate definitions:
for (const j of sups) {
for (let k = 0; k < counter; k++) {
matrix[k][j] = 0
matrix[j][k] = 0
}
matrix[j][j] = 1
}
return matrix
}
export function buildGlobalV(elems: Element[], skeleton: Skeleton) {
const { indexMatrix, sups, counter } = skeleton
const vector = new Array(counter).fill(0)
let i
for (i = 0; i < elems.length; i++) {
const index0 = indexMatrix[i][0]
const index1 = indexMatrix[i][1]
const index2 = indexMatrix[i][2]
const index3 = indexMatrix[i][3]
const force = elems[i].nodes[0].force || 0
const moment = elems[i].nodes[0].moment || 0
vector[index0] += elems[i].distVector[0] + force
vector[index1] += elems[i].distVector[1] + moment
vector[index2] += elems[i].distVector[2]
vector[index3] += elems[i].distVector[3]
}
i--
vector[indexMatrix[i][2]] += elems[i].nodes[1].force
vector[indexMatrix[i][3]] += elems[i].nodes[1].moment
// registrate definitions:
for (const j of sups) vector[j] = 0
return vector
}
export default function calculate(
units: Unit[],
options: CalculateOptions = { count: 100 }
) {
const elements = fragmentation(parse(units), options)
const skeleton: Skeleton = buildSkeleton(elements)
const GM = buildGlobalM(elements, skeleton)
const GV = buildGlobalV(elements, skeleton)
const solution = solve(GM, GV)
const localSolutions = []
const localReactions = []
for (let i = 0; i < elements.length; i++) {
const localSolution = skeleton.indexMatrix[i].map((el) => solution[el])
localSolutions.push(localSolution)
localReactions.push(
multiply(elements[i].localMatrix, localSolution).map(
(element, index) => element - elements[i].distVector[index]
)
)
}
return createGraph({ elements, localSolutions, localReactions })
}
|
965fa4c4edde13df7cdff28fd5b02b315ec092bf
|
TypeScript
|
gabsouza1/trabalhoTypeScript
|
/src/exercicio2.ts
| 3.46875
| 3
|
// Crie uma classe Veiculos com os atributos modelo, marca, ano, valorLocacao e
// quantidade de dias. Crie os getters e setters. No setters crie validações para não
// aceitar modelo, marca, ano, valorLocacao e quantidade em branco ou com valor
// zero. Crie um método passeio para receber a quantidade de dias e o valor da
// locação. O sistema calcule o total que será a multiplicação da quantidade de dias
// pelo valor da locação.
class Veiculos {
public _modelo: string;
public _marca: string;
public _ano: number;
public _valorLocacao: number;
public _qtdeDias: number;
constructor(modelo: string, marca: string, ano: number, valorLocacao: number, qtdeDias: number) {
this._modelo = modelo;
this._marca = marca;
this._ano = ano;
this._valorLocacao = valorLocacao;
this._qtdeDias = qtdeDias;
}
get modelo(){
return this._modelo;
}
get marca(){
return this._marca;
}
get ano(){
return this._ano;
}
get valorLocacao(){
return this._valorLocacao;
}
get qtdeDias(){
return this._qtdeDias;
}
set modelo(modelo: string){
if(modelo === ' '){
throw new Error('Modelo Inexistente')
}
this._modelo = modelo
}
set marca(marca: string){
if(marca === ' '){
throw new Error('Marca Inexistente')
}
this._marca = marca
}
set valorLocacao(valorLocacao: number){
if(valorLocacao === 0){
throw new Error('Valor Inexistente')
}
this._valorLocacao = valorLocacao
}
set ano(ano: number){
if(ano === 0){
throw new Error('Ano Inexistente')
}
this._ano = ano
}
set qtdeDias(qtdeDias: number){
if(qtdeDias === 0){
throw new Error('Quantidades de dias inexistentes')
}
this._qtdeDias = qtdeDias
}
passeio(){
return this._qtdeDias * this._valorLocacao
}
}
const veiculos = new Veiculos('Gol', 'Volkswagen', 2021, 250, 13 )
try {
veiculos.modelo = 'CLA 45'
veiculos.marca = 'Mercedez'
veiculos.ano = 2020
veiculos.valorLocacao = 1000
veiculos.qtdeDias = 5
console.log(veiculos.passeio())
console.log(veiculos)
} catch (error:any) {
console.log(error.message)
}
|
5abbfcdb650677d10d8dbcdd281404ebe9f4feee
|
TypeScript
|
boopathi/atomic
|
/src/visitor/list.ts
| 2.578125
| 3
|
import { Visitor, Node } from "./visitor";
export default class ListVisitor extends Visitor {
async visit({ name }: Node) {
console.log(">>>", name);
await new Promise(resolve => {
setTimeout(() => resolve(name), 1000);
});
}
}
|
e24b215acf03379201ba4dfeb21033f1e439f3fd
|
TypeScript
|
luchkonikita/rushy
|
/src/reporters/html.ts
| 2.546875
| 3
|
import * as path from 'path'
import * as pug from 'pug'
import BaseReporter from './base_reporter'
// We're resolving from '/dest/src/reporters' to '/templates'
const template = path.join(__dirname, '../../../templates', 'html.pug')
export default class HTMLReporter extends BaseReporter implements Reporter {
write(report: ReportsList, destFileName: string): string {
const urls = Object.keys(report).sort()
const reportKeys = Object.keys(this.config.reportQuery)
const header = ['Page'].concat(reportKeys)
const rows = urls.map(url => {
const results = reportKeys.map(key => report[url][key])
return [url].concat(results)
})
const html = pug.renderFile(template, { header, rows })
return this.writeReport(html, destFileName)
}
get ext(): string {
return 'html'
}
}
|
a75a7d8f333089c3b782afc173d583a1cdbca62f
|
TypeScript
|
kristupas21/react-ts-app-starter
|
/src/state/app/appReducer.ts
| 2.703125
| 3
|
import { ActionType, Reducer } from 'typesafe-actions';
import { AppState } from './appModel';
import { SET_APP_LOADING } from './appConstants';
type Action = ActionType<typeof import('./appActions')>;
type State = Readonly<AppState>
const initialState: State = {
isLoading: false,
};
const appReducer: Reducer<State, Action> = (state = initialState, action) => {
switch (action.type) {
case SET_APP_LOADING:
return {
...state,
isLoading: action.payload,
};
default:
return state;
}
};
export default appReducer;
|
aeaa8fcc2b8a62d1448628ffff59c67bd6816a38
|
TypeScript
|
LeeMoonki/WallahNode
|
/servers/fastify/src/routes/login.ts
| 2.546875
| 3
|
import { FastifyInstance } from '../types';
import { apiOptions } from './lib/apiOptions';
import bcrypt from 'bcrypt';
interface IBody {
id: string;
password: string;
}
async function routes(fastify: FastifyInstance): Promise<void> {
fastify.post<{ Body: IBody }>('/', async (request, reply) => {
const { id, password } = request.body;
request.log.info(`login info : ${request.body.id} ${request.body.password}`);
const encryted = await bcrypt.hash(password, 10);
const match = await bcrypt.compare(password, encryted);
return {
id,
password,
encryted,
length: encryted.length, // always 60 characters
match,
};
});
}
const options = {
prefix: 'login',
};
export default { routes, options: apiOptions(options) };
|
5303c005c9be4e448b1654fd0849713917b0faf6
|
TypeScript
|
bitmovin/bitmovin-player-ui
|
/src/ts/spatialnavigation/seekbarhandler.ts
| 2.59375
| 3
|
import { RootNavigationGroup } from './rootnavigationgroup';
import { NodeEventSubscriber } from './nodeeventsubscriber';
import { Action, Direction } from './types';
import {getBoundingRectFromElement} from './navigationalgorithm';
const DefaultScrubSpeedPercentage = 0.005;
const ScrubSpeedClearInterval = 100;
const ScrubSpeedMultiplier = 1.1;
/**
* Handles Spatial Navigation interaction with the seek bar. Ensures, that seek operations can be executed and that the
* scrubbing tooltip is shown as if the user scrubbed using the mouse/touchscreen.
*/
export class SeekBarHandler {
private readonly cursorPosition = { x: 0, y: 0};
private readonly eventSubscriber: NodeEventSubscriber;
private isScrubbing = false;
private scrubSpeedResetTimeout: number;
private scrubSpeedPercentage = DefaultScrubSpeedPercentage;
constructor(private readonly rootNavigationGroup: RootNavigationGroup) {
this.rootNavigationGroup.onAction = this.onAction;
this.eventSubscriber = new NodeEventSubscriber();
this.rootNavigationGroup.onNavigation = this.onNavigation;
}
private updateScrubSpeedPercentage(): void {
clearTimeout(this.scrubSpeedResetTimeout);
this.scrubSpeedPercentage *= ScrubSpeedMultiplier;
this.scrubSpeedResetTimeout = window.setTimeout(
() => this.scrubSpeedPercentage = DefaultScrubSpeedPercentage, ScrubSpeedClearInterval,
);
}
private getIncrement(direction: Direction, seekBarWrapper: HTMLElement): number {
this.updateScrubSpeedPercentage();
const seekBarWidth = seekBarWrapper.getBoundingClientRect().width;
const increment = seekBarWidth * this.scrubSpeedPercentage;
return direction === Direction.RIGHT ? increment : -increment;
}
private resetCursorPosition(): void {
this.cursorPosition.x = 0;
this.cursorPosition.y = 0;
}
private updateCursorPosition(direction: Direction, seekBarWrapper: HTMLElement): void {
this.cursorPosition.x += this.getIncrement(direction, seekBarWrapper);
}
private initializeCursorPosition(seekBarWrapper: HTMLElement): void {
const playbackPositionMarker = getPlaybackPositionMarker(seekBarWrapper);
const rect = getBoundingRectFromElement(playbackPositionMarker);
const startX = rect.x + (rect.width / 2);
const startY = rect.y;
this.cursorPosition.x = startX;
this.cursorPosition.y = startY;
}
private initializeOrUpdateCursorPosition(seekBarWrapper: HTMLElement, direction: Direction): void {
if (this.isScrubbing) {
this.updateCursorPosition(direction, seekBarWrapper);
} else {
this.initializeCursorPosition(seekBarWrapper);
}
this.isScrubbing = true;
}
private getCursorPositionMouseEventInit(): MouseEventInit {
return {
clientX: this.cursorPosition.x,
clientY: this.cursorPosition.y,
};
}
private dispatchMouseMoveEvent(seekBar: Element): void {
seekBar.dispatchEvent(new MouseEvent('mousemove', this.getCursorPositionMouseEventInit()));
}
private readonly onNavigation = (direction: Direction, target: HTMLElement, preventDefault: () => void): void => {
if (!isSeekBarWrapper(target)) {
return;
}
if (direction === Direction.UP || direction === Direction.DOWN) {
this.stopSeeking(getSeekBar(target));
return;
}
this.initializeOrUpdateCursorPosition(target, direction);
this.dispatchMouseMoveEvent(getSeekBar(target));
preventDefault();
};
private dispatchMouseClickEvent(seekBar: Element): void {
const mouseDownHandler = () => {
const mouseEventInit = this.getCursorPositionMouseEventInit();
document.dispatchEvent(new MouseEvent('mouseup', mouseEventInit));
this.eventSubscriber.off(seekBar, 'mousedown', mouseDownHandler);
this.stopSeeking(seekBar);
};
this.eventSubscriber.on(seekBar, 'mousedown', mouseDownHandler);
seekBar.dispatchEvent(new MouseEvent('mousedown'));
}
private stopSeeking(seekBar: Element): void {
this.resetCursorPosition();
this.isScrubbing = false;
this.dispatchMouseLeaveEvent(seekBar);
}
private dispatchMouseLeaveEvent(seekBar: Element): void {
seekBar.dispatchEvent(new MouseEvent('mouseleave'));
}
private readonly onAction = (action: Action, target: HTMLElement, preventDefault: () => void): void => {
if (!isSeekBarWrapper(target)) {
return;
}
const seekBar = getSeekBar(target);
if (action === Action.SELECT && this.isScrubbing) {
this.dispatchMouseClickEvent(seekBar);
preventDefault();
} else if (action === Action.BACK) {
this.stopSeeking(seekBar);
preventDefault();
}
};
/**
* Releases the SeekBraHandler, making sure all event subscribers are removed.
*/
public release(): void {
this.eventSubscriber.release();
this.rootNavigationGroup.onAction = undefined;
this.rootNavigationGroup.onNavigation = undefined;
}
}
function isSeekBarWrapper(element: HTMLElement): boolean {
return Array.from(element.classList).findIndex(className => /-ui-seekbar$/.test(className)) > -1;
}
function getSeekBar(seekBarWrapper: HTMLElement): Element {
return seekBarWrapper.children.item(0);
}
function getPlaybackPositionMarker(seekBarWrapper: HTMLElement): HTMLElement {
return seekBarWrapper.querySelector('[class*="seekbar-playbackposition-marker"]');
}
|
cf5f569e895945f7d737c12d3a31279cc83447f5
|
TypeScript
|
artsy/positron
|
/src/client/components/draft/paragraph/utils/utils.ts
| 2.78125
| 3
|
import { getDefaultKeyBinding, KeyBindingUtil } from "draft-js"
import Immutable from "immutable"
import React from "react"
import { StyleElements, StyleMap } from "../../typings"
/**
* Helpers for draft-js Paragraph component setup
*/
/**
* blockRenderMap determines how HTML blocks are rendered in
* draft's Editor component. 'unstyled' is equivalent to <p>.
*
* Element is 'div' because draft nests <div> tags with text,
* and <p> tags cannot have nested children.
*/
export const blockRenderMap = Immutable.Map({
unstyled: {
element: "div",
},
})
/**
* Default allowed StyleMap for Paragraph component
*/
export const paragraphStyleMap: StyleMap = [
{ element: "B", name: "BOLD" },
{ element: "I", name: "ITALIC" },
]
/**
* Default allowedStyles for Paragraph component
*/
export const allowedStylesParagraph: StyleElements[] = ["B", "I"]
/**
* Extend keybindings to open link input
*/
export const keyBindingFn = (e: React.KeyboardEvent<{}>) => {
if (KeyBindingUtil.hasCommandModifier(e) && e.keyCode === 75) {
// command + k
return "link-prompt"
} else {
// Use draft or browser default handling
return getDefaultKeyBinding(e)
}
}
|
d44cbf1aa299d10087274e2ffef078ea8aa93995
|
TypeScript
|
Arveymenon/node_design_patterns
|
/src/design_patterns/singleton/singleton.ts
| 3.015625
| 3
|
import { Database, MockDB } from "./services/database_service";
export class Singleton{
database: MockDB
constructor(){
let db: MockDB = {
url: 'test',
type: "mongo"
}
this.database = Database.getInstance(db)
}
}
export class Singleton2{
database: MockDB
constructor(){
let db: MockDB = {
url: 'testing2',
type: "my-sql"
}
this.database = Database.getInstance(db)
}
}
export default class RunSingleton{
constructor(){
let instance1 = new Singleton()
console.log(instance1.database.type)
let instance2 = new Singleton2()
console.log(instance2.database.type)
// though instance2 has "my-sql" as type, it will return "mongo" as type as the instance1 has already set the DB instance and hence it will remain like that
}
}
|
573adb509dc114d3d3a8a7ab9b3ba433ce311eb2
|
TypeScript
|
oselvar/connector
|
/packages/connector-core/src/types.ts
| 3.609375
| 4
|
/**
* The primary representation of a Work Item for use in *analysis*.
*
* This type is serialisable to CSV, which is also Oselvar's basic data format for connecting
* to external sources.
*/
export type WorkItem<Stage extends string> = {
id: string
name?: string
} & StageTimestamps<Stage>
export type StageTimestamps<Stage extends string> = Partial<Record<Stage, Date | undefined | null>>
/**
* The primary representation of a Work Item for use in *connectors*.
*
* It is useful when the system does not provide a set of stage/timestamp
* pairs for each work item.
*
* If the system provides a list of events for the work item, the
* `toWorkItem` function can then be used to flatten it to a set of stage/timestamp
* pairs.
*
* This conversion detects when a work item has flowed backwards,
* and treats it as if the work item had never moved foward. This way the internal
* model always represents forward flow.
*
* This makes analysis calculations and results easier to interpret.
* It also more accurately represents what *really* happened.
*
* * Moving backwards means acknowledging a mistake, that the forward move
* should not have been done.
*
* "We moved from doing to done. Then back to doing because we found a bug".
* That's accounted for as if the work item never left doing. The move to done was a mistake,
* and the way we know that is that we acknowledged a mistake.
*
* Many systems provide a list of events for each work items.
*/
export type HistoricWorkItem<Stage extends string> = {
id: string
name: string
snapshots: readonly WorkItemSnapshot<Stage>[]
}
export type WorkItemSnapshot<Stage extends string> = {
timestamp: Date
stage: Stage
}
|
2a254b65d39805e3c73ea31837f149cca8f02421
|
TypeScript
|
nguyer/aws-sdk-js-v3
|
/clients/node/client-sagemaker-node/types/_GitConfig.ts
| 2.96875
| 3
|
/**
* <p>Specifies configuration details for a Git repository in your AWS account.</p>
*/
export interface _GitConfig {
/**
* <p>The URL where the Git repository is located.</p>
*/
RepositoryUrl: string;
/**
* <p>The default branch for the Git repository.</p>
*/
Branch?: string;
/**
* <p>The Amazon Resource Name (ARN) of the AWS Secrets Manager secret that contains the credentials used to access the git repository. The secret must have a staging label of <code>AWSCURRENT</code> and must be in the following format:</p> <p> <code>{"username": <i>UserName</i>, "password": <i>Password</i>}</code> </p>
*/
SecretArn?: string;
}
export type _UnmarshalledGitConfig = _GitConfig;
|
61e40eb27927b2caa7df1c937413d4eb5834c61d
|
TypeScript
|
danmin20/deal-12
|
/client/src/lib/router.ts
| 2.609375
| 3
|
import { isClass } from './util';
type RouterType = {
$app: any;
routes: Route[];
fallback?: string;
};
type Route = {
path: string;
redirect?: string;
component?: any;
middlewares?: any;
};
class Router {
$app: HTMLDivElement;
routes: {
[key: string]: Route;
} = {};
fallback: string = '/';
constructor({ $app, routes, fallback = '/' }: RouterType) {
this.$app = $app;
this.fallback = fallback;
this.generateRoutes(routes);
this.initEvent();
}
generateRoutes(routes: Route[]) {
routes.forEach((route: Route) => {
this.routes[route.path] = route;
});
}
initEvent() {
window.addEventListener('hashchange', () => this.onHashChangeHandler());
}
getRoute(path: string) {
const route: Route = this.routes[path];
if (!route) throw new Error(`Not found route: ${path}`);
return route;
}
hasRoute(path: string) {
return typeof this.routes[path] !== 'undefined';
}
getComponent(route: Route) {
const component = route.component;
return component;
}
async onHashChangeHandler() {
this.$app.innerHTML = '';
const hash = window.location.hash;
let path = hash.substr(1);
/* 동적 라우팅 처리 */
let route;
const regex = /\w{1,}$/; // 동적 라우팅으로 전달되는 :id 는 모두 [문자열 + 숫자] 조합으로 간주
if (this.hasRoute(path)) {
route = this.getRoute(path);
} else if (regex.test(path)) {
// 주소가 없는 경우를 동적 라우팅으로 간주하고 이를 :id 로 치환
route = this.getRoute(path.replace(regex, ':id'));
} else {
// 그 외 입력되지 않은 모든 주소에 대해서는 fallback 실행
route = this.getRoute(this.fallback);
}
if (route.redirect) {
this.push(route.redirect);
return;
}
const component = this.getComponent(route);
if (isClass(component)) {
new component(this.$app);
} else {
throw new Error('invalid component');
}
}
push(path: string) {
window.location.hash = path;
}
}
/**
* - push(path: string): void - navigate
*/
export let $router: {
push: (path: string) => void;
};
/**
* @param {{$app: HTMLElement, routes: Route[], fallback?: string}} options
*/
export function initRouter(options: RouterType) {
const { $app } = options;
// dropdown 영역 밖 클릭 시 드랍다운 제거 이벤트는 최상단 $app에서 관리
handleDropdown($app);
// mutation observer 로 슬라이더 크기 관리....
handleMutationObserver($app);
const router = new Router(options);
$router = {
push: (path) => router.push(path),
};
router.onHashChangeHandler();
}
function handleDropdown($app: HTMLElement) {
$app.addEventListener('click', (e: MouseEvent) => {
const $dropdowns = $app.querySelectorAll<HTMLElement>('.dropdown');
$dropdowns.forEach((dropdown) => {
const isOpen = dropdown.className.includes('open-dropdown');
if (isOpen) {
dropdown.classList.remove('open-dropdown');
}
});
});
}
function handleMutationObserver($app: HTMLElement) {
const $buttons = $app.parentElement?.querySelector('.buttons');
const observer = new MutationObserver((mutationRecord) => {
const $slider = $app.querySelector('.image-navigation') as HTMLElement;
if ($slider && $slider.childElementCount > 1) {
const record = mutationRecord.filter((record) => {
const isActive = (<HTMLElement>record.target).className.includes(
'active'
);
if (isActive) {
return record;
}
})[0];
const target = record.target as HTMLElement;
const slidesIdx = findCurrentViewOnSlides($app);
let offset = slidesIdx + 1;
if (target.id === 'iphone') {
$slider.style.left = -390 * offset + 'px';
} else if (target.id === 'galaxy') {
$slider.style.left = -360 * offset + 'px';
}
}
});
observer.observe($buttons as HTMLElement, {
childList: true,
subtree: true,
attributes: true,
});
}
function findCurrentViewOnSlides($app: HTMLElement) {
const $imgaeNav = $app.querySelector('.image-nav') as HTMLElement;
const regex = /[\d]{1,}/;
const activatedTarget = $imgaeNav.querySelector('.on') as HTMLElement;
const targetIdx = activatedTarget.className.match(regex)?.[0];
return +targetIdx!;
}
|
d79fe40f69305a49bb04b01b365a2aa42de8ed17
|
TypeScript
|
JDevbois/anabolicavote-frontend
|
/anabolicavote/src/app/_models/vote.model.ts
| 2.90625
| 3
|
import { Candidate } from './candidate.model';
export class Vote {
private _candidate: Candidate;
private _id: number;
private _code: String;
constructor(
candidate: Candidate, code: String
) {
this._candidate = candidate;
this._code = code;
}
static fromJSON(json: any): Vote {
const vote = new Vote(
json.candidate,
json.code,
);
vote._id = json.id;
return vote;
}
toJSON(): any {
return {
candidate: this.candidate,
code: this.code,
}
}
public get candidate(): Candidate {
return this._candidate;
}
public get code(): String {
return this._code;
}
public get id(): number {
return this._id;
}
}
|
3e486667427ea894909cf4e43cd6a033727d94c5
|
TypeScript
|
himanshu-dixit/signoz
|
/frontend/src/actions/traces.ts
| 2.703125
| 3
|
import { ActionTypes } from './types';
import tracesAPI from '../api/tracesAPI';
import { Dispatch } from 'redux';
import { GlobalTime } from './global';
// PNOTE
// define trace interface - what it should return
// define action creator to show list of traces on component mount -- use useEffect ( , []) -> Mounts when loaded first time
// Date() - takes number of milliseconds as input, our API takes in microseconds
// Sample API call for traces - https://api.signoz.io/api/traces?end=1606968273667000&limit=20&lookback=2d&maxDuration=&minDuration=&service=driver&operation=&start=1606968100867000
export interface Tree{
name: string;
value: number;
children?: Tree[];
}
export interface RefItem{
refType: string;
traceID: string;
spanID: string;
}
export interface TraceTagItem{
key: string;
// type: string;
value: string;
}
export interface ProcessItem{
serviceName: string;
tags: TraceTagItem[];
}
// PNOTE - Temp DS for converting span to tree which can be consumed by flamegraph
export interface pushDStree {
id: string;
name: string;
value: number;
time: number;
startTime: number;
tags: TraceTagItem[];
children: pushDStree[];
}
export interface spanItem{
traceID: string; // index 0
spanID: string; // index 1
operationName: string; // index 2
startTime: number; // index 3
duration: number; // index 4
references: RefItem[]; // index 5
tags: []; //index 6
logs: []; // index 7
processID: string; // index 8
warnings: []; // index 9
children: pushDStree[]; // index 10 // PNOTE - added this as we are adding extra field in span item to convert trace to tree.
// Should this field be optional?
}
//let mapped_array :{ [id: string] : spanItem; } = {};
export interface traceItem{
traceID: string;
spans: spanItem[];
processes: { [id: string] : ProcessItem; } ;
warnings: [];
}
export interface traceResponse{
data: traceItem[];
total: number;
limit: number;
offset: number;
error: [];
}
export type span = [number, string, string, string, string, string, string, string|string[], string|string[], string|string[], pushDStree[]];
export interface spanList{
events: span[];
segmentID: string;
columns: string[];
}
// export interface traceResponseNew{
// [id: string] : spanList;
// }
export interface traceResponseNew{
[id: string] : spanList;
}
export interface spansWSameTraceIDResponse{
[id: string] : spanList;
}
export interface FetchTracesAction {
type: ActionTypes.fetchTraces;
payload: traceResponseNew;
}
export interface FetchTraceItemAction {
type: ActionTypes.fetchTraceItem;
payload: spansWSameTraceIDResponse;
}
export const fetchTraces = (globalTime: GlobalTime, filter_params: string ) => {
return async (dispatch: Dispatch) => {
if (globalTime){
let request_string = 'spans?limit=100&lookback=2d&start='+globalTime.minTime+'&end='+globalTime.maxTime+'&'+filter_params;
const response = await tracesAPI.get<traceResponseNew>(request_string);
dispatch<FetchTracesAction>({
type: ActionTypes.fetchTraces,
payload: response.data
//PNOTE - response.data in the axios response has the actual API response?
});
}
};
};
export const fetchTraceItem = (traceID: string) => {
return async (dispatch: Dispatch) => {
let request_string = 'traces/'+traceID;
const response = await tracesAPI.get<spansWSameTraceIDResponse>(request_string);
dispatch<FetchTraceItemAction>({
type: ActionTypes.fetchTraceItem,
payload: response.data
//PNOTE - response.data in the axios response has the actual API response?
});
};
};
|
16eceb0e2f57581a9b8347366036f51da28900f7
|
TypeScript
|
ant-design/ant-design
|
/components/steps/useLegacyItems.ts
| 2.609375
| 3
|
import * as React from 'react';
import toArray from 'rc-util/lib/Children/toArray';
import type { StepProps } from '.';
import warning from '../_util/warning';
function filter<T>(items: (T | null)[]): T[] {
return items.filter((item) => item) as T[];
}
export default function useLegacyItems(items?: StepProps[], children?: React.ReactNode) {
if (items) {
return items;
}
warning(!children, 'Steps', 'Step is deprecated. Please use `items` directly.');
const childrenItems = toArray(children).map((node: React.ReactElement<StepProps>) => {
if (React.isValidElement(node)) {
const { props } = node;
const item: StepProps = {
...props,
};
return item;
}
return null;
});
return filter(childrenItems);
}
|
fb8b468106b11347148112a5257c82b7673337e2
|
TypeScript
|
bakaproject/angular-persistence
|
/lib/tests/persistence.container.spec.ts
| 2.96875
| 3
|
import { PersistenceService, StorageType, IPersistenceContainer } from '../src/index';
describe('Persistent Container Test: Memory', () => {
let service: PersistenceService;
let container: IPersistenceContainer;
beforeEach(() => {
service = new PersistenceService();
container = service.createContainer('namespace');
});
afterEach(() => {
service = null;
container = null;
});
it("Should persist value in memory state", () => {
container.set('abc123', 'TESTVAL');
expect(container.get('abc123')).toBe('TESTVAL');
});
it("Should persist in container and not in root", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('abc123')).toBeUndefined();
});
it("Should persist root with namespace", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('namespace::abc123')).toBe('TESTVAL');
});
it("Should not persist value on new object", () => {
expect(container.get('abc123')).toBeUndefined();
});
it("Should remove persisted value in memory state", () => {
container.set('abc123', 'TESTVAL');
container.remove('abc123');
expect(container.get('abc123')).toBeUndefined();
});
it("Should remove info object when last item is removed", () => {
container.set('abc123', 'TESTVAL');
container.remove('abc123');
expect(service.get('namespace')).toBeUndefined();
});
it("Should remove persisted value when item is undefined`", () => {
container.set('abc123', undefined);
expect(container.get('abc123')).toBeUndefined();
});
it("Should removeAll when instructed", () => {
container.set('abc123', 'TESTVAL');
container.set('def456', 'TESTVAL');
container.removeAll();
expect(container.get('abc123')).toBeUndefined();
expect(container.get('def456')).toBeUndefined();
});
it("Should persist null value`", () => {
container.set('abc123', null);
expect(container.get('abc123')).toBeNull();
});
it("Should mutate object in storage", () => {
container.set('abc123', {mutated: false});
let obj = container.get('abc123');
obj.mutated = true;
expect(container.get('abc123')).toEqual({mutated: true});
});
it("Should be isolated from root scope", () => {
container.set('abc123', "TESTVAL");
service.set('abc123', "NEW_TESTVAL");
expect(container.get('abc123')).toBe('TESTVAL');
});
});
describe('Persistent Container Test: Memory - oneUse', () => {
let service: PersistenceService;
let container: IPersistenceContainer;
beforeEach(() => {
service = new PersistenceService();
container = service.createContainer('namespace', {oneUse: true});
});
afterEach(() => {
service = null;
container = null;
});
it("Should return persisted value on first use", () => {
container.set('abc123', 'TESTVAL');
expect(container.get('abc123')).toBe('TESTVAL');
});
it("Should return undefined on second use", () => {
container.set('abc123', 'TESTVAL');
container.get('abc123');
expect(container.get('abc123')).toBeUndefined();
});
});
describe('Persistent Container Test: Memory - expires', () => {
let service: PersistenceService;
let container: IPersistenceContainer;
beforeEach(() => {
service = new PersistenceService();
container = service.createContainer('namespace', {expireAfter: 100});
});
afterEach(() => {
service = null;
container = null;
});
it("Should persist if expires has not been reached", () => {
container.set('abc123', 'TESTVAL');
expect(container.get('abc123')).toBe('TESTVAL');
expect(container.get('abc123')).toBe('TESTVAL');
});
it("Should remove persisted value if expires has been reached", (done) => {
container.set('abc123', 'TESTVAL');
setTimeout ( () => {
expect(container.get('abc123')).toBeUndefined();
done();
}, 150);
});
it("Should not persist if get is hit within expires multiple times", (done) => {
container.set('abc123', 'TESTVAL');
setTimeout ( () => {
expect(container.get('abc123')).toBe('TESTVAL');
setTimeout ( () => {
expect(container.get('abc123')).toBeUndefined();
done();
}, 75);
}, 75);
});
});
describe('Persistent Container Test: Memory - timeout', () => {
let service: PersistenceService;
let container: IPersistenceContainer;
beforeEach(() => {
service = new PersistenceService();
container = service.createContainer('namespace', {timeout: 100});
});
afterEach(() => {
service = null;
container = null;
});
it("Should persist if expires has not been reached", (done) => {
container.set('abc123', 'TESTVAL');
expect(container.get('abc123')).toBe('TESTVAL');
setTimeout( () => {
expect(container.get('abc123')).toBe('TESTVAL');
done();
}, 75);
});
it("Should remove persisted value if expires has been reached", (done) => {
container.set('abc123', 'TESTVAL');
setTimeout ( () => {
expect(container.get('abc123')).toBeUndefined();
done();
}, 150);
});
it("Should not persist if get is hit within expires multiple times", (done) => {
container.set('abc123', 'TESTVAL');
setTimeout ( () => {
expect(container.get('abc123')).toBe('TESTVAL');
setTimeout ( () => {
expect(container.get('abc123')).toBe('TESTVAL');
done();
}, 75);
}, 75);
});
});
describe('Persistent Container Test: ImmutableMemory', () => {
let service: PersistenceService;
let container: IPersistenceContainer;
beforeEach(() => {
service = new PersistenceService();
container = service.createContainer('namespace', {type: StorageType.IMMUTABLE_MEMORY});
});
afterEach(() => {
service = null;
container = null;
});
it("Should persist value in memory state", () => {
container.set('abc123', 'TESTVAL');
expect(container.get('abc123')).toBe('TESTVAL');
});
it("Should persist in container and not in root", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('abc123', StorageType.IMMUTABLE_MEMORY)).toBeUndefined();
});
it("Should persist root with namespace", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('namespace::abc123', StorageType.IMMUTABLE_MEMORY)).toBe('TESTVAL');
});
it("Should not persist value on new object", () => {
expect(container.get('abc123')).toBeUndefined();
});
it("Should remove persisted value in memory state", () => {
container.set('abc123', 'TESTVAL');
container.remove('abc123');
expect(container.get('abc123')).toBeUndefined();
});
it("Should remove info object when last item is removed", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('namespace', StorageType.IMMUTABLE_MEMORY)).toBeTruthy();
container.remove('abc123');
expect(service.get('namespace', StorageType.IMMUTABLE_MEMORY)).toBeUndefined();
});
it("Should remove persisted value when item is undefined`", () => {
container.set('abc123', undefined);
expect(container.get('abc123')).toBeUndefined();
});
it("Should removeAll when instructed", () => {
container.set('abc123', 'TESTVAL');
container.set('def456', 'TESTVAL');
container.removeAll();
expect(container.get('abc123')).toBeUndefined();
expect(container.get('def456')).toBeUndefined();
});
it("Should persist null value`", () => {
container.set('abc123', null);
expect(container.get('abc123')).toBeNull();
});
it("Should not mutate object in storage", () => {
container.set('abc123', {mutated: false});
let obj = container.get('abc123');
obj.mutated = true;
expect(container.get('abc123')).toEqual({mutated: false});
});
it("Should be isolated from root scope", () => {
container.set('abc123', "TESTVAL");
service.set('abc123', "NEW_TESTVAL", {type: StorageType.IMMUTABLE_MEMORY});
expect(container.get('abc123')).toBe('TESTVAL');
});
});
describe('Persistent Container Test: Session', () => {
let service: PersistenceService;
let container: IPersistenceContainer;
beforeAll(() => {
sessionStorage.clear();
});
beforeEach(() => {
service = new PersistenceService();
container = service.createContainer('namespace', {type: StorageType.SESSION});
});
afterEach(() => {
service = null;
container = null;
});
it("Should persist value in memory state", () => {
container.set('abc123', 'TESTVAL');
expect(container.get('abc123')).toBe('TESTVAL');
});
it("Should persist in container and not in root", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('abc123', StorageType.SESSION)).toBeUndefined();
});
it("Should persist root with namespace", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('namespace::abc123', StorageType.SESSION)).toBe('TESTVAL');
});
it("Should persist value on new object", () => {
expect(container.get('abc123')).toBe('TESTVAL');
});
it("Should remove persisted value in memory state", () => {
container.set('abc123', 'TESTVAL');
container.remove('abc123');
expect(container.get('abc123')).toBeUndefined();
});
it("Should remove info object when last item is removed", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('namespace', StorageType.SESSION)).toBeTruthy();
container.remove('abc123');
expect(service.get('namespace', StorageType.SESSION)).toBeUndefined();
});
it("Should remove persisted value when item is undefined`", () => {
container.set('abc123', undefined);
expect(container.get('abc123')).toBeUndefined();
});
it("Should removeAll when instructed", () => {
container.set('abc123', 'TESTVAL');
container.set('def456', 'TESTVAL');
container.removeAll();
expect(container.get('abc123')).toBeUndefined();
expect(container.get('def456')).toBeUndefined();
});
it("Should persist null value`", () => {
container.set('abc123', null);
expect(container.get('abc123')).toBeNull();
});
it("Should not mutate object in storage", () => {
container.set('abc123', {mutated: false});
let obj = container.get('abc123');
obj.mutated = true;
expect(container.get('abc123')).toEqual({mutated: false});
});
it("Should be isolated from root scope", () => {
container.set('abc123', "TESTVAL");
service.set('abc123', "NEW_TESTVAL", {type: StorageType.SESSION});
expect(container.get('abc123')).toBe('TESTVAL');
});
});
describe('Persistent Container Test: Local', () => {
let service: PersistenceService;
let container: IPersistenceContainer;
beforeAll(() => {
localStorage.clear();
});
beforeEach(() => {
service = new PersistenceService();
container = service.createContainer('namespace', {type: StorageType.LOCAL});
});
afterEach(() => {
service = null;
container = null;
});
it("Should persist value in memory state", () => {
container.set('abc123', 'TESTVAL');
expect(container.get('abc123')).toBe('TESTVAL');
});
it("Should persist in container and not in root", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('abc123', StorageType.LOCAL)).toBeUndefined();
});
it("Should persist root with namespace", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('namespace::abc123', StorageType.LOCAL)).toBe('TESTVAL');
});
it("Should persist value on new object", () => {
expect(container.get('abc123')).toBe('TESTVAL');
});
it("Should remove persisted value in memory state", () => {
container.set('abc123', 'TESTVAL');
container.remove('abc123');
expect(container.get('abc123')).toBeUndefined();
});
it("Should remove info object when last item is removed", () => {
container.set('abc123', 'TESTVAL');
expect(service.get('namespace', StorageType.LOCAL)).toBeTruthy();
container.remove('abc123');
expect(service.get('namespace', StorageType.LOCAL)).toBeUndefined();
});
it("Should remove persisted value when item is undefined`", () => {
container.set('abc123', undefined);
expect(container.get('abc123')).toBeUndefined();
});
it("Should removeAll when instructed", () => {
container.set('abc123', 'TESTVAL');
container.set('def456', 'TESTVAL');
container.removeAll();
expect(container.get('abc123')).toBeUndefined();
expect(container.get('def456')).toBeUndefined();
});
it("Should persist null value`", () => {
container.set('abc123', null);
expect(container.get('abc123')).toBeNull();
});
it("Should not mutate object in storage", () => {
container.set('abc123', {mutated: false});
let obj = container.get('abc123');
obj.mutated = true;
expect(container.get('abc123')).toEqual({mutated: false});
});
it("Should be isolated from root scope", () => {
container.set('abc123', "TESTVAL");
service.set('abc123', "NEW_TESTVAL", {type: StorageType.LOCAL});
expect(container.get('abc123')).toBe('TESTVAL');
});
});
|
5825d7b8f886b3168437d8433f950c06765b53eb
|
TypeScript
|
rasmus-storjohann/fixMyMusic
|
/src/businessObjects/fixers/details/parserDetails.ts
| 3
| 3
|
export function toString(from, field: string): string | undefined
{
return isString(from[field]) ? from[field] + "" : undefined;
}
export function isString(s: any): boolean { return s && s + "" === s; }
export function toNumber(from, field): number | undefined
{
return isNumber(from[field]) ? from[field] + 0 : undefined;
}
export function isNumber(n: any): boolean { return n && n + 0 === n; }
|
053050f1b055c00055cc66bf81394c62ae33db9f
|
TypeScript
|
iChris96/movies-app
|
/src/models/Movies.ts
| 2.59375
| 3
|
import { Schema, model } from 'mongoose';
export interface IMovie {
id: number;
adult: boolean;
backdropPath: string;
genreIds: Array<number>;
originalLenguaje: string;
originalTitle: string;
overview: string;
popularity: number;
releaseDate: string;
title: string;
video: boolean;
voteAverage: number;
voteCount: number;
posterPath: string;
}
const MovieSchema = new Schema<IMovie>({
id: Number,
adult: Boolean,
genreIds: [Number],
overview: String,
popularity: Number,
title: String,
video: Boolean,
vote_average: { type: Number, alias: 'voteAverage' },
vote_count: { type: Number, alias: 'voteCount' },
backdrop_path: { type: String, alias: 'backdropPath' },
original_lenguaje: { type: String, alias: 'originalLenguaje' },
original_title: { type: String, alias: 'originalTitle' },
release_date: { type: String, alias: 'releaseDate' },
poster_path: { type: String, alias: 'posterPath' },
});
export const Movies = model<IMovie>('Movies', MovieSchema);
|
ffaca1190e4545212a9eaf50af9145e3feb55adc
|
TypeScript
|
DoctorMcKay/node-websocket13-jsonrpc
|
/src/classes/WsRpcOutgoingConnection.ts
| 2.6875
| 3
|
import {WebSocket} from 'websocket13';
import WsRpcConnection from './WsRpcConnection';
const ACTIVE_SUBPROTOCOL = 'jsonrpc-2.0';
export default class WsRpcOutgoingConnection extends WsRpcConnection {
/**
* Establish a new outgoing connection.
* @param {string} url
* @param {object} [options]
*/
constructor(url, options) {
let opts = Object.assign({}, options || {});
opts.protocols = [ACTIVE_SUBPROTOCOL];
let socket = new WebSocket(url, opts);
super(null, socket);
this._options = opts;
this._requestHandlers = {};
this._notificationHandlers = {};
socket.on('connected', (details) => {
this.emit('connected', details);
});
socket.on('disconnected', (code, reason, initiatedByUs) => {
this.emit('disconnected', code, reason, initiatedByUs);
});
socket.on('error', (err) => {
this.emit('error', err);
});
}
get server() {
return null;
}
get groups() {
return [];
}
joinGroup(group: string): boolean {
throw new Error('Cannot join an outgoing connection to a group.');
}
leaveGroup(group: string): boolean {
throw new Error('Cannot leave an outgoing connection from a group.');
}
/**
* Register a handler for a method.
* @param {string} name
* @param {function<Promise>} handler - A function to be invoked when the method is called.
* Must return a value immediately or return a Promise. Invoked with arguments (WsRpcConnection, any params)
*/
registerMethod(name, handler) {
this._requestHandlers[name] = handler;
}
/**
* Register a handler for an incoming notification. Notifications may not be responded to.
* @param {string} name
* @param {function} handler - Invoked with arguments (WsRpcConnection, any params)
*/
registerNotification(name, handler) {
this._notificationHandlers[name] = handler;
}
}
|
53920656c71dd71553882f9fde72931b34c3d90d
|
TypeScript
|
innogames/dr-json
|
/src/domain/context/data/filter/bySearch.ts
| 2.71875
| 3
|
import {DataEntry} from '../../../states/objects/editor/DataEntry';
export function bySearch(search: string): (entry: DataEntry) => boolean {
if (!search) {
return () => true;
}
search = search.toLowerCase();
return (entry: DataEntry) => {
const haystack = entry.toJson().replace('\\', '').toLowerCase();
return haystack.indexOf(search) >= 0;
};
}
|
d5cabd4148407260a446633aff90677aaed543b5
|
TypeScript
|
chevre-jp/factory
|
/src/place/screeningRoomSection.ts
| 2.546875
| 3
|
import * as PlaceFactory from '../place';
import { PlaceType } from '../placeType';
import { IPlace as ISeat, IPlaceWithOffer as ISeatWithOffer } from './seat';
/**
* セクション
*/
export interface IPlace extends Pick<
PlaceFactory.IPlace,
'project' | 'typeOf' | 'branchCode' | 'name' | 'containedInPlace' | 'containsPlace' | 'additionalProperty'
> {
typeOf: PlaceType.ScreeningRoomSection;
/**
* 座席リスト
*/
containsPlace: ISeat[];
/**
* 枝番号
*/
branchCode: string;
/**
* 座席数
*/
seatCount?: number;
}
export interface IPlaceWithOffer extends IPlace {
containsPlace: ISeatWithOffer[];
}
export interface ISearchConditions {
limit?: number;
page?: number;
sort?: any;
project?: { id?: { $eq?: string } };
parentOrganization?: {
id?: { $eq?: string };
};
branchCode?: {
$eq?: string;
$regex?: string;
};
containedInPlace?: {
branchCode?: { $eq?: string };
containedInPlace: {
branchCode?: { $eq?: string };
};
};
name?: {
$regex?: string;
};
$projection?: {
seatCount?: 1;
};
additionalProperty?: {
$elemMatch?: {
name?: {
/**
* 一致する名称の追加特性がひとつでも存在する
*/
$eq?: string;
};
};
};
}
|
3ea2ba21b1f31910581b5291af90bd2d13c8f034
|
TypeScript
|
tolym/life-helper-web
|
/src/app/core/services/logger.ts
| 3.640625
| 4
|
/**
* @todo
* 先简单弄一个,后面再优化
*/
import { environment } from 'src/environments/environment'
export interface LoggingOptions {
type: 'debug' | 'info' | 'warn' | 'error'
message: string
}
/**
* 日志服务(非单例服务)
*
* @description
* ```js
* // 必须使用以下方式导入,这里是特意设定成非 DI 的方式使用的
* const logger = new Logger('prefix')
* ```
*/
export class Logger {
/** 是否为生产环境 */
private readonly isProd: boolean = environment.production
constructor(private prefix?: string) {
// empty
}
debug(...args: unknown[]): void {
const message = this.makeMessage(args)
this.makeLog({ type: 'debug', message })
}
info(...args: unknown[]): void {
const message = this.makeMessage(args)
this.makeLog({ type: 'debug', message })
}
warn(...args: unknown[]): void {
const message = this.makeMessage(args)
this.makeLog({ type: 'debug', message })
}
error(...args: unknown[]): void {
const message = this.makeMessage(args)
this.makeLog({ type: 'debug', message })
}
private isValid(): boolean {
return !this.isProd
}
private makeMessage(msgs: unknown[]): string {
return msgs
.filter((msg) => ['string', 'number', 'boolean', 'object'].includes(typeof msg))
.map((msg) => {
if (typeof msg === 'string') {
return msg
} else if (typeof msg === 'number') {
return String(msg)
} else if (typeof msg === 'boolean') {
return String(msg)
} else {
return '\n' + JSON.stringify(msg, null, 2)
}
})
.join(' ')
}
private makeLog(options: LoggingOptions): void {
if (this.isValid()) {
const time = new Date().toISOString()
const prefix = this.prefix ? `[${this.prefix}] ` : ''
const sentence = `${time} ${options.type.toUpperCase()} ${prefix}${options.message}`
if (options.type === 'debug') {
console.log(sentence)
} else {
console[options.type](sentence)
}
}
}
}
|
e03d541d5bce45ba45f41367811499f1333e89b3
|
TypeScript
|
liangchunn/typescript-node-scripts
|
/src/scripts/migration/tslint-to-eslint/hash.ts
| 2.625
| 3
|
import crypto from 'crypto'
import * as fs from 'fs'
export function getFileHash(path: string) {
return new Promise((resolve) => {
const hash = crypto.createHash('sha256')
const input = fs.createReadStream(path, { encoding: 'utf-8' })
input.on('readable', () => {
const data = input.read()
if (data) {
hash.update(data)
} else {
return resolve(hash.digest('hex'))
}
})
})
}
|
66ee5bd3b438cb37baf2a9bcdd96fa7c90336193
|
TypeScript
|
designunit/uray
|
/src/reducers/userSettingsReducer.ts
| 2.609375
| 3
|
import {
ACTION_LAYER_FILTER_TREE_SET_CHECKED_KEYS,
ACTION_USER_SETTINGS_LAYER_MAKE_CURRENT,
ACTION_USER_SETTINGS_SET_LAYER_CLUSTER,
ACTION_USER_SETTINGS_SET_LAYER_VISIBLE,
} from '../app/actions'
import { IUserSettings, LayerId } from '../app/types'
export function userSettingsReducer(state: IUserSettings, action: any): IUserSettings {
if (action.type === ACTION_LAYER_FILTER_TREE_SET_CHECKED_KEYS) {
const id = action.payload.layerId
return {
...state,
layerFilterTreeCheckedKeys: {
...state.layerFilterTreeCheckedKeys,
[id]: action.payload.checkedKeys,
},
}
}
if (action.type === ACTION_USER_SETTINGS_LAYER_MAKE_CURRENT) {
const currentLayerId: LayerId = action.payload.id
return {
...state,
currentLayerId,
}
}
if (action.type === ACTION_USER_SETTINGS_SET_LAYER_VISIBLE) {
const layerId: LayerId = action.payload.layerId
const visible = action.payload.visible
return {
...state,
layerVisible: {
...state.layerVisible,
[layerId]: visible,
},
}
}
if (action.type === ACTION_USER_SETTINGS_SET_LAYER_CLUSTER) {
const layerId: LayerId = action.payload.layerId
const clusteringEnabled = action.payload.clusteringEnabled
return {
...state,
layerClusterIndex: {
...state.layerClusterIndex,
[layerId]: clusteringEnabled,
},
}
}
return state
}
|
e7e4ce4d4e326de5f0d1229dc9ee47430e79e8f8
|
TypeScript
|
dreiv/ng-test
|
/src/app/service/languages.service.spec.ts
| 2.515625
| 3
|
/* tslint:disable:no-unused-variable */
import { TestBed, inject } from '@angular/core/testing';
import { LanguagesService } from './languages.service';
describe('LanguagesService', () => {
let service: LanguagesService; // to access properties and methods
// setup
beforeEach(() => {
TestBed.configureTestingModule({
providers: [LanguagesService]
}).compileComponents();
});
beforeEach(inject([LanguagesService], s => {
service = s;
}));
// specs
it('should create an instance of LanguagesService', () => {
expect(service).toBeTruthy();
})
it('should return the available languages', () => {
const languages = service.get();
expect(languages).toContain('en');
expect(languages).toContain('de');
expect(languages).toContain('fr');
expect(languages.length).toEqual(3);
})
});
|
c661738b328d501092194315ffbc55bdcafe72f2
|
TypeScript
|
TheLox95/expert-platform-frontend
|
/src/tools/uploadManager/UploadFile.ts
| 2.5625
| 3
|
import { HttpFun } from "requests/http"
const uploadFile = <F>(http: HttpFun, file: File, onProgress: (v: number) => void) => {
const data = new FormData()
data.append('files', file)
return () => {
return http<F[]>({
disableGlobal: true,
url: `${process.env.REACT_APP_BACKEND_URL}/offerings/upload`,
method: 'post',
data,
onUploadProgress: function(progressEvent: {loaded: number, total: number} ) {
var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
onProgress(percentCompleted)
},
headers: {
'Content-Type': 'multipart/form-data'
}
})
.catch(() => {
onProgress(-1)
throw file;
})
}
}
export default uploadFile;
|
83dcc26f0d461c17fa99693465d99153facb17d9
|
TypeScript
|
tech-espm/labs-eventos
|
/models/palestranteResumido.ts
| 2.75
| 3
|
import Sql = require("../infra/sql");
import Empresa = require("./empresa");
import Evento = require("./evento");
import Palestrante = require("./palestrante");
import TipoEmpresa = require("./tipoEmpresa");
import emailValido = require("../utils/emailValido");
export = class PalestranteResumido {
public id: number;
public nome: string;
public email: string;
public empresa: string;
private static validar(p: PalestranteResumido): string {
p.nome = (p.nome || "").normalize().trim();
if (p.nome.length > 100)
return "Nome inválido";
p.email = (p.email || "").normalize().trim().toUpperCase();
if (p.email.length > 100 || (p.email && !emailValido(p.email)))
return "E-mail inválido";
p.empresa = (p.empresa || "").normalize().trim();
if (p.empresa.length > 100)
return "Empresa inválido";
return null;
}
public static async criar(idevento: number, pr: PalestranteResumido): Promise<string> {
let res: string;
if ((res = PalestranteResumido.validar(pr)))
return res;
if (!pr.nome && !pr.email && !pr.empresa)
return null;
if (!pr.nome || !pr.email || !pr.empresa)
return "Dados inválidos!";
pr.id = await Palestrante.obterIdDeEmail(idevento, pr.email);
if (pr.id)
return null;
let p = new Palestrante();
p.id = 0;
p.idevento = idevento;
p.idempresa = await Empresa.obterIdDeNome(idevento, pr.empresa);
p.nome = pr.nome;
p.nome_curto = (pr.nome.length <= 45 ? pr.nome : pr.nome.substr(0, 45)),
p.email = pr.email;
p.oculto = 0;
p.prioridade = 0;
p.versao = 0;
if (!p.idempresa) {
let e = new Empresa();
e.id = 0;
e.idevento = idevento;
e.nome = pr.empresa;
e.nome_curto = (pr.empresa.length <= 45 ? pr.empresa : pr.empresa.substr(0, 45));
e.idtipo = await TipoEmpresa.obterIdPadrao();
e.versao = 0;
res = await Empresa.criar(e, { buffer: new Buffer(Evento.gerarPNGVazio()) });
if (res && res !== parseInt(res).toString())
return res;
p.idempresa = e.id;
}
res = await Palestrante.criar(p, { buffer: new Buffer(Evento.gerarPNGVazio()) });
pr.id = p.id;
return res;
}
}
|
4eb2e0ed0f23fa9e3d08726e578e053cfa750274
|
TypeScript
|
theniteshsingh/next-auth
|
/packages/next-auth/tests/middleware.test.ts
| 2.6875
| 3
|
import { NextMiddleware, NextRequest } from "next/server"
import { NextAuthMiddlewareOptions, withAuth } from "../src/next/middleware"
it("should not match pages as public paths", async () => {
const options: NextAuthMiddlewareOptions = {
pages: { signIn: "/", error: "/" },
secret: "secret",
}
const req = new NextRequest("http://127.0.0.1/protected/pathA", {
headers: { authorization: "" },
})
const handleMiddleware = withAuth(options) as NextMiddleware
const res = await handleMiddleware(req, null as any)
expect(res).toBeDefined()
expect(res?.status).toBe(307)
})
it("should not redirect on public paths", async () => {
const options: NextAuthMiddlewareOptions = { secret: "secret" }
const req = new NextRequest("http://127.0.0.1/_next/foo", {
headers: { authorization: "" },
})
const handleMiddleware = withAuth(options) as NextMiddleware
const res = await handleMiddleware(req, null as any)
expect(res).toBeUndefined()
})
it("should redirect according to nextUrl basePath", async () => {
const options: NextAuthMiddlewareOptions = { secret: "secret" }
const req = {
nextUrl: {
pathname: "/protected/pathA",
search: "",
origin: "http://127.0.0.1",
basePath: "/custom-base-path",
},
headers: new Headers({ authorization: "" }),
}
const handleMiddleware = withAuth(options) as NextMiddleware
const res = await handleMiddleware(req as NextRequest, null as any)
expect(res).toBeDefined()
expect(res?.status).toEqual(307)
expect(res?.headers.get("location")).toContain(
"http://127.0.0.1/custom-base-path/api/auth/signin?callbackUrl=%2Fcustom-base-path%2Fprotected%2FpathA"
)
})
it("should redirect according to nextUrl basePath", async () => {
// given
const options: NextAuthMiddlewareOptions = { secret: "secret" }
const handleMiddleware = withAuth(options) as NextMiddleware
const req1 = {
nextUrl: {
pathname: "/protected/pathA",
search: "",
origin: "http://127.0.0.1",
basePath: "/custom-base-path",
},
headers: new Headers({ authorization: "" }),
}
// when
const res = await handleMiddleware(req1 as NextRequest, null as any)
// then
expect(res).toBeDefined()
expect(res?.status).toEqual(307)
expect(res?.headers.get("location")).toContain(
"http://127.0.0.1/custom-base-path/api/auth/signin?callbackUrl=%2Fcustom-base-path%2Fprotected%2FpathA"
)
const req2 = {
nextUrl: {
pathname: "/api/auth/signin",
search: "callbackUrl=%2Fcustom-base-path%2Fprotected%2FpathA",
origin: "http://127.0.0.1",
basePath: "/custom-base-path",
},
headers: new Headers({ authorization: "" }),
}
// and when follow redirect
const resFromRedirectedUrl = await handleMiddleware(
req2 as NextRequest,
null as any
)
// then return sign in page
expect(resFromRedirectedUrl).toBeUndefined()
})
|
eb36785519b502c47017ad33511d33fe88cd2d6f
|
TypeScript
|
jedielson/kong-playground
|
/microservices/catalog/src/utils/test/authors/author.spec-builder.ts
| 2.6875
| 3
|
import * as Factory from 'factory.ts';
import * as Faker from 'faker';
import { Book } from '../../../modules/bookstore/book/book.entity';
import { Author } from '../../../modules/bookstore/author/author.entity';
import { IBuilder } from '../common/IBuilder';
export class AuthorBuilder implements IBuilder<AuthorBuilder, Author> {
asyncFactory: Factory.Async.Factory<Author, keyof Author>;
transformFactory: Factory.Async.TransformFactory<
Author,
keyof Author,
Author
>;
books: Book[];
withDefaultConfigs(): AuthorBuilder {
this.withAsyncFactory().withAsyncTransform();
return this;
}
withAsyncFactory(): AuthorBuilder {
this.asyncFactory = Factory.Async.makeFactory<Author>(new Author());
return this;
}
withAsyncTransform(): AuthorBuilder {
const b = this.books;
this.transformFactory = this.asyncFactory.transform((a: Author) => {
a.name = Faker.name.findName(
Faker.name.firstName(),
Faker.name.lastName(),
);
a.books = b;
return a;
});
return this;
}
withBooks(books: Book[]): AuthorBuilder {
this.books = books;
return this;
}
build(): Promise<Author> {
return this.transformFactory.build();
}
async buildList(length: number): Promise<Author[]> {
return this.transformFactory.buildList(length);
}
}
|
17b149799f043549f42dd1a6a33ed23f895a9c63
|
TypeScript
|
jgretz/pghbeer
|
/site/app/services/loadDataForEvent.ts
| 2.8125
| 3
|
import * as R from 'ramda';
import type {Beer, EventItemData} from '~/Types';
import {DATA_URL} from '~/constants';
function projectBeers(data: EventItemData[]) {
return data.map((d) => d.beer);
}
const groupBeersByBrewery = R.groupBy(function (beer: Beer) {
return beer.brewery.name;
});
function sortBreweriesByName(a: string, b: string) {
return a.localeCompare(b);
}
function sortBeersByName(a: Beer, b: Beer) {
return a.name.localeCompare(b.name);
}
function sortBreweriesAndBeers(data: Record<string, Beer[]>) {
const keys = Object.keys(data);
const sortedData: Record<string, Beer[]> = keys.reduce(function (record, key) {
record[key] = R.sort(sortBeersByName, data[key]);
return record;
}, {} as Record<string, Beer[]>);
return {
breweries: R.sort(sortBreweriesByName, keys),
data: sortedData,
};
}
const prepare = R.pipe(projectBeers, groupBeersByBrewery, sortBreweriesAndBeers);
export async function loadDataForEvent(eventId: number) {
const url = `${DATA_URL}${eventId}`;
const res = await fetch(url);
const data: EventItemData[] = await res.json();
return prepare(data);
}
|
7a9012c1060c5202d7fe7597923752248fa8ce70
|
TypeScript
|
serverless-tencent/serverless-warmer
|
/src/warm.ts
| 2.609375
| 3
|
import { program } from 'commander';
import ora from 'ora';
import chalk from 'chalk';
import assert from 'assert';
import { Sls } from './components/sls';
import { Faas } from './components/faas';
import { Credential, WarmOptions } from './typings';
const getCredential = (): Credential | null => {
const { TENCENT_SECRET_ID, TENCENT_SECRET_KEY, TENCENT_TOKEN } = process.env;
if (TENCENT_SECRET_ID && TENCENT_SECRET_KEY) {
return {
secretId: TENCENT_SECRET_ID,
secretKey: TENCENT_SECRET_KEY,
token: TENCENT_TOKEN,
};
}
return null;
};
export async function warm(options: WarmOptions): Promise<boolean> {
let isWarmUped = false;
const credential = getCredential();
if (credential) {
const spinner = ora();
try {
if (options.type === 'function') {
spinner.start(`Warming up function ${options.functionName}`);
const faas = new Faas({
...credential,
region: options.region,
});
isWarmUped = await faas.warmUp(options);
} else {
assert(options.name, '[OPTIONS] name is required');
assert(options.app, '[OPTIONS] app is required');
spinner.start(
`Warming up application ${options.app}, stage ${options.stage}, name ${options.name}`,
);
const sls = new Sls({
...credential,
region: options.region,
});
isWarmUped = await sls.warmUp(options);
}
if (isWarmUped) {
spinner.succeed('Warm up success');
} else {
spinner.stop();
}
} catch (e) {
spinner.fail(e.message);
}
} else {
console.log(chalk.red(`Missing credential information!`));
}
return isWarmUped;
}
const warmCommand = (): void => {
program
.description('Warm up serverless application or function')
.option('-r, --region [region]', 'region of function', 'ap-guangzhou')
.option('-n, --name [name]', 'name config in serverless.yml')
.option('-a, --app [app]', 'app name')
.option('-s, --stage [stage]', 'app stage', 'dev')
.option('-o, --org [org]', 'app org name')
.option('-f, --function-name [functionName]', 'app function name')
.action((options) => {
warm({
type: options?.functionName ? 'function' : 'app',
...options,
});
});
};
export { warmCommand };
|
7095e2cfbdb9f087d0fe285c75c126b630430d6a
|
TypeScript
|
Sabai-Technologies/simple-object-validator
|
/ts/typings/folktale/data.validation.d.ts
| 3.734375
| 4
|
// Type definitions for data.validation
declare interface SemiGroup {
concat(c:SemiGroup):SemiGroup;
}
declare class Validation {
// -- Constructors -----------------------------------------------------
/**
* Constructs a new `Validation[α, β]` structure holding a `Failure` value.
*
* @summary a → Validation[α, β]
*/
static Failure(a:SemiGroup):Failure;
/**
* Constructs a new `Etiher[α, β]` structure holding a `Success` value.
*
* @summary β → Validation[α, β]
*/
static Success(a:any):Success;
// -- Conversions ------------------------------------------------------
/**
* Constructs a new `Validation[α, β]` structure from a nullable type.
*
* Takes the `Failure` case if the value is `null` or `undefined`. Takes the
* `Success` case otherwise.
*
* @summary α → Validation[α, α]
*/
static fromNullable(a:any):Validation;
/**
* Constructs a new `Either[α, β]` structure from a `Validation[α, β]` type.
*
* @summary Either[α, β] → Validation[α, β]
*/
//TODO manage Either
//static fromEither(a:Either):Validation<any,any>;
// -- Predicates -------------------------------------------------------
/**
* True if the `Validation[α, β]` contains a `Failure` value.
*
* @summary Boolean
*/
isFailure:boolean;
/**
* True if the `Validation[α, β]` contains a `Success` value.
*
* @summary Boolean
*/
isSuccess:boolean;
// -- Applicative ------------------------------------------------------
/**
* Creates a new `Validation[α, β]` instance holding the `Success` value `b`.
*
* `b` can be any value, including `null`, `undefined` or another
* `Validation[α, β]` structure.
*
* @summary β → Validation[α, β]
*/
static of(a:any):Validation;
/**
* Applies the function inside the `Success` case of the `Validation[α, β]` structure
* to another applicative type.
*
* The `Validation[α, β]` should contain a function value, otherwise a `TypeError`
* is thrown.
*
* @method
* @summary (@Validation[α, β → γ], f:Applicative[_]) => f[β] → f[γ]
*/
ap(b:Validation):Validation;
// -- Functor ----------------------------------------------------------
/**
* Transforms the `Success` value of the `Validation[α, β]` structure using a regular
* unary function.
*
* @method
* @summary (@Validation[α, β]) => (β → γ) → Validation[α, γ]
*/
map(fn:(n:any) => any):Validation;
// -- Show -------------------------------------------------------------
/**
* Returns a textual representation of the `Validation[α, β]` structure.
*
* @method
* @summary (@Validation[α, β]) => Void → String
*/
toString():string;
// -- Eq ---------------------------------------------------------------
/**
* Tests if an `Validation[α, β]` structure is equal to another `Validation[α, β]`
* structure.
*
* @method
* @summary (@Validation[α, β]) => Validation[α, β] → Boolean
*/
isEqual(a:any):boolean;
// -- Extracting and recovering ----------------------------------------
/**
* Extracts the `Success` value out of the `Validation[α, β]` structure, if it
* exists. Otherwise throws a `TypeError`.
*
* @method
* @summary (@Validation[α, β]) => Void → β :: partial, throws
* @see {@link module:lib/validation~Validation#getOrElse} — A getter that can handle failures.
* @see {@link module:lib/validation~Validation#merge} — The convergence of both values.
* @throws {TypeError} if the structure has no `Success` value.
*/
get():any;
/**
* Extracts the `Success` value out of the `Validation[α, β]` structure. If the
* structure doesn't have a `Success` value, returns the given default.
*
* @method
* @summary (@Validation[α, β]) => β → β
*/
getOrElse(a:any):any;
/**
* Transforms a `Failure` value into a new `Validation[α, β]` structure. Does nothing
* if the structure contain a `Success` value.
*
* @method
* @summary (@Validation[α, β]) => (α → Validation[γ, β]) → Validation[γ, β]
*/
orElse(f:Function):any;
/**
* Returns the value of whichever side of the disjunction that is present.
*
* @summary (@Validation[α, α]) => Void → α
*/
merge():any;
// -- Folds and Extended Transformations -------------------------------
/**
* Applies a function to each case in this data structure.
*
* @method
* @summary (@Validation[α, β]) => (α → γ), (β → γ) → γ
*/
fold(f:Function, g:Function):any;
/**
* Catamorphism.
*
* @method
* @summary (@Validation[α, β]) => { Success: α → γ, Failure: α → γ } → γ
*/
cata<T>(v:{Sucess:(a:any)=>T, Failure:(a:any)=>T}):T;
/**
* Swaps the disjunction values.
*
* @method
* @summary (@Validation[α, β]) => Void → Validation[β, α]
*/
swap():Validation;
/**
* Maps both sides of the disjunction.
*
* @method
* @summary (@Validation[α, β]) => (α → γ), (β → δ) → Validation[γ, δ]
*/
bimap(g:(a:any[]) => any, f:Function):Validation;
/**
* Maps the failure side of the disjunction.
*
* @method
* @summary (@Validation[α, β]) => (α → γ) → Validation[γ, β]
*/
failureMap(f:Function):Validation;
/**
* Maps the failure side of the disjunction.
*
* @method
* @deprecated in favour of {@link module:lib/validation~Validation#failureMap}
* @summary (@Validation[α, β]) => (α → γ) → Validation[γ, β]
*/
leftMap(f:Function):Validation;
}
declare class Success extends Validation {
bimap(_:any, f:Function):Success;
}
declare class Failure extends Validation {
fold(_:any, g:Function):SemiGroup;
bimap(g:(a:any[]) => any, _:any):Failure;
}
declare module 'data.validation' {
export = Validation;
}
|
693eaafb5d2afa8af2feed74bd9f15dc982cc99f
|
TypeScript
|
nicky-lenaers/mogr
|
/src/pagination/types/query-options.spec.ts
| 2.546875
| 3
|
import { GraphQLObjectType, GraphQLString, GraphQLNonNull, GraphQLSchema } from "graphql";
import { QueryOptionsType } from "./query-options";
import { mockServer } from "graphql-tools";
import { base64Encode } from "../utils";
describe('QueryOptionsType', () => {
it('should construct a correct GraphQL Input Object Type', async () => {
const TestType = new GraphQLObjectType({
name: 'TestType',
fields: () => ({
foo: { type: GraphQLString },
bar: { type: new GraphQLNonNull(GraphQLString) }
})
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'TestQueries',
fields: () => ({
testQueryOptions: {
type: TestType,
args: {
queryOptions: {
type: QueryOptionsType(TestType)
}
}
}
})
})
});
const response = { foo: 'Foo', bar: 'Bar' };
const server = mockServer(schema, { TestType: () => response });
const res = await server.query(`
query testQueryOptions($queryOptions: QueryOptionsTestType) {
testQueryOptions(queryOptions: $queryOptions) {
foo,
bar
}
}
`, {
queryOptions: {
orderBy: [
{ field: 'foo', direction: 'ASC' },
{ field: 'bar', direction: 'DESC' }
],
first: 1,
last: 1,
before: base64Encode('3'),
after: base64Encode('1')
}
});
expect(res).toEqual({ data: { testQueryOptions: response } });
});
});
|
bd10eef7145b937d4a3086d4d88c202dba8df0ee
|
TypeScript
|
veeqtor/microservices-with-node-js
|
/nats-test/src/events/base-publisher.ts
| 2.59375
| 3
|
import { Stan } from "node-nats-streaming";
import { Subjects } from "./subjects";
interface IEvent {
subject: Subjects;
data: any;
}
abstract class Publisher<T extends IEvent> {
abstract subject: T["subject"];
constructor(private client: Stan) {}
publishEvent(data: T["data"]): Promise<string> {
return new Promise((resolve, reject) => {
this.client.publish(this.subject, JSON.stringify(data), (err, guid) => {
if (err) {
return reject(err);
} else {
console.log(`Event Published guid: ${guid}`);
resolve(`Event Published guid: ${guid}`);
}
});
});
}
}
export default Publisher;
|
7c0d343746cefadcf8820c4187d00a1512080a7f
|
TypeScript
|
Kezzo/aika-server
|
/src/utility/is-mail.ts
| 2.6875
| 3
|
import _ = require('underscore');
export default function isMail(stringToCheck: string) {
if (!stringToCheck) {
return false;
}
if (stringToCheck.length > 320) {
return false;
}
const stringSplitByAt: string[] = stringToCheck.split('@');
// @ is missing.
if (stringSplitByAt.length < 2) {
return false;
}
if (!stringSplitByAt[0] || !stringSplitByAt[1]) {
return false;
}
if (stringSplitByAt[0].length > 64 || stringSplitByAt[1].length > 255) {
return false;
}
return stringSplitByAt[1].includes('.');
}
|
70ea472bc7406c74236519985337481ee7458ca6
|
TypeScript
|
arunbaswar/HolaAngular4
|
/src/app.component.ts
| 2.5625
| 3
|
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { EmployeeService } from './services/employee.service';
import { Employee } from './classes/employee';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: []
})
export class AppComponent implements OnInit {
employeeList: Employee[];
searchControl: FormControl;
filteredOptions: Observable<Employee[]>;
constructor(private empServices: EmployeeService) {
this.employeeList = [];
this.searchControl = new FormControl();
}
ngOnInit() {
this.filteredOptions = this.searchControl.valueChanges.pipe(
startWith<string | Employee>(''),
map(value => typeof value === 'string' ? value : value.email),
map(email => email ? this.filterEmployeeList(email) : this.employeeList.slice())
);
this.loadEmployees();
}
filterEmployeeList(email: string): Employee[] {
return this.employeeList.filter(obj => obj.email.toLowerCase().indexOf(email.toLowerCase()) === 0);
}
loadEmployees() {
// return this.empServices.getEmployees().subscribe(data => { this.employeeList = data });
return this.employeeList = this.empServices.getEmployees();
}
displayFn(employee?: Employee): string | undefined {
return employee ? employee.email : undefined;
}
}
|
2e1961792a3faeca20b90d7ce4677dc1d0dfaf3a
|
TypeScript
|
UnnamedXAer/rn-like-music
|
/utils/storage/externalStorage.ts
| 2.6875
| 3
|
import RNFS from 'react-native-fs';
import Dir from '../../models/dir';
import { DirStat } from '../../models/dirStat';
import Playable from '../../models/playable';
import showToast from '../showToast';
import { isFilePlayable } from './isFilePlayable';
import { extractPrettyPathPrefixes } from './prettyPathPrefixes';
const loopThroughDirs = async (path: string) => {
const dirs = await RNFS.readDir(path);
if (dirs) {
const elements: Dir[] = [];
for (let i = dirs.length - 1; i >= 0; i--) {
const dir = dirs[i];
if (!dir) {
console.log('NO DIR', dir);
continue;
}
if (dir.isDirectory()) {
elements.push(new Dir(dir.path, '', dir.name));
continue;
}
if (isFilePlayable(dir.name)) {
elements.push(new Playable(dir.path, '', dir.name));
continue;
}
}
return elements;
} else {
console.log('NO DIRS: ', dirs);
throw new Error('Unable to read directory: ' + path);
}
};
const readFile = async (path: string) => {
const results = await RNFS.readFile('file://' + path, 'base64');
if (results) {
return results;
} else {
console.log('NO DIRS: ', results);
throw new Error('Unable to read directory: ' + path);
}
};
export const getDirSongs = async (path: string) => {
const songs: Playable[] = [];
const paths: string[] = [path];
const errors: { [path: string]: string } = {};
do {
const currentPath = paths.shift()!;
let dirs: RNFS.ReadDirItem[] | null = null;
try {
dirs = await RNFS.readDir(currentPath);
} catch (err) {
errors[currentPath] = err.message;
}
if (dirs !== null) {
for (let i = dirs.length - 1; i >= 0; i--) {
const dir = dirs[i];
if (dir.isDirectory()) {
paths.push(dir.path);
continue;
}
if (isFilePlayable(dir.name)) {
songs.push(new Playable(dir.path, dir.path, dir.name));
continue;
}
}
}
} while (paths.length > 0);
if (__DEV__ && Object.keys(errors).length > 0) {
console.log('[getDirSongs] ', errors);
showToast('There were problems with some paths. Checkout the console logs.');
}
return songs;
};
export const getMainDirsAndPrettyPrefixes = async () => {
const dirs = await RNFS.getAllExternalFilesDirs();
const prettyPathPrefixes = extractPrettyPathPrefixes(dirs);
const mainDirs: Dir[] = [];
let sdCardCnt = 0;
for (let i = 0; i < dirs.length; i++) {
let dir = dirs[i];
const isInternalStorage = dir.startsWith('/storage/emulated/0');
const idx = dir.indexOf('/Android/data/com.likemusic/');
dir = dir.substring(0, idx);
if (isInternalStorage) {
const dirName = 'Internal Storage';
const prettyDir = `/Device/${dirName}`;
mainDirs.push(new Dir(dir, prettyDir, dirName));
continue;
}
const dirName = 'SD Card' + (sdCardCnt === 0 ? '' : ' ' + sdCardCnt);
const prettyDir = `/Device/${dirName}`;
mainDirs.push(new Dir(dir, prettyDir, dirName));
sdCardCnt++;
}
return { mainDirs, prettyPathPrefixes };
};
export const getDirInfo = async (dir: Dir | Playable) => {
console.log('path', dir.path);
const statResult = await RNFS.stat('file://' + dir.path);
const dirStat = new DirStat(
dir.path,
dir.prettyPath,
dir.name,
dir instanceof Playable ? 'file' : 'folder',
+statResult.size,
);
return dirStat;
};
export const readStorage = async (path: string) => {
return await loopThroughDirs(path);
};
export const readStorageFile = async (filePath: string) => {
return await readFile(filePath);
};
|
7a587abc6408348db68e76af150d24b352d64950
|
TypeScript
|
thomaspoignant/scim2-parse-filter
|
/test/flatten.test.ts
| 2.984375
| 3
|
import { eq, and, or } from "./test_util";
import { Filter, parse, flatten } from "../src";
import { assert } from "chai";
function to_s(f: Filter): any {
switch (f.op) {
case "or":
case "and":
return `${f.op}(${f.filters.map(to_s).join(" ")})`;
case "eq":
return `${f.attrPath}=${f.compValue}`;
default:
return JSON.stringify(f);
}
}
const test = (text: string, e: Filter) => {
it(text, () => {
assert.equal(to_s(flatten(parse(text))), to_s(e));
});
};
const make: (num: number) => [Filter, string] = num => [
eq(`n${num}`, num),
`n${num} eq ${num}`
];
const [a1, e1] = make(1);
const [a2, e2] = make(2);
const [a3, e3] = make(3);
const [a4, e4] = make(4);
describe("flatten", () => {
describe("simple", () => {
test(`(${e1} and ${e2}) and ${e3}`, and(a1, a2, a3));
test(`(${e1} and (${e2} and ${e4})) and ${e3}`, and(a1, a2, a4, a3));
test(`(${e1} and ((${e2} and ${e4}))) and ${e3}`, and(a1, a2, a4, a3));
test(
`xx[${e1} and ((${e2} and ${e4}))]`,
and(eq("xx.n1", 1), eq("xx.n2", 2), eq("xx.n4", 4))
);
});
describe("andor", () => {
test(`(${e1} or ${e2}) and ${e3}`, and(or(a1, a2), a3));
test(`${e1} or (${e2} and ${e3})`, or(a1, and(a2, a3)));
test(`(${e1}) or (${e2} and ${e3})`, or(a1, and(a2, a3)));
});
});
|
4b6846355ddaa5fe552b305c53d61cee547e47c2
|
TypeScript
|
Parsa33033/Adjust
|
/backend/Adjust/src/main/webapp/app/entities/move/move.reducer.ts
| 2.625
| 3
|
import axios from 'axios';
import { ICrudGetAction, ICrudGetAllAction, ICrudPutAction, ICrudDeleteAction } from 'react-jhipster';
import { cleanEntity } from 'app/shared/util/entity-utils';
import { REQUEST, SUCCESS, FAILURE } from 'app/shared/reducers/action-type.util';
import { IMove, defaultValue } from 'app/shared/model/move.model';
export const ACTION_TYPES = {
FETCH_MOVE_LIST: 'move/FETCH_MOVE_LIST',
FETCH_MOVE: 'move/FETCH_MOVE',
CREATE_MOVE: 'move/CREATE_MOVE',
UPDATE_MOVE: 'move/UPDATE_MOVE',
DELETE_MOVE: 'move/DELETE_MOVE',
SET_BLOB: 'move/SET_BLOB',
RESET: 'move/RESET',
};
const initialState = {
loading: false,
errorMessage: null,
entities: [] as ReadonlyArray<IMove>,
entity: defaultValue,
updating: false,
updateSuccess: false,
};
export type MoveState = Readonly<typeof initialState>;
// Reducer
export default (state: MoveState = initialState, action): MoveState => {
switch (action.type) {
case REQUEST(ACTION_TYPES.FETCH_MOVE_LIST):
case REQUEST(ACTION_TYPES.FETCH_MOVE):
return {
...state,
errorMessage: null,
updateSuccess: false,
loading: true,
};
case REQUEST(ACTION_TYPES.CREATE_MOVE):
case REQUEST(ACTION_TYPES.UPDATE_MOVE):
case REQUEST(ACTION_TYPES.DELETE_MOVE):
return {
...state,
errorMessage: null,
updateSuccess: false,
updating: true,
};
case FAILURE(ACTION_TYPES.FETCH_MOVE_LIST):
case FAILURE(ACTION_TYPES.FETCH_MOVE):
case FAILURE(ACTION_TYPES.CREATE_MOVE):
case FAILURE(ACTION_TYPES.UPDATE_MOVE):
case FAILURE(ACTION_TYPES.DELETE_MOVE):
return {
...state,
loading: false,
updating: false,
updateSuccess: false,
errorMessage: action.payload,
};
case SUCCESS(ACTION_TYPES.FETCH_MOVE_LIST):
return {
...state,
loading: false,
entities: action.payload.data,
};
case SUCCESS(ACTION_TYPES.FETCH_MOVE):
return {
...state,
loading: false,
entity: action.payload.data,
};
case SUCCESS(ACTION_TYPES.CREATE_MOVE):
case SUCCESS(ACTION_TYPES.UPDATE_MOVE):
return {
...state,
updating: false,
updateSuccess: true,
entity: action.payload.data,
};
case SUCCESS(ACTION_TYPES.DELETE_MOVE):
return {
...state,
updating: false,
updateSuccess: true,
entity: {},
};
case ACTION_TYPES.SET_BLOB: {
const { name, data, contentType } = action.payload;
return {
...state,
entity: {
...state.entity,
[name]: data,
[name + 'ContentType']: contentType,
},
};
}
case ACTION_TYPES.RESET:
return {
...initialState,
};
default:
return state;
}
};
const apiUrl = 'api/moves';
// Actions
export const getEntities: ICrudGetAllAction<IMove> = (page, size, sort) => ({
type: ACTION_TYPES.FETCH_MOVE_LIST,
payload: axios.get<IMove>(`${apiUrl}?cacheBuster=${new Date().getTime()}`),
});
export const getEntity: ICrudGetAction<IMove> = id => {
const requestUrl = `${apiUrl}/${id}`;
return {
type: ACTION_TYPES.FETCH_MOVE,
payload: axios.get<IMove>(requestUrl),
};
};
export const createEntity: ICrudPutAction<IMove> = entity => async dispatch => {
const result = await dispatch({
type: ACTION_TYPES.CREATE_MOVE,
payload: axios.post(apiUrl, cleanEntity(entity)),
});
dispatch(getEntities());
return result;
};
export const updateEntity: ICrudPutAction<IMove> = entity => async dispatch => {
const result = await dispatch({
type: ACTION_TYPES.UPDATE_MOVE,
payload: axios.put(apiUrl, cleanEntity(entity)),
});
return result;
};
export const deleteEntity: ICrudDeleteAction<IMove> = id => async dispatch => {
const requestUrl = `${apiUrl}/${id}`;
const result = await dispatch({
type: ACTION_TYPES.DELETE_MOVE,
payload: axios.delete(requestUrl),
});
dispatch(getEntities());
return result;
};
export const setBlob = (name, data, contentType?) => ({
type: ACTION_TYPES.SET_BLOB,
payload: {
name,
data,
contentType,
},
});
export const reset = () => ({
type: ACTION_TYPES.RESET,
});
|
92dc8456caa98b086d96af98a0761d234d1c6f86
|
TypeScript
|
LBrenac/pptx-automizer
|
/src/helper/xml-pretty-print.ts
| 2.953125
| 3
|
// Thanks to https://github.com/aishwar/xml-pretty-print
// Alternative: https://github.com/riversun/xml-beautify
type PrettyPrintToken = {
match: string;
tag: string;
offset: number;
preContent: string;
};
export class XmlPrettyPrint {
xmlStr: string;
TAB: string;
constructor(xmlStr: string) {
this.xmlStr = xmlStr;
this.TAB = ' ';
}
dump(): void {
console.log(this.prettify());
}
prettify(): string {
return this.parse(this.xmlStr).join('\n');
}
parse(xmlStr: string): string[] {
const opener = /<(\w+)[^>]*?>/m;
const closer = /<\/[^>]*>/m;
let idx = 0;
let indent = 0;
let processing = '';
const tags = [];
const output = [];
while (idx < xmlStr.length) {
processing += xmlStr[idx];
const openToken = this.getToken(opener, processing);
const closeToken = this.getToken(closer, processing);
if (openToken) {
// Check if it is a singular element, e.g. <link />
if (processing[processing.length - 2] != '/') {
this.addLine(output, openToken.preContent, indent);
this.addLine(output, openToken.match, indent);
tags.push(openToken.tag);
indent += 1;
processing = '';
} else {
this.addLine(output, openToken.preContent, indent);
this.addLine(output, openToken.match, indent);
processing = '';
}
} else if (closeToken) {
this.addLine(output, closeToken.preContent, indent);
if (tags[tags.length] == closeToken.tag) {
tags.pop();
indent -= 1;
}
this.addLine(output, closeToken.match, indent);
processing = '';
}
idx += 1;
}
if (tags.length) {
console.log(
'WARNING: xmlFile may be malformed. Not all opening tags were closed. Following tags were left open:',
);
console.log(tags);
}
return output;
}
getToken(regex: RegExp, str: string): PrettyPrintToken {
if (regex.test(str)) {
const matches = regex.exec(str);
const match = matches[0];
const offset = str.length - match.length;
const preContent = str.substring(0, offset);
return {
match,
tag: matches[1],
offset,
preContent,
};
}
}
addLine(output: string[], content: string, indent: number): void {
// Trim the content
content = content.replace(/^\s+|\s+$/, '');
if (content) {
let tabs = '';
while (indent--) {
tabs += this.TAB;
}
output.push(tabs + content);
}
}
}
|
7a243aa89d4f154466e1343410dba0aafc262e21
|
TypeScript
|
GeeksHacking/GeekHub-Frontend
|
/components/app/TokenContext.ts
| 2.75
| 3
|
import {createContext, useContext} from "react";
const TokenContext = createContext<{ token: Nullable<string> }>({
token: null
})
export const useToken = () => {
const context = useContext(TokenContext)
console.log(context.token)
return context.token || ""
}
export default TokenContext
|
da650a0cdbb7e2fb845dc81b5d240f1850592c92
|
TypeScript
|
Irwing-Herrera/rxjs
|
/src/observables/09-from-avanzado.ts
| 3.390625
| 3
|
import { of, from, Observable } from "rxjs";
/**
* of = toma argumentos y genera una secuencia
* from = array, promise, iterable, observable
*/
/**
* Respuesta de observer
*
* @property {any}
*/
const observer = {
next: (val) => console.log("next:", val),
complete: () => console.log("complete"),
};
const miGenerador = function* () {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
};
const miIterable = miGenerador();
// for( let id of miIterable ){
// console.log(id);
// }
from(miIterable).subscribe(observer);
// const source$ = from([1,2,3,4,5]);
// const source$ = of(...[1,2,3,4,5]);
// const source$ = from('Fernando');
/**
* Peticion HTTP
*
* @property {Observable<Response>}
*/
const source$: Observable<Response> = from<Promise<Response>>(
fetch("https://api.github.com/users/Irwing-Herrera")
);
source$.subscribe(async (resp) => {
// console.log(resp);
const dataResp = await resp.json();
console.log(dataResp);
});
source$.subscribe(observer);
|
d056a15dda46ad5b503f60d601603d981ba17a6f
|
TypeScript
|
SeesePlusPlus/velma
|
/src/utils/astWalker.ts
| 2.71875
| 3
|
// NOTE: This file was copied/ported to TypeScript from the ethereum/remix project at https://github.com/ethereum/remix
// History of modifications made from Remix are not captured in this repository. See https://github.com/seeseplusplus/remix/tree/introduce-sdb for history
// Remix (and therefore this file) is under the MIT License:
/* The MIT License (MIT)
*
* Copyright (c) 2016
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AstWalker {
/**
* visit all the AST nodes
*
* @param {Object} ast - AST node
* @param {Object or Function} callback - if (Function) the function will be called for every node.
* - if (Object) callback[<Node Type>] will be called for
* every node of type <Node Type>. callback["*"] will be called fo all other nodes.
* in each case, if the callback returns false it does not descend into children.
* If no callback for the current type, children are visited.
*/
public walk(ast, callback) {
if (callback instanceof Function) {
callback = {'*': callback}
}
if (!('*' in callback)) {
callback['*'] = function () { return true }
}
if (this.manageCallBack(ast, callback) && ast.children && ast.children.length > 0) {
for (const k in ast.children) {
const child = ast.children[k]
this.walk(child, callback)
}
}
}
public walkDetail(ast, parent, depth, callback) {
if (callback instanceof Function) {
callback = {'*': callback}
}
if (!('*' in callback)) {
callback['*'] = function () { return true }
}
if (this.manageCallBackDetail(ast, parent, depth, callback) && ast.children && ast.children.length > 0) {
for (const k in ast.children) {
const child = ast.children[k]
this.walkDetail(child, ast, depth + 1, callback)
}
}
}
/**
* walk the given @astList
*
* @param {Object} sourcesList - sources list (containing root AST node)
* @param {Function} - callback used by AstWalker to compute response
*/
public walkAstList(sourcesList, callback) {
const walker = new AstWalker()
for (const k in sourcesList) {
walker.walk(sourcesList[k].AST, callback)
}
}
private manageCallBack(node, callback) {
if (node.name in callback) {
return callback[node.name](node)
} else {
return callback['*'](node)
}
}
private manageCallBackDetail(node, parent, depth, callback) {
if (node.name in callback) {
return callback[node.name](node, parent, depth)
} else {
return callback['*'](node, parent, depth)
}
}
}
|
5cef8222184853df0bf8092c00d20ce6d51da9e0
|
TypeScript
|
spacejack/vdom-timeline
|
/src/timeline/delays/playtimeline.ts
| 2.8125
| 3
|
import Emitter from '../emitter'
import PromiseToken from '../promise-token'
import {TimelinePromise, DelayFactory} from '../timeline-factory'
/**
* Creates a cancelable, pausable/resumable delay.
* Accepts a Timeline.
*/
const PlayTimeline: DelayFactory<TimelinePromise<any>> = function(
canceled: Promise<void>, paused: Emitter, resumed: Emitter,
timeline: TimelinePromise<any>
) {
const [promise, resolve] = PromiseToken<void>()
canceled.then(() => {
timeline.cancel()
})
paused.onemit(() => {
timeline.pause()
})
resumed.onemit(() => {
timeline.resume()
})
timeline.then(resolve)
return promise
}
export default PlayTimeline
|
d6a3e0854f2be031c8f76c43f1091bc952c5150a
|
TypeScript
|
BodyaNets/api-repo
|
/src/models/shoe.ts
| 2.578125
| 3
|
import { IDomainEntity, thanksTypescript } from "@codiac.io/codiac-common";
import { CriteriaBase, StringFilter } from "@codiac.io/codiac-common/contracts";
export class Shoe implements IDomainEntity {
constructor(public size: number, public brand: string, public model: string, id?: string) {
this.id = id;
}
id: string | undefined;
}
export class shoeCriteria extends CriteriaBase<Shoe> {
@thanksTypescript public size?: number;
@thanksTypescript public brand?: StringFilter;
@thanksTypescript public model?: string;
}
|
30e1c7f571436302cceca674d34b94ebff0e7c36
|
TypeScript
|
CosmosContracts/ts-relayer
|
/src/binary/ibc-setup/commands/keys-generate.spec.ts
| 2.5625
| 3
|
import fs from 'fs';
import test from 'ava';
import sinon from 'sinon';
import { Options, run } from './keys-generate';
const fsWriteFileSync = sinon.stub(fs, 'writeFileSync');
const consoleLog = sinon.stub(console, 'log');
test.beforeEach(() => {
sinon.reset();
fsWriteFileSync.returns();
});
test('generates mnemonic to stdout', (t) => {
const options: Options = {
keyFile: null,
};
run(options);
t.assert(consoleLog.calledOnce);
t.assert(consoleLog.calledWithMatch(/[\\w ]+/));
t.assert(fsWriteFileSync.notCalled);
});
test('generates mnemonic to file', (t) => {
const options: Options = {
keyFile: '/home/user/mnemonic.txt',
};
run(options);
const [path, contents] = fsWriteFileSync.getCall(0).args;
t.is(path, options.keyFile);
t.regex(contents as string, /[\\w ]+/);
t.assert(consoleLog.calledOnce);
t.assert(consoleLog.calledWithMatch(/Saved mnemonic to/));
});
|
be89da26d5cf7aa0dc430a0224e3b710c11fde14
|
TypeScript
|
eps1lon/mesh-ooc-projection
|
/src/off/nodesToText.ts
| 3.1875
| 3
|
import {
Face,
Format,
Meta,
Node,
Vertex,
ColoredVertex,
isColoredVertex
} from './nodes';
export default function toText(node: Node): string {
switch (node.type) {
case 'vertex':
return vertex(node);
case 'face':
return face(node);
case 'format':
return format(node);
case 'meta':
return meta(node);
}
}
function vertex(vertex_node: ColoredVertex | Vertex): string {
const { x, y, z } = vertex_node;
let line = [x, y, z].join(' ');
if (isColoredVertex(vertex_node)) {
const { r, g, b } = vertex_node.color;
line = `${line} ${[r, g, b].join(' ')}`;
}
return line;
}
function face({ vertices }: Face) {
return `${vertices.length} ${vertices.join(' ')}`;
}
function format(node: Format) {
return node.format;
}
function meta({ vertex_count, face_count, edge_count }: Meta) {
return [vertex_count, face_count, edge_count].join(' ');
}
|
9ec3d4cafafdf7aa4232b83bbae445f6d5fd66b6
|
TypeScript
|
NirvanaChow/team
|
/src/devkit/command/command_handler.ts
| 2.859375
| 3
|
import {InjectionToken } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { concatMap, map } from 'rxjs/operators';
import { FrameContext } from '../frame/index';
import { VariableParseService } from '../variable/index';
import { Command } from './command';
import { CommandContext } from './command_context';
import { TaskFunc, TaskFlow } from './flow/index';
/**
* 命令处理抽象类,所有具体的命令处理类必须继承它,并实现schedule方法。
*
* ### 概述
* 一个CommandHandler只能处理一种类型的Command,一种类型的Command也只能有一个CommandHandler.
* 在CommandHandler内部,执行过程被拆解为一个一个的Task,CommandHandler内部会通过一个编排器对这些Task进行串联。
*
* ### 定义并注册CommandHandler
*
* **定义一个CommandHandler**
*
* 通过以下步骤可以定义一个CommandHandler
* - 继承CommandHandler基类,并在构造函数中注入依赖的服务;
* - 在schedule方法中依次添加要执行的任务;
* - 使用NgCommandHandler注解指定对应的Command名称。
*
* ```ts
* @Injectable()
* @NgCommandHandler({
* commandName: 'formLoad'
* })
* class FormLoadHandler extends CommandHandler {
* constructor(private dataService: DataService) {
* super();
* }
* schedule() {
* this.addTask('loadData', () => {
* return this.dataService.loadData();
* });
* }
* }
* ```
* **注册CommandHandler**
*
* 我们将包含FormLoadHandler的数组传递给CommandModule.setup方法,由它来统一进行注册。
* ```ts
* @NgModule({
* imports: [
* CommandModule.setup([FormLoadHandler], [FormLoadHandlerExtender])
* ]
* })
* class SimpleModule {}
* ```
*
* ### 任务编排
*
* CommandHandler内任务的串联是通过rxjs来实现的,所有的任务都会被合并到一个执行流中。
* 如果任务是异步的,并且下一任务依赖这个异步结果,则异步任务函数必须返回一个Observable对象,
* 这样才能保证异步任务返回结果后再执行下一任务。
*
* 为了演示任务串联的过程,我们假设有这么一个场景,我们要展示当前用户下属部门的列表,并批量编辑它们。
* * 假设服务器端没有对数据进行整合,完成数据加载我们需要执行以下两个步骤:
* - 根据用户内码获取用户信息;
* - 根据用户信息中的部门内码获取下属部门列表;
*
* ```ts
* @Injectable()
* @NgCommandHandler({
* commandName: 'formLoad'
* })
* class FormLoadHandler extends CommandHandler {
*
* constructor(
* private userService: UserService,
* private deptService: DeptService
* ) {
* super();
* }
*
* schedule() {
* // 获取用户信息
* this.addTask('getUser', (preTaskResult: any, context: TaskExecutionContext) => {
* const userId = context.command.params.userId;
* return this.userService.geInfoById(userId);
* });
*
* // 获取后代部门列表
* this.addTask('getDepts', (userInfo: any) => {
* return this.deptService.getDescendantsById(userInfo.deptId);
* });
* }
* }
* ```
* 在getUser中我们获取用户信息,并将用户信息传递给下一任务,所以获取用户信息的任务函数需要返回一个Observable,
* 只有异步结束并将用户信息发送到流执行流里的时候,getDepts任务才执行。
*
* ### 执行上下文
*
* 在实现任务函数时,我们可以通过任务上下文获取外部信息,任务上下文主要包括两部分:
* - 通过任务函数的第一个参数直接获取上一步任务返回的结果。
* - 通过任务函数的第二个参数获取上下文对象,其中command属性保存的是一个Command对象,进而获取它上边携带的参数;
* - 通过任务函数的第二个参数获取上下文对象,其中results属性保存了已经执行了的任务的结果。
*
* 下面我通过一个示例来演示任务函数获取外部信息的使用。假设我们有这样一个场景:
* - 点击保存;
* - 检查库存;
* - 检查账户余额;
* - 检查通过后执行保存;
*
* ```ts
* @Injectable()
* @NgCommandHandler({
* commandName: 'save'
* })
* class SaveHandler extends CommandHandler {
*
* private orderData: any;
*
* constructor(
* private checkService: CheckService,
* private orderService: OrderService
* ) {
* super();
* }
*
* schedule() {
*
* // 解析参数
* this.addTask('getOrderData', (preTaskResult: any, context: TaskExecutionContext) => {
* // 第2个参数是上下文对象
* const command: Command = context.command;
* this.orderData = command.params.orderData;
* });
*
* // 检查库存
* this.addTask('checkQuantity', (preTaskResult: any, context: TaskExecutionContext) => {
* return this.checkService.checkQuantity(this.orderData.quantity);
* });
*
* // 检查账户余额
* this.addTask('checkQuantity', (isQuantityAvailable: any, context: TaskExecutionContext) => {
* // 第1个参数是上一步的执行结果
* if (isQuantityAvailable) {
* return false;
* }
* return this.checkService.checkMoney(this.orderData.totalMoney);
* });
*
* // 执行保存
* this.addTask('checkQuantity', (preTaskResult: any, context: TaskExecutionContext) => {
* // 从context的result中获取已经执行过的任务结果,key是任务的名称
* if (!context.result['checkQuantity'] || !context.result['checkQuantity']) {
* return;
* }
* return this.orderService.save(this.orderData);
* });
* }
* }
* ```
* 从上面的例子我们可以看到获取上下文的几种使用方式:
* - 检查账户余额前,我们通过第一个参数获取上一步检查库存的执行结果;
* - 保存数据时,我们通过上下文对象的command属性拿到Command对象,进而获取订单数据;
* - 保存前,我们通过上下文对象的results属性拿到之前检查库存和检查账户余额的结果。
*/
abstract class CommandHandler {
/**
* 任务流程图
*/
private taskFlow: TaskFlow;
/**
* 上下文
*/
protected frameContext: FrameContext;
/**
* 变量解析服务
*/
protected parseService: VariableParseService;
/**
* 构造函数
*/
constructor() {
}
/**
* 构造执行流程
*/
abstract schedule();
/**
* 初始化
*/
public init(frameContext: FrameContext) {
this.frameContext = frameContext;
this.parseService = frameContext.injector.get<VariableParseService>(VariableParseService);
this.taskFlow = new TaskFlow();
this.schedule();
}
/**
* 执行任务
* @param command 要执行的命令
*/
public execute(command: Command) {
const initContext = new CommandContext(command, this.frameContext);
const context$ = new BehaviorSubject<CommandContext>(initContext);
const currentTask = this.taskFlow.getNext('', initContext);
currentTask.execute(initContext).subscribe();
// const hideOrder$ = context$.pipe(
// concatMap((context: CommandContext) => {
// console.log('----------' + currentTask.name + '----------');
// const result$ = currentTask.execute(context);
// return result$.pipe(
// map((result: any) => {
// // 写入执行结果
// context.results[currentTask.name] = result;
// currentTask = this.taskFlow.getNext(currentTask.name, context);
// // 操作控制流
// if (currentTask) {
// context$.next(context);
// } else {
// context$.complete();
// }
// // 将结果流转换为context流
// return context;
// })
// );
// })
// );
// 订阅流
// hideOrder$.subscribe();
// hideOrder$.subscribe({
// next: (context: CommandContext) => {
// // console.log('----------next----------');
// // console.log(context);
// },
// complete: () => {
// console.log('----------complete----------');
// },
// error: (error) => {
// console.log('----------error----------');
// console.log(error);
// }
// });
}
/**
* 添加任务,只有子类可以添加任务,外部不能访问
* @param name 任务名称
* @param func 任务函数
*/
protected addTask(name: string, func: TaskFunc) {
this.taskFlow.addNode(name, func);
}
/**
* 添加任务,只有子类可以添加任务,外部不能访问
* @param name 任务名称
* @param func 任务函数
*/
protected addLink(from: string, to: string, condition: string | boolean) {
this.taskFlow.addLink(from, to, condition);
}
/**
* 插入任务
* @param name 要扩展的任务名称
* @param func 扩展函数
*/
public insertTask(target: string, name: string, func: TaskFunc) {
throw new Error('Not Implemented');
}
/**
* 插入任务
* @param name 要扩展的任务名称
* @param func 扩展函数
*/
public afterTask(target: string, name: string, func: TaskFunc) {
throw new Error('Not Implemented');
}
/**
* 替换任务
* @param name 要替换的任务名称
* @param func 替换函数
*/
public replaceTask(name: string, func: TaskFunc) {
throw new Error('Not Implement');
}
/**
* 调用方法
*/
public invoke(serviceInstance: any, method: string, args: any[], context: CommandContext) {
const parsedArgs = this.parseService.parse(args, context);
return serviceInstance[method](...parsedArgs);
}
}
/**
* 命令处理器注入Token
*/
const COMMAND_HANDLERS_TOKEN = new InjectionToken<CommandHandler>('@Farris Command Handlers');
export { CommandHandler, COMMAND_HANDLERS_TOKEN };
|
8ea167cba14f7e615a87e143208e78d7db54941e
|
TypeScript
|
seebees/aws-sdk-js-v3
|
/packages/json-parser/src/index.ts
| 2.75
| 3
|
import {BodyParser, Decoder, Member, SerializationModel} from "@aws-sdk/types";
import {toDate} from "@aws-sdk/protocol-timestamp";
type Scalar = string|number|boolean|null;
interface Json {
[index: string]: Scalar|Json|JsonArray;
}
interface JsonArray extends Array<Scalar|Json|JsonArray> {}
type JsonValue = Json|Scalar|JsonArray;
export class JsonParser implements BodyParser {
constructor(private readonly base64Decoder: Decoder) {}
public parse<OutputType>(
shape: Member,
input: string
): OutputType {
return this.unmarshall(shape.shape, JSON.parse(input));
}
private unmarshall(shape: SerializationModel, input: JsonValue): any {
if (shape.type === 'structure') {
if (typeof input !== 'object' || input === null) {
return undefined;
}
return Object.keys(shape.members)
.reduce((output: {[key: string]: any}, memberName: string) => {
const {
locationName = memberName,
shape: memberShape
} = shape.members[memberName];
const value = (input as Json)[locationName];
if (value !== undefined) {
output[memberName] = this.unmarshall(memberShape, value);
}
return output;
}, {});
}
if (shape.type === 'list') {
if (!Array.isArray(input)) {
return undefined;
}
const {shape: memberShape} = shape.member;
return input.map(value => this.unmarshall(memberShape, value));
}
if (shape.type === 'map') {
if (typeof input !== 'object' || input === null) {
return undefined;
}
const {shape: valueShape} = shape.value;
return Object.keys(input)
.reduce((output: {[key: string]: any}, key: string) => {
output[key] = this.unmarshall(
valueShape,
(input as Json)[key]
);
return output;
}, {});
}
if (shape.type === 'timestamp') {
if (typeof input !== 'number') {
return undefined;
}
return toDate(input);
}
if (shape.type === 'blob') {
if (typeof input !== 'string') {
return undefined;
}
return this.base64Decoder(input);
}
return input;
}
}
|
2c222ecd4cfecc658cba19512616748d9058f844
|
TypeScript
|
futantan/RegExp-Builder
|
/src/__tests__/index.spec.ts
| 2.765625
| 3
|
import { RegexBuilder } from '../index';
describe('RegexBuilder', () => {
it('should matchBegin', () => {
expect(new RegexBuilder().matchBegin().toString()).toBe('/^/');
});
it('should matchEnd', () => {
expect(new RegexBuilder().matchEnd().toString()).toBe('/$/');
});
it('zeroOrMoreOf', () => {
expect(new RegexBuilder().zeroOrMoreOf('a').toString()).toBe('/a*/');
expect(new RegexBuilder().zeroOrMoreOf('abc').toString()).toBe('/(?:abc)*/');
});
it('oneOrMoreOf', () => {
expect(new RegexBuilder().oneOrMoreOf('a').toString()).toBe('/a+/');
expect(new RegexBuilder().oneOrMoreOf('abc').toString()).toBe('/(?:abc)+/');
});
it('optional', () => {
expect(new RegexBuilder().optional('a').toString()).toBe('/a?/');
expect(new RegexBuilder().optional('abc').toString()).toBe('/(?:abc)?/');
});
it('anyOf', () => {
expect(new RegexBuilder().anyOf(['a', 'b', 'c']).toString()).toBe('/(a|b|c)/');
});
it('nTimesOf', () => {
expect(new RegexBuilder().nTimesOf('hello', 3).toString()).toBe('/hello{3}/');
});
it('moreThanNTimesOf', () => {
expect(new RegexBuilder().moreThanNTimesOf('hello', 3).toString()).toBe('/hello{3,}/');
});
it('expressionTimesBetween', () => {
expect(new RegexBuilder().expressionTimesBetween('hello', 3, 6).toString()).toBe('/hello{3,6}/');
});
it('anySingleCharacter', () => {
expect(new RegexBuilder().anySingleCharacter().toString()).toBe('/./');
});
it('formfeed', () => {
expect(new RegexBuilder().formfeed().toString()).toBe('/\\f/');
});
it('newline', () => {
expect(new RegexBuilder().newline().toString()).toBe('/\\n/');
});
it('carriageReturn', () => {
expect(new RegexBuilder().carriageReturn().toString()).toBe('/\\r/');
});
it('tab', () => {
expect(new RegexBuilder().tab().toString()).toBe('/\\t/');
});
it('anyDigit', () => {
expect(new RegexBuilder().anyDigit().toString()).toBe('/\\d/');
});
it('anyNonDigit', () => {
expect(new RegexBuilder().anyNonDigit().toString()).toBe('/\\D/');
});
it('whitespace', () => {
expect(new RegexBuilder().whitespace().toString()).toBe('/\\s/');
});
it('notAWhitespace', () => {
expect(new RegexBuilder().notAWhitespace().toString()).toBe('/\\S/');
});
it('anyWordCharacter', () => {
expect(new RegexBuilder().anyWordCharacter().toString()).toBe('/\\w/');
});
it('anyNonWordCharacter', () => {
expect(new RegexBuilder().anyNonWordCharacter().toString()).toBe('/\\W/');
});
it('capture', () => {
expect(new RegexBuilder().capture('hello').toString()).toBe('/(hello)/');
});
it('nonCapture', () => {
expect(new RegexBuilder().nonCapture('hello').toString()).toBe('/(?:hello)/');
});
it('positiveLookahead', () => {
expect(new RegexBuilder().positiveLookahead('hello').toString()).toBe('/(?=hello)/');
});
it('negativeLookahead', () => {
expect(new RegexBuilder().negativeLookahead('hello').toString()).toBe('/(?!hello)/');
});
it('aSingleCharacterInString', () => {
expect(new RegexBuilder().aSingleCharacterInString('hello').toString()).toBe('/[hello]/');
});
it('anySingleCharacterExcept', () => {
expect(new RegexBuilder().anySingleCharacterExcept('abc').toString()).toBe('/[^abc]/');
})
});
|
b89051cf085e53221a00470691d4c8360db0ed66
|
TypeScript
|
roberto14118927/front
|
/src/app/services/api/api.service.ts
| 2.53125
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { API } from '../../../config/config'
const httpOptions = {
headers: new HttpHeaders({
// 'Content-Type': 'application/json' ,
'Authorization': 'Token c5bbe9679b287d21c8846f1adc4ceecc56605a0b',
})
};
@Injectable({
providedIn: 'root'
})
export class ApiService {
api: string = API;
constructor(private http: HttpClient) { }
/**
*
* @param point
*/
getAll(point: string): Observable<any> {
return this.http.get(`${this.api}/${point}/`, httpOptions);
}
/**
*
* @param point
* @param id
*/
getById(point: string, id: number): Observable<any> {
return this.http.get(`${this.api}/${point}/${id}`, httpOptions);
}
/**
*
* @param point
*/
getSelect(point: string): Observable<any> {
return this.http.get(`${this.api}/${point}/?fields=id,name`, httpOptions);
}
/**
*
* @param point
* @param id
*/
getSelectById(point: string, id:number): Observable<any> {
return this.http.get(`${this.api}/${point}/${id}?fields=id,name`, httpOptions);
}
/**
*
* @param point
* @param params
*/
getSelectByParams(point: string, params:string): Observable<any> {
return this.http.get(`${this.api}/${point}/?fields=${params}`, httpOptions);
}
/**
*
* @param point
* @param id
* @param params
*/
getSelectByIdAndParams(point: string, id:number, params:string): Observable<any> {
return this.http.get(`${this.api}/${point}/${id}?fields=${params}`, httpOptions);
}
/**
*
* @param point
* @param data
*/
create(point: string, data: any): Observable<any> {
return this.http.post(`${this.api}/${point}/`, data, httpOptions);
}
/**
*
* @param point
* @param id
* @param data
*/
update(point: string, id: number, data: any) : Observable<any> {
return this.http.put(`${this.api}/${point}/${id}`, data, httpOptions);
}
/**
*
* @param point
* @param id
*/
delete(point: string, id: number) {
return this.http.delete(`${this.api}/${point}/${id}`, httpOptions);
}
}
|
364dab02a838302105aade47832026b9f7cb805d
|
TypeScript
|
SapphireDb/sapphiredb-js
|
/projects/sapphiredb/src/lib/collection/prefilter/count-prefilter.ts
| 2.828125
| 3
|
import {IPrefilter} from './iprefilter';
export class CountPrefilter<T> implements IPrefilter<T, number> {
prefilterType = 'CountPrefilter';
execute(values: T[]) {
return values.length;
}
public hash() {
return `${this.prefilterType}`;
}
}
|
76815096e99bf2cf3fca8b31189b3bded69d5d83
|
TypeScript
|
arpitnath/name-generator
|
/src/services/names.services.ts
| 3.25
| 3
|
export const generateRandomNames = (arr: string[]): string[] => {
if (arr.length === 0) {
return ['Error']
}
const randomNames: string[] = []
const names = new Map()
const maxLimit = 5
while (names.size < 5) {
let index = Math.ceil(Math.random() * arr.length)
if (index >= arr.length) {
index = Math.ceil(Math.random() * maxLimit)
}
if (!names.get(index)) {
index = Math.ceil(Math.random() * (arr.length - 1))
names.set(index, arr[index])
}
}
names.forEach((name) => randomNames.push(name))
return randomNames
}
export const checkOriginOfNames = (
generatedRandomNames: string[],
inputList: string[]
): boolean => {
const randomNames = generatedRandomNames
for (let i of randomNames) {
let check = inputList.includes(i)
if (!check) return false
}
return true
}
|
b6ad13d9041071a0f4e66bac987a0e34cfaa544c
|
TypeScript
|
yerim926/COMP229-Assignment2
|
/Server/Controllers/business.ts
| 2.765625
| 3
|
import express, { Request, Response, NextFunction } from 'express';
import Business from "../Models/business";
export function DisplayBusinessListPage(req: Request, res: Response, next: NextFunction): void
{
//mongo db - find method to return all the business collection
Business.find(function(err,businessCollection){
if(err)
{
return console.error(err);
}
// (Read) print out the business list
// console.log(business);
//render the business-list content partial page
res.render('index', {title: 'Business Contact List', page: 'business-list', business: businessCollection})
});
}
export function DisplayEditPage(req: Request, res: Response, next: NextFunction):void
{
let id = req.params.id;
console.log(id);
// pass the id to the db
//db.business.find({"_id": id})
Business.findById(id,{},{},(err, businessContactToEdit) =>
{
if(err)
{
console.error(err);
res.end(err);
}
//show the edit view
res.render('index',{title: 'Edit', page: 'edit', business: businessContactToEdit})
});
}
|
da1ff9255d6de863b1d3dcc291d08577102cccc7
|
TypeScript
|
plusxp/recoil-table
|
/packages/recoil-table/src/atoms/sort.ts
| 2.703125
| 3
|
import { atomFamily, selectorFamily } from 'recoil';
import { columnSortAtom } from './columns';
import { guardRecoilDefaultValue } from './helpers';
export interface Sort {
columnId: string;
isDesc: boolean;
}
/**
* Stores the id of the actively sorted column.
**/
const sortColumnIdAtom = atomFamily<string, string>({
key: 'recoil-table-sort-column-id-atom',
default: '',
});
export const sortAtom = selectorFamily<Sort, string>({
key: 'recoil-table-sort-atom',
get:
(tableKey) =>
({ get }) => {
const columnId = get(sortColumnIdAtom(tableKey));
if (columnId) {
const colSortState = get(columnSortAtom(`${tableKey}-${columnId}`));
return { columnId, isDesc: colSortState.isDesc };
}
return { columnId: '', isDesc: false };
},
set:
(tableKey) =>
({ get, set }, newValue) => {
// if default value, reset global and column specific
if (guardRecoilDefaultValue(newValue)) {
const columnId = get(sortColumnIdAtom(tableKey));
set(columnSortAtom(`${tableKey}-${columnId}`), {
isSorted: false,
isDesc: false,
});
set(sortColumnIdAtom(tableKey), newValue);
return;
}
const columnId = get(sortColumnIdAtom(tableKey));
set(columnSortAtom(`${tableKey}-${columnId}`), {
isSorted: false,
isDesc: false,
});
set(sortColumnIdAtom(tableKey), newValue.columnId);
set(columnSortAtom(`${tableKey}-${newValue.columnId}`), (prev) => ({
isSorted: true,
isDesc: !prev.isDesc,
}));
},
});
|
f8013f1d69b96e266b972074aea0004c69b182be
|
TypeScript
|
Binyame/lotic.ai
|
/__test__/models/hcProviderInvite.test.ts
| 2.5625
| 3
|
import { factory } from '../utils';
describe('Model - HCProviderInvite', () => {
let clinician, clinicians;
beforeAll(async () => {
clinician = await factory.create('Clinician');
clinicians = JSON.stringify([clinician.toJSON()]);
});
test('should create a HCProviderInvite', async() => {
const record = await factory.create('HCProviderInvite', { code: 'Example', clinicians });
expect(record.code).toEqual('Example');
});
describe('Validations', () => {
test('requires a valid code', async () => {
await expect(factory.create('HCProviderInvite', { code: null, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { code: false, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { code: true, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { code: 123, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { code: { foo: 'bar' }, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { code: 'Name', clinicians })).resolves.toBeDefined();
});
test('requires a valid active', async () => {
await expect(factory.create('HCProviderInvite', { active: null, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { active: 1234, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { active: 'random-string', clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { active: { foo: 'bar' }, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { active: false, clinicians })).resolves.toBeDefined();
await expect(factory.create('HCProviderInvite', { active: true, clinicians })).resolves.toBeDefined();
});
test('active defaultsTo true', async () => {
const hcProviderInvite = await factory.create('HCProviderInvite', {
clinicians
});
await expect(hcProviderInvite.active).toEqual(true);
});
test('requires a valid providerId', async () => {
const hcProvider = await factory.create('HCProvider');
await expect(factory.create('HCProviderInvite', { providerId: null, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { providerId: false, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { providerId: true, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { providerId: 'random-string', clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { providerId: { foo: 'bar' }, clinicians })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { providerId: hcProvider.id, clinicians })).resolves.toBeDefined();
});
test('requires a valid clinicians', async () => {
await expect(factory.create('HCProviderInvite', { clinicians: null })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { clinicians: false })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { clinicians: true })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { clinicians: 'random-string' })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { clinicians: { foo: 'bar' } })).rejects.toThrow();
await expect(factory.create('HCProviderInvite', { clinicians })).resolves.toBeDefined();
});
describe('Relationships', () => {
test('belongsTo HCProvider', async () => {
const hcProvider = await factory.create('HCProvider');
const record = await factory.create('HCProviderInvite', {
clinicians
});
await record.setHCProvider(hcProvider);
const found = await record.getHCProvider();
expect(found.id).toEqual(hcProvider.id);
});
});
});
});
|
bee7e330f5cd8880316bb36b4087d8d53d08049e
|
TypeScript
|
ULL-ESIT-INF-DSI-2021/ull-esit-inf-dsi-20-21-prct06-generics-solid-alu0101166247
|
/tests/ejercicio-2-spec/ejercicio-2.spec.ts
| 2.671875
| 3
|
/* eslint-disable max-len */
import 'mocha';
import {expect} from 'chai';
import {forceUnits, Fuerza} from '../../src/ejercicio-2/fuerza';
import {lengthUnits, Longitud} from '../../src/ejercicio-2/longitud';
import {Masa, massUnits} from '../../src/ejercicio-2/masa';
import {Temperatura, temperatureUnits} from '../../src/ejercicio-2/temperatura';
import {Tiempo, timeUnits} from '../../src/ejercicio-2/tiempo';
import {speedUnits, Velocidad} from '../../src/ejercicio-2/velocidad';
import {Volumen, volumeUnits} from '../../src/ejercicio-2/volumen';
const force: Fuerza = new Fuerza;
const mass: Masa = new Masa;
const time: Tiempo = new Tiempo;
const speed: Velocidad = new Velocidad;
const vol: Volumen = new Volumen;
const temp: Temperatura = new Temperatura;
const length: Longitud = new Longitud;
// Pruebas
describe('Pruebas para el ejercicio 2 - Conversor de unidades', () => {
it('force.convert(100, forceUnits.NewtonToKilopondio) returns value 100 Newtons -> 10.197162129999999 Kilopondios', () => {
expect(force.convert(100, forceUnits.NewtonToKilopondio)).to.be.equal("100 Newtons -> 10.197162129999999 Kilopondios");
});
it('force.convert(100, forceUnits.KilopondioToNewton) returns value 100 Kilopondios -> 980.665 Newtons', () => {
expect(force.convert(100, forceUnits.KilopondioToNewton)).to.be.equal("100 Kilopondios -> 980.665 Newtons");
});
it('mass.convert(100, massUnits.KilogramosToGramos) returns value 100 Kilogramos -> 100000 Gramos', () => {
expect(mass.convert(100, massUnits.KilogramosToGramos)).to.be.equal("100 Kilogramos -> 100000 Gramos");
});
it('mass.convert(100, massUnits.GramosToKilogramos) returns value 100 Gramos -> 0.1 Kilogramos', () => {
expect(mass.convert(100, massUnits.GramosToKilogramos)).to.be.equal("100 Gramos -> 0.1 Kilogramos");
});
it('time.convert(100, timeUnits.MinutosToSegundos) returns value 100 Minutos -> 6000 Segundos', () => {
expect(time.convert(100, timeUnits.MinutosToSegundos)).to.be.equal("100 Minutos -> 6000 Segundos");
});
it('time.convert(100, timeUnits.SegundosToMinutos) returns value 100 Segundos -> 1.6666666666666667 Minutos', () => {
expect(time.convert(100, timeUnits.SegundosToMinutos)).to.be.equal("100 Segundos -> 1.6666666666666667 Minutos");
});
it('speed.convert(100, speedUnits.KMpHToMph) returns value 100 KMpH -> 62.137100000000004 MpH', () => {
expect(speed.convert(100, speedUnits.KMpHToMph)).to.be.equal("100 KMpH -> 62.137100000000004 MpH");
});
it('speed.convert(100, speedUnits.MpHToKMpH) returns value 100 MpH -> 160.934 KMpH', () => {
expect(speed.convert(100, speedUnits.MpHToKMpH)).to.be.equal("100 MpH -> 160.934 KMpH");
});
it('vol.convert(100, volumeUnits.LitrosToMililitros) returns value 100 Litros -> 100000 Mililitros', () => {
expect(vol.convert(100, volumeUnits.LitrosToMililitros)).to.be.equal("100 Litros -> 100000 Mililitros");
});
it('vol.convert(100, volumeUnits.MililitrosToLitros) returns value 100 Mililitros -> 0.1 Litros', () => {
expect(vol.convert(100, volumeUnits.MililitrosToLitros)).to.be.equal("100 Mililitros -> 0.1 Litros");
});
it('temp.convert(100, temperatureUnits.CelsiusToFahrenheit) returns value 100 °C -> 212 °F', () => {
expect(temp.convert(100, temperatureUnits.CelsiusToFahrenheit)).to.be.equal("100 °C -> 212 °F");
});
it('temp.convert(100, temperatureUnits.FahrenheitToCelsius) returns value 100 °F -> 37.77777777777778 °C', () => {
expect(temp.convert(100, temperatureUnits.FahrenheitToCelsius)).to.be.equal("100 °F -> 37.77777777777778 °C");
});
it('length.convert(100, lengthUnits.CentimetrosToMetros) returns value 100 Centimetros -> 1 Metros', () => {
expect(length.convert(100, lengthUnits.CentimetrosToMetros)).to.be.equal("100 Centimetros -> 1 Metros");
});
it('length.convert(100, lengthUnits.MetrosToCentimetros) returns value 100 Metros -> 10000 Centimetros', () => {
expect(length.convert(100, lengthUnits.MetrosToCentimetros)).to.be.equal("100 Metros -> 10000 Centimetros");
});
});
|
1e349f82b740031daa623c1d2619147872fcaecb
|
TypeScript
|
ted-piotrowski/puppeteer-camera
|
/src/chrome_extension/S3StreamerInput.ts
| 2.53125
| 3
|
import * as AWS from 'aws-sdk';
export interface S3StreamerInput {
recorder: MediaRecorder;
bucket: string;
key?: string;
}
export class S3Streamer {
private recorder: MediaRecorder;
private bucket: string;
private key: string;
private s3: AWS.S3;
private uploadId: string;
private uploadParts: Promise<AWS.S3.UploadPartOutput>[];
constructor(input: S3StreamerInput) {
const { recorder, bucket, key } = input;
this.recorder = recorder;
this.bucket = bucket;
this.key = key;
this.uploadParts = [];
this.s3 = new AWS.S3();
recorder.ondataavailable = async (event) => {
console.log('data available', this.key)
try {
if (event.data.size > 0) {
this.uploadParts.push(this.s3.uploadPart({
Body: event.data,
Bucket: bucket,
Key: this.key,
PartNumber: this.uploadParts.length + 1,
UploadId: this.uploadId,
ContentLength: event.data.size
}).promise());
}
} catch (e) {
console.log('ondataavailable error', e)
if (this.uploadId) {
await this.s3.abortMultipartUpload({
Bucket: bucket,
UploadId: this.uploadId,
Key: this.key
}).promise();
}
}
};
}
async start() {
return new Promise((res, rej) => {
this.recorder.onstart = async () => {
console.log('onstart', this.key)
const data = await this.s3.createMultipartUpload({
Bucket: this.bucket,
Key: this.key,
}).promise();
this.uploadId = data.UploadId;
res();
}
this.recorder.start();
})
}
async stop() {
return new Promise<string>((res, rej) => {
this.recorder.onstop = async () => {
console.log('onstop', this.key, this.uploadParts.length)
try {
const s3Parts = await Promise.all(this.uploadParts);
const { Location } = await this.s3.completeMultipartUpload({
Bucket: this.bucket,
Key: this.key,
UploadId: this.uploadId,
MultipartUpload: {
Parts: s3Parts.map((resp, index) => { return { ETag: resp.ETag, PartNumber: index + 1 } })
}
}).promise();
return res(Location);
} catch (e) {
console.log('onstop error', e)
if (this.uploadId) {
await this.s3.abortMultipartUpload({
Bucket: this.bucket,
Key: this.key,
UploadId: this.uploadId,
}).promise();
}
return rej(e);
}
}
this.recorder.stop();
});
}
}
|
b89f5c76becf392c5a5361cac12fe25a1b2cfaaf
|
TypeScript
|
cafreeman/generator-mobx-react
|
/generators/app/templates/src_ts/Store.ts
| 2.640625
| 3
|
import { observable, computed, action } from 'mobx';
class Store {
name: string = '<%= name %>';
description: string = '<%= description %>';
@observable numClicks: number = 0;
@computed get oddOrEven(): string {
return this.numClicks % 2 === 0 ? 'even' : 'odd';
}
@action clickButton(): void {
this.numClicks++;
}
}
export { Store };
|
afd1f731e1166189bbfe36fbe418e003ca181c04
|
TypeScript
|
itanex/nasa-picture-of-the-day
|
/src/app/shared/functions/date-to-stuct.fn.ts
| 2.6875
| 3
|
import { NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
/**
* Converts a Native Date object to the ngbDateStuct object
* @param date Date to convert; If not provided, generates a current date
*/
export function dateToStuct(date?: Date): NgbDateStruct {
let d = date || new Date();
return {
year: d.getFullYear(),
month: d.getMonth() + 1,
day: d.getDate()
};
}
|
10a7e69fc113aea0e1f3e9dc135f844efcb02f3b
|
TypeScript
|
PaulyWolly/redux-form-demo
|
/src/app/actions/index.ts
| 2.609375
| 3
|
import { Action } from "@ngrx/store";
import { ICountry, ICity } from "../state/application-state";
export const FORM_NAME_CHANGED = 'FORM_NAME_CHANGED';
export const FORM_SET_VALIDITY = 'FORM_SET_VALIDITY';
export const LOAD_COUNTRIES = 'LOAD_COUNTRIES';
export const COUNTRIES_LOADED = 'COUNTRIES_LOADED';
export const FORM_COUNTRY_CHANGED = 'FORM_COUNTRY_CHANGED';
export const LOAD_CITIES_FOR_COUNTRY = 'LOAD_CITIES_FOR_COUNTRY';
export const CITIES_FOR_COUNTRY_LOADED = 'CITIES_FOR_COUNTRY_LOADED';
export const FORM_CITY_CHANGED = 'FORM_CITY_CHANGED';
export interface IFormNameChangedAction extends Action {
payload: {
value: string;
}
}
export interface IFormSetValidityAction extends Action {
payload: {
isValid: boolean;
}
}
export interface ILoadCountriesAction extends Action {
payload: {
}
}
export interface ICountriesLoadedAction extends Action {
payload: {
countries: ICountry[]
}
}
export interface IFormCountryChangedAction extends Action {
payload: {
country: ICountry
}
}
export interface ILoadCitiesForCountryAction extends Action {
payload: {
countryId: string
}
}
export interface ICitiesForCountryLoadedAction extends Action {
payload: {
countryId: string,
cities: ICity[]
}
}
export interface IFormCityChangedAction extends Action {
payload: {
city: ICity
}
}
export function formNameChanged(value: string): IFormNameChangedAction {
return {
type: FORM_NAME_CHANGED,
payload: {
value
}
};
}
export function formSetValidity(isValid: boolean): IFormSetValidityAction {
return {
type: FORM_SET_VALIDITY,
payload: {
isValid
}
};
}
export function loadCountries(): ILoadCountriesAction {
return {
type: LOAD_COUNTRIES,
payload: {}
}
};
export function countriesLoaded(countries: ICountry[]) : ICountriesLoadedAction {
return {
type: COUNTRIES_LOADED,
payload: {
countries
}
}
};
export function formCountryChanged(country: ICountry): IFormCountryChangedAction {
return {
type: FORM_COUNTRY_CHANGED,
payload: {
country
}
}
};
export function loadCitiesForCountry(countryId: string): ILoadCitiesForCountryAction {
return {
type: LOAD_CITIES_FOR_COUNTRY,
payload: {
countryId
}
}
};
export function citiesForCountryLoaded(countryId: string, cities: ICity[]): ICitiesForCountryLoadedAction {
return {
type: CITIES_FOR_COUNTRY_LOADED,
payload: {
countryId,
cities
}
}
}
export function formCityChanged(city: ICity) : IFormCityChangedAction {
return {
type: FORM_CITY_CHANGED,
payload: {
city
}
}
}
|
4806db7330e0137c192d002371b3f18a185be99a
|
TypeScript
|
amm297/big-data-v
|
/src/app/pages/appartment/services/apartment_adapter.ts
| 2.703125
| 3
|
import { Appartment } from '../domain/appartment'
import { AppartmentDetails } from '../domain/appartment_details'
import { Location } from '../domain/location'
import { Price } from '../domain/price'
import { Review } from '../domain/review'
import { PropertyType } from '../domain/property_type'
import { BedType } from '../domain/bed_type'
import { RoomType } from '../domain/room_type'
import { CancellationPolicyType } from '../domain/cancellation_policy_type'
export function adapt(appartments: Array<string>): Array<Appartment> {
return appartments.map(apt => adaptApparment(apt))
}
function adaptApparment(appartment): Appartment {
const adaptedAppartment = new Appartment();
adaptedAppartment.details = adaptDetails(appartment);
adaptedAppartment.location = adaptLocation(appartment);
adaptedAppartment.price = adaptPrice(appartment);
adaptedAppartment.review = adaptReview(appartment);
adaptedAppartment.new_rate = appartment['new_rate']
return adaptedAppartment;
}
function adaptDetails(appartment): AppartmentDetails {
const details = new AppartmentDetails()
details.id = appartment['id']
details.url = appartment['url']
details.name = appartment['name']
details.description = appartment['description']
details.houseRules = appartment['house_rules']
details.image = appartment['picture_url']
details.propertyType = PropertyType[appartment['property_type']]
details.roomType = RoomType[appartment['room_type']]
details.accomodates = appartment['accommodates']
details.bathrooms = appartment['bathrooms']
details.bedrooms = appartment['bedrooms']
details.beds = appartment['beds']
details.bedType = BedType[appartment['bed_type']]
details.amenities = appartment['amenities']
details.squareFeet = appartment['square_feet']
return details;
}
function adaptLocation(appartment): Location {
const location = new Location()
location.address = appartment['street']
location.neighborhood = appartment['neighbourhood']
location.zipcode = appartment['zipcode']
location.latitude = appartment['latitude']
location.longitude = appartment['longitude']
return location;
}
function adaptPrice(appartment): Price {
const price = new Price()
price.price = appartment['price']
price.securityDeposit = appartment['security_depositt']
price.cleaningFee = appartment['cleaning_feee']
price.cancellationPolicy = CancellationPolicyType[appartment['cancellation_policy']]
return price;
}
function adaptReview(appartment): Review {
const review = new Review()
review.reviews = appartment['number_of_reviews']
review.reviewsScoreRate = appartment['review_scores_rating']
review.reviewsScoreAccuracy = appartment['review_scores_accuracy']
review.reviewsScoreCleanliness = appartment['review_scores_cleanliness']
review.reviewScoreCheckin = appartment['review_scores_checkin']
review.reviewScoreCommunication = appartment['review_scores_communication']
review.reviewScoreLocation = appartment['review_scores_location']
review.reviewScoreValue = appartment['review_scores_value']
return review;
}
|
291e43f53b7c3a0fbd612c325cfd31b7d25346b6
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/db-hafas-stations-autocomplete/index.d.ts
| 2.8125
| 3
|
// Type definitions for db-hafas-stations-autocomplete 2.0
// Project: https://github.com/derhuerst/db-hafas-stations-autocomplete
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = autocomplete;
/**
* Search & autocompletion for [Deutsche Bahn](https://en.wikipedia.org/wiki/Deutsche_Bahn) stations.
* Pulls its data from [`db-hafas-stations`](https://github.com/derhuerst/db-hafas-stations).
*
* @example
* import autocomplete = require('db-hafas-stations-autocomplete')
*
* autocomplete('Münch', 3)
* // =>
* // [
* // {
* // id: '624637',
* // relevance: 0.878345935,
* // score: 4.601702707916342,
* // weight: 143.8
* // },
* // {
* // id: '620368',
* // relevance: 0.878345935,
* // score: 4.601702707916342,
* // weight: 143.8
* // },
* // {
* // id: '8000261',
* // relevance: 0.878345935,
* // score: 4.601702707916342,
* // weight: 143.8
* // }
* // ]
*/
declare function autocomplete(
query: string,
/** @default 6 */
limit?: number,
/**
* If you set `fuzzy` to `true`, words with a
* [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) `<= 3` will be taken into account.
* This is a lot slower though.
*
* @default false
*/
fuzzy?: boolean,
/**
* Setting `completion` to `false` speeds things up.
*
* @default true
*/
completion?: boolean,
): autocomplete.Result[];
declare namespace autocomplete {
interface Result {
id: string;
relevance: number;
score: number;
weight: number;
}
}
|
fd389907aa7e5c17fe4d54e8f10f309c3f24a177
|
TypeScript
|
headintheclouddev/typings-suitescript-2.0
|
/N/file.d.ts
| 3.140625
| 3
|
export interface File {
description: string;
encoding: string;
fileType: Type;
folder: number;
readonly id: number;
isInactive: boolean;
isOnline: boolean;
readonly isText: boolean;
name: string;
readonly path: string;
readonly size: number;
readonly url: string;
save: () => number;
getContents: () => string;
getReader: () => FileReader; // Since 2019.1
/** Method used to return the iterator of segments delimited by a separator. Separator is included in each segment. Empty separator is not allowed */
getSegments: (options: { separator: string }) => FileIterator; // Since 2019.1
resetStream: () => void;
appendLine: (option: FileAppendLineOptions) => File;
lines: { iterator: () => FileIterator; };
}
/** Use for special read operations. Reads from a file until a specified delimiter is reached. Reads an arbitrary number of characters from a file. Since 2019.1. */
interface FileReader {
/**
* Returns string from current position to the next occurrence of options.tag.
* Returns the rest of the string if tag is not found. Returns null if reading is already finished.
* All types of characters are supported. If there's a character that does not exist until the end of the file, the rest of the file is returned.
*/
readUntil: (options: { tag: string }) => string;
/**
* Returns the next options.number characters from the current position.
* Returns less than the number if there is not enough characters to read in the file.
* Returns null if reading is already finished.
*/
readChars: (options: { number: number }) => string;
}
interface FileIterator {
each: (options: any) => boolean;
}
interface FileAppendLineOptions {
/** Internal ID of the file as a number or a string, or the relative file path to the file in the file cabinet. */
value: string;
}
interface FileLoadOptions {
/** Internal ID of the file as a number or a string, or the relative file path to the file in the file cabinet. */
id: (number | string);
}
interface FileDeleteOptions {
/** Internal ID of the file. */
id: (number | string);
}
interface FileCopyOptions {
/** The internal ID of the folder to copy the file to. This folder must already exist in the File Cabinet. */
folder: number;
/** The internal ID of the file to copy. The file must already exist in the file cabinet. */
id: number;
/**
* The conflict resolution value.
* This parameter specifies the type of conflict resolution to apply when a conflict occurs while copying a file
* (for example, if the target folder already contains a file with the same name).
* Use the values in the file.ConflictResolution enum to set this parameter. The default value is ConflictResolution.FAIL.
*/
conflictResolution: ConflictResolution;
}
interface FileCreateOptions {
/** The file name. */
name: string;
/** The file type. */
fileType: Type;
/** The file content. */
contents?: string;
/** The file content. */
description?: string;
/** The internal ID of the folder used when the file is saved. */
folder?: number;
/** The file encoding. */
encoding?: Encoding;
/** The file status. */
isInactive?: boolean;
/** The file status. */
isOnline?: boolean;
}
/** Method used to create a new file in the NetSuite file cabinet. */
export function create(options: FileCreateOptions): File;
/** Copy an existing file in the NetSuite File Cabinet. */
export function copy(options: FileCopyOptions): File;
/** Method used to delete an existing file from the NetSuite file cabinet. */
declare function deleteFunc(options: FileDeleteOptions): void;
export {deleteFunc as delete};
/** Method used to load an existing file from the NetSuite file cabinet. */
export function load(options: FileLoadOptions): File;
/** Method used to load an existing file from the NetSuite file cabinet. */
export function load(idOrPath: number | string): File;
export enum ConflictResolution {
/** Fail with an error if a conflict occurs. */
FAIL,
/** Overwrite the existing file if a conflict occurs.
* The attributes and permissions of the overwritten file are preserved (meaning that the copied file has the same attributes and permissions as the file that was overwritten).
*/
OVERWRITE,
/**
* Add a numeric suffix to the name of the copied file if a conflict occurs.
* For example, if you are copying a file named file.txt and a conflict occurs, the name of the copied file is file (1).txt.
*/
RENAME_TO_UNIQUE
}
/** Enumeration that holds the string values for supported character encoding. */
export enum Encoding {
UTF_8,
WINDOWS_1252,
ISO_8859_1,
GB18030,
SHIFT_JIS,
MAC_ROMAN,
GB2312,
BIG5,
}
/** Enumeration that holds the string values for supported file types. */
export enum Type {
AUTOCAD,
BMPIMAGE,
CSV,
EXCEL,
FLASH,
FREEMARKER,
GIFIMAGE,
GZIP,
HTMLDOC,
ICON,
JAVASCRIPT,
JPGIMAGE,
JSON,
MESSAGERFC,
MP3,
MPEGMOVIE,
MSPROJECT,
PDF,
PJPGIMAGE,
PLAINTEXT,
PNGIMAGE,
POSTSCRIPT,
POWERPOINT,
QUICKTIME,
RTF,
SMS,
STYLESHEET,
TAR,
TIFFIMAGE,
VISIO,
WEBAPPPAGE,
WEBAPPSCRIPT,
WORD,
XMLDOC,
XSD,
ZIP,
}
|
1c147be6601157c74e72bf7cc88bff8d2f54dc75
|
TypeScript
|
shanelonergan/typescript-practice
|
/index.ts
| 2.796875
| 3
|
// Import stylesheets
import './style.css';
function greeter(person) {
return person + " is a huuuuuuuuge idiot lmao";
}
let user = "Sukrit";
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = `<h1>${greeter(user)}</h1>`;
|
411ea7c1714ba4b43b9996cb0135df793629fb2e
|
TypeScript
|
alirahal22/employee-dashboard
|
/src/utils/encrypt.ts
| 2.515625
| 3
|
/** Performs RSA public key encryption to string payload */
export const rsaEncrypt = (key: string, clearText: string): string => {
const CryptoJs = require("hybrid-crypto-js");
const crypt = new CryptoJs.Crypt();
return crypt.encrypt(key, clearText);
};
|
ae6d37d08ab907875f05e96d5632234c21098a4c
|
TypeScript
|
mk-hill/nd9990-c3-microservices-v1
|
/project/filter/src/validation/error.ts
| 3.0625
| 3
|
import { Response } from 'express';
export enum ErrorMessages {
READ = 'Unable to read image URL, please ensure resource exists.',
FILTER = 'Unable to filter image.',
SAVE = 'Unable save image.',
MISSING_IMAGE_URL = 'Image URL required.',
}
export const handleErrorResponse = (res: Response, message: string) => {
const errorMessageIsIntendedForUser = Object.values(ErrorMessages)
.map((val) => val.toString())
.includes(message);
if (!errorMessageIsIntendedForUser) {
message = 'Internal error'; // Default to avoid sending unknown error messages in response
}
const statusCode = message === ErrorMessages.READ ? 422 : 500; // Assume url was the problem if Jimp couldn't read
res.status(statusCode).send(message);
};
|
3b129e91e9be16443778d9bad1054e216ccb2cfe
|
TypeScript
|
tuplo/envsubst
|
/src/index.ts
| 2.546875
| 3
|
/* eslint no-template-curly-in-string:off */
import { includeVariable } from "./include-variable";
const varNames = "[a-zA-Z_]+[a-zA-Z0-9_]*";
const placeholders = ["\\$_", "\\${_}", "{{_}}"];
const envVars = placeholders
.map((placeholder) => placeholder.replace("_", `(${varNames})`))
.join("|");
const rgEnvVars = new RegExp(envVars, "gm");
type EnvsubstFn = (input: string, shellFormat?: string) => string;
const envsubst: EnvsubstFn = (input, shellFormat) => {
const match = input.matchAll(rgEnvVars);
if (!match) return input;
return Array.from(match)
.map((m) => {
const [varInput, varName] = m
.slice(0, placeholders.length + 1)
.filter(Boolean);
const value =
typeof process.env[varName] === "undefined"
? varInput
: process.env[varName];
return [varInput, value];
})
.filter(([varInput]) => varInput && includeVariable(shellFormat, varInput))
.reduce(
(acc, [varInput = "", value = ""]) => acc.replace(varInput, value),
input
);
};
export default envsubst;
|
d6245d65a50854f716efd01a331e3c67ae5ba24b
|
TypeScript
|
neotek/nuget-tree
|
/src/main.ts
| 2.859375
| 3
|
import { NuGetTree } from "./nuGetTree";
import { ISettings } from "./settings";
import { IPackage } from "./interfaces/package";
export function init(settings: ISettings): Promise<IPackage[]>
{
return new NuGetTree(settings).run();
}
export async function initMany(solutions: string[]): Promise<IPackage[]>
{
const promises = solutions.map(solution => new NuGetTree( { solution: solution } as any).run());
const results = await Promise.all(promises);
// Reduce, distinct and sort
return results.reduce((a, b) => a.concat(b), [])
.filter((obj, pos, arr) => {
return arr.map(mapObj => mapObj.id).indexOf(obj.id) === pos;
}).sort((current, next) => current.id.localeCompare(next.id));
}
|
63965935e0781cd1f7bfc375a2d9c27d769d80be
|
TypeScript
|
Duclearc/MEAN-forum
|
/MEAN-forum-client/src/app/auth/auth.service.ts
| 2.515625
| 3
|
import { Injectable } from "@angular/core";
import { User, UserLoginData, UserProfileData } from './user.model';
import { HttpClient } from "@angular/common/http";
import { Router } from "@angular/router";
import { BehaviorSubject } from "rxjs";
@Injectable({ providedIn: 'root' })
export class AuthService {
private hostURL: string = 'http://localhost:3000';
private apiURL: string = this.hostURL + '/api/users';
private token: string = null;
private expiry: string = null;
emptyUser: UserProfileData = {
id: null,
username: null,
imgPath: null,
}
private user = new BehaviorSubject<UserProfileData>(null);
private authStatusListener = new BehaviorSubject<boolean>(false);
private loadingStatusListener = new BehaviorSubject<boolean>(false);
constructor(private http: HttpClient, private router: Router) { }
getHostURL() {
return this.hostURL;
}
setUser() { // ! Must always be called after this.token has been assigned!
this.http.get<{ user: UserProfileData }>(this.apiURL + '/me')
.subscribe(response => {
this.user.next(response.user);
})
}
getUserListener() {
return this.user.asObservable();
}
getToken() {
return this.token;
}
loadPage(path: string = '') {
this.loadingStatusListener.next(true);
this.router.navigate(['/' + path]);
this.loadingStatusListener.next(false);
}
getLoadingStatusListener() {
return this.loadingStatusListener.asObservable();
}
getAuthStatusListener() {
return this.authStatusListener.asObservable();
}
authenticateUser() {
this.loadingStatusListener.next(true);
const session = JSON.parse(localStorage.getItem('session'));
if (session) {
this.token = session.token;
this.expiry = session.expiry;
this.setUser();
}
const now = new Date();
const expiryDate = new Date(this.expiry);
if (this.token && expiryDate >= now) {
this.authStatusListener.next(true);
this.loadingStatusListener.next(false);
return
} else {
const clearStorage = session ? true : false; // "is this the user's first login?"
this.logoutUser(clearStorage);
}
}
createUser(user: User, imgFile: File = null) {
this.loadingStatusListener.next(true);
const userData = new FormData();
userData.append("username", user.username);
userData.append("email", user.email);
userData.append("password", user.password);
if (imgFile) {
userData.append("imgFile", imgFile, Math.random().toString());
}
this.http.post<{ message: string, user: User }>(this.apiURL + '/register', userData)
.subscribe(
responseData => {
console.log(responseData.message);
// login new user
const newUser: UserLoginData = {
email: user.email,
password: user.password
};
this.loginUser(newUser);
},
err => {
alert('This email address is taken');
console.log(err);
}
);
}
loginUser(user: UserLoginData) {
this.loadingStatusListener.next(true);
this.http.post<{ message: string, token: string, userId: string }>(this.apiURL + '/login', user)
.subscribe(
responseData => {
// setting up the expiry date
const now = new Date();
const expiryHour = now.getHours() + 1;
now.setHours(expiryHour);
const expiryTime = now.toISOString();
// storing values
const session = JSON.stringify({
expiry: expiryTime,
token: responseData.token,
});
localStorage.setItem('session', session);
this.token = responseData.token;
this.setUser();
// sending feedback
console.log(responseData.message);
this.authStatusListener.next(true);
this.loadPage();
},
err => {
alert('Oh, oh. Was there a typo somewhere?');
console.log(err);
this.loadingStatusListener.next(false);
},
() => this.loadingStatusListener.next(false)
);
}
logoutUser(clearStorage: boolean = true) {
this.loadingStatusListener.next(true);
this.token = null;
this.expiry = null;
if (clearStorage) { localStorage.removeItem('session') };
this.user.next(null);
this.authStatusListener.next(false);
this.loadingStatusListener.next(false);
}
}
|
72cef156ac2c066ebe4765d4d02396a3fe929581
|
TypeScript
|
maliquan/game
|
/game1/src/view/cfg/ObjCfg.ts
| 2.625
| 3
|
/**
* Created by maliquan on 16/4/22.
*/
class ObjCfg{
// public static objCfg:number[][] = [
// //[maxHp, minAtt, maxAtt, def, speed]
// [100, 10, 20, 1, 1]
// ];
public static getObjCfg(name:string):ObjectVo{
var level:number = (Math.random()*10 +1 + 10 * FightScene.curMapLevel)>>0;
var vo:ObjectVo = new ObjectVo(name,[
50 + level*50,//血
10 + level*10,//最小攻击
15 + level*15,//最大攻击
5 + level*5,//防御
1//速度
]);
return vo;
}
}
|
a02db923bbadb737d6881e051271f80818266726
|
TypeScript
|
runem/lit-analyzer
|
/packages/lit-analyzer/src/test/parser/dependencies/parse-dependencies.ts
| 2.609375
| 3
|
import { parseAllIndirectImports } from "../../../lib/analyze/parse/parse-dependencies/parse-dependencies.js";
import { isFacadeModule } from "../../../lib/analyze/parse/parse-dependencies/visit-dependencies.js";
import { prepareAnalyzer } from "../../helpers/analyze.js";
import { tsTest } from "../../helpers/ts-test.js";
tsTest("Correctly finds all imports in a file", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "file1.ts", text: `` },
{ fileName: "file2.ts", text: `` },
{ fileName: "file3.ts", text: `` },
{ fileName: "file4.ts", text: `` },
{
fileName: "file5.ts",
text: `
import "file1";
import * as f2 from "file2";
import { } from "file3";
(async () => {
await import("file4");
})();
`,
entry: true
}
]);
const dependencies = parseAllIndirectImports(sourceFile, context);
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file1.ts", "file2.ts", "file3.ts", "file4.ts", "file5.ts"]);
});
tsTest("Correctly follows all project-internal imports with (default) maxInternalDepth=Infinity", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "file1.ts", text: ` ` },
{ fileName: "file2.ts", text: `import * from "file1"` },
{ fileName: "file3.ts", text: `import * from "file2"` },
{ fileName: "file4.ts", text: `import * from "file3"` },
{ fileName: "file5.ts", text: `import * from "file4"`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context);
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file1.ts", "file2.ts", "file3.ts", "file4.ts", "file5.ts"]);
});
tsTest("Correctly follows project-internal imports with maxInternalDepth=1", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "file1.ts", text: `export class MyClass { }` },
{ fileName: "file2.ts", text: `import * from "file1";export class MyClass { }` },
{ fileName: "file3.ts", text: `import * from "file2";export class MyClass { }`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context, { maxInternalDepth: 1 });
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file2.ts", "file3.ts"]);
});
tsTest("Correctly follows project-internal imports with maxInternalDepth=5", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "file1.ts", text: `export class MyClass { }` },
{ fileName: "file2.ts", text: `import * from "file1";export class MyClass { }` },
{ fileName: "file3.ts", text: `import * from "file2";export class MyClass { }` },
{ fileName: "file4.ts", text: `import * from "file3";export class MyClass { }` },
{ fileName: "file5.ts", text: `import * from "file4";export class MyClass { }` },
{ fileName: "file6.ts", text: `import * from "file5";export class MyClass { }` },
{ fileName: "file7.ts", text: `import * from "file6";export class MyClass { }`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context, { maxInternalDepth: 5 });
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file2.ts", "file3.ts", "file4.ts", "file5.ts", "file6.ts", "file7.ts"]);
});
tsTest("Correctly follows project-external imports with maxExternalDepth=1", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "node_modules/file1.ts", text: `export class MyClass { }` },
{ fileName: "node_modules/file2.ts", text: `import * from "./file1";export class MyClass { }` },
{ fileName: "node_modules/file3.ts", text: `import * from "./file2";export class MyClass { }`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context, { maxExternalDepth: 1 });
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["node_modules/file2.ts", "node_modules/file3.ts"]);
});
tsTest("Correctly follows project-external imports with maxExternalDepth=5", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "node_modules/file1.ts", text: `export class MyClass { }` },
{ fileName: "node_modules/file2.ts", text: `import * from "./file1";export class MyClass { }` },
{ fileName: "node_modules/file3.ts", text: `import * from "./file2";export class MyClass { }` },
{ fileName: "node_modules/file4.ts", text: `import * from "./file3";export class MyClass { }` },
{ fileName: "node_modules/file5.ts", text: `import * from "./file4";export class MyClass { }` },
{ fileName: "node_modules/file6.ts", text: `import * from "./file5";export class MyClass { }` },
{ fileName: "node_modules/file7.ts", text: `import * from "./file6";export class MyClass { }`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context, { maxExternalDepth: 5 });
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, [
"node_modules/file2.ts",
"node_modules/file3.ts",
"node_modules/file4.ts",
"node_modules/file5.ts",
"node_modules/file6.ts",
"node_modules/file7.ts"
]);
});
tsTest("Correctly resets depth when going from internal to external module with maxInternalDepth=1", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "node_modules/file1.ts", text: `export class MyClass { }` },
{ fileName: "node_modules/file2.ts", text: `import * from "./file1";export class MyClass { }` },
{ fileName: "file3.ts", text: `import * from "./node_modules/file2";export class MyClass { }`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context, { maxInternalDepth: 1 });
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file3.ts", "node_modules/file2.ts"]);
});
tsTest("Correctly resets depth when going from internal to external module with maxInternalDepth=2", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "node_modules/file1.ts", text: `export class MyClass { }` },
{ fileName: "node_modules/file2.ts", text: `import * from "./file1";export class MyClass { }` },
{ fileName: "file3.ts", text: `import * from "./node_modules/file2";export class MyClass { }` },
{ fileName: "file4.ts", text: `import * from "./file3";export class MyClass { }`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context, { maxInternalDepth: 2 });
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file3.ts", "file4.ts", "node_modules/file2.ts"]);
});
tsTest("Correctly resets depth when going from internal to external module when first external module is a facade module", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "node_modules/file1.ts", text: `export class MyClass { }` },
{ fileName: "node_modules/file2.ts", text: `import * from "./file1";export class MyClass { }` },
{ fileName: "node_modules/file3.ts", text: `import * from "./file2"` },
{ fileName: "file4.ts", text: `import * from "./node_modules/file3";export class MyClass { }`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context, { maxInternalDepth: 1 });
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file4.ts", "node_modules/file2.ts", "node_modules/file3.ts"]);
});
tsTest("Correctly follows modules when going from internal to external module when second external module is a facade module", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "node_modules/file1.ts", text: `export class MyClass { }` },
{ fileName: "node_modules/file2.ts", text: `import * from "./file1";export class MyClass { }` },
{ fileName: "node_modules/file3.ts", text: `import * from "./file2"` },
{ fileName: "node_modules/file4.ts", text: `import * from "./file3";export class MyClass { }` },
{ fileName: "file5.ts", text: `import * from "./node_modules/file4";export class MyClass { }`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context, { maxInternalDepth: 1, maxExternalDepth: 2 });
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file5.ts", "node_modules/file2.ts", "node_modules/file3.ts", "node_modules/file4.ts"]);
});
tsTest("Correctly handles recursive imports", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "file1.ts", text: `import * from "file3"` },
{ fileName: "file2.ts", text: `import * from "file1"` },
{ fileName: "file3.ts", text: `import * from "file2"`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context);
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file1.ts", "file2.ts", "file3.ts"]);
});
tsTest("Correctly follows both exports and imports", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "file1.ts", text: `` },
{ fileName: "file2.ts", text: `export * from "file1"` },
{ fileName: "file3.ts", text: `import * from "file2"`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context);
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file1.ts", "file2.ts", "file3.ts"]);
});
tsTest("Correctly identifies facade modules", t => {
const { program, context } = prepareAnalyzer([
{ fileName: "file1.ts", text: `export class MyClass { }` },
{ fileName: "file2.ts", text: `export * from "file1";` },
{ fileName: "file3.ts", text: `import * from "file1";` },
{ fileName: "file4.ts", text: `import * from "file1"; export * from "file2";` },
{ fileName: "file5.ts", text: `import * from "file2"; export class MyClass { }"` }
]);
t.is(isFacadeModule(program.getSourceFile("file1.ts")!, context.ts), false);
t.is(isFacadeModule(program.getSourceFile("file2.ts")!, context.ts), true);
t.is(isFacadeModule(program.getSourceFile("file3.ts")!, context.ts), true);
t.is(isFacadeModule(program.getSourceFile("file4.ts")!, context.ts), true);
t.is(isFacadeModule(program.getSourceFile("file5.ts")!, context.ts), false);
});
tsTest("Correctly follows facade modules one level", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "file1.ts", text: `export class MyClass { }` },
{ fileName: "file2.ts", text: `import * from "file1"; export class MyClass { }` },
{ fileName: "file3.ts", text: `import * from "file2";` },
{ fileName: "file4.ts", text: `import * from "file3"; export class MyClass { }"`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context, { maxInternalDepth: 1 });
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file2.ts", "file3.ts", "file4.ts"]);
});
tsTest("Correctly follows facade modules multiple levels", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "file0.ts", text: `export class MyClass { }` },
{ fileName: "file1.ts", text: `export * from "file0"; export class MyClass { }` },
{ fileName: "file2.ts", text: `export * from "file1";` },
{ fileName: "file3.ts", text: `import * from "file2";` },
{ fileName: "file4.ts", text: `import * from "file3"; export class MyClass { }"`, entry: true }
]);
const dependencies = parseAllIndirectImports(sourceFile, context, { maxInternalDepth: 1 });
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file1.ts", "file2.ts", "file3.ts", "file4.ts"]);
});
tsTest("Ignores type-only imports in a file", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "file1.ts", text: `` },
{
fileName: "file2.ts",
text: `
import type { MyElement } from "./file1";
`,
entry: true
}
]);
const dependencies = parseAllIndirectImports(sourceFile, context);
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file2.ts"]);
});
tsTest("Ignores type-only exports in a file", t => {
const { sourceFile, context } = prepareAnalyzer([
{ fileName: "file1.ts", text: `` },
{
fileName: "file2.ts",
text: `
export type { MyElement } from "./file1";
`,
entry: true
}
]);
const dependencies = parseAllIndirectImports(sourceFile, context);
const sortedFileNames = Array.from(dependencies)
.map(file => file.fileName)
.sort();
t.deepEqual(sortedFileNames, ["file2.ts"]);
});
|
a260fcaed6f8b7bc65d31fbf790e25ad96a7074b
|
TypeScript
|
murphym215/angular-tour-of-heroes
|
/src/app/in-memory-data.service.ts
| 2.921875
| 3
|
/**
* Created by MatthewMurphy on 7/4/2017.
*/
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const beers = [
{id: 0, name: 'Belgian', description: 'A beer that varies in alcohol strength, regular, dubbel, tripel, quad'},
{id: 11, name: 'IPA', description: 'An IPA typically has a citrusy aroma. ' },
{id: 12, name: 'Shandy', description: 'A true summer beer, a mixture of beer and just about any flavor you like. For example, wheat beer mixed with lemonade'},
{id: 13, name: 'Pale Ale', description: 'Similar to an IPA, but less hoppy. '},
{id: 14, name: 'Stout', description: 'Son of the Porter style, interpretation can vary, I like Bourbon Barrel Stouts'},
{id: 15, name: 'Porter', description: 'The working mans beer, dark easy to drink, sometimes made with coffee flavoring'},
{id: 16, name: 'Gose', description: 'A sour style of beer, very tart, but oh so tasty'},
{id: 17, name: 'Hefeweizen', description: 'German style wheat beer with hints on banana and cloves'},
{id: 18, name: 'Wheat', description: 'A wheat style is made with, you guessed it, Wheat. The yeast strain makes the style'},
{id: 19, name: 'Black IPA', description: 'An IPA made with a dark grain to give it a black color and hint of dark flavor. '},
{id: 20, name: 'Irish Red Ale', description: 'Red in color, made with an Irish yeast strain. Yeah, I wont say no to this style '}
];
return {beers};
}
}
|
c3df2e605348e8ba59840e397edcaaca1dcf964f
|
TypeScript
|
damiensawyer/dcapjs
|
/src/maths.ts
| 3.578125
| 4
|
/**
* Takes two numbers and returns their sum
* @param a first input to sum
* @param b second input to sum
* @returns sum of a and b
*/
export function sum(a: number, b: number) {
return a + b;
}
export function multiply(a: number, b: number) {
return a * b;
}
export function divide(a: number, b: number) {
return a / b;
}
export function subtract(a: number, b: number){
return a - b;
}
/**https://stackoverflow.com/a/40270735 */
export const doubleNumber = (a: number) : number => a * 2;
export default function HelloWorld():string {return 'Hello World'};
|
d7ddcf619f3f635e704406dc6cd967552298f01b
|
TypeScript
|
pablomayobre/Dewyll
|
/src/Moves/Util.ts
| 3.09375
| 3
|
import { Board, getDirection } from '../Base/Pieces'
export interface Action<M> {
from: number
to: number
eats: number | null
continues: M
}
export type Overlay = Array<Action<MoveType> | null>
export type MoveOverlay<T, P> = (
board: Board<T, P>,
from: number,
) => Overlay | null
/*
0..3 = (Bishop, Queen, King) down-right, up-right, down-left, up-left
4..7 = (Rook, Queen, King) right, left, down, up
8..15 = (Knight) all L shapes possible
*/
export const standardDirection = {
x: [1, 1, -1, -1, 1, -1, 0, 0, 2, -2, -2, 2, 1, -1, -1, 1],
y: [1, -1, 1, -1, 0, 0, 1, -1, 1, 1, -1, -1, 2, 2, -2, -2],
}
export const getPlayer = <T, P>(
board: Board<T, P>,
from: number,
): [P, 1 | -1] => {
const tile = board[from]
if (tile === null) {
throw new Error('Selected tile is empty') // Hopefully this will never happen
}
return [tile.owner, getDirection(tile.direction)]
}
export enum MoveType {
KING = 'King',
QUEEN = 'Queen',
BISHOP = 'Bishop',
ROOK = 'Rook',
KNIGHT = 'Knight',
PAWN = 'Pawn',
DEATH = 'Death',
DRAUGHT = 'Draught',
KILLER_DRAUGHT = '!Draught',
FINISH = '!Finish',
}
|
61511ffd17a8ec53855f9bd8efc60e56f688b41a
|
TypeScript
|
jeffersonshibuya/moveit
|
/src/models/User.ts
| 2.625
| 3
|
import Adapters from 'next-auth/adapters'
import { EntitySchemaColumnOptions } from 'typeorm'
export default class User extends (<any>Adapters.TypeORM.Models.User.model) {
constructor(name, email, image, emailVerified) {
super(name, email, image, emailVerified)
}
}
type UserSchema = {
name: string
target: typeof User
columns: {
username?: {
type: 'varchar'
nullable: boolean
}
name?: EntitySchemaColumnOptions
email?: EntitySchemaColumnOptions
image?: EntitySchemaColumnOptions
emailVerified?: EntitySchemaColumnOptions,
level?: {
type: 'int',
nullable: boolean,
}
}
}
export const UserSchema: UserSchema = {
name: "User",
target: User,
columns: {
...Adapters.TypeORM.Models.User.schema.columns,
level: {
type: "int",
nullable: true,
}
}
}
|
9987ef1a109cea4ab76ab34a2d97ed24ad8a1ff1
|
TypeScript
|
cmdo/server
|
/src/Database/Mongo.ts
| 2.875
| 3
|
import { MongoClient } from "mongodb";
import { EventEmitter } from "../Utils";
export class Mongo extends EventEmitter {
public name: string;
public client: MongoClient;
/**
* Create a new mongodb node.
*
* @param name - Database name to run queries against.
* @param uri - Database connection endpoint.
*/
constructor(name: string, uri: string) {
super();
this.name = name;
this.client = new MongoClient(uri, {
poolSize: 10,
useNewUrlParser: true,
useUnifiedTopology: true,
ignoreUndefined: false
});
}
/**
* Connects the mongodb client to the server and keeps it alive.
*
* @returns mongodb instance
*/
public async connect() {
await this.client.connect();
// ### Connect Actions
this.emit("connected");
this.watch();
// ### Close Event
this.client.on("close", () => {
this.emit("disconnected");
this.connect();
});
}
/**
* Get database instance.
*
* @param name - Name of the database.
*
* @returns database
*/
public get db() {
return this.client.db(this.name);
}
/**
* Get a mongodb collection to perform query operations on.
*
* @param name - Name of the collection.
*
* @returns mongodb collection
*/
public collection<T = any>(name: string) {
return this.db.collection<T>(name);
}
/**
* Start watching for changes to data and inform any listeners
* of changes occurred.
*/
private watch() {
const cursor = (this.db as any).watch({ fullDocument: "updateLookup" });
cursor.on("change", (event: any) => {
this.emit("change", event);
});
}
}
|