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
|
|---|---|---|---|---|---|---|
d4ac1e7d7256669449d2ace299cb370d1a748c26
|
TypeScript
|
burin-sapsiri/HDLC
|
/index.ts
| 2.765625
| 3
|
const crc = require("crc");
const EventEmitter = require("events").EventEmitter;
const FRAME_BOUNDARY_OCTET = 0x7E;
const CONTROL_ESCAPE_OCTET = 0x7D;
const INVERT_OCTET = 0x20;
const MINIHDLC_MAX_FRAME_LENGTH = 4096;
class HDLC {
public pendingFrame: any = {};
public eventEmitter = new EventEmitter();
public byteSendingFunction = (byte) => {};
public HDLC(){}
public init(byteSendingFunction) {
this.byteSendingFunction = byteSendingFunction;
this.pendingFrame.framePosition = 0;
this.pendingFrame.frameChecksum = undefined;
this.pendingFrame.escapeCharacter = false;
this.pendingFrame.receivedFrameBuffer = [];
this.pendingFrame.isStared = false;
}
public sendchar(data) {
this.byteSendingFunction(data & 0xff);
}
public byteReceiver(bytes) {
for (var i = 0; i < bytes.length; i++) {
/* FRAME FLAG */
var data = bytes[i];
/* FRAME FLAG */
if (data === FRAME_BOUNDARY_OCTET) {
if (this.pendingFrame.escapeCharacter === true) {
this.pendingFrame.escapeCharacter = false;
}
else if (this.pendingFrame.framePosition >= 2) {
this.pendingFrame.frameChecksum ^= 0xffff
console.log(this.pendingFrame.frameChecksum.toString(16))
if (this.pendingFrame.frameChecksum === ((this.pendingFrame.receivedFrameBuffer[this.pendingFrame.framePosition - 1] << 8) | (this.pendingFrame.receivedFrameBuffer[this.pendingFrame.framePosition - 2] & 0xff))) {
/* Call the user defined function and pass frame to it */
this.eventEmitter.emit("newFrame", this.pendingFrame.receivedFrameBuffer.slice(0, this.pendingFrame.receivedFrameBuffer.length - 2));
}
}
this.pendingFrame.framePosition = 0;
this.pendingFrame.frameChecksum = 0xffff;
this.pendingFrame.escapeCharacter = false;
this.pendingFrame.receivedFrameBuffer = [];
continue;
}
if (this.pendingFrame.escapeCharacter) {
this.pendingFrame.escapeCharacter = false;
data ^= INVERT_OCTET;
}
else if (data === CONTROL_ESCAPE_OCTET) {
this.pendingFrame.escapeCharacter = true;
continue;
}
this.pendingFrame.receivedFrameBuffer[this.pendingFrame.framePosition] = data;
if (this.pendingFrame.framePosition - 2 >= 0) {
this.pendingFrame.frameChecksum = crc.crc16kermit([this.pendingFrame.receivedFrameBuffer[this.pendingFrame.framePosition - 2]], this.pendingFrame.frameChecksum);
}
this.pendingFrame.framePosition++;
if (this.pendingFrame.framePosition === MINIHDLC_MAX_FRAME_LENGTH) {
this.pendingFrame.framePosition = 0;
this.pendingFrame.frameChecksum = undefined;
this.pendingFrame.escapeCharacter = false;
this.pendingFrame.receivedFrameBuffer = [];
}
}
}
public sendFrame(rawFrame) {
var byte;
var fcs = 0xffff
this.sendchar(FRAME_BOUNDARY_OCTET);
for (var i = 0; i < rawFrame.length; i++) {
byte = rawFrame[i];
fcs = crc.crc16kermit([byte], fcs);
if ((byte === CONTROL_ESCAPE_OCTET) || (byte === FRAME_BOUNDARY_OCTET)) {
this.sendchar(CONTROL_ESCAPE_OCTET);
byte ^= INVERT_OCTET;
}
this.sendchar(byte);
}
fcs ^= 0xffff
byte = fcs & 0x00ff;
if ((byte === CONTROL_ESCAPE_OCTET) || (byte === FRAME_BOUNDARY_OCTET)) {
this.sendchar(CONTROL_ESCAPE_OCTET);
byte ^= INVERT_OCTET;
}
this.sendchar(byte);
byte = (fcs & 0xff00) >> 8;
if ((byte === CONTROL_ESCAPE_OCTET) || (byte === FRAME_BOUNDARY_OCTET)) {
this.sendchar(CONTROL_ESCAPE_OCTET);
byte ^= INVERT_OCTET;
}
this.sendchar(byte);
this.sendchar(FRAME_BOUNDARY_OCTET);
}
public clear() {
this.pendingFrame.framePosition = 0;
this.pendingFrame.frameChecksum = 0xffff;
this.pendingFrame.escapeCharacter = false;
this.pendingFrame.receivedFrameBuffer = [];
}
}
export {HDLC};
|
66f7f331e304deed5938a29724861cd68b744516
|
TypeScript
|
Woohaik/EventosDeportivos-Frontend
|
/src/store/reducers/customerReducer.ts
| 2.78125
| 3
|
import { CustomerState, CustomerAction, EDIT_CUSTOMER, LOGIN_CUSTOMER, DELETE_CUSTOMER, LOGOUT_CUSTOMER } from "../types";
import { isJwtExpired } from "../../utils"
const initialState: CustomerState = {
customer: {
dni: "",
email: "",
lastname: "",
name: "",
id: 0
}, token: localStorage.getItem("customer-token") || "",
}
const customerReducer = (state: CustomerState = initialState, action: CustomerAction): CustomerState => {
switch (action.type) {
case LOGIN_CUSTOMER:
localStorage.setItem("customer-token", action.logedCustomer.token);
localStorage.setItem("customer-refresh-token", action.logedCustomer.refreshToken);
state.token = action.logedCustomer.token;
state.customer = action.logedCustomer.customer;
return state;
case EDIT_CUSTOMER:
state.customer = action.toEditCustomer
return state;
case DELETE_CUSTOMER:
localStorage.removeItem("customer-token");
localStorage.removeItem("customer-refresh-token");
state.token = "";
state.customer = {
dni: "",
email: "",
lastname: "",
name: "",
id: NaN
}
return state;
case LOGOUT_CUSTOMER:
localStorage.removeItem("customer-token");
localStorage.removeItem("customer-refresh-token");
state.token = "";
state.customer = {
dni: "",
email: "",
lastname: "",
name: "",
id: NaN
}
return state;
default: return state;
}
}
export const isLogged = (token: string): boolean => {
return !isJwtExpired(token)
}
export default customerReducer;
|
0a627fec7dff5b5ac795b4d425d8653a5a7ffecf
|
TypeScript
|
knraulmendoza/practics-api
|
/src/modules/login/user.controller.ts
| 2.65625
| 3
|
/*
https://docs.nestjs.com/controllers#controllers
*/
import {
Body,
Controller,
Get,
HttpException,
HttpStatus,
Post,
Res,
} from '@nestjs/common';
import { UserDto } from './dto/user.dto';
import { User } from './user.entity';
import { UserService } from './user.service';
@Controller('user')
export class UserController {
constructor(private userService: UserService) {}
@Get()
async getAll(): Promise<User[]> {
return await this.userService.getAll();
}
@Post()
async create(@Body() userDto: UserDto, @Res() response): Promise<User> {
try {
const resp = await this.userService.create(userDto);
return response
.status(HttpStatus.CREATED)
.json({ status: true, message: 'Ok', data: resp });
} catch (error) {
return response
.status(HttpStatus.BAD_REQUEST)
.json({ status: false, message: error.sqlMessage });
}
}
}
|
98ce73044976add536c36be902da435a419cf7ee
|
TypeScript
|
hshine1226/bee-js
|
/test/utils/eth.spec.ts
| 2.859375
| 3
|
/* eslint @typescript-eslint/no-empty-function: 0 */
import { ethToSwarmAddress, fromLittleEndian, isEthAddress, toLittleEndian } from '../../src/utils/eth'
describe('eth', () => {
describe('isEthAddress', () => {
const testValues = [
{ value: () => {}, result: false },
{ value: new Function(), result: false },
{ value: 'function', result: false },
{ value: {}, result: false },
{ value: '0xc6d9d2cd449a754c494264e1809c50e34d64562b', result: true },
{ value: '0xc6d9d2cd449a754c494264e1809c50e34d64562b'.toUpperCase(), result: true },
{ value: 'c6d9d2cd449a754c494264e1809c50e34d64562b', result: true },
{ value: 'c6d9d2cd449a754c494264e1809c50e34d64562b'.toUpperCase(), result: true },
{ value: 'E247A45c287191d435A8a5D72A7C8dc030451E9F', result: true },
{ value: '0xE247A45c287191d435A8a5D72A7C8dc030451E9F', result: true },
{ value: '0xE247a45c287191d435A8a5D72A7C8dc030451E9F', result: false },
{ value: '0xe247a45c287191d435a8a5d72a7c8dc030451e9f', result: true },
{ value: '0xE247A45C287191D435A8A5D72A7C8DC030451E9F', result: true },
{ value: '0XE247A45C287191D435A8A5D72A7C8DC030451E9F', result: true },
{ value: '1234567890123456789012345678901234567890', result: true },
{ value: 1234567890123456789012345678901234567890, result: false },
]
testValues.forEach(({ value, result }) => {
test(`should test if value ${value} is address: ${result}`, () => {
expect(isEthAddress((value as unknown) as string)).toBe(result)
})
})
})
describe('toLittleEndian', () => {
const testValues = [
{ value: '1', result: '01' },
{ value: 1, result: '01' },
{ value: '123', result: '2301' },
{ value: '0123', result: '2301' },
{ value: '0123', result: '230100', pad: 6 },
{ value: '0x0123', result: '230100', pad: 6 },
{ value: 124, result: '7c' },
{ value: 28721856816, result: '30c1f4af06' },
]
testValues.forEach(({ value, result, pad }) => {
test(`should conver value ${value}${pad ? ` with pad ${pad}` : ''} to ${result}`, () => {
expect(toLittleEndian(value, pad)).toBe(result)
})
})
const wrongTestValues = [124.1, -1, () => {}, new Function(), Number.MAX_SAFE_INTEGER + 1]
wrongTestValues.forEach(value =>
test(`should throw for non string or positive int values: ${value}`, () => {
expect(() => toLittleEndian((value as unknown) as string)).toThrow()
}),
)
})
describe('fromLittleEndian', () => {
const testValues = ['0123', '0x0123', 124, 28721856816]
testValues.forEach(value => {
test(`should conver value ${value} back and forth`, () => {
// We are converting first time to make for the comparison value to be padded and of the same type
const littleEndian1 = toLittleEndian(value)
const bigEndian = fromLittleEndian(littleEndian1)
const littleEndian2 = fromLittleEndian(bigEndian)
expect(littleEndian1).toBe(littleEndian2)
})
})
testValues.forEach(value => {
test(`should conver value ${value} back and forth with padding`, () => {
// We are converting first time to make for the comparison value to be padded and of the same type
const littleEndian1 = toLittleEndian(value, 10)
const bigEndian = fromLittleEndian(littleEndian1, 10)
const littleEndian2 = fromLittleEndian(bigEndian, 10)
expect(littleEndian1).toBe(littleEndian2)
})
})
})
describe('ethToSwarmAddress', () => {
const testValues = [
{
value: '1815cac638d1525b47f848daf02b7953e4edd15c',
result: 'b003840cac8f71dc3e6025dbccae613fd107dcb2fb187808b54cab92cfdd8299',
},
{
value: '0x1815cac638d1525b47f848daf02b7953e4edd15c',
result: 'b003840cac8f71dc3e6025dbccae613fd107dcb2fb187808b54cab92cfdd8299',
},
{
value: '0737e7c2e82fac12ca9e2bae01bea910593300e6',
result: 'ba898f4dd93c5b29dc2d9daff3ef3d183fa6b5bfac9c23d975c0ee1fb06fcad9',
},
{
value: 'd26bc1715e933bd5f8fad16310042f13abc16159',
result: '8e186467e0ed20b73667b5353210c0e650401cde0461c25c6b3e4a1f636b8cb8',
},
]
testValues.forEach(({ value, result }) => {
test(`should create from ${value} to ${result}`, () => {
expect(ethToSwarmAddress(value)).toBe(result)
})
})
const wrongTestValues = [
{
address: '1815cac638d1525b47f848daf02b7953e4edd15cf',
netId: 1,
},
{
address: '1815cac638d1525b47f848daf02b7953e4edd15c',
netId: 0,
},
{
address: '1815cac638d1525b47f848daf02b7953e4edd15c',
netId: Number.MAX_SAFE_INTEGER + 1,
},
{
address: '1815cac638d1525b47f848daf02b7953e4edd15c',
netId: () => {},
},
{
address: () => {},
netId: 1,
},
]
wrongTestValues.forEach((address, netId) =>
test(`should throw for incorrect values address ${address} netId ${netId}`, () => {
expect(() => ethToSwarmAddress((address as unknown) as string, (netId as unknown) as number)).toThrow()
}),
)
})
})
|
42cc56e53158c61b038c7e62d2a20ac86d13c67d
|
TypeScript
|
JowieXiang/backend
|
/application/micado-backend/src/models/settings.model.ts
| 2.578125
| 3
|
import { Entity, model, property } from '@loopback/repository';
@model({
settings: { idInjection: false, postgresql: { schema: 'micadoapp', table: 'settings' } }
})
export class Settings extends Entity {
@property({
type: 'string',
required: true,
id: 1,
postgresql: { columnName: 'key', dataType: 'character varying', dataLength: null, dataPrecision: null, dataScale: null, nullable: 'NO' },
})
key: string;
@property({
type: 'string',
length: 1500,
postgresql: { columnName: 'value', dataType: 'character varying', dataLength: 1500, dataPrecision: null, dataScale: null, nullable: 'YES' },
})
value?: string;
// Define well-known properties here
// Indexer property to allow additional data
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// [prop: string]: any;
constructor(data?: Partial<Settings>) {
super(data);
}
}
export interface SettingsRelations {
// describe navigational properties here
}
export type SettingsWithRelations = Settings & SettingsRelations;
|
92e74b87111efea995431b38928db76096d91be4
|
TypeScript
|
hugojosefson/highland-deno
|
/src/stream-redirect.ts
| 2.609375
| 3
|
import { Stream } from "./stream.ts";
/**
* Used as a Redirect marker when writing to a Stream's incoming buffer
*/
export class StreamRedirect<R> {
__HighlandStreamRedirect__ = true;
to: Stream<R>;
constructor(to: Stream<R>) {
this.to = to;
}
}
|
da701e76b65b15ca0593df9e2044818802d2a53a
|
TypeScript
|
johney-suk/WantoDo
|
/back/src/exceptions/MongoException.ts
| 2.5625
| 3
|
import { Error as MongooseError } from 'mongoose';
class MongoException extends Error {
public status: number = 0;
public type: string = 'MongoDBException';
public name: string = '';
public errorCode: number = 0;
constructor(mongoError: MongooseError, msg?: string) {
super(msg || mongoError.message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, MongoException);
}
this.switchError(mongoError.name);
}
private switchError(name: string) {
switch (name) {
default:
this.defaultException();
break;
}
}
private defaultException() {
this.status = 500;
this.name = 'MongoException';
this.errorCode = 30001;
this.message = this.message || 'MongoException';
}
}
export default MongoException;
|
3e744659ed072a51ec0b578ffaed84bb60dcc7f4
|
TypeScript
|
nghiattran/transpiler
|
/src/language/pascal/intermediate/RoutineCodeImpl.ts
| 2.671875
| 3
|
import {RoutineCode} from '../../../intermediate/RoutineCode';
export class RoutineCodeImpl implements RoutineCode {
private text : string;
public static DECLARED : RoutineCodeImpl = new RoutineCodeImpl('DECLARED');
public static FORWARD : RoutineCodeImpl = new RoutineCodeImpl('FORWARD');
public static READ : RoutineCodeImpl = new RoutineCodeImpl('READ');
public static READLN : RoutineCodeImpl = new RoutineCodeImpl('READLN');
public static WRITE : RoutineCodeImpl = new RoutineCodeImpl('WRITE');
public static WRITELN : RoutineCodeImpl = new RoutineCodeImpl('WRITELN');
public static ABS : RoutineCodeImpl = new RoutineCodeImpl('ABS');
public static ARCTAN : RoutineCodeImpl = new RoutineCodeImpl('ARCTAN');
public static CHR : RoutineCodeImpl = new RoutineCodeImpl('CHR');
public static COS : RoutineCodeImpl = new RoutineCodeImpl('COS');
public static EOF : RoutineCodeImpl = new RoutineCodeImpl('EOF');
public static EOLN : RoutineCodeImpl = new RoutineCodeImpl('EOLN');
public static EXP : RoutineCodeImpl = new RoutineCodeImpl('EXP');
public static LN : RoutineCodeImpl = new RoutineCodeImpl('LN');
public static ODD : RoutineCodeImpl = new RoutineCodeImpl('ODD');
public static ORD : RoutineCodeImpl = new RoutineCodeImpl('ORD');
public static PRED : RoutineCodeImpl = new RoutineCodeImpl('PRED');
public static ROUND : RoutineCodeImpl = new RoutineCodeImpl('ROUND');
public static SIN : RoutineCodeImpl = new RoutineCodeImpl('SIN');
public static SQR : RoutineCodeImpl = new RoutineCodeImpl('SQR');
public static SQRT : RoutineCodeImpl = new RoutineCodeImpl('SQRT');
public static SUCC : RoutineCodeImpl = new RoutineCodeImpl('SUCC');
public static TRUNC : RoutineCodeImpl = new RoutineCodeImpl('TRUNC');
/**
* Constructor.
*/
constructor(text : string) {
text = text || this.toString().toLowerCase();
}
/**
* Getter.
* @return the text of the definition code.
*/
public getText() : string {
return this.text;
}
}
|
45049c7515133f1645ed0a939d781198542e25a7
|
TypeScript
|
devhedges/parse
|
/packages/parse/src/lib/tokenizer/tokenizer.spec.ts
| 3.234375
| 3
|
import {
tokenizeSingleChar,
tokenizeMultipleChars,
skipWhiteSpace,
tokenizer,
TokenType,
} from './tokenizer';
describe('tokenizer', () => {
it('should tokenize single character tokens', () => {
const results = tokenizeSingleChar(TokenType.BRACKET, '[', '[', 0);
const [length, token] = results;
expect(results).toHaveLength(2);
expect(length).toEqual(1);
expect(token).toHaveProperty('type', TokenType.BRACKET);
expect(token).toHaveProperty('value', '[');
});
it('should tokenize single character tokens', () => {
const results = tokenizeSingleChar(TokenType.BRACKET, ']', '[', 0);
const [length, token] = results;
expect(results).toHaveLength(2);
expect(length).toEqual(0);
expect(token).toBeNull();
});
it('should tokenize multiple character tokens', () => {
const regexp = /[0-9]/;
const results = tokenizeMultipleChars('NUMBER', regexp, '123', 0);
const [length, token] = results;
expect(results).toHaveLength(2);
expect(length).toEqual(3);
expect(token).toHaveProperty('type', 'NUMBER');
expect(token).toHaveProperty('value', '123');
});
it('should tokenize multiple character tokens', () => {
const regexp = /[0-9]/;
const results = tokenizeMultipleChars('NUMBER', regexp, 'abc', 0);
const [length, token] = results;
expect(results).toHaveLength(2);
expect(length).toEqual(0);
expect(token).toBeNull();
});
it('should skip whitespace', () => {
let [length, token] = skipWhiteSpace(
`
`,
0
);
expect(length).toEqual(1);
expect(token).toBeNull();
[length, token] = skipWhiteSpace(``, 0);
expect(length).toEqual(0);
expect(token).toBeNull();
});
it('should tokenize an input string', () => {
const results = tokenizer('[add 2 3]');
expect(results).toHaveLength(5);
expect(results[0]).toHaveProperty('type', TokenType.BRACKET);
});
it('should tokenize', () => {
let results = tokenizer('[newsletter-ad]');
expect(results).toHaveLength(3);
expect(results[0]).toHaveProperty('type', TokenType.BRACKET);
expect(results[1]).toHaveProperty('type', TokenType.NAME);
expect(results[2]).toHaveProperty('type', TokenType.BRACKET);
results = tokenizer('<newsletter-ad>');
expect(results).toHaveLength(3);
expect(results[0]).toHaveProperty('type', TokenType.ARROW);
expect(results[1]).toHaveProperty('type', TokenType.NAME);
expect(results[2]).toHaveProperty('type', TokenType.ARROW);
});
it.each([
['[newsletter]', 3],
['<newsletter>', 3],
['[newsletter][/newsletter]', 6],
['<newsletter></newsletter>', 6],
['<newsletter name-for="test"></newsletter>', 9],
['[newsletter name=]', 5],
['[newsletter name="q2w13"]', 6],
["[newsletter name='q2w13']", 6],
['[newsletter name=q2w13]', 6],
['<newsletter name=>', 5],
['<newsletter name="q2w13">', 6],
["<newsletter name='q2w13'>", 6],
['<newsletter name=q2w13>', 6],
['<newsletter =>', 4],
[
`
<!-- COMMENTS -->
[newsletter name=1234]
[/newsletter]
`,
12,
],
[
`
<!-- COMMENTS -->
[newsletter name="1234"]
<h1>HERE</h1>
[/newsletter]
`,
19,
],
['?', 1],
['\u2340+_)(*&^%$%#@!~`:;"\'', 1],
['😘 😗 😙', 1],
["😘='😙'", 1],
['[blurb name="top.bottom"]', 6],
])('tokenizer( %s )', async (input, expected) => {
const result = tokenizer(input);
expect(result).toHaveLength(expected);
});
});
|
163bf66346eff5260dad542cf3abe9ca8d2d7cf9
|
TypeScript
|
ericchingalo/comment-app
|
/src/app/store/reducers/comment.reducers.ts
| 2.84375
| 3
|
import * as fromAction from '../actions/comment.actions'
import { Comment } from '../../comment-module/modules/comment.module';
export interface CurrentState{
comments: Comment[],
loading: boolean,
loaded: boolean
}
export const initialState: CurrentState = {
loaded: false,
loading: false,
comments: []
}
export function CommentReducer(
state: CurrentState = initialState,
action: {type: string; payload: any}
){
switch(action.type){
case fromAction.CREATE_COMMENT: {
const comment: Comment = {
user: 'Eric',
commentText: action.payload,
commentId: getRandString(),
showDate: true,
//lastUpdate: Date, --------->work on it
showEditForm: false,
showDeleteDialog : false
}
const comments = [...state.comments, comment];
return {...state, comments};
};
case fromAction.EDIT_COMMENT: {
const newComments = state.comments.map(comment =>{
if(comment.commentId != action.payload.commentId){
return comment;
}else{
return {...comment, commentText: action.payload.commentText};
}
});
return {...state, comments: newComments};
};
case fromAction.DELETE_COMMENT: {
const comment = state.comments.filter(comment => comment.commentId != action.payload.commentId);
return {...state, comments: comment};
};
case fromAction.DELETE_CONFIRM: {
const newComments = state.comments.map(comment =>{
if(comment.commentId !== action.payload.commentId){
return comment;
}else{
return {...comment,
showDeleteDialog: !action.payload.showDeleteDialog
}
}
});
return {...state, comments: newComments};
};
case fromAction.EDIT_COMMENT_FORM: {
const newComments = state.comments.map(comment =>{
if(comment.commentId !== action.payload.commentId){
return comment;
}else{
return {...comment,
showEditForm: !action.payload.showEditForm
}
}
});
return {...state, comments: newComments};
};
default: {
}
}
return state;
}
function getNewID() {
var myDate = new Date();
var varID = myDate.getHours() + "" + myDate.getMinutes() + "" + myDate.getSeconds() + "" + myDate.getMilliseconds();
if (varID.length > 15) {
varID = varID.substr(0, 15);
}
return varID;
}
function getRandString(){
return getNewID();
}
export const getAllComments = (state: CurrentState) => state.comments;
|
bb48206b6f50ea8c5412e2fab2d7e70605f9440b
|
TypeScript
|
marcoshuck/utn.web.dev
|
/TypeScript/2_Datos/2_2_tipos.ts
| 2.609375
| 3
|
const unNumero: number = 22;
const unaPalabra: string = "Hola, mundo!"
const unLogico: boolean = true;
const unNada: void = void;
const unaVariableSinValor: null = null;
const unVariableSinDefinir: undefined = undefined;
const unCualquiera: any = 22;
|
d76ca4a700718b4d6d87e1e080d957118a071cbe
|
TypeScript
|
Rabindra-pandey/pokemon-assi
|
/src/app/models/pokemon.ts
| 2.546875
| 3
|
export interface PokemonDetails {
name: string;
height: number;
wight: number;
abilities: string;
}
export interface PokemonAPI {
count: number;
next: string;
previous: string;
results: [];
}
|
55583953d598d6cf8823ec84b12db849e045a6a5
|
TypeScript
|
mathdeziel/vscode
|
/src/vs/base/common/resources.ts
| 2.578125
| 3
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as paths from 'vs/base/common/paths';
import URI from 'vs/base/common/uri';
import { equalsIgnoreCase } from 'vs/base/common/strings';
import { Schemas } from 'vs/base/common/network';
import { isLinux } from 'vs/base/common/platform';
import { CharCode } from 'vs/base/common/charCode';
export function getComparisonKey(resource: URI): string {
return hasToIgnoreCase(resource) ? resource.toString().toLowerCase() : resource.toString();
}
export function hasToIgnoreCase(resource: URI): boolean {
// A file scheme resource is in the same platform as code, so ignore case for non linux platforms
// Resource can be from another platform. Lowering the case as an hack. Should come from File system provider
return resource.scheme === Schemas.file ? !isLinux : true;
}
export function basenameOrAuthority(resource: URI): string {
return basename_urlpath(resource.path) || resource.authority;
}
export function isEqualOrParent(resource: URI, candidate: URI, ignoreCase?: boolean): boolean {
if (resource.scheme === candidate.scheme && resource.authority === candidate.authority) {
if (resource.scheme === 'file') {
return paths.isEqualOrParent(resource.fsPath, candidate.fsPath, ignoreCase);
}
return paths.isEqualOrParent(resource.path, candidate.path, ignoreCase, '/');
}
return false;
}
export function isEqual(first: URI, second: URI, ignoreCase?: boolean): boolean {
const identityEquals = (first === second);
if (identityEquals) {
return true;
}
if (!first || !second) {
return false;
}
if (ignoreCase) {
return equalsIgnoreCase(first.toString(), second.toString());
}
return first.toString() === second.toString();
}
export function basename(resource: URI): string {
if (resource.scheme === 'file') {
return paths.basename(resource.fsPath);
}
return basename_urlpath(resource.path);
}
export function dirname(resource: URI): URI {
if (resource.scheme === 'file') {
return URI.file(paths.dirname(resource.fsPath));
}
let dirname = dirname_urlpath(resource.path);
if (resource.authority && dirname.length && dirname.charCodeAt(0) !== CharCode.Slash) {
return null; // If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character
}
return resource.with({
path: dirname
});
}
export function joinPath(resource: URI, pathFragment: string): URI {
if (resource.scheme === 'file') {
return URI.file(paths.join(resource.path || '/', pathFragment));
}
let path = resource.path || '';
let last = path.charCodeAt(path.length - 1);
let next = pathFragment.charCodeAt(0);
if (last !== CharCode.Slash) {
if (next !== CharCode.Slash) {
path += '/';
}
} else {
if (next === CharCode.Slash) {
pathFragment = pathFragment.substr(1);
}
}
return resource.with({
path: path + pathFragment
});
}
export function distinctParents<T>(items: T[], resourceAccessor: (item: T) => URI): T[] {
const distinctParents: T[] = [];
for (let i = 0; i < items.length; i++) {
const candidateResource = resourceAccessor(items[i]);
if (items.some((otherItem, index) => {
if (index === i) {
return false;
}
return isEqualOrParent(candidateResource, resourceAccessor(otherItem));
})) {
continue;
}
distinctParents.push(items[i]);
}
return distinctParents;
}
function dirname_urlpath(path: string): string {
const idx = ~path.lastIndexOf('/');
if (idx === 0) {
return '';
} else if (~idx === 0) {
return path[0];
} else if (~idx === path.length - 1) {
return dirname_urlpath(path.substring(0, path.length - 1));
} else {
return path.substring(0, ~idx);
}
}
function basename_urlpath(path: string): string {
const idx = ~path.lastIndexOf('/');
if (idx === 0) {
return path;
} else if (~idx === path.length - 1) {
return basename_urlpath(path.substring(0, path.length - 1));
} else {
return path.substr(~idx + 1);
}
}
|
167c89611b8e2b050c0a7af2a1f972fb20550b7a
|
TypeScript
|
suyash/char-rnn
|
/web/src/index.ts
| 2.75
| 3
|
import * as tf from "@tensorflow/tfjs";
import debug from "debug";
import { decode, encode, sample, sleep } from "./utils";
debug.enable("*");
const INITIAL_TEXT: string = "Immortal longings in me: now no more";
let speed: number = 38;
let playing: boolean = false;
let text: string = INITIAL_TEXT;
let predictionContainer: HTMLElement;
let speedElement: HTMLInputElement;
let textElement: HTMLPreElement;
let button: HTMLButtonElement;
window.addEventListener("DOMContentLoaded", main);
async function main(): Promise<void> {
const log: debug.IDebugger = debug("main");
predictionContainer = document.querySelector("#predictionContainer") as HTMLElement;
speedElement = document.querySelector("#speedControlSlider") as HTMLInputElement;
textElement = document.querySelector("pre") as HTMLInputElement;
button = document.querySelector("#controls button") as HTMLButtonElement;
(speedElement as any).value = speed;
speedElement.addEventListener("change", onSpeedChange);
button.addEventListener("click", () => onButtonClick(model));
textElement.innerText = text;
let model: tf.Model;
try {
model = await tf.loadModel("indexeddb://model_shakespeare");
log("loaded from idb");
} catch (err) {
model = await tf.loadModel("model/shakespeare/v1/model.json");
const result: tf.io.SaveResult = await model.save("indexeddb://model_shakespeare");
log("saving to idb:", result);
}
model.summary();
(document.querySelector("#loadingMessage") as HTMLElement).classList.add("hidden");
(document.querySelector("#controls") as HTMLElement).classList.remove("hidden");
predictionContainer.classList.remove("hidden");
setTimeout(() => textElement.focus(), 0);
}
function onSpeedChange(e: Event): void {
const log: debug.IDebugger = debug("onSpeedChange");
speed = (e.target as any).value;
log("speed changed to", speed);
}
function onButtonClick(model: tf.Model): void {
if (playing) {
playing = false;
button.innerText = "Start";
} else {
playing = true;
button.classList.add("hidden");
predictionContainer.classList.remove("editable");
textElement.removeAttribute("contenteditable");
predict(model);
}
}
async function predict(model: tf.Model): Promise<void> {
while (playing) {
const [nc]: [string, void] = await Promise.all([
next(text, model),
sleep((41 - speed) * 6),
]);
textElement.innerText += nc;
text = text.substr(1) + nc;
}
}
async function next(c: string, model: tf.Model): Promise<string> {
const predictions: tf.Tensor<tf.Rank.R1> = tf.tidy(() => generatePredictions(c, model));
const data: Float32Array = await predictions.data() as Float32Array;
predictions.dispose();
const nextCode: number = sample(data);
return decode(nextCode);
}
function generatePredictions(c: string, model: tf.Model): tf.Tensor<tf.Rank.R1> {
const batchSize: number = (model.input as tf.SymbolicTensor).shape[0];
const sequenceLength: number = c.length;
const vocabSize: number = (model.input as tf.SymbolicTensor).shape[2];
const inp: tf.Tensor<tf.Rank.R3> = tf.tidy(() => generateInput(c, batchSize, vocabSize));
const predictions: tf.Tensor<tf.Rank> = model.predict(inp, { batchSize }) as tf.Tensor<tf.Rank>;
const lastPrediction: tf.Tensor<tf.Rank.R3> = tf.slice3d(
predictions as tf.Tensor<tf.Rank.R3>,
[0, sequenceLength - 1, 0],
[batchSize, 1, vocabSize],
);
return lastPrediction.reshape([batchSize, vocabSize]).sum(0);
}
function generateInput(c: string, batchSize: number, vocabSize: number): tf.Tensor<tf.Rank.R3> {
const code: number[] = encode(c);
const tensor: tf.Tensor<tf.Rank.R2> = tf.oneHot(code, vocabSize);
return tf.stack(Array.from({ length: batchSize }).map(() => tensor)) as tf.Tensor<tf.Rank.R3>;
}
|
1818bd0a25feba9a20cb5217d9dd3dea92628b7c
|
TypeScript
|
Exormeter/Moveit-Backend
|
/src/routes/allUsersRoute.ts
| 2.5625
| 3
|
import * as User from '../models/user'; // import User
import { BaseRoute } from './baseRoute';
export class AllUsersRoute extends BaseRoute {
public static create(router) {
console.log("Create all users route");
/**
@api {get} /allUsers Alle Benutzernamen und pushToken
@apiName GetAllUsers
@apiGroup User
@apiSuccess {String[]} response Alle Benutzernamen und pushToken
@apiSuccess {String} response.benutzernameAndPushToken Ein Benutzername und pushToken
*/
router.get('/allUsers', (req, res, next) => {
if (req.isAuthenticated()) {
new AllUsersRoute().users(req, res, next);
} else {
res.redirect('/login');
}
});
}
constructor() {
super();
}
public users(req, res, next) {
User.find({}, { _id: 0, username: 1, pushToken: 1 }, function (err, users) {
if (err) {
res.json(err);
} else {
res.json(users);
}
});
}
}
|
3ffb08b3ebfc611076eded0601a97ff7cd891b2e
|
TypeScript
|
pushrocks/lik
|
/test/test.objectmap.ts
| 2.875
| 3
|
// import test framework
import { expect, tap } from '@pushrocks/tapbundle';
import * as events from 'events';
import * as smartpromise from '@pushrocks/smartpromise';
// import the module
import * as lik from '../ts/index';
// Objectmap
interface ITestObject {
propOne: string;
propTwo: string;
}
let testObjectmap: lik.Objectmap<ITestObject>;
let testObject1: ITestObject = {
propOne: 'hello',
propTwo: 'hello2'
};
let testObject2: ITestObject = {
propOne: 'hello',
propTwo: 'hello2'
};
tap.test('new lik.Objectmap() -> should correctly instantiate an Objectmap', async () => {
testObjectmap = new lik.Objectmap<ITestObject>();
expect(testObjectmap).be.instanceof(lik.Objectmap);
});
tap.test('lik.Objectmap.add() -> should correctly add an object to Objectmap', async () => {
testObjectmap.add(testObject1);
// tslint:disable-next-line:no-unused-expression
expect(testObjectmap.checkForObject(testObject1)).be.true;
// tslint:disable-next-line:no-unused-expression
expect(testObjectmap.checkForObject(testObject2)).be.false;
});
tap.test('lik.Objectmap.remove() -> should correctly remove an object to Objectmap', async () => {
testObjectmap.add(testObject2);
testObjectmap.remove(testObject1);
// tslint:disable-next-line:no-unused-expression
expect(testObjectmap.checkForObject(testObject1)).be.false;
// tslint:disable-next-line:no-unused-expression
expect(testObjectmap.checkForObject(testObject2)).be.true;
});
tap.test('Objectmap.forEach -> should correctly run a function forEach map object', async () => {
testObjectmap.forEach(itemArg => {
expect(itemArg).to.have.property('propOne');
});
});
tap.test('lik.Objectmap.find() -> should correctly find an object', async () => {
let myObject = { propOne: 'helloThere', propTwo: 'helloAnyway' };
testObjectmap.add(myObject);
let referenceObject = testObjectmap.find(itemArg => {
return itemArg.propOne === 'helloThere';
});
// tslint:disable-next-line:no-unused-expression
expect(myObject === referenceObject).be.true;
});
tap.test('lik.Objectmap.getArray() -> should return a cloned array', async () => {
let myObject = { propOne: 'test1', propTwo: 'wow, how awesome' };
testObjectmap.add(myObject);
let clonedArray = testObjectmap.getArray();
expect(clonedArray[clonedArray.length - 1]).to.eql(myObject);
});
tap.test('should get one object and then remove it', async () => {
let originalLength = testObjectmap.getArray().length;
let oneObject = testObjectmap.getOneAndRemove();
// tslint:disable-next-line:no-unused-expression
expect(oneObject).not.be.null;
expect(testObjectmap.getArray().length).equal(originalLength - 1);
expect(testObjectmap.getArray()).to.not.contain(oneObject);
});
tap.start();
|
c2707be52f7c64685b85eb950d867824e81054c7
|
TypeScript
|
bevkwok/react-capstone
|
/server/src/controllers/productController.ts
| 2.71875
| 3
|
import { Response, Request } from 'express'
import { ProductDoc } from '../interfaces/product'
import { Product } from '../models/productModel'
const getAllProducts = async(req: Request, res: Response): Promise<void> => {
try {
const products: ProductDoc[] = await Product.find()
if (products.length === 0) {
res.status(404).send({ message: "Product List is empty"})
}
res.status(200).json({ products })
} catch (error) {
throw error
}
}
const getProduct = async (req: Request, res: Response): Promise<void> => {
try {
const id = req.params.id
let product: ProductDoc | null = await Product.findById(id)
if (!product) {
res.status(404).send({ message: "Can't find the product you are looking for"})
}
res.status(200).json({ product })
} catch (error) {
throw error
}
}
const addProduct = async(req: Request, res: Response): Promise<void> => {
try {
const body = req.body
console.log(body);
const product: ProductDoc = new Product({
name: body.name,
category: body.category,
image: body.image,
price: body.price,
countInStock: body.countInStock,
rating: body.rating,
numReviews: body.numReviews,
description: body.description
})
const newProduct: ProductDoc = await product.save()
res
.status(201)
.json({ message: "Product added", product: newProduct })
} catch (error) {
throw error
}
}
export { getAllProducts, getProduct, addProduct }
|
f9de6e0a4148ee32086308cc46699bc369333997
|
TypeScript
|
cnscorpions/data-story
|
/tests/unit/core/Feature.test.ts
| 3.125
| 3
|
import Feature from '../../../src/core/Feature'
test('a Feature can be instantiate from various types', () => {
[
'str', 123, [], {}, {foo: 'bar'},
].forEach(value => {
expect(new Feature(value)).toBeInstanceOf(Feature)
})
});
test('a Feature can hold attributes', () => {
let feature = new Feature({
foo: 'bar'
})
expect(feature.get('foo')).toBe('bar')
});
test('it can get dot notated attributes', () => {
let feature = new Feature({
user: {
name: 'ajthinking'
}
})
expect(feature.get('user.name')).toBe('ajthinking')
})
|
38aa9bdc48f6745be153253facf084dfad1e82a9
|
TypeScript
|
thrashplay/devops-tools
|
/packages/modular-cli/src/cli-builder.ts
| 2.6875
| 3
|
import { Arguments, Argv, CommandBuilder, CommandModule } from 'yargs'
import yargs from 'yargs'
import { each, identity, isNil, map, merge, reduce } from 'lodash'
import { createCli } from '@thrashplay/logging'
import { ConfigurationOptions, CommandSet, Task, Result } from '.'
const log = createCli()
const getConfigurationOptions = (task: Task) => {
return isNil(task.getConfigurationOptions) ? {} : task.getConfigurationOptions()
}
export const createBuilder = (tasks: Task[]): CommandBuilder => {
const reducerFunction = (options: ConfigurationOptions, task: Task) => merge(options, getConfigurationOptions(task))
return reduce(tasks, reducerFunction, {} as ConfigurationOptions)
}
export const createHandler = (tasks: Task[]) => async (args: Arguments) => {
return reduce(tasks, (previousChain, currentTask) => {
return previousChain
.then((context: object) => {
log.debug('Executing task: ', currentTask.constructor.name)
log.debug('Context: ', JSON.stringify(context))
return Promise.all([
Promise.resolve(context),
currentTask.execute(args, context) as Promise<Result<object>>,
])
})
.then(([originalContext, result]) => {
if (result.result === 'error') {
throw new Error('Failed executing task!')
}
return merge(originalContext, result.context)
})
}, Promise.resolve({}))
.catch((error) => {
if (error.message) {
log.error('')
log.error(error.message)
log.error('')
} else {
log.error('Error executing command: ', error)
}
if (!isNil(error.stack)) {
const stack = error.stack
log.debug(stack)
}
process.exit(-1)
})
}
export interface YargsOptions {
configureCallback?: (yargs: Argv) => Argv
scriptName?: string
usage?: string
wrap?: number
}
export const configure = (commands: CommandModule[], {
configureCallback = identity,
scriptName = process.argv[1],
usage = '$0 <command> [options]',
wrap = Math.min(150, yargs.terminalWidth()),
}: YargsOptions) => {
each(commands, (command) => yargs.command(command))
return configureCallback(
yargs
.scriptName(scriptName)
.usage(usage)
.wrap(wrap)
.demandCommand()
.help()
.fail((message: string, error: Error) => {
yargs.showHelp()
console.log('')
log.error(message)
console.log('')
if (error) {
throw error
}
}),
)
}
export const execute = (commands: CommandSet, options: YargsOptions) => {
const commandModules = map(commands, (configuration, command) => ({
builder: createBuilder(configuration.tasks),
command,
desc: configuration.description,
handler: createHandler(configuration.tasks),
}))
try {
configure(commandModules, options).parse()
} catch (e) {
log.error('Failed to execute command:', e)
}
}
|
624e4bce66ac6d5737bbf64a4207907b387b8ad6
|
TypeScript
|
adroaldofilho/api-thedica
|
/src/modules/profissao/profissao.model.ts
| 2.734375
| 3
|
// import { IPost } from "../Post/interface";
export interface IProfissao {
readonly id: number,
nome: string,
conselho: string
// Posts?: IPost[];
}
export function createProfissao({id, nome, conselho}: any): IProfissao {
return {
id, nome, conselho
// , Posts
}
}
export function createProfissoes(data: any[]): IProfissao[] {
return data.map(createProfissao);
}
|
5fc0710b10294b43f11686ce6dea307218c8c7ef
|
TypeScript
|
GeekChanaa/SchoolV2
|
/SchoolSpa/src/app/_services/room.service.ts
| 2.625
| 3
|
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators'
import { Room } from '../_models/room';
import { PaginatedResult } from '../_models/pagination';
@Injectable({
providedIn: 'root'
})
export class RoomService {
// Base URL for the api
baseUrl = "https://localhost:5001/api/room/";
// Constructor
constructor(private http: HttpClient) { }
httpOptions = {
headers : new HttpHeaders({'Content-Type':'application/json; charset=utf-8'})
};
// Getting all Rooms
getRooms(page?, itemsPerPage?, roomParams?): Observable<PaginatedResult<Room[]>>{
const paginatedResult : PaginatedResult<Room[]> = new PaginatedResult<Room[]>();
let params = new HttpParams();
if(page != null && itemsPerPage != null){
params = params.append('pageNumber',page);
params = params.append('pageSize', itemsPerPage);
}
// Other filter and sort params
if(roomParams != null)
{
if(roomParams.orderBy != null)
params = params.append("orderBy", roomParams.orderBy);
if(roomParams.searchBy != null)
params = params.append("searchBy", roomParams.searchBy);
if(roomParams.searchValue != null)
params = params.append("searchValue", roomParams.searchValue);
if(roomParams.reverseOrder != null)
params = params.append("reverseOrder", roomParams.reverseOrder);
}
return this.http.get<Room[]>(this.baseUrl, {observe : 'response', params})
.pipe(
map(response => {
paginatedResult.result = response.body;
if(response.headers.get('Pagination') != null){
paginatedResult.pagination = JSON.parse(response.headers.get('Pagination'))
}
return paginatedResult;
})
)
}
// Getting Room By ID
getRoom(id: number): Observable<Room>{
return this.http.get<Room>(this.baseUrl+id);
}
// Delete Room by ID
deleteRoomById(id:number): Observable<Room>{
return this.http.delete<Room>(this.baseUrl+id, this.httpOptions);
}
// Create Room
createRoom(model: any): Observable<Room>{
return this.http.post<Room>(this.baseUrl,model,this.httpOptions);
}
// Edit Room
editRoom(id:number , model:any): Observable<Room>{
return this.http.put<Room>(this.baseUrl+id, model, this.httpOptions);
}
// counting Rooms
count(){
return this.http.get(this.baseUrl+"count", this.httpOptions);
}
}
|
004e4e86907b2b78c083143a7b6c44f6f10d9e39
|
TypeScript
|
future4code/Patricia-Matiesque
|
/semana15/aula2/Restaurant/src/dessert.ts
| 3.390625
| 3
|
import { Dish } from "./dish";
export class Dessert extends Dish {
public slicesNumber: number;
constructor(
price: number,
cost: number,
ingredients: string[],
timeToCook: number,
slicesNumber: number
) {
super(price, cost, ingredients, timeToCook);
this.slicesNumber = slicesNumber;
}
public getSlicePrice(): number {
return this.price / this.slicesNumber;
}
}
export const brigadeiro = new Dessert(10, 5, ["leite condensado", "Chocolate"], 30, 5);
console.log(brigadeiro.getSlicePrice());
console.log(brigadeiro.getProfit());
export const beijinho = new Dessert(8, 4, ["leite condensado", "Coco"], 30, 5);
console.log(beijinho.getSlicePrice());
console.log(beijinho.getProfit());
|
ce359d71ee9bd887f70be71029c93e73a49cbe2e
|
TypeScript
|
hangcs/doppelgunner-blog
|
/src/app/models/post.ts
| 2.921875
| 3
|
export class Post {
constructor(public title: string, public content: string, public createdAt: any, public lastUpdate: any) {}
clone(): Post {
let newPost = new Post(this.title,this.content, this.createdAt, this.lastUpdate);
return newPost;
}
}
|
30a72a37d962d33ebb3c811126962e4457b4b34b
|
TypeScript
|
CalionVarduk/ts-utils
|
/tests/logging/logger.spec.ts
| 3
| 3
|
import { Logger, createConsoleLogger } from '../../src/logging/logger';
import { LogType } from '../../src/logging/log-type.enum';
import { LogMessage } from '../../src/logging/log-message';
import { Nullable } from '../../src/types/nullable';
import { ILogger, LoggerDelegate } from '../../src/logging/logger.interface';
import each from 'jest-each';
each([
[LogType[LogType.Debug]],
[LogType[LogType.Information]],
[LogType[LogType.Warning]],
[LogType[LogType.Error]]
])
.test('createConsoleLogger should create a proper delegate',
(typeName: keyof typeof LogType) =>
{
let debugCalled = false;
let infoCalled = false;
let warnCalled = false;
let errorCalled = false;
const oldDebug = console.debug;
const oldInfo = console.info;
const oldWarn = console.warn;
const oldError = console.error;
console.debug = function() { debugCalled = true; };
console.info = function() { infoCalled = true; };
console.warn = function() { warnCalled = true; };
console.error = function() { errorCalled = true; };
const message = 'foo';
const type = LogType[typeName];
const logger = new Logger();
const delegate = createConsoleLogger();
logger.listen(delegate);
logger.logMessage(message, type);
const actual = (function()
{
switch (type)
{
case LogType.Debug: return debugCalled;
case LogType.Information: return infoCalled;
case LogType.Warning: return warnCalled;
case LogType.Error: return errorCalled;
}
})()!;
console.debug = oldDebug;
console.info = oldInfo;
console.warn = oldWarn;
console.error = oldError;
expect(actual).toBe(true);
}
);
test('ctor should create properly',
() =>
{
const result = new Logger();
expect(result.isDisposed).toBe(false);
expect(result.listeners.length).toBe(0);
expect(result.logLevel).toBe(LogType.Debug);
expect(result.timestamp).toBeGreaterThanOrEqual(0);
}
);
test('dispose should remove all listeners',
() =>
{
const logger = new Logger();
const listener = logger.listen(() => {});
logger.dispose();
expect(logger.listeners.length).toBe(0);
expect(logger.isDisposed).toBe(true);
expect(listener.isDisposed).toBe(true);
}
);
test('dispose invoked more than once should not throw',
() =>
{
const logger = new Logger();
logger.dispose();
const action = () => logger.dispose();
expect(action).not.toThrow();
expect(logger.listeners.length).toBe(0);
expect(logger.isDisposed).toBe(true);
}
);
each([
[LogType.Debug, LogType.Debug, true],
[LogType.Debug, LogType.Information, false],
[LogType.Debug, LogType.Warning, false],
[LogType.Debug, LogType.Error, false],
[LogType.Information, LogType.Debug, true],
[LogType.Information, LogType.Information, true],
[LogType.Information, LogType.Warning, false],
[LogType.Information, LogType.Error, false],
[LogType.Warning, LogType.Debug, true],
[LogType.Warning, LogType.Information, true],
[LogType.Warning, LogType.Warning, true],
[LogType.Warning, LogType.Error, false],
[LogType.Error, LogType.Debug, true],
[LogType.Error, LogType.Information, true],
[LogType.Error, LogType.Warning, true],
[LogType.Error, LogType.Error, true],
[LogType.Error, LogType.Error + 1, false]
])
.test('log should publish message, if logger level allows it (%#): type: %f, level: %f, should publish: %s',
(type: LogType, level: LogType, shouldPublish: boolean) =>
{
const logger = new Logger();
logger.logLevel = level;
const message = new LogMessage('foo', type);
let interceptedMessage: Nullable<LogMessage> = null;
let interceptedTimestamp: Nullable<number> = null;
let interceptedLogger: Nullable<ILogger> = null;
logger.listen((m, t, l) =>
{
interceptedMessage = m;
interceptedTimestamp = t;
interceptedLogger = l;
});
const minTimestamp = logger.timestamp;
logger.log(message);
const maxTimestamp = logger.timestamp;
if (shouldPublish)
{
expect(interceptedMessage).toBe(message);
expect(interceptedTimestamp).toBeGreaterThanOrEqual(minTimestamp);
expect(interceptedTimestamp).toBeLessThanOrEqual(maxTimestamp);
expect(interceptedLogger).toBe(logger);
}
else
{
expect(interceptedMessage).toBeNull();
expect(interceptedTimestamp).toBeNull();
expect(interceptedLogger).toBeNull();
}
}
);
each([
[LogType.Debug, LogType.Debug, true],
[LogType.Debug, LogType.Information, false],
[LogType.Debug, LogType.Warning, false],
[LogType.Debug, LogType.Error, false],
[LogType.Information, LogType.Debug, true],
[LogType.Information, LogType.Information, true],
[LogType.Information, LogType.Warning, false],
[LogType.Information, LogType.Error, false],
[LogType.Warning, LogType.Debug, true],
[LogType.Warning, LogType.Information, true],
[LogType.Warning, LogType.Warning, true],
[LogType.Warning, LogType.Error, false],
[LogType.Error, LogType.Debug, true],
[LogType.Error, LogType.Information, true],
[LogType.Error, LogType.Warning, true],
[LogType.Error, LogType.Error, true],
[LogType.Error, LogType.Error + 1, false]
])
.test('logMessage should publish message, if logger level allows it (%#): type: %f, level: %f, should publish: %s',
(type: LogType, level: LogType, shouldPublish: boolean) =>
{
const message = 'foo';
const logger = new Logger();
logger.logLevel = level;
let interceptedMessage: Nullable<LogMessage> = null;
let interceptedTimestamp: Nullable<number> = null;
let interceptedLogger: Nullable<ILogger> = null;
logger.listen((m, t, l) =>
{
interceptedMessage = m;
interceptedTimestamp = t;
interceptedLogger = l;
});
const minTimestamp = logger.timestamp;
logger.logMessage(message, type);
const maxTimestamp = logger.timestamp;
if (shouldPublish)
{
expect(interceptedMessage!.message).toBe(message);
expect(interceptedMessage!.type).toBe(type);
expect(interceptedTimestamp).toBeGreaterThanOrEqual(minTimestamp);
expect(interceptedTimestamp).toBeLessThanOrEqual(maxTimestamp);
expect(interceptedLogger).toBe(logger);
}
else
{
expect(interceptedMessage).toBeNull();
expect(interceptedTimestamp).toBeNull();
expect(interceptedLogger).toBeNull();
}
}
);
each([
[LogType.Debug, true],
[LogType.Information, false],
[LogType.Warning, false],
[LogType.Error, false]
])
.test('logDebug should publish message, if logger level allows it (%#): type: %f, level: %f, should publish: %s',
(level: LogType, shouldPublish: boolean) =>
{
const message = 'foo';
const logger = new Logger();
logger.logLevel = level;
let interceptedMessage: Nullable<LogMessage> = null;
let interceptedTimestamp: Nullable<number> = null;
let interceptedLogger: Nullable<ILogger> = null;
logger.listen((m, t, l) =>
{
interceptedMessage = m;
interceptedTimestamp = t;
interceptedLogger = l;
});
const minTimestamp = logger.timestamp;
logger.logDebug(message);
const maxTimestamp = logger.timestamp;
if (shouldPublish)
{
expect(interceptedMessage!.message).toBe(message);
expect(interceptedMessage!.type).toBe(LogType.Debug);
expect(interceptedTimestamp).toBeGreaterThanOrEqual(minTimestamp);
expect(interceptedTimestamp).toBeLessThanOrEqual(maxTimestamp);
expect(interceptedLogger).toBe(logger);
}
else
{
expect(interceptedMessage).toBeNull();
expect(interceptedTimestamp).toBeNull();
expect(interceptedLogger).toBeNull();
}
}
);
each([
[LogType.Debug, true],
[LogType.Information, true],
[LogType.Warning, false],
[LogType.Error, false]
])
.test('logInformation should publish message, if logger level allows it (%#): type: %f, level: %f, should publish: %s',
(level: LogType, shouldPublish: boolean) =>
{
const message = 'foo';
const logger = new Logger();
logger.logLevel = level;
let interceptedMessage: Nullable<LogMessage> = null;
let interceptedTimestamp: Nullable<number> = null;
let interceptedLogger: Nullable<ILogger> = null;
logger.listen((m, t, l) =>
{
interceptedMessage = m;
interceptedTimestamp = t;
interceptedLogger = l;
});
const minTimestamp = logger.timestamp;
logger.logInformation(message);
const maxTimestamp = logger.timestamp;
if (shouldPublish)
{
expect(interceptedMessage!.message).toBe(message);
expect(interceptedMessage!.type).toBe(LogType.Information);
expect(interceptedTimestamp).toBeGreaterThanOrEqual(minTimestamp);
expect(interceptedTimestamp).toBeLessThanOrEqual(maxTimestamp);
expect(interceptedLogger).toBe(logger);
}
else
{
expect(interceptedMessage).toBeNull();
expect(interceptedTimestamp).toBeNull();
expect(interceptedLogger).toBeNull();
}
}
);
each([
[LogType.Debug, true],
[LogType.Information, true],
[LogType.Warning, true],
[LogType.Error, false]
])
.test('logWarning should publish message, if logger level allows it (%#): type: %f, level: %f, should publish: %s',
(level: LogType, shouldPublish: boolean) =>
{
const message = 'foo';
const logger = new Logger();
logger.logLevel = level;
let interceptedMessage: Nullable<LogMessage> = null;
let interceptedTimestamp: Nullable<number> = null;
let interceptedLogger: Nullable<ILogger> = null;
logger.listen((m, t, l) =>
{
interceptedMessage = m;
interceptedTimestamp = t;
interceptedLogger = l;
});
const minTimestamp = logger.timestamp;
logger.logWarning(message);
const maxTimestamp = logger.timestamp;
if (shouldPublish)
{
expect(interceptedMessage!.message).toBe(message);
expect(interceptedMessage!.type).toBe(LogType.Warning);
expect(interceptedTimestamp).toBeGreaterThanOrEqual(minTimestamp);
expect(interceptedTimestamp).toBeLessThanOrEqual(maxTimestamp);
expect(interceptedLogger).toBe(logger);
}
else
{
expect(interceptedMessage).toBeNull();
expect(interceptedTimestamp).toBeNull();
expect(interceptedLogger).toBeNull();
}
}
);
each([
[LogType.Debug, true],
[LogType.Information, true],
[LogType.Warning, true],
[LogType.Error, true],
[LogType.Error + 1, false]
])
.test('logError should publish message, if logger level allows it (%#): type: %f, level: %f, should publish: %s',
(level: LogType, shouldPublish: boolean) =>
{
const message = 'foo';
const logger = new Logger();
logger.logLevel = level;
let interceptedMessage: Nullable<LogMessage> = null;
let interceptedTimestamp: Nullable<number> = null;
let interceptedLogger: Nullable<ILogger> = null;
logger.listen((m, t, l) =>
{
interceptedMessage = m;
interceptedTimestamp = t;
interceptedLogger = l;
});
const minTimestamp = logger.timestamp;
logger.logError(message);
const maxTimestamp = logger.timestamp;
if (shouldPublish)
{
expect(interceptedMessage!.message).toBe(message);
expect(interceptedMessage!.type).toBe(LogType.Error);
expect(interceptedTimestamp).toBeGreaterThanOrEqual(minTimestamp);
expect(interceptedTimestamp).toBeLessThanOrEqual(maxTimestamp);
expect(interceptedLogger).toBe(logger);
}
else
{
expect(interceptedMessage).toBeNull();
expect(interceptedTimestamp).toBeNull();
expect(interceptedLogger).toBeNull();
}
}
);
test('listen should register a new listener',
() =>
{
const delegate: LoggerDelegate = () => {};
const logger = new Logger();
const result = logger.listen(delegate);
expect(result.isDisposed).toBe(false);
expect(result.delegate).toBe(delegate);
expect(logger.listeners.length).toBe(1);
expect(logger.listeners).toContain(result);
}
);
test('listen should throw when invoked on disposed logger',
() =>
{
const logger = new Logger();
logger.dispose();
const action = () => logger.listen(() => {});
expect(action).toThrow();
}
);
test('listen invoked inside listener delegate should throw',
() =>
{
const logger = new Logger();
const firstListener = logger.listen(() => {});
logger.listen(() =>
{
firstListener.dispose();
logger.listen(() => {});
});
const action = () => logger.logInformation('foo');
expect(action).toThrow();
}
);
test('ILoggerListener.dispose should remove listener properly',
() =>
{
const logger = new Logger();
const result = logger.listen(() => {});
result.dispose();
expect(result.isDisposed).toBe(true);
expect(logger.listeners.length).toBe(0);
}
);
test('ILoggerListener.dispose invoked more than once should not throw',
() =>
{
const logger = new Logger();
const result = logger.listen(() => {});
result.dispose();
const action = () => result.dispose();
expect(action).not.toThrow();
expect(result.isDisposed).toBe(true);
expect(logger.listeners.length).toBe(0);
}
);
|
19f3891b552797f59668d9788f4b98fc3935c3c6
|
TypeScript
|
ICT37108G1-LB-spring-2019/lab4-anianichka
|
/src/app/student.service.ts
| 2.546875
| 3
|
import { Injectable } from '@angular/core';
import { IStudent } from './StudentInterface'
@Injectable({
providedIn: 'root'
})
export class StudentService {
constructor() { }
student: IStudent[] = [
{
name: 'Zura',
lastName: 'MgalobliShvili',
id: 350505050
},
{
name: 'Lasha',
lastName: 'ZurasBichi',
id: 4949494949
}];
getStudentList(): IStudent[] {
return this.student;
}
addStudent(students: IStudent){
this.student.push(students);
console.log(this.student);
}
deleteStudnet(studen) {
for(let i = 0; i<this.student.length;i++){
if(studen === this.student[i].id){
this.student.splice(i, 1);
}
}
}
updateStudent(student: IStudent) {
}
}
|
510b9692253da69aef9075eff11c12c60406e3ad
|
TypeScript
|
MatheusBVieira/evento-dot-com-frontend
|
/utils/toCurrency.ts
| 2.75
| 3
|
export const toCurrency = (number: number) =>
number?.toLocaleString('pt-BR', {
style: 'currency',
currency: 'BRL',
minimumFractionDigits: 2,
});
export const currencyToFloat = (number: string) => {
let value = Number(String(number).replace(/\D/g, ''));
return parseFloat((value / 100).toFixed(2));
};
|
c2e1d91c7c20d0bd434d36e98fcc6bb8c6a31a41
|
TypeScript
|
jcmagsay/data-structures
|
/problems/knapsack.ts
| 3.28125
| 3
|
function max(a, b) {
return Math.max(a, b);
}
function knapsack(iterator, capacity, weights, scores) {
const nextIteration = iterator - 1;
const currentWeight = weights[nextIteration];
const currentScore = scores[nextIteration];
console.log({
iter: iterator,
cap: capacity,
currentScore,
currentWeight,
slice: nextIteration
})
let path1 = 0;
let path2 = 0;
if (
!scores.length
|| !weights.length
|| iterator === 0
|| capacity === 0
|| nextIteration <= 0
) {
return 0;
} else if (
weights.length === 1
&& weights[0] > capacity
) {
return 0;
} else if (
currentWeight <= capacity
) {
const reducedCapacity = capacity - currentWeight;
const includeCurrentScore = knapsack(nextIteration, reducedCapacity, weights, scores);
const excludeCurrentScore = currentScore + knapsack(nextIteration, capacity, weights, scores)
path1 = max(includeCurrentScore, excludeCurrentScore);
} else {
path2 = knapsack(nextIteration, capacity, weights, scores);
}
return max(path1, path2);
}
function packBagpackDp(scores, weights, capacity) {
return knapsack(scores.length, capacity, weights, scores);
}
const _data = {
scores: [15, 10, 9, 5],
weights: [1, 5, 3, 4],
capacity: 8,
};
const _data1 = {
scores: [20, 5, 10, 40, 15, 25],
weights: [1, 2, 3, 8, 7, 4],
capacity: 10,
};
const _data2 = {
scores: [19, 8, 6, 20, 3, 16],
weights: [8, 2, 3, 10, 1, 5],
capacity: 17,
};
console.log({
// test: packBagpack(data.scores, data.weights, data.capacity),
// test1: packBagpack(data1.scores, data1.weights, data1.capacity),
test2: packBagpackDp(_data2.scores, _data2.weights, _data2.capacity),
});
|
5c1cf10d2a069da8d8eb0578fade7fd8c28b8f19
|
TypeScript
|
prafulrana/blender-node
|
/src/blender/bpy/types/MeshLoopColorLayer.ts
| 2.625
| 3
|
import * as util from 'util'
import { BlenderCollection, Indexable } from '../../collection'
import { BlenderInterop } from '../../../worker/interop'
import { PythonInterop } from '../../../python/interop'
import { MeshLoopColor } from './MeshLoopColor'
/**
* MeshLoopColorLayer
*
* https://docs.blender.org/api/current/bpy.types.MeshLoopColorLayer.html
*/
export class MeshLoopColorLayer {
constructor(public interop: BlenderInterop, public accessor: string) { }
/**
*
* @desc bpy_prop_collection of MeshLoopColor, (readonly)
*/
public get data(): BlenderCollection<MeshLoopColor> & Indexable<MeshLoopColor> {
return BlenderCollection.createGeneric(this.interop, `${this.accessor}.data`, MeshLoopColor)
}
/**
* Sets the layer as active for display and editing
* @desc boolean, default False
*/
public get active(): boolean {
return PythonInterop.getBoolean(this.interop, `${this.accessor}.active`)
}
/**
* Sets the layer as active for rendering
* @desc boolean, default False
*/
public get active_render(): boolean {
return PythonInterop.getBoolean(this.interop, `${this.accessor}.active_render`)
}
/**
* Name of Vertex color layer
* @desc string, default '', (never None)
*/
public get name(): string {
return PythonInterop.getString(this.interop, `${this.accessor}.name`)
}
/**
* Sets the layer as active for display and editing
* @desc boolean, default False
*/
public set active(value: boolean) {
PythonInterop.setBoolean(this.interop, `${this.accessor}.active`, value)
}
/**
* Sets the layer as active for rendering
* @desc boolean, default False
*/
public set active_render(value: boolean) {
PythonInterop.setBoolean(this.interop, `${this.accessor}.active_render`, value)
}
/**
* Name of Vertex color layer
* @desc string, default '', (never None)
*/
public set name(value: string) {
PythonInterop.setString(this.interop, `${this.accessor}.name`, value)
}
[util.inspect.custom]() {
return this.accessor
}
}
|
7c49afa8322151b19dbc2237feaa0b485f36b6ef
|
TypeScript
|
mrsaleh/usdz-ts
|
/src/Utils/PixarIntegerEncoderBits.test.ts
| 2.796875
| 3
|
import {IntegerEncoder} from 'Utils/PixarIntegerEncoder'
import { Utils } from 'Utils/Utils';
const input = [123, 1, 1, 100000, 0, 1, 0];
const mostCommonOccurance = 1;
const output = IntegerEncoder.CalculateBits(input,mostCommonOccurance);
//01 00 00 11 01 00 01 XX
const expectedOuput = [0,1 ,0,0 ,0,0 ,1,1 ,0,1, 0,0, 0,1];
const isEqual = Utils.IsEqual(output,expectedOuput);
test('Encoder bits', () => {
expect(isEqual).toBe(true);
});
|
adcc4c4edbef9b47d6d4c3cbf34b254983fa5c5e
|
TypeScript
|
wbjqiqi/design-patterns-ts
|
/design-pattern/16-command/receiver-models/rabbit-receiver.ts
| 3
| 3
|
/* rabbit-receiver.ts */
// 兔子
import { ILeftReceiver, IRightReceiver } from './receiver-interface';
import { ITarget } from './target-interface';
export class RabbitReceiver implements IRightReceiver, ILeftReceiver {
public rabbit: ITarget;
private rightLogs: number[] = [];
private leftLogs: number[] = [];
constructor (rabbit: ITarget) {
this.rabbit = rabbit;
}
private getPosition () {
console.log(`Now rabbit is at ${this.rabbit.position}`);
}
public moveRight (step: number) {
const moveStep = parseInt(Math.random() * 60) * step;
this.rabbit.position += moveStep;
this.rightLogs.unshift(moveStep);
console.log(`Rabbit move right ${moveStep}`);
this.getPosition();
}
public rightUndo () {
this.rabbit.position -= Number(this.rightLogs[0]);
this.rightLogs.shift();
this.getPosition();
}
public moveLeft (step: number) {
const moveStep = parseInt(Math.random() * 60) * step;
this.rabbit.position -= moveStep;
this.leftLogs.unshift(moveStep);
console.log(`Rabbit move left ${moveStep}`);
this.getPosition();
}
public leftUndo () {
this.rabbit.position += Number(this.leftLogs[0]);
this.leftLogs.shift();
this.getPosition();
}
}
|
9e1f13252022625f56501884425339f8b181fc55
|
TypeScript
|
studiometa/js-toolkit
|
/packages/js-toolkit/services/raf.ts
| 2.53125
| 3
|
/* eslint-disable no-use-before-define, @typescript-eslint/no-use-before-define */
import { useService } from './service.js';
import { getRaf as getRequestAnimationFrame } from '../utils/nextFrame.js';
import { useScheduler } from '../utils/scheduler.js';
import { isFunction } from '../utils/is.js';
import type { ServiceInterface } from './index.js';
const scheduler = useScheduler(['update', 'render']);
export type RafService = ServiceInterface<RafServiceProps>;
export interface RafServiceProps {
time: DOMHighResTimeStamp;
}
/**
* Create raf service.
*/
function createRafService(): RafService {
let isTicking = false;
const RAF = getRequestAnimationFrame();
/**
* Trigger callbacks.
*/
function trigger(props: RafServiceProps) {
callbacks.forEach((callback) => {
scheduler.update(() => {
const render = callback(props) as (() => unknown) | void;
if (isFunction(render)) {
scheduler.render(() => {
// @ts-ignore
render(props);
});
}
});
});
}
/**
* Loop.
*/
function loop() {
// eslint-disable-next-line no-use-before-define
props.time = performance.now();
trigger(props);
if (!isTicking) {
return;
}
RAF(loop);
}
const { add, remove, has, props, callbacks } = useService({
props: {
time: performance.now(),
} as RafServiceProps,
init() {
isTicking = true;
RAF(loop);
},
kill() {
isTicking = false;
},
});
return {
add,
remove,
has,
props: () => props,
};
}
let raf;
/**
* Use the RequestAnimationFrame (raf) service.
*/
export default function useRaf(): RafService {
if (!raf) {
raf = createRafService();
}
return raf;
}
|
c4b273c0c6008d54f0c7edc80f8989fc2ca6b465
|
TypeScript
|
JohnApache/hasaki-cli
|
/src/command/template/action.ts
| 2.53125
| 3
|
import { Command } from 'commander';
import {
GetTemplates,
UpdateTemplates,
ResetTemplates,
} from '../../config/template';
import { Exit } from '../../common';
import { ErrorLog, SuccessLog } from '../../common/log';
import { CheckTemplate } from '../../common/template';
import {
AddTemplatePrompt,
DeleteTemplatePrompt,
ClearTemplatePrompt,
UpdateTemplatePrompt,
ResetTemplatePrompt,
} from './prompt';
const ListAction = async (): Promise<void> => {
const templates = await GetTemplates();
console.table(templates);
};
const AddAction = async (): Promise<void> => {
const answer = await AddTemplatePrompt();
const templates = GetTemplates();
templates.unshift({
templateName : answer.templateName,
remoteAddress: answer.remoteAddress,
});
UpdateTemplates(templates);
SuccessLog('add template success!');
};
const UpdateAction = async (): Promise<void> => {
if (!CheckTemplate()) {
ErrorLog('current template list is empty.');
return Exit();
}
const answer = await UpdateTemplatePrompt();
const templates = GetTemplates();
const newTemplates = templates.map(v => {
if (v.templateName === answer.updateItem.templateName) {
return {
templateName : answer.templateName,
remoteAddress: answer.remoteAddress,
};
}
return v;
});
UpdateTemplates(newTemplates);
SuccessLog('update template success!');
};
const DeleteAction = async (): Promise<void> => {
if (!CheckTemplate()) {
ErrorLog('current template list is empty.');
return Exit();
}
const templates = GetTemplates();
const answer = await DeleteTemplatePrompt();
if (answer.confirmDelete) {
const newTemplates = templates.filter(t =>
answer.deleteItems.every(v => v.templateName !== t.templateName));
UpdateTemplates(newTemplates);
SuccessLog('delete templates success!');
return;
}
console.log('cancel delete operation.');
};
const ClearAction = async (): Promise<void> => {
const answer = await ClearTemplatePrompt();
if (answer.confirmClear) {
UpdateTemplates([]);
SuccessLog('clear templates list success!');
return;
}
console.log('cancel clear operation.');
};
const ResetAction = async (): Promise<void> => {
const answer = await ResetTemplatePrompt();
if (answer.confirmReset) {
ResetTemplates();
SuccessLog('reset template success!');
return;
}
console.log('cancel reset operation.');
};
const TemplateAction = (command: Command): Promise<void> => {
const options = command.opts();
const usedOptions = Object.keys(options).filter(v => options[v]);
if (usedOptions.length > 1) {
ErrorLog('template command only allow one option!');
return Exit();
}
if (options.list) {
return ListAction();
}
if (options.add) {
return AddAction();
}
if (options.delete) {
return DeleteAction();
}
if (options.update) {
return UpdateAction();
}
if (options.clear) {
return ClearAction();
}
if (options.reset) {
return ResetAction();
}
return command.help();
};
export default TemplateAction;
|
36b569ea7cac3dae9d8ab310ac2e4b9861828c02
|
TypeScript
|
Megatone/Angular5-Ethereum-Wallet-Platform
|
/Ethereum-Wallet-Platform-Frontend/src/app/models/alert.model.ts
| 2.640625
| 3
|
import { Router } from '@angular/router';
export class Alert {
public message: String;
public type: String;
public status: boolean;
public redirect: boolean;
public url: String;
constructor(alert: any = {}) {
this.load(alert);
}
public load(alert: any = {}) {
const _this = <Alert>alert;
this.message = _this.message ? _this.message : '';
this.type = _this.type ? _this.type : '';
this.status = _this.status ? _this.status : false;
this.redirect = _this.redirect ? _this.redirect : false;
this.url = _this.url ? _this.url : '';
}
public error(message: String, redirect: Boolean = false, url: String = ''): Alert {
this.load({ type: 'error', message, status: true, redirect, url });
this.saveLocal();
return this;
}
public success(message: String, redirect: Boolean = false, url: String = ''): Alert {
this.load({ type: 'success', message, status: true, redirect, url });
this.saveLocal();
return this;
}
public info(message: String, redirect: Boolean = false, url: String = ''): Alert {
this.load({ type: 'info', message, status: true, redirect, url });
this.saveLocal();
return this;
}
public warning(message: String, redirect: Boolean = false, url: String = ''): Alert {
this.load({ type: 'warning', message, status: true, redirect, url });
this.saveLocal();
return this;
}
public show(): Alert {
this.status = true;
return this;
}
public hide(): Alert {
this.status = false;
return this;
}
public suscribeChanges(router: Router): void {
$(window).bind('emitAlert', () => {
this.loadLocal();
if (this.redirect === true) {
setTimeout(() => { router.navigate([this.url]); }, 1500);
}
});
}
public saveLocal(): void {
localStorage.setItem('alert', JSON.stringify(this));
$(window).trigger($.Event('emitAlert'));
}
public loadLocal(): Alert {
const alert = JSON.parse(localStorage.getItem('alert'));
this.load((alert !== null) ? alert : {});
return this;
}
}
|
7311f332e6a30bde4c0a8e3d2b56b751238714f6
|
TypeScript
|
AndreiDC/test-jest
|
/integer/23.ts
| 3.296875
| 3
|
/* From the beginning of the day N seconds have passed (N is integer).
Find an amount of full minutes passed from the beginning of the last hour.*/
export function lastHaurs(n) {
let lh, int, aju: number;
aju = Math.floor(n / 3600);
int = aju * 3600;
lh = n - int;
return Math.floor(lh / 60);
}
|
613e1a30b0dbce387332528a2eb29429646ca491
|
TypeScript
|
swimos/swim
|
/swim-js/swim-runtime/swim-core/swim-util/src/main/assert/Assert.ts
| 2.984375
| 3
|
// Copyright 2015-2023 Swim.inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Values} from "../values/Values";
import {AssertException} from "./AssertException";
/**
* Callable [[Assert]] interface.
*
* @public
*/
export interface AssertFunction extends Assert {
/**
* Asserts that `condition` is truthy.
*
* @throws [[AssertException]] with `message` if `condition` is falsy.
*/
(condition: unknown, message?: string): void;
}
/**
* Type that implements common assertion functions.
* @public
*/
export interface Assert {
/**
* Asserts that `condition` is truthy.
*
* @throws [[AssertException]] with `message` if `condition` is falsy.
*/
ok(condition: unknown, message?: string): void;
/**
* Asserts that `condition` is falsy.
*
* @throws [[AssertException]] with `message` if `condition` is truthy.
*/
notOk(condition: unknown, message?: string): void;
/**
* Asserts that `lhs` is identical (`===`) to `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is not identical (`!==`) to `rhs`.
*/
identical(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is not identical (`!==`) to `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is identical (`===`) to `rhs`.
*/
notIdentical(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is less than (`<`) `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is not less than (`!<`) `rhs`.
*/
lessThan(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is less than or equal (`<=`) to `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is not less than or equal (`!<=`) to `rhs`.
*/
lessThanOrEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is greater than (`>`) `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is not greater than (`!>`) `rhs`.
*/
greaterThan(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is greater than or equal (`>=`) to `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is not greater than or equal (`!>=`) to `rhs`.
*/
greaterThanOrEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is not less than (`!<`) `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is less than (`<`) `rhs`.
*/
notLessThan(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is not less than or equal (`!<=`) to `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is less than or equal (`<=`) to `rhs`.
*/
notLessThanOrEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is not greater than (`!>`) `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is greater than (`>`) `rhs`.
*/
notGreaterThan(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is not greater than or equal (`!>=`) to `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is greater than or equal (`>=`) to `rhs`.
*/
notGreaterThanOrEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `object` has the prototype of `constructor` in its prototype chain.
*
* @throws [[AssertException]] with `message` if `object` does not have the prototype of `constructor` in its prototype chain.
*/
instanceOf(object: unknown, constructor: Function, message?: string): void;
/**
* Asserts that `object` does not have the prototype of `constructor` in its prototype chain.
*
* @throws [[AssertException]] with `message` if `object` does have the prototype of `constructor` in its prototype chain.
*/
notInstanceOf(object: unknown, constructor: Function, message?: string): void;
/**
* Asserts that `lhs` is [[Values.equal structurally equal]] to `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is not structurally equal to `rhs`.
*/
equal(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is not [[Values.equal structurally equal]] to `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is structurally equal to `rhs`.
*/
notEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is [[Values.equivalent structurally equivalent]] to `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is not structurally equivalent to `rhs`.
*/
equivalent(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` is not [[Values.equivalent structurally equivalent]] to `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` is structurally equivalent to `rhs`.
*/
notEquivalent(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` [[Values.compare structurally orders before]] `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` does not structurally order before `rhs`.
*/
compareLessThan(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` does not [[Values.compare structurally order before]] `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` does structurally order before `rhs`.
*/
compareNotLessThan(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` [[Values.compare structurally orders before or the same as]] `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` does not structurally order before or the same as `rhs`.
*/
compareLessThanOrEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` does not [[Values.compare structurally order before or the same as]] `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` does structurally order before or the same as `rhs`.
*/
compareNotLessThanOrEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` [[Values.compare structurally orders the same as]] `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` does not structurally order before or the same as `rhs`.
*/
compareEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` does not [[Values.compare structurally order the same as]] `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` does structurally order before or the same as `rhs`.
*/
compareNotEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` [[Values.compare structurally orders after or the same as]] `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` does not structurally order after or the same as `rhs`.
*/
compareGreaterThanOrEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` does not [[Values.compare structurally order after or the same as]] `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` does structurally order after or the same as `rhs`.
*/
compareNotGreaterThanOrEqual(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` [[Values.compare structurally orders after]] `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` does not structurally order after `rhs`.
*/
compareGreaterThan(lhs: unknown, rhs: unknown, message?: string): void;
/**
* Asserts that `lhs` does not [[Values.compare structurally order after]] `rhs`.
*
* @throws [[AssertException]] with `message` if `lhs` does structurally order after `rhs`.
*/
compareNotGreaterThan(lhs: unknown, rhs: unknown, message?: string): void;
}
/** @public */
export const Assert = (function () {
const Assert = function (condition: unknown, message?: string): void {
if (!condition) {
throw new AssertException(message);
}
} as AssertFunction;
Assert.ok = function (condition: unknown, message?: string): void {
if (!condition) {
throw new AssertException(message);
}
};
Assert.notOk = function (condition: unknown, message?: string): void {
if (condition) {
throw new AssertException(message);
}
};
Assert.equal = function (lhs: unknown, rhs: unknown, message?: string): void {
if (!Values.equal(lhs, rhs)) {
throw new AssertException(message);
}
};
Assert.notEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if (Values.equal(lhs, rhs)) {
throw new AssertException(message);
}
};
Assert.identical = function (lhs: unknown, rhs: unknown, message?: string): void {
if (lhs !== rhs) {
throw new AssertException(message);
}
};
Assert.notIdentical = function (lhs: unknown, rhs: unknown, message?: string): void {
if (lhs === rhs) {
throw new AssertException(message);
}
};
Assert.lessThan = function (lhs: unknown, rhs: unknown, message?: string): void {
if (!((lhs as any) < (rhs as any))) {
throw new AssertException(message);
}
};
Assert.lessThanOrEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if (!((lhs as any) <= (rhs as any))) {
throw new AssertException(message);
}
};
Assert.greaterThan = function (lhs: unknown, rhs: unknown, message?: string): void {
if (!((lhs as any) > (rhs as any))) {
throw new AssertException(message);
}
};
Assert.greaterThanOrEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if (!((lhs as any) >= (rhs as any))) {
throw new AssertException(message);
}
};
Assert.notLessThan = function (lhs: unknown, rhs: unknown, message?: string): void {
if ((lhs as any) < (rhs as any)) {
throw new AssertException(message);
}
};
Assert.notLessThanOrEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if ((lhs as any) <= (rhs as any)) {
throw new AssertException(message);
}
};
Assert.notGreaterThan = function (lhs: unknown, rhs: unknown, message?: string): void {
if ((lhs as any) > (rhs as any)) {
throw new AssertException(message);
}
};
Assert.notGreaterThanOrEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if ((lhs as any) >= (rhs as any)) {
throw new AssertException(message);
}
};
Assert.instanceOf = function (object: unknown, constructor: Function, message?: string): void {
if (!(object instanceof constructor)) {
throw new AssertException(message);
}
};
Assert.notInstanceOf = function (object: unknown, constructor: Function, message?: string): void {
if (object instanceof constructor) {
throw new AssertException(message);
}
};
Assert.compareLessThan = function (lhs: unknown, rhs: unknown, message?: string): void {
if (!(Values.compare(lhs, rhs) < 0)) {
throw new AssertException(message);
}
};
Assert.compareNotLessThan = function (lhs: unknown, rhs: unknown, message?: string): void {
if (Values.compare(lhs, rhs) < 0) {
throw new AssertException(message);
}
};
Assert.compareLessThanOrEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if (!(Values.compare(lhs, rhs) <= 0)) {
throw new AssertException(message);
}
};
Assert.compareNotLessThanOrEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if (Values.compare(lhs, rhs) <= 0) {
throw new AssertException(message);
}
};
Assert.compareEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if (!(Values.compare(lhs, rhs) === 0)) {
throw new AssertException(message);
}
};
Assert.compareNotEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if (Values.compare(lhs, rhs) === 0) {
throw new AssertException(message);
}
};
Assert.compareGreaterThanOrEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if (!(Values.compare(lhs, rhs) >= 0)) {
throw new AssertException(message);
}
};
Assert.compareNotGreaterThanOrEqual = function (lhs: unknown, rhs: unknown, message?: string): void {
if (Values.compare(lhs, rhs) >= 0) {
throw new AssertException(message);
}
};
Assert.compareGreaterThan = function (lhs: unknown, rhs: unknown, message?: string): void {
if (!(Values.compare(lhs, rhs) > 0)) {
throw new AssertException(message);
}
};
Assert.compareNotGreaterThan = function (lhs: unknown, rhs: unknown, message?: string): void {
if (Values.compare(lhs, rhs) > 0) {
throw new AssertException(message);
}
};
return Assert;
})();
|
48bfe9fb51fe3ed491fee6c6ef3b595a950ee2fe
|
TypeScript
|
Tanvir-Kang/Portfolio
|
/src/pages/AboutMe.tsx/personalInfo.ts
| 2.609375
| 3
|
import { ImageCardProps } from "../../components/ImageCard/cardTypes";
import { TextCardProps } from "../../components/TextCard/cardTypes";
import PROFILE_PICTURE from "../../Static/Images/IMG_2662.jpg"
import { icons } from "../../Static/Images/LanguageIcons";
import { LanguageCardType } from "../../components/LanguageCards/landCardTypes";
export const profilePicture: ImageCardProps = {
title: "Profile Picture",
image: PROFILE_PICTURE
}
export const profileDescription: TextCardProps = {
titleText: "A little bit about me...",
secondaryText: "I'm currently looking for a role which would allow me to build on my existing skills while providing the room to learn \
new languages, frameworks, and the land of DevOps. I have an interest in both frontend and backend developement but would like to \
continue to grow my knowledge of best practices, architecture, and creating efficient software.",
bodyText: "Hello! I'm Tanvir, a junior level software developer based in Vancouver, BC. I'm a determined individual with a lot to learn about programming.\
My defining characteristics are an ability to put away my ego when working with others, gritty when problems get tough, a very keen eye for details \
and most importantly I try to learn something new everyday.",
}
export const PrimaryLanguages: LanguageCardType[] = [
{
imageURL: icons.typeScript,
cardTitle: "Typescript"
},
{
imageURL: icons.react,
cardTitle: "React"
},
{
imageURL: icons.java,
cardTitle: "Java"
}
];
export const SecondaryLanguage: LanguageCardType[] = [
{
imageURL: icons.CSharp,
cardTitle: "C#"
},
{
imageURL: icons.HTML,
cardTitle: "HTML"
},
{
imageURL: icons.CSS,
cardTitle: "CSS"
},
{
imageURL: icons.git,
cardTitle: "git"
},
{
imageURL: icons.springBoot,
cardTitle: "Spring Boot"
},
]
|
4ae2884eabdaa42c54e2ed9d429051fade3ebfe4
|
TypeScript
|
typvp/typvp-api
|
/src/resolvers/typingTest/test.type.ts
| 2.609375
| 3
|
import {ObjectType, Field, ID, Int, registerEnumType} from 'type-graphql'
import {Account} from '../account/account.type'
export enum ResultType {
SINGLEPLAYER = 'SINGLEPLAYER',
RACE = 'RACE',
TRIAL = 'TRIAL',
}
registerEnumType(ResultType, {
name: 'ResultType',
})
@ObjectType()
export class Test {
@Field(type => ID)
id: string
@Field(type => String)
createdAt: string
@Field(type => String)
updatedAt: string
@Field(type => Int)
cpm: number
@Field(type => Int)
rawCpm: number
@Field(type => Int)
wpm: number
@Field(type => Int)
correct: number
@Field(type => Int)
incorrect: number
@Field(type => Int)
corrections: number
@Field(type => Int)
wordIndex: number
@Field(type => Account)
account?: Account
@Field(type => ResultType)
type: keyof typeof ResultType
}
@ObjectType()
export class TestsWithCount {
@Field(type => [Test])
results: Test[]
@Field(type => Int)
allTestCount: number
@Field(type => Int)
filteredTestCount: number
}
|
fbbdf20e9f280729539a2223154b16f75ce85720
|
TypeScript
|
mikearnaldi/effect-ts
|
/packages/system/src/Effect/validate.ts
| 3.125
| 3
|
import * as A from "../Array"
import type * as NA from "../NonEmptyArray"
import type { Effect } from "./effect"
import type { ExecutionStrategy } from "./ExecutionStrategy"
import { validate_, validateExec_, validatePar_, validateParN_ } from "./validate_"
/**
* Feeds elements of type `A` to `f` and accumulates all errors in error
* channel or successes in success channel.
*
* This combinator is lossy meaning that if there are errors all successes
* will be lost.
*/
export function validate<A, R, E, B>(f: (a: A) => Effect<R, E, B>) {
return (as: Iterable<A>) => validate_(as, f)
}
/**
* Feeds elements of type `A` to `f` and accumulates all errors in error
* channel or successes in success channel.
*
* This combinator is lossy meaning that if there are errors all successes
* will be lost.
*/
export function validatePar<A, R, E, B>(f: (a: A) => Effect<R, E, B>) {
return (as: Iterable<A>) => validatePar_(as, f)
}
/**
* Feeds elements of type `A` to `f` and accumulates all errors in error
* channel or successes in success channel.
*
* This combinator is lossy meaning that if there are errors all successes
* will be lost.
*/
export function validateParN(n: number) {
return <A, R, E, B>(f: (a: A) => Effect<R, E, B>) => (as: Iterable<A>) =>
validateParN_(n)(as, f)
}
/**
* Feeds elements of type `A` to `f` and accumulates all errors in error
* channel or successes in success channel.
*
* This combinator is lossy meaning that if there are errors all successes
* will be lost.
*/
export function validateExec<R, E, A, B>(
es: ExecutionStrategy,
f: (a: A) => Effect<R, E, B>
): (as: Iterable<A>) => Effect<R, NA.NonEmptyArray<E>, A.Array<B>> {
return (as) => validateExec_(as, es, f)
}
|
e7806254025aff395481f5517d26a892f0c3164e
|
TypeScript
|
kluntje/kluntje
|
/packages/js-utils/src/dom-helpers/lib/getInnerText.ts
| 3.390625
| 3
|
/**
* returns innerText of given Element
* @param {HTMLElement} el
* @returns {string}
* @example
* const myArticle = document.querySelector('article');
* const articleText = getInnerText(myArticle);
*/
export const getInnerText = (el: HTMLElement): string => {
return el.innerText || el.textContent || '';
};
|
3283343f22d4d009ba7382b22eff8aa3013ae4a6
|
TypeScript
|
uk-gov-mirror/hmcts.rpa-jui-webapp
|
/src/app/shared/components/hmcts-em-viewer-ui/data/js-wrapper/pdf-annotate-wrapper.spec.ts
| 2.53125
| 3
|
import {PdfAnnotateWrapper} from './pdf-annotate-wrapper';
import { RenderOptions } from './renderOptions.model';
declare global { interface Window { PDFAnnotate: any; } }
describe('pdfAnnotateWrapper', () => {
const pdfAnnotateWrapper = new PdfAnnotateWrapper();
const mockUI = {
createPage(pageNumber) {},
renderPage(pageNumber, RENDER_OPTIONS) {},
enableRect(type) {},
disableRect() {},
getUi() {}
};
window.PDFAnnotate = {
UI: mockUI,
getStoreAdapter() {},
setStoreAdapter(documentId) {},
LocalStoreAdapter() {}
};
it('should set store adapter', () => {
const storeAdapter = 'myStoreAdapter';
spyOn(window.PDFAnnotate, 'setStoreAdapter').and.stub();
pdfAnnotateWrapper.setStoreAdapter(storeAdapter);
expect(window.PDFAnnotate.setStoreAdapter).toHaveBeenCalledWith(storeAdapter);
});
it('should set store adapter with no store adapter passed', () => {
spyOn(window.PDFAnnotate, 'setStoreAdapter').and.stub();
pdfAnnotateWrapper.setStoreAdapter(null);
expect(window.PDFAnnotate.setStoreAdapter).toHaveBeenCalled();
});
it('should call createPage with the provided page number', () => {
const pageNumber = 1;
spyOn(window.PDFAnnotate.UI, 'createPage').and.stub();
pdfAnnotateWrapper.createPage(pageNumber);
expect(window.PDFAnnotate.UI.createPage).toHaveBeenCalledWith(pageNumber);
});
it('should call renderPage with the provided page number and render options', () => {
const pageNumber = 1;
const renderOptions = new RenderOptions('documentId', null, 1, 0, []);
spyOn(window.PDFAnnotate.UI, 'renderPage').and.stub();
pdfAnnotateWrapper.renderPage(pageNumber, renderOptions);
expect(window.PDFAnnotate.UI.renderPage).toHaveBeenCalledWith(pageNumber, renderOptions);
});
it('should call enableRect with the provided type', () => {
const type = 'rect';
spyOn(window.PDFAnnotate.UI, 'enableRect').and.stub();
pdfAnnotateWrapper.enableRect(type);
expect(window.PDFAnnotate.UI.enableRect).toHaveBeenCalledWith(type);
});
it('should call disableRect', () => {
spyOn(window.PDFAnnotate.UI, 'disableRect').and.stub();
pdfAnnotateWrapper.disableRect();
expect(window.PDFAnnotate.UI.disableRect).toHaveBeenCalled();
});
it('should return UI object', () => {
const returnedUi = pdfAnnotateWrapper.getUi();
expect(returnedUi).toBe(mockUI);
});
it('should return store adapter', function () {
spyOn(window.PDFAnnotate, 'getStoreAdapter').and.stub();
pdfAnnotateWrapper.getStoreAdapter();
expect(window.PDFAnnotate.getStoreAdapter).toHaveBeenCalled();
});
});
|
107980174a0335ba5479ad1c7e0df04f6a6b3d5a
|
TypeScript
|
jgudo/movx
|
/src/redux/reducers/miscReducer.ts
| 2.84375
| 3
|
import {
IS_LOADING,
SET_DARK_MODE,
} from '@app/constants/actionType';
import { IMiscState } from '@app/types/types';
import { TMiscActionType } from '../actions/miscActions';
const defaultState: IMiscState = {
isLoading: false,
darkMode: true,
}
export default (state = defaultState, action: TMiscActionType) => {
switch (action.type) {
case IS_LOADING:
return {
...state,
isLoading: action.payload,
};
case SET_DARK_MODE:
return {
...state,
darkMode: action.payload,
};
default:
return state;
}
};
|
22e8665af61662261254ab327daa25646d960538
|
TypeScript
|
nitrogenlabs/starfire
|
/src/main/Comments.ts
| 2.8125
| 3
|
import assert from 'assert';
import {Util} from '../common/Util';
import {DocBuilders} from '../doc/DocBuilders';
const childNodesCacheKey = Symbol('child-nodes');
export class Comments {
static getSortedChildNodes(node, text, options, resultArray?) {
if(!node) {
return;
}
const {locEnd, locStart, printer} = options;
if(resultArray) {
if(node && printer.canAttachComment && printer.canAttachComment(node)) {
// This reverse insertion sort almost always takes constant
// time because we almost always (maybe always?) append the
// nodes in order anyway.
let i;
for(i = resultArray.length - 1; i >= 0; --i) {
if(
locStart(resultArray[i]) <= locStart(node) &&
locEnd(resultArray[i]) <= locEnd(node)
) {
break;
}
}
resultArray.splice(i + 1, 0, node);
return;
}
} else if(node[childNodesCacheKey]) {
return node[childNodesCacheKey];
}
let childNodes;
if(printer.getCommentChildNodes) {
childNodes = printer.getCommentChildNodes(node);
} else if(node && typeof node === 'object') {
childNodes = Object.keys(node)
.filter((n) => n !== 'enclosingNode' && n !== 'precedingNode' && n !== 'followingNode')
.map((n) => node[n]);
}
if(!childNodes) {
return;
}
if(!resultArray) {
Object.defineProperty(node, childNodesCacheKey, {enumerable: false, value: (resultArray = [])});
}
childNodes.forEach((childNode) => {
Comments.getSortedChildNodes(childNode, text, options, resultArray);
});
return resultArray;
}
// As efficiently as possible, decorate the comment object with
// .precedingNode, .enclosingNode, and/or .followingNode properties, at
// least one of which is guaranteed to be defined.
static decorateComment(node, comment, text, options) {
const locStart = options.locStart;
const locEnd = options.locEnd;
const childNodes = Comments.getSortedChildNodes(node, text, options);
let precedingNode;
let followingNode;
// Time to dust off the old binary search robes and wizard hat.
let left: number = 0;
let right: number = childNodes.length;
while(left < right) {
const middle = (left + right) >> 1;
const child = childNodes[middle];
if(
locStart(child) - locStart(comment) <= 0 &&
locEnd(comment) - locEnd(child) <= 0
) {
// The comment is completely contained by this child node.
comment.enclosingNode = child;
Comments.decorateComment(child, comment, text, options);
return; // Abandon the binary search at this level.
}
if(locEnd(child) - locStart(comment) <= 0) {
// This child node falls completely before the comment.
// Because we will never consider this node or any nodes
// before it again, this node must be the closest preceding
// node we have encountered so far.
precedingNode = child;
left = middle + 1;
continue;
}
if(locEnd(comment) - locStart(child) <= 0) {
// This child node falls completely after the comment.
// Because we will never consider this node or any nodes after
// it again, this node must be the closest following node we
// have encountered so far.
followingNode = child;
right = middle;
continue;
}
/* istanbul ignore next */
throw new Error('Comment location overlaps with node location');
}
// We don't want comments inside of different expressions inside of the same
// template literal to move to another expression.
if(
comment.enclosingNode &&
comment.enclosingNode.type === 'TemplateLiteral'
) {
const quasis = comment.enclosingNode.quasis;
const commentIndex = Comments.findExpressionIndexForComment(quasis, comment, options);
if(
precedingNode &&
Comments.findExpressionIndexForComment(quasis, precedingNode, options) !==
commentIndex
) {
precedingNode = null;
}
if(
followingNode &&
Comments.findExpressionIndexForComment(quasis, followingNode, options) !==
commentIndex
) {
followingNode = null;
}
}
if(precedingNode) {
comment.precedingNode = precedingNode;
}
if(followingNode) {
comment.followingNode = followingNode;
}
}
static attach(comments, ast, text, options) {
if(!Array.isArray(comments)) {
return;
}
const tiesToBreak = [];
const locStart = options.locStart;
const locEnd = options.locEnd;
comments.forEach((comment, i) => {
if(options.parser === 'json' && locStart(comment) - locStart(ast) <= 0) {
Util.addLeadingComment(ast, comment);
return;
}
Comments.decorateComment(ast, comment, text, options);
const precedingNode = comment.precedingNode;
const enclosingNode = comment.enclosingNode;
const followingNode = comment.followingNode;
const pluginHandleOwnLineComment =
options.printer.handleComments && options.printer.handleComments.ownLine
? options.printer.handleComments.ownLine
: () => false;
const pluginHandleEndOfLineComment =
options.printer.handleComments && options.printer.handleComments.endOfLine
? options.printer.handleComments.endOfLine
: () => false;
const pluginHandleRemainingComment =
options.printer.handleComments && options.printer.handleComments.remaining
? options.printer.handleComments.remaining
: () => false;
const isLastComment = comments.length - 1 === i;
if(Util.hasNewline(text, locStart(comment), {backwards: true})) {
// If a comment exists on its own line, prefer a leading comment.
// We also need to check if it's the first line of the file.
if(
pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)
) {
// We're good
} else if(followingNode) {
// Always a leading comment.
Util.addLeadingComment(followingNode, comment);
} else if(precedingNode) {
Util.addTrailingComment(precedingNode, comment);
} else if(enclosingNode) {
Util.addDanglingComment(enclosingNode, comment);
} else {
// There are no nodes, let's attach it to the root of the ast
/* istanbul ignore next */
Util.addDanglingComment(ast, comment);
}
} else if(Util.hasNewline(text, locEnd(comment))) {
if(
pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)
) {
// We're good
} else if(precedingNode) {
// There is content before this comment on the same line, but
// none after it, so prefer a trailing comment of the previous node.
Util.addTrailingComment(precedingNode, comment);
} else if(followingNode) {
Util.addLeadingComment(followingNode, comment);
} else if(enclosingNode) {
Util.addDanglingComment(enclosingNode, comment);
} else {
// There are no nodes, let's attach it to the root of the ast
/* istanbul ignore next */
Util.addDanglingComment(ast, comment);
}
} else {
if(
pluginHandleRemainingComment(comment, text, options, ast, isLastComment)
) {
// We're good
} else if(precedingNode && followingNode) {
// Otherwise, text exists both before and after the comment on
// the same line. If there is both a preceding and following
// node, use a tie-breaking algorithm to determine if it should
// be attached to the next or previous node. In the last case,
// simply attach the right node;
const tieCount = tiesToBreak.length;
if(tieCount > 0) {
const lastTie = tiesToBreak[tieCount - 1];
if(lastTie.followingNode !== comment.followingNode) {
Comments.breakTies(tiesToBreak, text, options);
}
}
tiesToBreak.push(comment);
} else if(precedingNode) {
Util.addTrailingComment(precedingNode, comment);
} else if(followingNode) {
Util.addLeadingComment(followingNode, comment);
} else if(enclosingNode) {
Util.addDanglingComment(enclosingNode, comment);
} else {
// There are no nodes, let's attach it to the root of the ast
/* istanbul ignore next */
Util.addDanglingComment(ast, comment);
}
}
});
Comments.breakTies(tiesToBreak, text, options);
comments.forEach((comment) => {
// These node references were useful for breaking ties, but we
// don't need them anymore, and they create cycles in the AST that
// may lead to infinite recursion if we don't delete them here.
delete comment.precedingNode;
delete comment.enclosingNode;
delete comment.followingNode;
});
}
static breakTies(tiesToBreak, text, options) {
const tieCount = tiesToBreak.length;
if(tieCount === 0) {
return;
}
const precedingNode = tiesToBreak[0].precedingNode;
const followingNode = tiesToBreak[0].followingNode;
let gapEndPos = options.locStart(followingNode);
// Iterate backwards through tiesToBreak, examining the gaps
// between the tied comments. In order to qualify as leading, a
// comment must be separated from followingNode by an unbroken series of
// gaps (or other comments). Gaps should only contain whitespace or open
// parentheses.
let indexOfFirstLeadingComment;
for(
indexOfFirstLeadingComment = tieCount;
indexOfFirstLeadingComment > 0;
--indexOfFirstLeadingComment
) {
const comment = tiesToBreak[indexOfFirstLeadingComment - 1];
assert.strictEqual(comment.precedingNode, precedingNode);
assert.strictEqual(comment.followingNode, followingNode);
const gap = text.slice(options.locEnd(comment), gapEndPos).trim();
if(gap === '' || /^\(+$/.test(gap)) {
gapEndPos = options.locStart(comment);
} else {
// The gap string contained something other than whitespace or open
// parentheses.
break;
}
}
tiesToBreak.forEach((comment, i) => {
if(i < indexOfFirstLeadingComment) {
Util.addTrailingComment(precedingNode, comment);
} else {
Util.addLeadingComment(followingNode, comment);
}
});
tiesToBreak.length = 0;
}
static printComment(commentPath, options) {
const comment = commentPath.getValue();
comment.printed = true;
return options.printer.printComment(commentPath, options);
}
static findExpressionIndexForComment(quasis, comment, options) {
const startPos = options.locStart(comment) - 1;
for(let i = 1; i < quasis.length; ++i) {
if(startPos < Comments.getQuasiRange(quasis[i]).start) {
return i - 1;
}
}
// We haven't found it, it probably means that some of the locations are off.
// Let's just return the first one.
/* istanbul ignore next */
return 0;
}
static getQuasiRange(expr) {
if(expr.start !== undefined) {
// Babylon
return {start: expr.start, end: expr.end};
}
// Flow
return {start: expr.range[0], end: expr.range[1]};
}
static printLeadingComment(commentPath, print, options) {
const comment = commentPath.getValue();
const contents = Comments.printComment(commentPath, options);
if(!contents) {
return '';
}
const isBlock = Util.isBlockComment(comment);
// Leading block comments should see if they need to stay on the
// same line or not.
if(isBlock) {
return DocBuilders.concat([
contents,
Util.hasNewline(options.originalText, options.locEnd(comment))
? DocBuilders.hardline
: ' '
]);
}
return DocBuilders.concat([contents, DocBuilders.hardline]);
}
static printTrailingComment(commentPath, print, options) {
const comment = commentPath.getValue();
const contents = Comments.printComment(commentPath, options);
if(!contents) {
return '';
}
const isBlock = Util.isBlockComment(comment);
// We don't want the line to break
// when the parentParentNode is a ClassDeclaration/-Expression
// And the parentNode is in the superClass property
const parentNode = commentPath.getNode(1);
const parentParentNode = commentPath.getNode(2);
const isParentSuperClass =
parentParentNode &&
(parentParentNode.type === 'ClassDeclaration' ||
parentParentNode.type === 'ClassExpression') &&
parentParentNode.superClass === parentNode;
if(
Util.hasNewline(options.originalText, options.locStart(comment), {
backwards: true
})
) {
// This allows comments at the end of nested structures:
// {
// x: 1,
// y: 2
// // A comment
// }
// Those kinds of comments are almost always leading comments, but
// here it doesn't go "outside" the block and turns it into a
// trailing comment for `2`. We can simulate the above by checking
// if this a comment on its own line; normal trailing comments are
// always at the end of another expression.
const isLineBeforeEmpty = Util.isPreviousLineEmpty(
options.originalText,
comment,
options.locStart
);
return DocBuilders.lineSuffix(
DocBuilders.concat([DocBuilders.hardline, isLineBeforeEmpty ? DocBuilders.hardline : '', contents])
);
} else if(isBlock || isParentSuperClass) {
// Trailing block comments never need a newline
return DocBuilders.concat([' ', contents]);
}
return DocBuilders.concat([DocBuilders.lineSuffix(' ' + contents), !isBlock ? DocBuilders.breakParent : '']);
}
static printDanglingComments(path, options, sameIndent?, filter?) {
const parts = [];
const node = path.getValue();
if(!node || !node.comments) {
return '';
}
path.each((commentPath) => {
const comment = commentPath.getValue();
if(
comment &&
!comment.leading &&
!comment.trailing &&
(!filter || filter(comment))
) {
parts.push(Comments.printComment(commentPath, options));
}
}, 'comments');
if(parts.length === 0) {
return '';
}
if(sameIndent) {
return DocBuilders.join(DocBuilders.hardline, parts);
}
return DocBuilders
.indent(DocBuilders.concat([DocBuilders.hardline, DocBuilders.join(DocBuilders.hardline, parts)]));
}
static prependCursorPlaceholder(path, options, printed) {
if(path.getNode() === options.cursorNode && path.getValue()) {
return DocBuilders.concat([DocBuilders.cursor, printed]);
}
return printed;
}
static printComments(path, print, options, needsSemi: boolean = false) {
const value = path.getValue();
const printed = print(path);
const comments = value && value.comments;
if(!comments || comments.length === 0) {
return Comments.prependCursorPlaceholder(path, options, printed);
}
const leadingParts = [];
const trailingParts = [needsSemi ? ';' : '', printed];
path.each((commentPath) => {
const comment = commentPath.getValue();
const leading = comment.leading;
const trailing = comment.trailing;
if(leading) {
const contents = Comments.printLeadingComment(commentPath, print, options);
if(!contents) {
return;
}
leadingParts.push(contents);
const text = options.originalText;
if(Util.hasNewline(text, Util.skipNewline(text, options.locEnd(comment)))) {
leadingParts.push(DocBuilders.hardline);
}
} else if(trailing) {
trailingParts.push(Comments.printTrailingComment(commentPath, print, options));
}
}, 'comments');
return Comments.prependCursorPlaceholder(path, options, DocBuilders.concat(leadingParts.concat(trailingParts)));
}
}
|
8d867f3f8b6ecc67fb8a9d8b2ef23a1f8248f3c0
|
TypeScript
|
Tomella/cossap-3d
|
/source/label/css2drenderer.ts
| 2.5625
| 3
|
import { CSS2DObject } from "./css2dobject";
/**
* Refactored THREE.CSS2DRenderer
* @author mrdoob / http://mrdoob.com/
*/
export class CSS2DRenderer {
domElement: HTMLElement;
private viewMatrix;
private vector;
private viewProjectionMatrix;
private width: number;
private height: number;
private widthHalf: number;
private heightHalf: number;
constructor() {
console.log("CSS2DRenderer", THREE.REVISION);
this.vector = new THREE.Vector3();
this.viewMatrix = new THREE.Matrix4();
this.viewProjectionMatrix = new THREE.Matrix4();
this.domElement = document.createElement("div");
this.domElement.style.overflow = "hidden";
}
render(scene, camera) {
let self = this;
scene.updateMatrixWorld();
if (camera.parent === null) camera.updateMatrixWorld();
camera.matrixWorldInverse.getInverse(camera.matrixWorld);
this.viewMatrix.copy(camera.matrixWorldInverse.getInverse(camera.matrixWorld));
this.viewProjectionMatrix.multiplyMatrices(camera.projectionMatrix, this.viewMatrix);
renderObject(scene, camera);
function renderObject(object, camera) {
if (object instanceof CSS2DObject) {
camera.updateMatrixWorld();
self.vector.setFromMatrixPosition(object.matrixWorld);
self.vector.applyMatrix4(self.viewProjectionMatrix);
let element = object.element;
let x = (self.vector.x * self.widthHalf / 2200000 + self.widthHalf);
let y = (-self.vector.y * self.heightHalf / 2400000 + self.heightHalf);
let xStr = x.toString();
let yStr = y.toString();
let style = "translate(-50%,-50%) translate("
+ xStr + "px,"
+ yStr + "px)";
element.style.WebkitTransform = style;
element.style.MozTransform = style;
element.style.oTransform = style;
element.style.transform = style;
if (element.parentNode !== self.domElement) {
self.domElement.appendChild(element);
}
}
for (let i = 0, l = object.children.length; i < l; i++) {
renderObject(object.children[i], camera);
}
}
}
setSize(width, height) {
this.width = width;
this.height = height;
this.widthHalf = this.width / 2;
this.heightHalf = this.height / 2;
this.domElement.style.width = width + "px";
this.domElement.style.height = height + "px";
}
}
|
8b65dac53106978d66ea23252efceebba3c7373a
|
TypeScript
|
shivam-kantival-mt/test-react-app
|
/src/hooks/useScrollRatio/index.ts
| 2.828125
| 3
|
import { RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import debounce from 'lodash/debounce';
//typeDefs
import { ScrollRatioComputeParams } from './interfaces';
//helpers
import { computeScrollRatio } from './helpers';
export default function useScrollRatio<S extends HTMLElement>({
hasElementDimensionChanged,
}: {
readonly hasElementDimensionChanged?: boolean;
}): [number, RefObject<S>] {
const ref = useRef<S>(null),
[currentScrollRatio, setCurrentScrollRatio] = useState<number>(1),
computeAndSetScrollRatio = useMemo(
() =>
debounce<(scrollRatioComputeParams: ScrollRatioComputeParams) => void>(
scrollRatioComputeParams => {
setCurrentScrollRatio(computeScrollRatio(scrollRatioComputeParams));
},
50
),
[]
);
const onScroll = useCallback<EventListener>(
event => {
const currentTarget = event.currentTarget as S;
currentTarget && computeAndSetScrollRatio(currentTarget);
},
[computeAndSetScrollRatio]
);
//to setup and cleanup onscroll
useEffect(() => {
const currentRef = ref.current;
currentRef?.addEventListener('scroll', onScroll);
return function () {
currentRef?.removeEventListener('scroll', onScroll);
};
}, [onScroll]);
//to init state
useEffect(() => {
setCurrentScrollRatio(computeScrollRatio(ref.current));
}, []);
//to handle windowResize
useEffect(() => {
const currentRef = ref.current,
onResize = () => {
setCurrentScrollRatio(computeScrollRatio(currentRef));
};
window.addEventListener('resize', onResize);
return function () {
window.removeEventListener('resize', onResize);
};
});
//to update scrollRatio if element changed the data being displayed and inturn may have updated scroll behavior
useEffect(() => {
hasElementDimensionChanged && setCurrentScrollRatio(computeScrollRatio(ref.current));
}, [hasElementDimensionChanged]);
return [currentScrollRatio, ref];
}
|
1a90e4128ac3188a825e4ec88d887fc064c805dc
|
TypeScript
|
tensorflow/tfjs
|
/tfjs-layers/src/engine/training_tensors.ts
| 2.71875
| 3
|
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* Interfaces and methods for training models using tf.Tensor objects.
*/
import * as tfc from '@tensorflow/tfjs-core';
import {Tensor, Tensor1D} from '@tensorflow/tfjs-core';
import {expandDims, gather, sliceAlongFirstAxis} from '../backend/tfjs_backend';
import {BaseCallback, CustomCallbackArgs, ModelLoggingVerbosity, YieldEveryOptions} from '../base_callbacks';
import {ClassWeight, ClassWeightMap} from './training_utils';
/**
* Interface configuration model training based on data as `tf.Tensor`s.
*/
export interface ModelFitArgs {
/**
* Number of samples per gradient update. If unspecified, it
* will default to 32.
*/
batchSize?: number;
/**
* Integer number of times to iterate over the training data arrays.
*/
epochs?: number;
/**
* Verbosity level.
*
* Expected to be 0, 1, or 2. Default: 1.
*
* 0 - No printed message during fit() call.
* 1 - In Node.js (tfjs-node), prints the progress bar, together with
* real-time updates of loss and metric values and training speed.
* In the browser: no action. This is the default.
* 2 - Not implemented yet.
*/
verbose?: ModelLoggingVerbosity | 2;
/**
* List of callbacks to be called during training.
* Can have one or more of the following callbacks:
* - `onTrainBegin(logs)`: called when training starts.
* - `onTrainEnd(logs)`: called when training ends.
* - `onEpochBegin(epoch, logs)`: called at the start of every epoch.
* - `onEpochEnd(epoch, logs)`: called at the end of every epoch.
* - `onBatchBegin(batch, logs)`: called at the start of every batch.
* - `onBatchEnd(batch, logs)`: called at the end of every batch.
* - `onYield(epoch, batch, logs)`: called every `yieldEvery` milliseconds
* with the current epoch, batch and logs. The logs are the same
* as in `onBatchEnd()`. Note that `onYield` can skip batches or
* epochs. See also docs for `yieldEvery` below.
*/
callbacks?: BaseCallback[]|CustomCallbackArgs|CustomCallbackArgs[];
/**
* Float between 0 and 1: fraction of the training data
* to be used as validation data. The model will set apart this fraction of
* the training data, will not train on it, and will evaluate the loss and
* any model metrics on this data at the end of each epoch.
* The validation data is selected from the last samples in the `x` and `y`
* data provided, before shuffling.
*/
validationSplit?: number;
/**
* Data on which to evaluate the loss and any model
* metrics at the end of each epoch. The model will not be trained on this
* data. This could be a tuple [xVal, yVal] or a tuple [xVal, yVal,
* valSampleWeights]. The model will not be trained on this data.
* `validationData` will override `validationSplit`.
*/
validationData?: [
Tensor|Tensor[], Tensor|Tensor[]
]|[Tensor | Tensor[], Tensor|Tensor[], Tensor|Tensor[]];
/**
* Whether to shuffle the training data before each epoch. Has
* no effect when `stepsPerEpoch` is not `null`.
*/
shuffle?: boolean;
/**
* Optional object mapping class indices (integers) to
* a weight (float) to apply to the model's loss for the samples from this
* class during training. This can be useful to tell the model to "pay more
* attention" to samples from an under-represented class.
*
* If the model has multiple outputs, a class weight can be specified for
* each of the outputs by setting this field an array of weight object
* or an object that maps model output names (e.g., `model.outputNames[0]`)
* to weight objects.
*/
classWeight?: ClassWeight|ClassWeight[]|ClassWeightMap;
/**
* Optional array of the same length as x, containing
* weights to apply to the model's loss for each sample. In the case of
* temporal data, you can pass a 2D array with shape (samples,
* sequenceLength), to apply a different weight to every timestep of every
* sample. In this case you should make sure to specify
* sampleWeightMode="temporal" in compile().
*/
sampleWeight?: Tensor;
/**
* Epoch at which to start training (useful for resuming a previous training
* run). When this is used, `epochs` is the index of the "final epoch".
* The model is not trained for a number of iterations given by `epochs`,
* but merely until the epoch of index `epochs` is reached.
*/
initialEpoch?: number;
/**
* Total number of steps (batches of samples) before
* declaring one epoch finished and starting the next epoch. When training
* with Input Tensors such as TensorFlow data tensors, the default `null` is
* equal to the number of unique samples in your dataset divided by the
* batch size, or 1 if that cannot be determined.
*/
stepsPerEpoch?: number;
/**
* Only relevant if `stepsPerEpoch` is specified. Total number of steps
* (batches of samples) to validate before stopping.
*/
validationSteps?: number;
/**
* Configures the frequency of yielding the main thread to other tasks.
*
* In the browser environment, yielding the main thread can improve the
* responsiveness of the page during training. In the Node.js environment,
* it can ensure tasks queued in the event loop can be handled in a timely
* manner.
*
* The value can be one of the following:
* - `'auto'`: The yielding happens at a certain frame rate (currently set
* at 125ms). This is the default.
* - `'batch'`: yield every batch.
* - `'epoch'`: yield every epoch.
* - any `number`: yield every `number` milliseconds.
* - `'never'`: never yield. (yielding can still happen through `await
* nextFrame()` calls in custom callbacks.)
*/
yieldEvery?: YieldEveryOptions;
}
export function checkBatchSize(batchSize: number) {
tfc.util.assert(
batchSize > 0 && Number.isInteger(batchSize),
() => `batchSize is required to be a positive integer, but got ${
batchSize}`);
}
/**
* Slice a Tensor or an Array of Tensors, by start and stop indices.
*
* Porting Note: The `_slice_arrays` function in PyKeras is covered by this
* function and `sliceArraysByIndices()` together.
*
* @param arrays: the input.
* @param start: the starting index (inclusive).
* @param stop: the stopping index (exclusive).
* @returns The result of the slicing. If `arrays` is an `Array` of
* `tf.Tensor`s, the slicing will be applied to all elements of the `Array`
* in the same way.
*/
export function sliceArrays(
arrays: Tensor|Tensor[], start: number, stop: number): Tensor|Tensor[] {
if (arrays == null) {
return [null];
} else if (Array.isArray(arrays)) {
return arrays.map(array => sliceAlongFirstAxis(array, start, stop - start));
} else { // Tensor.
return sliceAlongFirstAxis(arrays, start, stop - start);
}
}
/**
* Slice a Tensor or an Array of Tensors, by random-order indices.
*
* Porting Note: The `_slice_arrays` function in PyKeras is covered by this
* function and `sliceArrays()` together.
*
* @param arrays The input `tf.Tensor` or `Array` of `tf.Tensor`s to slice.
* If an `Array` of `tf.Tensor`s, all `tf.Tensor`s will be sliced in the
* same fashion.
* @param indices The indices to use for slicing along the first (batch)
* dimension.
* @returns Result(s) of the slicing.
*/
export function sliceArraysByIndices(
arrays: Tensor|Tensor[], indices: Tensor1D): Tensor|Tensor[] {
return tfc.tidy(() => {
if (arrays == null) {
return null;
} else if (Array.isArray(arrays)) {
return arrays.map(
array => (sliceArraysByIndices(array, indices) as Tensor));
} else {
// TODO(cais): indices should be a pre-constructed Tensor1D to avoid
// tensor1d() calls.
return gather(
arrays,
indices.dtype === 'int32' ? indices : tfc.cast(indices, 'int32'));
}
});
}
/**
* Returns a list of batch indices (tuples of indices).
* @param size: Integer, total size of the data to slice into batches.
* @param batchSize: Integer, batch size.
* @returns An Array of [batchStart, batchEnd] tuples. batchStart is
* inclusive; batchEnd is exclusive. I.e., each batch consists of indices x
* that satisfy batchStart <= x < batchEnd.
*/
export function makeBatches(
size: number, batchSize: number): Array<[number, number]> {
const output: Array<[number, number]> = [];
let batchStart = 0;
let batchEnd: number = null;
while (batchStart < size) {
batchEnd = batchStart + batchSize;
if (batchEnd >= size) {
batchEnd = size;
}
output.push([batchStart, batchEnd]);
batchStart = batchEnd;
}
return output;
}
/**
* Ensure tensors all have a rank of at least 2.
*
* If a tensor has a rank of 1, it is dimension-expanded to rank 2.
* If any tensor has a rank of 0 (i.e., is a scalar), an error will be thrown.
*/
export function ensureTensorsRank2OrHigher(tensors: Tensor|Tensor[]): Tensor[] {
const outs: Tensor[] = [];
if (tensors instanceof Tensor) {
tensors = [tensors];
}
// Make Tensors at least 2D.
for (let i = 0; i < tensors.length; ++i) {
const tensor = tensors[i];
if (tensor.rank === 1) {
outs.push(expandDims(tensor, 1));
} else if (tensor.rank === 0) {
throw new Error(
'Expected tensor to be at least 1D, but received a 0D tensor ' +
'(scalar).');
} else {
outs.push(tensor);
}
}
return outs;
}
/**
* Compare a set of tensors with a reference (old) set, discard the ones
* in the new set that are not present in the reference set.
*
* This method is used for memory clenaup during calls such as
* LayersModel.fit().
*
* @param tensors New set which may contain Tensors not present in
* `refTensors`.
* @param refTensors Reference Tensor set.
*/
// TODO(cais, kangyizhang): Deduplicate with tfjs-data.
export function disposeNewTensors(
tensors: Tensor|Tensor[]|{[inputName: string]: Tensor},
refTensors: Tensor|Tensor[]|{[inputName: string]: Tensor}): void {
if (tensors == null) {
return;
}
const oldTensorIds: number[] = [];
if (refTensors instanceof Tensor) {
oldTensorIds.push(refTensors.id);
} else if (Array.isArray(refTensors)) {
refTensors.forEach(t => oldTensorIds.push(t.id));
} else if (refTensors != null) {
// `oldTensors` is a map from string name to Tensor.
for (const name in refTensors) {
const oldTensor = refTensors[name];
oldTensorIds.push(oldTensor.id);
}
}
const tensorsToDispose: Tensor[] = [];
if (tensors instanceof Tensor) {
if (oldTensorIds.indexOf(tensors.id) === -1) {
tensorsToDispose.push(tensors);
}
} else if (Array.isArray(tensors)) {
tensors.forEach(t => {
if (oldTensorIds.indexOf(t.id) === -1) {
tensorsToDispose.push(t);
}
});
} else if (tensors != null) {
// `oldTensors` is a map from string name to Tensor.
for (const name in tensors) {
const tensor = tensors[name];
if (oldTensorIds.indexOf(tensor.id) === -1) {
tensorsToDispose.push(tensor);
}
}
}
tensorsToDispose.forEach(t => {
if (!t.isDisposed) {
t.dispose();
}
});
}
|
82d179f599603551e6efa337a7bf29d3e58b021d
|
TypeScript
|
kabbash/EFS
|
/Trainer-FrontEnd/src/app/your-tools/Models/calories-dto.ts
| 2.71875
| 3
|
export class Calculator {
age: number;
height: number;
weight: number;
neck: number;
waist: number;
hip: number;
fats: number;
carbPercentage: number;
gender: string = "0";
equation: string = "0";
activityRange: string = "1";
showResult: boolean = false;
caloriesResult = new caloriesResult();
healthyFatsResult = new healthyFatsResult();
bodyFatsResult = new bodyFatsResult();
carbResult = new carbResult();
proteinResult = new proteinResult();
perfectWeightResult = new perfectWeightResult();
reset() {
this.activityRange = "1";
this.age = undefined;
this.equation = "0";
this.gender = "0";
this.height = undefined;
this.weight = undefined;
this.neck = undefined;
this.waist = undefined;
this.hip = undefined;
this.fats = undefined;
this.carbPercentage = undefined;
this.healthyFatsResult = new healthyFatsResult();
this.bodyFatsResult = new bodyFatsResult();
this.carbResult = new carbResult();
this.proteinResult = new proteinResult();
this.perfectWeightResult = new perfectWeightResult();
this.showResult = false;
}
calcCalories() {
let calories = 0;
switch (this.equation) {
case "1":
if (this.gender == "0")
calories = (13.397 * this.weight) + (4.799 * this.height) - (5.677 * this.age) + 88.362;
else
calories = (9.247 * this.weight) + (3.098 * this.height) - (4.330 * this.age) + 447.593;
break;
case "2":
calories = 370 + (21.6 * (1 - (this.fats / 100)) * this.weight);
break;
default:
calories = (10 * this.weight) + (6.25 * this.height) - (5 * this.age);
if (this.gender == "1")
calories -= 161;
else
calories += 5;
break;
}
calories *= Number(this.activityRange);
this.caloriesResult.maintainWeight = isNaN(calories) ? "0" : calories.toFixed();
this.caloriesResult.lossHalfKilo = isNaN(calories) ? "0" : (calories - 500).toFixed();
this.caloriesResult.lossOneKilo = isNaN(calories) ? "0" : (calories - 1000).toFixed();
this.caloriesResult.gainHalfKilo = isNaN(calories) ? "0" : (calories + 500).toFixed();
this.caloriesResult.gainOneKilo = isNaN(calories) ? "0" : (calories + 1000).toFixed();
this.showResult = true;
}
calcCarb() {
this.equation = "0";
this.calcCalories();
this.carbResult.maintainWeight = (((this.carbPercentage / 100) * Number(this.caloriesResult.maintainWeight)) / 3.75).toFixed();
this.carbResult.lossHalfKilo = (((this.carbPercentage / 100) * Number(this.caloriesResult.lossHalfKilo)) / 3.75).toFixed();
this.carbResult.lossOneKilo = (((this.carbPercentage / 100) * Number(this.caloriesResult.lossOneKilo)) / 3.75).toFixed();
this.carbResult.gainHalfKilo = (((this.carbPercentage / 100) * Number(this.caloriesResult.gainHalfKilo)) / 3.75).toFixed();
this.carbResult.gainOneKilo = (((this.carbPercentage / 100) * Number(this.caloriesResult.gainOneKilo)) / 3.75).toFixed();
}
calcHealthyFats() {
this.equation = "0";
this.calcCalories();
this.healthyFatsResult.maintainWeight = (((20 / 100) * Number(this.caloriesResult.maintainWeight)) / 8.75).toFixed() + ' - ' + (((35 / 100) * Number(this.caloriesResult.maintainWeight)) / 8.75).toFixed();
this.healthyFatsResult.lossHalfKilo = (((20 / 100) * Number(this.caloriesResult.lossHalfKilo)) / 8.75).toFixed() + ' - ' + (((35 / 100) * Number(this.caloriesResult.lossHalfKilo)) / 8.75).toFixed();
this.healthyFatsResult.lossOneKilo = (((20 / 100) * Number(this.caloriesResult.lossOneKilo)) / 8.75).toFixed() + ' - ' + (((35 / 100) * Number(this.caloriesResult.lossOneKilo)) / 8.75).toFixed();
this.healthyFatsResult.gainHalfKilo = (((20 / 100) * Number(this.caloriesResult.gainHalfKilo)) / 8.75).toFixed() + ' - ' + (((35 / 100) * Number(this.caloriesResult.gainHalfKilo)) / 8.75).toFixed();
this.healthyFatsResult.gainOneKilo = (((20 / 100) * Number(this.caloriesResult.gainOneKilo)) / 8.75).toFixed() + ' - ' + (((35 / 100) * Number(this.caloriesResult.gainOneKilo)) / 8.75).toFixed();
}
calcProtein() {
this.equation = "0";
this.calcCalories();
this.proteinResult.maintainWeight = (1.2 * Number(this.weight)).toFixed();
this.proteinResult.gainWeight = (1.2 * Number(this.weight)).toFixed() + ' - ' + (1.6 * Number(this.weight)).toFixed();
this.proteinResult.lossWeight = (1.6 * Number(this.weight)).toFixed() + ' - ' + (2.2 * Number(this.weight)).toFixed();
this.showResult = true;
}
calcBodyFats() {
let fats = 0;
if (this.gender == "1") {
let femaleMeasure = Number(this.waist) + Number(this.hip) - Number(this.neck);
fats = (495 / (1.29579 - (0.35004 * Math.log10(femaleMeasure)) + (0.22100 * Math.log10(this.height)))) - 450;
}
else {
fats = (495 / (1.0324 - (0.19077 * Math.log10(this.waist - this.neck)) + (0.15456 * Math.log10(this.height)))) - 450;
}
if (isNaN(fats))
fats = 0;
this.bodyFatsResult.fatsPercentage = fats.toFixed(1) + '%';
this.bodyFatsResult.fatsKG = fats == 0 ? "0" : ((fats / 100) * this.weight).toFixed(1) + ' كجم ';
this.bodyFatsResult.notFatsKG = fats == 0 ? "0" : (this.weight - ((fats / 100) * this.weight)).toFixed(1) + ' كجم ';
let fatClass = "";
if (this.gender == "1") {
if (fats < 14)
fatClass = "دهون اساسية";
if (fats >= 14 && fats < 21)
fatClass = "رياضى محترف";
if (fats >= 21 && fats < 25)
fatClass = "فتنس";
if (fats >= 25 && fats < 32)
fatClass = "متوسط";
if (fats >= 32)
fatClass = "سمين";
} else {
if (fats < 6)
fatClass = "دهون اساسية";
if (fats >= 6 && fats < 14)
fatClass = "رياضى محترف";
if (fats >= 14 && fats < 18)
fatClass = "فتنس";
if (fats >= 18 && fats < 25)
fatClass = "متوسط";
if (fats >= 25)
fatClass = "سمين";
}
this.bodyFatsResult.fatClass = fats == 0 ? "غير مصنف" : fatClass;
this.showResult = true;
}
calcPerfectWeight() {
let miller = "0";
if (this.gender == "1") {
miller = (53.1 + (1.36 * ((this.height - 152) / 2.5))).toFixed();
} else {
miller = (56.2 + (1.41 * ((this.height - 152) / 2.5))).toFixed();
}
this.perfectWeightResult.miller = miller;
this.showResult = true;
}
}
export class caloriesResult {
maintainWeight: string;
lossHalfKilo: string;
lossOneKilo: string;
gainHalfKilo: string;
gainOneKilo: string;
}
export class carbResult {
maintainWeight: string;
lossHalfKilo: string;
lossOneKilo: string;
gainHalfKilo: string;
gainOneKilo: string;
}
export class healthyFatsResult {
maintainWeight: string;
lossHalfKilo: string;
lossOneKilo: string;
gainHalfKilo: string;
gainOneKilo: string;
}
export class proteinResult {
maintainWeight: string;
lossWeight: string;
gainWeight: string;
}
export class perfectWeightResult {
robinson: string;
hamwi: string;
miller: string;
devine: string;
healthyBMI: string;
}
export class bodyFatsResult {
fatsPercentage: string;
fatsKG: string;
notFatsKG: string;
fatClass: string;
}
|
e6e05d5366fea71cc0071f6cdbe6a7e09d092cfc
|
TypeScript
|
yiqu/recursion-ng-forms
|
/src/app/pipes.pipe.ts
| 2.5625
| 3
|
import {Pipe, PipeTransform} from '@angular/core';
@Pipe ({
name : 'labelName'
})
export class AnimalPipeDisplay implements PipeTransform {
transform(val : string) : string {
if (val === 'petName') {
return 'Pet Name';
}
return val;
}
}
|
18e86d2dcddd2f948daefea8a51fd29666912e4c
|
TypeScript
|
halloverden/norwegian-data-validators-ts
|
/src/validators/ssn-validator.ts
| 2.859375
| 3
|
import { getMod11ControlDigit } from '../utilities/mod11-utilities';
import { ssnFactors } from '../utilities/ssn-utilities';
export function validateSsn( ssn: string ): boolean {
if ( !ssn || ssn.length !== 11 ) {
return false;
}
let factorSum = 0;
for ( let i = 0; i < ssnFactors.length; i++ ) {
factorSum += parseInt( ssn.charAt( i ), 10 ) * ssnFactors[ i ];
}
let controlDigit1 = 11 - ( factorSum % 11 );
if ( controlDigit1 === 11 ) {
controlDigit1 = 0;
}
let controlDigit2 = getMod11ControlDigit( ssn.substr( 0, ssn.length - 1 ) );
return controlDigit1 === parseInt( ssn.charAt( 9 ), 10 )
&& controlDigit2 === parseInt( ssn.charAt( 10 ), 10 );
}
|
659a5406a2784bfb311162b620b937785ab467a0
|
TypeScript
|
Codaisseur/50-typescript-demo
|
/index.ts
| 4.03125
| 4
|
// function sum(a: number, b: number) {
// return a + b;
// }
// const c = sum(3, 4); //7
// console.log(c);
// function multiplyArrayByTen(array: number[]) {
// return array.map(element => (element *= 10));
// }
// const numbers = [1, 2, 3];
// const numbersMultipliedByTen = multiplyArrayByTen([]);
// console.log(numbersMultipliedByTen);
type Person = {
firstName: string;
lastName: string;
};
function fullName({ firstName, lastName }: Person) {
return firstName + lastName;
}
const firstName = "Dom";
const lastName = "Gemoli";
const allTheName = fullName({
firstName,
lastName,
});
console.log(allTheName);
|
333c70e3be47d2b5dfe9a2e6d194ca8fa53cdefc
|
TypeScript
|
willneedit/mixed-reality-extension-sdk
|
/packages/sdk/src/asset/material.ts
| 2.65625
| 3
|
/*!
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import {
Actor,
Animation,
AssetContainer,
AssetLike,
AssetUserType,
Color3,
Color3Like,
Color4,
Color4Like,
Guid,
Vector2,
Vector2Like,
ZeroGuid
} from '..';
import {
observe,
Patchable,
readPath
} from '../internal';
import { AssetInternal } from './assetInternal';
// break import cycle
import { Asset } from './asset';
/**
* Describes the properties of a Material.
*/
export interface MaterialLike {
/** The base color of this material. */
color: Partial<Color4Like>;
/** The main (albedo) texture asset ID */
mainTextureId: Guid;
/** The main texture's offset from default */
mainTextureOffset: Vector2Like;
/** The main texture's scale from default */
mainTextureScale: Vector2Like;
/** The lighting-independent color of this material. */
emissiveColor: Partial<Color3Like>;
/** The emissive (unlit) texture asset ID */
emissiveTextureId: Guid;
/** The emissive texture's offset from default */
emissiveTextureOffset: Vector2Like;
/** The emissive texture's scale from default */
emissiveTextureScale: Vector2Like;
/** How the color/texture's alpha channel should be handled */
alphaMode: AlphaMode;
/** Visibility threshold in masked alpha mode */
alphaCutoff: number;
}
/**
* Controls how transparency is handled.
*/
export enum AlphaMode {
/** The object is rendered opaque, and transparency info is discarded. */
Opaque = 'opaque',
/**
* Any parts with alpha above a certain cutoff ([[Material.alphaCutoff]])
* will be rendered solid. Everything else is fully transparent.
*/
Mask = 'mask',
/**
* A pixel's transparency is directly proportional to its alpha value.
*/
Blend = 'blend'
}
/**
* Represents a material on a mesh.
*/
export class Material extends Asset implements MaterialLike, Patchable<AssetLike> {
private _color = Color4.FromColor3(Color3.White(), 1.0);
private _mainTextureId = ZeroGuid;
private _mainTextureOffset = Vector2.Zero();
private _mainTextureScale = Vector2.One();
private _emissiveColor = Color3.Black();
private _emissiveTextureId = ZeroGuid;
private _emissiveTextureOffset = Vector2.Zero();
private _emissiveTextureScale = Vector2.One();
private _alphaMode = AlphaMode.Opaque;
private _alphaCutoff = 0.5;
private _internal = new AssetInternal(this);
/** @hidden */
public get internal() { return this._internal; }
/** @inheritdoc */
public get color() { return this._color; }
public set color(value) { if (value) { this._color.copy(value); } }
/** @returns A shared reference to this material's texture asset */
public get mainTexture() {
return this.container.context.internal.lookupAsset(this._mainTextureId)?.texture;
}
public set mainTexture(value) {
this.mainTextureId = value?.id ?? ZeroGuid;
}
/** @inheritdoc */
public get mainTextureId() { return this._mainTextureId; }
public set mainTextureId(value) {
if (!value) {
value = ZeroGuid;
}
if (!this.container.context.internal.lookupAsset(value)) {
value = ZeroGuid; // throw?
}
if (value === this._mainTextureId) { return; }
if (this.mainTexture) {
this.mainTexture.clearReference(this);
}
this._mainTextureId = value;
if (this.mainTexture) {
this.mainTexture.addReference(this);
}
this.materialChanged('mainTextureId');
}
/** @inheritdoc */
public get mainTextureOffset() { return this._mainTextureOffset; }
public set mainTextureOffset(value) { if (value) { this._mainTextureOffset.copy(value); } }
/** @inheritdoc */
public get mainTextureScale() { return this._mainTextureScale; }
public set mainTextureScale(value) { if (value) { this._mainTextureScale.copy(value); } }
/** @inheritdoc */
public get emissiveColor() { return this._emissiveColor; }
public set emissiveColor(value) { if (value) { this._emissiveColor.copy(value); } }
/** @returns A shared reference to this material's texture asset */
public get emissiveTexture() {
return this.container.context.internal.lookupAsset(this._emissiveTextureId)?.texture;
}
public set emissiveTexture(value) {
this.emissiveTextureId = value?.id ?? ZeroGuid;
}
/** @inheritdoc */
public get emissiveTextureId() { return this._emissiveTextureId; }
public set emissiveTextureId(value) {
if (!value) {
value = ZeroGuid;
}
if (!this.container.context.internal.lookupAsset(value)) {
value = ZeroGuid; // throw?
}
if (value === this._emissiveTextureId) { return; }
if (this.emissiveTexture) {
this.emissiveTexture.clearReference(this);
}
this._emissiveTextureId = value;
if (this.emissiveTexture) {
this.emissiveTexture.addReference(this);
}
this.materialChanged('emissiveTextureId');
}
/** @inheritdoc */
public get emissiveTextureOffset() { return this._emissiveTextureOffset; }
public set emissiveTextureOffset(value) { if (value) { this._emissiveTextureOffset.copy(value); } }
/** @inheritdoc */
public get emissiveTextureScale() { return this._emissiveTextureScale; }
public set emissiveTextureScale(value) { if (value) { this._emissiveTextureScale.copy(value); } }
/** @inheritdoc */
public get alphaMode() { return this._alphaMode; }
public set alphaMode(value) { this._alphaMode = value; this.materialChanged('alphaMode'); }
/** @inheritdoc */
public get alphaCutoff() { return this._alphaCutoff; }
public set alphaCutoff(value) { this._alphaCutoff = value; this.materialChanged('alphaCutoff'); }
/** @inheritdoc */
public get material(): Material { return this; }
/** The list of animations that target this actor, by ID. */
/* public get targetingAnimations() {
return this.container.context.animations
.filter(anim => anim.targetIds.includes(this.id))
.reduce(
(map, anim) => {
map.set(anim.id, anim);
return map;
},
new Map<Guid, Animation>()
) as ReadonlyMap<Guid, Animation>;
}*/
/** The list of animations that target this actor, by name. */
/* public get targetingAnimationsByName() {
return this.container.context.animations
.filter(anim => anim.targetIds.includes(this.id) && anim.name)
.reduce(
(map, anim) => {
map.set(anim.name, anim);
return map;
},
new Map<string, Animation>()
) as ReadonlyMap<string, Animation>;
}*/
/** INTERNAL USE ONLY. To create a new material from scratch, use [[AssetManager.createMaterial]]. */
public constructor(container: AssetContainer, def: AssetLike) {
super(container, def);
if (!def.material) {
throw new Error("Cannot construct material from non-material definition");
}
this.copy(def);
// material patching: observe the nested material properties
// for changed values, and write them to a patch
observe({
target: this._color,
targetName: 'color',
notifyChanged: (...path: string[]) => this.materialChanged(...path)
});
observe({
target: this._mainTextureOffset,
targetName: 'mainTextureOffset',
notifyChanged: (...path: string[]) => this.materialChanged(...path)
});
observe({
target: this._mainTextureScale,
targetName: 'mainTextureScale',
notifyChanged: (...path: string[]) => this.materialChanged(...path)
});
observe({
target: this._emissiveColor,
targetName: 'emissiveColor',
notifyChanged: (...path: string[]) => this.materialChanged(...path)
});
observe({
target: this._emissiveTextureOffset,
targetName: 'emissiveTextureOffset',
notifyChanged: (...path: string[]) => this.materialChanged(...path)
});
observe({
target: this._emissiveTextureScale,
targetName: 'emissiveTextureScale',
notifyChanged: (...path: string[]) => this.materialChanged(...path)
});
}
public copy(from: Partial<AssetLike>): this {
if (!from) {
return this;
}
// Pause change detection while we copy the values into the actor.
const wasObserving = this.internal.observing;
this.internal.observing = false;
super.copy(from);
if (from.material) {
if (from.material.color) {
this.color.copy(from.material.color);
}
if (from.material.mainTextureOffset) {
this.mainTextureOffset.copy(from.material.mainTextureOffset);
}
if (from.material.mainTextureScale) {
this.mainTextureScale.copy(from.material.mainTextureScale);
}
if (from.material.mainTextureId) {
this.mainTextureId = from.material.mainTextureId;
}
if (from.material.emissiveColor) {
this.emissiveColor.copy(from.material.emissiveColor);
}
if (from.material.emissiveTextureOffset) {
this.emissiveTextureOffset.copy(from.material.emissiveTextureOffset);
}
if (from.material.emissiveTextureScale) {
this.emissiveTextureScale.copy(from.material.emissiveTextureScale);
}
if (from.material.emissiveTextureId) {
this.emissiveTextureId = from.material.emissiveTextureId;
}
if (from.material.alphaMode) {
this.alphaMode = from.material.alphaMode;
}
if (from.material.alphaCutoff) {
this.alphaCutoff = from.material.alphaCutoff;
}
}
this.internal.observing = wasObserving;
return this;
}
/** @hidden */
public toJSON(): AssetLike {
return {
...super.toJSON(),
material: {
color: this.color.toJSON(),
mainTextureId: this.mainTextureId,
mainTextureOffset: this.mainTextureOffset.toJSON(),
mainTextureScale: this.mainTextureScale.toJSON(),
emissiveColor: this.emissiveColor.toJSON(),
emissiveTextureId: this.emissiveTextureId,
emissiveTextureOffset: this.emissiveTextureOffset.toJSON(),
emissiveTextureScale: this.emissiveTextureScale.toJSON(),
alphaMode: this.alphaMode,
alphaCutoff: this.alphaCutoff
}
};
}
private materialChanged(...path: string[]): void {
if (this.internal.observing) {
this.container.context.internal.incrementGeneration();
this.internal.patch = this.internal.patch || { material: {} } as AssetLike;
readPath(this, this.internal.patch.material, ...path);
}
}
/** @hidden */
public breakReference(ref: AssetUserType) {
if (ref instanceof Actor && ref.appearance.material === this) {
ref.appearance.material = null;
} else if (ref instanceof Animation && ref.isOrphan()) {
ref.delete();
}
}
}
|
638eaf8354f16552549e68b4432460c6f4162394
|
TypeScript
|
RobertoWeegeJr/RubiksCube
|
/scr/Face.ts
| 3.0625
| 3
|
import { Color, Position } from "./Enumerations";
export class Face3x3 {
private _dimension: number;
public get dimension(): number {
return this._dimension;
}
public set dimension(value: number) {
this._dimension = value;
}
private _face: Color[][];
public get face(): Color[][] {
return this._face;
}
public set face(value: Color[][]) {
if (!value) {
throw new Error("Face is required");
}
this._face = value;
}
private _adjacentFaces: Map<Position, Face3x3>;
public get adjacentFaces(): Map<Position, Face3x3> {
return this._adjacentFaces;
}
public set adjacentFaces(value: Map<Position, Face3x3>) {
this._adjacentFaces = value;
}
private _positionAdjacentFaces: Map<Position, Position>;
public get positionAdjacentFaces(): Map<Position, Position> {
return this._positionAdjacentFaces;
}
public set positionAdjacentFaces(value: Map<Position, Position>) {
this._positionAdjacentFaces = value;
}
constructor(color: Color) {
if (!color) {
throw new Error("Color is required");
}
this.dimension = 3;
this.face = []
this.adjacentFaces = new Map();
this.positionAdjacentFaces = new Map();
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.face[i][j] = color;
}
}
}
}
|
ef5949d297cbbb01f975e3f2768d308ad46cab67
|
TypeScript
|
salieri/tartarus-data
|
/src/task/spider/navigator/navigator.ts
| 2.6875
| 3
|
import _ from 'lodash';
import { promisify } from 'util';
import { SpiderHandle } from '../handle';
import { LogLevel } from '../../task';
const wait = promisify(setTimeout);
export type SpiderNavigatorUrlCallback = (h: SpiderHandle) => string | null;
export type SpiderNavigatorIsDoneCallback = (h: SpiderHandle) => boolean;
export interface SpiderNavigatorOpts {
baseTarget: string;
target: SpiderNavigatorUrlCallback | string;
isDone?: SpiderNavigatorIsDoneCallback;
}
export interface SpiderNavigatorFetchResponse {
rawData: string;
rawResponse: any;
}
export abstract class SpiderNavigator {
protected opts: SpiderNavigatorOpts;
public constructor(opts: SpiderNavigatorOpts) {
this.opts = opts;
}
protected abstract fetch(target: string, h: SpiderHandle): Promise<SpiderNavigatorFetchResponse>;
public getBaseTarget(): string {
return this.opts.baseTarget;
}
protected getNext(previousHandle: SpiderHandle): string | null {
if (typeof this.opts.target === 'string') {
return this.opts.target;
}
return this.opts.target(previousHandle);
}
public isDone(h: SpiderHandle): boolean {
if (this.opts.isDone) {
return this.opts.isDone(h);
}
const response = h.getResponseData();
if (!response) {
return true;
}
const data = response.data;
return ((_.isEmpty(data)) || (!_.isArray(data)) || (data.length < 1));
}
public async attemptFetch(previousHandle: SpiderHandle, iteration: number): Promise<SpiderHandle | null> {
const target = await this.getNext(previousHandle);
const siteConfig = previousHandle.getSiteConfig();
if (!target) {
return null;
}
const spider = previousHandle.getSpider();
/* eslint-disable no-await-in-loop */
for (let i = 0; i < siteConfig.behavior.maxRetries; i += 1) {
const response = await this.fetch(target, previousHandle); // this throws SkippableError, so don't catch it here
try {
const data = await spider.getData().parse(response.rawData);
return new SpiderHandle(
spider,
iteration,
response,
data,
);
} catch (err) {
previousHandle.getSpider().report(
LogLevel.Error,
`Data parsing failed while trying to fetch ${target}`,
err.message,
);
previousHandle.getSpider().report(
LogLevel.Debug,
'Data parsing failure RAW DATA ===>',
response.rawData,
'<=== RAW DATA',
'RAW RESPONSE ===>',
response.rawResponse,
'<=== RAW RESPONSE',
);
if (i >= siteConfig.behavior.maxRetries - 1) {
throw err;
} else {
await this.pause(siteConfig.behavior.retryDelay);
}
}
}
// never reached
return null;
}
public async pause(lengthInMs: number): Promise<void> {
await wait(lengthInMs);
}
}
|
f7154db3d22d1b4c9c75f3e97fbce9deda1f2b17
|
TypeScript
|
wcc17/apple-music-share-server
|
/src/service/room-service.ts
| 2.765625
| 3
|
import { JSDictionary } from '../util/dictionary';
import { Song } from '../model/song';
import { User } from '../model/user';
export class RoomService {
private roomQueues: JSDictionary<string, Song[]>;
private roomUsers: JSDictionary<string, User[]>;
private roomVotesToSkipDict: JSDictionary<string, number>;
private roomId: number;
constructor() {
this.roomQueues = new JSDictionary<string, Song[]>();
this.roomUsers = new JSDictionary<string, User[]>();
this.roomVotesToSkipDict = new JSDictionary<string, number>();
this.roomId = 100000;
}
public addRoom(roomId: string): void {
this.roomQueues.put(roomId.toString(), []);
}
public addSongToQueue(roomId: string, song: Song) {
song.orderInQueue = this.getOrderInQueue(roomId, song);
this.addObjectToQueue(roomId, song, this.roomQueues);
}
public addUserToRoom(socket: any, roomId: string, user: User) {
socket.join(roomId);
this.addObjectToQueue(roomId, user, this.roomUsers);
}
public getRoomQueue(roomId: string): Song[] {
return this.roomQueues.get(roomId.toString());
}
public getRoomVotesToSkip(roomId: string): number {
return this.roomVotesToSkipDict.get(roomId.toString());
}
public setRoomQueue(roomId: string, queue: Song[]): void {
this.roomQueues.put(roomId.toString(), queue);
}
public getRoomUsers(roomId: string): User[] {
let users: User[] = this.roomUsers.get(roomId.toString());
if(users) {
return users;
} else {
return [];
}
}
public getUserFromRoom(roomId: string, userId: number): User {
let users: User[] = this.getRoomUsers(roomId);
for(let user of users) {
if(user.getId() === userId) {
return user;
}
}
return null;
}
public getLeaderFromRoom(roomId: string): User {
let users: User[] = this.getRoomUsers(roomId);
for(let user of users) {
if(user.getIsLeader()) {
return user;
}
}
return null;
}
public promoteUserToLeaderInRoom(newLeaderUser: User, roomId: string): void {
let users: User[] = this.getRoomUsers(roomId);
users.forEach((user, index) => {
if(newLeaderUser.getId() === user.getId()) {
users[index].setIsLeader(true);
}
});
}
//TODO: need to do this in a way that old roomIds can be re-used without restarting the whole server
//TODO: this is stupid right
public getNextRoomId(io: any): number {
this.roomId++;
while(this.checkExistingRoom(io, this.roomId)) {
this.roomId++;
}
return this.roomId;
}
public checkExistingRoom(io: any, roomId: number): boolean {
let rooms: any[] = this.getSocketRooms(io);
if(roomId && rooms[roomId]) {
return true;
}
return false;
}
public removeUserFromRoom(userId: number, roomId: number): void {
let users: User[] = this.getRoomUsers(roomId.toString());
var i = users.length;
while(i--) {
if(users[i].getId() === userId) {
users.splice(i, 1);
break;
}
}
}
public removeSongFromQueue(roomId: string, song: Song): boolean {
if(this.roomQueues.get(roomId)) {
let queue: Song[] = this.roomQueues.get(roomId);
let requestingUser: User = new User(song.requestedBy);
var i = queue.length;
while(i--) {
let userToMatch: User = new User(queue[i].requestedBy);
if(requestingUser.getId() === userToMatch.getId()
&& song.id === queue[i].id
&& song.orderInQueue === queue[i].orderInQueue) {
queue.splice(i, 1);
this.fixQueueOrder(roomId); //only fix the queue order if a song was actually removed
return true;
}
}
}
return false;
}
public handleDisconnectedUser(io: any, socket: any, user: User, roomId: number): User {
let roomExists: boolean = this.checkExistingRoom(io, roomId);
if(roomExists) {
user.setIsLeader(false);
} else {
user.setIsLeader(true);
this.addRoom(roomId.toString());
}
this.addUserToRoom(socket, roomId.toString(), user);
return user;
}
public incrementVoteCount(roomId: string, user: User): number {
this.setVoteCountForRoom(roomId, this.getRoomVotesToSkip(roomId)+1);
this.setUserHasVotedForRoom(user, roomId);
return this.getRoomVotesToSkip(roomId);
}
public resetVoteCount(roomId: string): void {
this.setVoteCountForRoom(roomId, 0);
this.resetUserHasVotedForAllUsersInRoom(roomId);
}
public getRoomUserCount(roomId: string): number {
return this.getRoomUsers(roomId).length;
}
private setVoteCountForRoom(roomId: string, newVoteCount: number): void {
this.roomVotesToSkipDict.put(roomId, newVoteCount);
}
private setUserHasVotedForRoom(userThatVoted: User, roomId: string) {
let users: User[] = this.getRoomUsers(roomId);
users.forEach((user, index) => {
if(userThatVoted.getId() === user.getId()) {
users[index].setHasVotedForCurrentSong(true);
}
});
}
private resetUserHasVotedForAllUsersInRoom(roomId: string) {
let users: User[] = this.getRoomUsers(roomId);
users.forEach((user, index) => {
users[index].setHasVotedForCurrentSong(false);
});
}
private getOrderInQueue(roomId: string, song: Song): number {
let roomQueue = this.getRoomQueue(roomId);
if(roomQueue) {
return this.getRoomQueue(roomId).length;
} else {
return 0;
}
}
private fixQueueOrder(roomId: string): void {
let queue: Song[] = this.roomQueues.get(roomId);
if(queue) {
let i: number = 0;
for(let song of queue) {
song.orderInQueue = i;
i++;
}
}
}
private addObjectToQueue(key: string, obj: any, queue: JSDictionary<string, any[]>): void {
if(queue.get(key)) {
let arr: any[] = queue.get(key);
if(arr) {
arr.push(obj);
} else {
arr = [obj];
}
queue.put(key, arr);
} else {
queue.put(key, [ obj ]);
}
}
private getSocketRooms(io: any): any {
return io.sockets.adapter.rooms;
}
}
|
364e8569bf79f71e64c538c898618e037e66e701
|
TypeScript
|
ess-dmsc/user-office-frontend
|
/src/hooks/call/useCallsData.ts
| 2.5625
| 3
|
import { useEffect, useState } from 'react';
import { Call, CallsFilter } from 'generated/sdk';
import { useDataApi } from 'hooks/common/useDataApi';
export function useCallsData(filter?: CallsFilter) {
const [callsFilter, setCallsFilter] = useState(filter);
const [callsData, setCallsData] = useState<Call[]>([]);
const [loadingCalls, setLoadingCalls] = useState(true);
const api = useDataApi();
useEffect(() => {
api()
.getCalls({ filter: callsFilter })
.then(data => {
if (data.calls) {
setCallsData(data.calls);
}
setLoadingCalls(false);
});
}, [api, callsFilter]);
return { loadingCalls, callsData, setCallsData, setCallsFilter };
}
|
9cb867f407eb21c113aa0b5a2cfdbf5837f56a98
|
TypeScript
|
Yurii19/rtsbt-raw
|
/src/reducers/articlesReducer.ts
| 2.984375
| 3
|
const GET_ARTICLES = "GET_ARTICLES";
export const UPDATE_ARTICLES = "UPDATE_ARTICLES";
export const SELECT_ARTICLE = "SELECT_ARTICLE";
export interface IAction {
type: string;
payload: object;
}
const initialState = {
articles: [],
articlesSelected: null
};
function articlesReducer(state = initialState, action: IAction) {
switch (action.type) {
case SELECT_ARTICLE:
return state;
case GET_ARTICLES:
return state;
case UPDATE_ARTICLES:
return { articles: action.payload };
default:
return state;
}
}
interface IPayload { articles: [] }
export const getArticles = () => ({ type: GET_ARTICLES });
export const updateArticles = (payload: IPayload) => ({ type: UPDATE_ARTICLES, payload });
export const selectArticle = (payload: number) => ({ type: SELECT_ARTICLE, payload });
export default articlesReducer;
|
cd94ddad5300198d5e266897d227465f8e8b1e87
|
TypeScript
|
Sasuke1374/ghostybot
|
/src/commands/util/uptime.ts
| 2.84375
| 3
|
import { Message } from "discord.js";
import dayJs from "dayjs";
import duration from "dayjs/plugin/duration";
import Command from "structures/Command";
import Bot from "structures/Bot";
dayJs.extend(duration);
export default class UptimeCommand extends Command {
constructor(bot: Bot) {
super(bot, {
name: "uptime",
description: "Returns the uptime of the bot",
category: "util",
aliases: ["up"],
});
}
async execute(message: Message) {
const lang = await this.bot.utils.getGuildLang(message.guild?.id);
const uptime = dayJs
.duration(this.bot?.uptime ?? 0)
.format(" D [days], H [hrs], m [mins], s [secs]");
return message.channel.send({
content: lang.UTIL.UPTIME.replace("{member}", `${this.bot.user?.username}`).replace(
"{time}",
uptime,
),
});
}
}
|
984338fe08eb16de6309bd42a4b6a3d0660c8047
|
TypeScript
|
kreo/parsers
|
/types/tokens/Border.ts
| 2.6875
| 3
|
import Token, { TokenInterface } from './Token';
import { ColorToken, ColorValue } from './Color';
import { MeasurementToken, MeasurementValue } from './Measurement';
import { TokensType } from './index';
export interface BorderValue {
color:
| ColorToken
| {
value: ColorValue;
};
type:
| 'none'
| 'hidden'
| 'dotted'
| 'dashed'
| 'solid'
| 'double'
| 'groove'
| 'ridge'
| 'inset'
| 'outset';
width:
| MeasurementToken
| {
value: MeasurementValue;
};
align?: string;
radii?:
| MeasurementToken
| {
value: MeasurementValue;
};
rectangleCornerRadii?: Array<
| MeasurementToken
| {
value: MeasurementValue;
}
>;
dashes?: Array<
| MeasurementToken
| {
value: MeasurementValue;
}
>;
}
export class BorderToken extends Token implements TokenInterface {
type: TokensType = 'border';
value: BorderValue;
constructor(element: Partial<BorderToken>) {
super(element);
this.value = element.value!;
}
}
|
50ee826a39ab1656da7925148da6f771b092e322
|
TypeScript
|
turkaytunc/pelp
|
/frontend/src/context/reducers/userReducer.ts
| 2.71875
| 3
|
import { User } from '../../interfaces';
import { UserAction } from '../actions/UserAction';
export const userReducer = (state: User, action: UserAction): User => {
switch (action.type) {
case 'ADD_USER': {
return action.payload as User;
}
default:
return state;
}
};
|
d92e1171afc558d3e85e276538d49ca07c8ba90a
|
TypeScript
|
nbelleme/hvsz-web
|
/src/app/foodsupply/food-supply.ts
| 2.515625
| 3
|
/**
* Created by nicolas on 05/05/2017.
*/
export class FoodSupply {
private _id: number;
public _level: number;
private _capacity: number;
private _name: string;
get id(): number {
return this._id;
}
set id(value: number) {
this._id = value;
}
get level(): number {
return this._level;
}
set level(value: number) {
this._level = value;
}
get capacity(): number {
return this._capacity;
}
set capacity(value: number) {
this._capacity = value;
}
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value;
}
}
|
3169d7ebbd7a08722f88ab9de1482c9720c708d0
|
TypeScript
|
ElBureeto/Capstone2
|
/capstone2/src/app/balance/balance.component.ts
| 2.609375
| 3
|
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../services/api/api.service';
import { NgxSpinnerService } from "ngx-spinner";
export class CircuitData {
circuit1: number[][] = [];
circuit2: number[][] = [];
circuitUsage: number[] = [0.0, 0.0];
}
@Component({
selector: 'app-balance',
templateUrl: './balance.component.html',
styleUrls: ['./balance.component.css']
})
export class BalanceComponent implements OnInit {
data: CircuitData;
savings: number = 0.0;
balanced: boolean = false;
constructor(
private api: ApiService,
private spinner: NgxSpinnerService
) { }
ngOnInit() {
this.data = new CircuitData();
this.getSensors();
}
getSensors(): void {
this.spinner.show();
this.api.getSensors().subscribe(res => {
this.spinner.hide();
res = Object.values(res);
let id: number = 1;
let sensors: number[][] = res.map(function (value) {
return [id++, parseFloat(parseFloat(value).toPrecision(3))];
});
// this.data.circuit1 = sensors.slice(0, sensors.length/2);
// this.data.circuit2 = sensors.slice(sensors.length/2, sensors.length);
for (var i=0; i<sensors.length/2; i++) {
this.data.circuit1.push(sensors[i*2]);
this.data.circuit2.push(sensors[(i*2)+1]);
}
this.calculateCircuitUsage(this.data);
this.savings = this.calculateSavings(this.data);
});
}
calculateCircuitUsage(data: CircuitData) {
for (var i = 0; i < data.circuit1.length; i++) {
data.circuitUsage[0] += data.circuit1[i][1];
}
for (var i = 0; i < data.circuit2.length; i++) {
data.circuitUsage[1] += data.circuit2[i][1];
}
}
calculateSavings(data: CircuitData): number {
let tempData: CircuitData = JSON.parse(JSON.stringify(data));
this.balanceSensors(tempData);
tempData.circuitUsage = [0.0, 0.0];
this.calculateCircuitUsage(tempData);
return Math.abs(data.circuitUsage[0] - data.circuitUsage[1]) - Math.abs(tempData.circuitUsage[0] - tempData.circuitUsage[1]);
}
colorSensor(sensor: number): number {
if (sensor >= 0 && sensor <= 5) return 0;
else if (sensor > 5 && sensor <= 15) return 1;
else return 2;
}
balanceSensors(data: CircuitData): CircuitData {
let sensors = data.circuit1.concat(data.circuit2);
sensors.sort(function (a, b) { return b[1] > a[1] ? 1 : -1 });
let tempCircuit1 = [];
let tempCircuit2 = [];
let tempCircuitUsage = [0.0, 0.0];
for (var i = 0; i < 10; i++) {
if (tempCircuitUsage[0] > tempCircuitUsage[1]) {
tempCircuitUsage[1] += sensors[i][1];
tempCircuit2.push(sensors[i]);
}
else {
tempCircuitUsage[0] += sensors[i][1];
tempCircuit1.push(sensors[i]);
}
}
data.circuit1 = tempCircuit1;
data.circuit2 = tempCircuit2;
data.circuitUsage = tempCircuitUsage;
this.savings = 0;
return data;
}
}
|
beb9df0610223fc98adc99a9b248f6470b3a59a6
|
TypeScript
|
tabb-global/js-service-common
|
/src/exceptions/LoggableExceptionFilter.ts
| 2.703125
| 3
|
import { Request } from 'express';
import { LoggerService } from '../logging/LoggerService';
export class LoggableExceptionFilter {
public constructor(
protected readonly logger: LoggerService,
) {
}
protected log(e: any, r: Request, defaultLevel?: string) {
let message;
let level;
let other;
//Parse message
if (!e.message && !e.name)
message = 'Unknown Exception';
else if (typeof e.message === 'string' || e.message instanceof String)
message = e.message;
else if (e.name)
message = e.name;
else if (e.message.errorObject)
message = e.message.errorObject.message;
else if (e.message.message && (typeof e.message.message === 'string' || e.message.message instanceof String))
message = e.message.message;
//Parse level
if (e.message && e.message instanceof Object && e.message.level)
level = e.message.level;
else
level = defaultLevel || 'error';
if (e.message && e.message instanceof Object && e.message.other)
other = e.message.other;
this.logger.mainLog(message, level, r, e, other);
}
}
|
9a7e6beb63f5e847149a81503da6e9c2d004ed31
|
TypeScript
|
sondregj/hitori
|
/src/utils.ts
| 2.71875
| 3
|
import { IHitoriColumn, IHitoriRow } from './types'
export function transposeBoard(
board: IHitoriRow[] | IHitoriColumn[],
): IHitoriRow[] | IHitoriColumn[] {
return board[0].cells.map((col, i) => ({
cells: board.map(row => row.cells[i]),
}))
}
|
743caca553846c1098be506559c1384b8c24532d
|
TypeScript
|
majidakhter/AngularMVCMicroservices
|
/AromaCareGlow.Commerce.Web.AngularMVC1.1/wwwroot/app/legacy_V1/src/app/shared/date-formats/date-formats.ts
| 3.359375
| 3
|
import * as moment from 'moment';
export class DateFormats {
constructor() {
this.DATE_MONTH_DAY = DateFormats.determineMonthDayFormat(moment.localeData().longDateFormat('ll'));
}
/**
* Date format that moment.js uses by Default, which happens to be a date time offset value.
* Example: 02/03/2018 08:05PM CST => 2018-02-03T20:05:00-06:00
*/
public readonly DEFAULT: string = '';
/**
* Date format used specifically when formatting dates that will be part of a URL. Our APIs require this format
* and should NOT include the time component.
* Example: 02/03/2018 => 2018-02-03
*/
public readonly URL_DATE: string = 'YYYY-MM-DD';
/**
* Date format that returns just the Day of Month part of the date.
* Example: 02/03/2018 => 3
*/
public readonly DAY_OF_MONTH: string = 'D';
/**
* Date format that returns just the Day of Week part of the date in medium format.
* Example: 02/03/2018 => Sat
*/
public readonly DAY_OF_WEEK_MEDIUM: string = 'ddd';
/**
* Date format that returns just the Day of Week part of the date in short format.
* Example: 02/03/2018 => Sa
*/
public readonly DAY_OF_WEEK_SHORT: string = 'dd';
/**
* Date format that returns the year (in YYYY format).
* Example: 02/03/2018 => 2018
*/
public readonly YEAR: string = 'YYYY';
/**
* Date format that returns just the time part of the date in 24 hour format.
* Example: 02/03/2018 3:00PM => 15:00
*/
public readonly TIME_24HOUR_SHORT: string = 'HH:mm';
/**
* Date format that returns just the AM/PM time part of the date.
* Example: 02/03/2018 3:00PM => PM
*/
public readonly TIME_AMPM: string = 'A';
/**
* Date format that returns the date part only, zero padded single digits. This format
* is fully localized using moment's built-in 'L' format.
* Example: 2/3/2018 3:00PM => 02/03/2018
*/
public readonly DATE_SHORT: string = 'L';
/**
* Date format string that specifies only the month text in 3 characters.
* Example: Jun
*/
public readonly MONTH_SHORT: string = 'MMM';
/**
* Date format that returns the month (in long form) and year joined together. This format is not
* localized fully as it assumes US order.
* Example: 02/03/2018 => Feburary 2018
*/
public readonly DATE_MONTH_YEAR: string = 'MMMM YYYY';
/**
* Date format that returns the month (in short form) and day of month joined together. This format
* is fully localized using moment's built-in 'll' format.
* Example: 02/03/2018 => Feb 3
*/
public readonly DATE_MONTH_DAY: string = '';
/**
* Date format that returns the month (in short form), day of month and year joined together. This format
* is fully localized using moment's built-in 'll' format.
* Example: 02/03/2018 => Feb 3, 2018
*/
public readonly DATE_MONTH_DAY_YEAR: string = 'll';
/**
* Date format that returns the day of the week(in short form), month (in short form), day of month and year joined together.
* This format is fully localized using moment's built-in 'll' format.
* Example: 02/03/2018 => Sat Feb 3, 2018
*/
public readonly DATE_DAY_MONTH_DATE_YEAR: string = 'ddd ll';
/**
* Date format that returns the Day of Week (medium form) with Day of Month joined together. This format is not
* localized fully as it assumes US order.
* Example: 02/03/2018 => Sat 3
*/
public readonly DATE_DAY_OF_WEEK_DAY_OF_MONTH: string = `${this.DAY_OF_WEEK_MEDIUM} ${this.DAY_OF_MONTH}`;
/**
* Date format that returns the Day of Week (medium form) with the long date format. This format
* is not fully localized because it assumes US order and punctuation.
* Example: Tue Apr 10, 2018
*/
public readonly DAY_OF_WEEK_LONG_DATE: string = `${this.DAY_OF_WEEK_MEDIUM} ${this.DATE_MONTH_DAY_YEAR}`;
/**
* Date format that specifies a ISO 8601 Date string, with the date and time, but no timezone or offset
* Example: YYYY-MM-DDTHH:mm:ss.SSS
*/
public readonly ISO_8601: string = 'YYYY-MM-DDTHH:mm:ss.SSS';
/**
* Date format string that specifies the Date only portion of an ISO date string.
* Example: 2018-07-24
*/
public readonly ISO_DATE: string = 'YYYY-MM-DD';
/**
* Determines the localized format for what would be 'MMM D' in the 'en' locale. Unfortunately, moment does not have a direct
* long date format for this particular situation (see https:// github.com/moment/moment/issues/3341). This method will take the
* closest existing long date format (ll) and strip the year part off, accounting for when the YYYY part is in the beginning or
* end of the format.
*/
static determineMonthDayFormat(format: string): string {
if (format.indexOf('YYYY') === 0) {
// In some locales, the Year is presented first, along with various punctuation (period, comma) as well as sometimes
// hard coded words in brackets. The RegEx below strips everything off that shouldn't be there related to the YYYY prefix.
return format.replace(/YYYY(\.)?(\s)?(\[([^\x00-\x7F]|\w)+\])?(\s)?/gi, '');
}
// In other locales, the year is presented at the end (or almost end). It can have various punctuation around it as well
// as hard coded words in brackets. The RegEx below strips everything off that shouldn't be there related to the YYYY suffix.
return format.replace(/(\s)?,?(\[([^\x00-\x7F]|\w)+\])?(\s)?YYYY.*/gi, '');
}
public dayMonthDateFormat(format: string): string{
return (moment(format).format('ddd MMM DD'));
}
public yearMonthDateFormat(format: string): string{
return moment(format).format('YYYY-MM-DD');
}
public hoursMinutesFormat(format: string): string{
return moment(format, 'HH:mm:ss').format('HH:mm');
}
}
|
a3bc3409707eab28670b155ae6eee2452a0d4f16
|
TypeScript
|
kevin-litthub/vax-dist-app
|
/notaryAPI/src/routers/notary.router.ts
| 2.625
| 3
|
import { Request, Response, Router } from 'express';
import { connection } from '..';
import Event from '../entities/event.entity';
import { v4 as uuid } from 'uuid';
import createEvent from '../utils/helperFunctions';
import { isNil } from 'ramda';
const router = Router();
router.post('/event', async (req: Request, res: Response) => {
const token = await req.headers['authorization']?.split(' ')[1];
console.log('req.body => ', req.body);
const hash = await req.body.hash;
console.log('hash => ', hash);
if (hash && token) {
const { event, savedEvent } = await createAndSaveEvent(hash, token);
res.status(200).send({
id: event.id,
hash: hash,
nonce: savedEvent?.nonce,
timestamp: event.timestamp,
});
}
if (hash === null && !isNil(token)) {
try {
const { event, savedEvent } = await createAndSaveEvent(hash, token);
res.status(200).send({ id: event.id, timestamp: savedEvent?.timestamp });
} catch (err) {
console.log('error => ', err);
}
}
});
router.get('/event/:id', async (req: Request, res: Response) => {
const id = req.params.id;
if (id) {
try {
const event = await connection.manager.findOne(Event, { id: id });
res.status(200).send({ id: event?.id, hash: event?.hash, nonce: event?.nonce, timestamp: event?.timestamp });
} catch (error) {
console.log(`The hash ${id} was not stored ${error}`);
}
}
});
export default router;
async function createAndSaveEvent(hash: string | null, token: string) {
const id = uuid();
const event = createEvent(hash, id, token);
await connection.manager.save(event);
const savedEvent = await connection.manager.findOne(Event, { id: id });
return { event, savedEvent };
}
|
19726c49592183eab7c286a71a94ad4311667b36
|
TypeScript
|
VincentVen/Framing
|
/src2/modules/games/public/CardLogic.ts
| 3.296875
| 3
|
/**
* 全局模块-牌型判断逻辑
* @author none
*
*/
class CardLogic {
public constructor() {
}
/** 花色掩码 **/
public MASK_COLOR: number = 0xF0;
/** 数值掩码 **/
public MASK_VALUE: number = 0x0F;
/** 扑克数据 **/
public cardDataArray: number[] =
[
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, //方块 A - K
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, //梅花 A - K
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, //红桃 A - K
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, //黑桃 A - K
0x4E, 0x4F,//大小鬼
];
/** 获取数值 **/
public getCardValue(cardData: number): number {
return (cardData & this.MASK_VALUE);
}
/** 获取花色 **/
public getCardColor(cardData: number): number {
return (cardData & this.MASK_COLOR) / 16;
}
/** 根据值获取牌数据 **/
public getCardByValue(cardData: number[], cardValue: number): number {
for (var i: number = 0; i < cardData.length; i++) {
if (this.getCardValue(cardData[i]) == cardValue) {
return cardData[i];
}
}
return 0;
}
/** 根据数值排序,从大到小 **/
public SortByValue(cardData: number[]): void {
var self: CardLogic = this;
cardData.sort((left, right) => {
if (self.getCardValue(left) > self.getCardValue(right)) {
return -1;
}
else if (self.getCardValue(left) < self.getCardValue(right)) {
return 1;
}
else {
return 0;
}
});
}
/** 根据花色排序,从大到小 **/
public SortByColor(cardData: number[]): void {
var self: CardLogic = this;
cardData.sort((left, right) => {
if (self.getCardColor(left) > self.getCardColor(right)) {
return -1;
}
else if (self.getCardColor(left) < self.getCardColor(right)) {
return 1;
}
else {
return 0;
}
});
}
}
|
164967598a636da12d270002eebd036035055426
|
TypeScript
|
ngjunxiang/Node-TypeScript-Template
|
/src/controllers/AuthController.ts
| 2.578125
| 3
|
import {Request, Response} from "express";
import * as jwt from "jsonwebtoken";
import {getRepository} from "typeorm";
import {validate} from "class-validator";
import {generate} from "generate-password";
import {User} from "../entity/User";
import config from "../config/config";
import EmailController from "./EmailController";
class AuthController {
static login = async (req: Request, res: Response) => {
// Check if email and password are set
let {email, password} = req.body;
if (!(email && password)) {
res.status(400).send({
success: false,
data: null,
message: "email or password is blank"
});
}
// Get user from database
const userRepository = getRepository(User);
let user: User;
try {
user = await userRepository.findOneOrFail({where: {email}});
} catch (error) {
res.status(401).send({
success: false,
data: null,
message: "invalid email or password"
});
}
// Check if encrypted password match
if (!user.checkIfUnencryptedPasswordIsValid(password)) {
res.status(401).send({
success: false,
data: null,
message: "invalid email or password"
});
return;
}
// Sign JWT, valid for 1 hour
const token = jwt.sign(
{userId: user.id, email: user.email},
config.jwtSecret,
{expiresIn: "1h"}
);
// Send the jwt in the response
res.status(200).send({
success: true,
data: {"authorization": token, "role": user.role},
message: "login successful"
});
};
static changePassword = async (req: Request, res: Response) => {
// Get ID from JWT
const id = res.locals.jwtPayload.userId;
// Get parameters from the body
const {oldPassword, newPassword} = req.body;
if (!(oldPassword && newPassword)) {
res.status(400).send({
success: false,
data: null,
message: "new and old passwords do not match"
});
}
// Get user from the database
const userRepository = getRepository(User);
let user: User;
try {
user = await userRepository.findOneOrFail(id);
} catch (id) {
res.status(401).send({
success: false,
data: null,
message: "no such user"
});
}
// Check if old password matches
if (!user.checkIfUnencryptedPasswordIsValid(oldPassword)) {
res.status(401).send({
success: false,
data: null,
message: "old password does not match"
});
return;
}
// Validate the model (password length)
user.password = newPassword;
const errors = await validate(user);
if (errors.length > 0) {
res.status(400).send({
success: false,
data: errors,
message: "password validation error"
});
return;
}
// Hash the new password and save
user.hashPassword();
userRepository.save(user);
res.status(204).send({
success: true,
data: null,
message: "password changed successfully"
});
};
static forgotPassword = async (req: Request, res: Response) => {
let {email: email} = req.body;
if (!email) {
res.status(400).send({
success: false,
data: null,
message: "email is blank"
});
}
// Get user from database
const userRepository = getRepository(User);
let user: User;
try {
user = await userRepository.findOneOrFail({where: {email: email}});
} catch (error) {
res.status(404).send({
success: false,
data: null,
message: "invalid email"
});
}
// Generate new random password
let randPassword = generate({
length: 10,
numbers: true,
symbols: true
});
user.password = randPassword;
// Hash the new password and save
user.hashPassword();
userRepository.save(user);
res.status(204).send({
success: true,
data: null,
message: "password reset successfully"
});
// Send email with new password
EmailController.sendForgotPasswordEmail(email, randPassword);
}
}
export default AuthController;
|
21a66ce28940161ae536dc6eac6bc36be761bd8d
|
TypeScript
|
FlorentinMonteil/nanogl-pbr
|
/PbrSurface.d.ts
| 2.53125
| 3
|
import Chunk from "./Chunk";
import Input from "./Input";
import Enum from "./Enum";
import ChunksSlots from "./ChunksSlots";
export declare enum PbrWorkflowType {
NONE = "NONE",
METALNESS = "METALNESS",
SPECULAR = "SPECULAR"
}
export declare type PbrSurface = MetalnessSurface | SpecularSurface;
export declare abstract class AbstractPbrSurface extends Chunk {
readonly type: PbrWorkflowType;
protected pbrInputType: Enum<readonly ["SPECULAR", "METALNESS"]>;
constructor();
protected _genCode(slots: ChunksSlots): void;
}
export declare class MetalnessSurface extends AbstractPbrSurface {
readonly type: PbrWorkflowType.METALNESS;
readonly baseColor: Input;
readonly baseColorFactor: Input;
readonly metalness: Input;
readonly metalnessFactor: Input;
readonly roughness: Input;
readonly roughnessFactor: Input;
constructor();
protected _genCode(slots: ChunksSlots): void;
}
export declare class SpecularSurface extends AbstractPbrSurface {
readonly type: PbrWorkflowType.SPECULAR;
readonly baseColor: Input;
readonly baseColorFactor: Input;
readonly specular: Input;
readonly specularFactor: Input;
readonly glossiness: Input;
readonly glossinessFactor: Input;
constructor();
protected _genCode(slots: ChunksSlots): void;
}
|
1ba131496ff539969a384d5e1e5836335f0d5229
|
TypeScript
|
caiomamprin/microSaaS-node-react
|
/backend/src/models/linksRepository.ts
| 2.6875
| 3
|
import linkModel, {ILinkModel} from './linkModel';
import {Link} from './link';
import LinkModel from './linkModel';
//No BANCODE DADOS - Encontrar um link para o codigo.
function findByCode(code: string){
return linkModel.findOne<ILinkModel>({ where: { code } });
}
//No BANCODE DADOS - Adicionar um novo link.
function add(link: Link){
return linkModel.create<ILinkModel>(link);
}
//No BANCODE DADOS - Para atualizar os hits de um link existente.
async function hit(code: string){
const link = await findByCode(code);
if(!link) return null;
link.hits!++;
link.save();
}
//Exportar as funçõers criadas para podermos utilizar no backand.
export default {
findByCode,
add,
hit,
}
|
c30d8909f804bc19b616d9aa9ec9cb444fe16399
|
TypeScript
|
hmcts/cmc-legal-rep-frontend
|
/src/test/app/forms/models/feeAccount.ts
| 2.875
| 3
|
/* Allow chai assertions which don't end in a function call, e.g. expect(thing).to.be.undefined */
/* tslint:disable:no-unused-expression */
import { expect } from 'chai'
import { Validator } from '@hmcts/class-validator'
import { expectValidationError } from 'test/app/forms/models/validationUtils'
import { FeeAccount, ValidationErrors } from 'forms/models/feeAccount'
describe('FeeAccount', () => {
describe('constructor', () => {
it('should set the primitive fields to undefined', () => {
const feeAccount = new FeeAccount()
expect(feeAccount.reference).to.be.undefined
})
})
describe('deserialize', () => {
it('should return an instance initialised with defaults for undefined', () => {
expect(new FeeAccount().deserialize(undefined)).to.eql(new FeeAccount())
})
it('should return an instance initialised with defaults for null', () => {
expect(new FeeAccount().deserialize(null)).to.eql(new FeeAccount())
})
it('should return an instance from given object', () => {
const reference = 'PBA0082848'
const result = new FeeAccount().deserialize({
reference: reference
})
expect(result.reference).to.be.equals(reference)
})
})
describe('validation', () => {
const validator: Validator = new Validator()
it('should reject fee account with undefined', () => {
const errors = validator.validateSync(new FeeAccount(undefined))
expect(errors.length).to.equal(1)
expectValidationError(errors, ValidationErrors.FEE_ACCOUNT_REQUIRED)
})
it('should reject fee account with null type', () => {
const errors = validator.validateSync(new FeeAccount(null))
expect(errors.length).to.equal(1)
expectValidationError(errors, ValidationErrors.FEE_ACCOUNT_REQUIRED)
})
it('should reject fee account with empty string', () => {
const errors = validator.validateSync(new FeeAccount(''))
expect(errors.length).to.equal(1)
expectValidationError(errors, ValidationErrors.FEE_ACCOUNT_REQUIRED)
})
it('should reject fee account with white spaces string', () => {
const errors = validator.validateSync(new FeeAccount(' '))
expect(errors.length).to.equal(1)
expectValidationError(errors, ValidationErrors.FEE_ACCOUNT_REQUIRED)
})
it('should reject fee account with invalid format', () => {
const errors = validator.validateSync(new FeeAccount('abc1234567'))
expect(errors.length).to.equal(1)
expectValidationError(errors, ValidationErrors.FEE_ACCOUNT_INVALID)
})
it('should accept valid fee account', () => {
const errors = validator.validateSync(new FeeAccount('PBA0082848'))
expect(errors.length).to.equal(0)
})
})
describe('fromObject', () => {
it('should have undefined when input is undefined', () => {
const feeAccount = FeeAccount.fromObject(undefined)
expect(feeAccount).to.equal(undefined)
})
it('should have valid fee account', () => {
const feeAccount = FeeAccount.fromObject({
reference: 'PBA0082848'
})
expect(feeAccount.reference).to.equal('PBA0082848')
})
})
})
|
ee74b55e0231d94b806c643541051328791fd7ae
|
TypeScript
|
brunodantascg/estudo-typescript
|
/curso-2021/Curso-TypeScript/exericio-lista/2-estrutura-decisao/estrutura-decisao.ts
| 4.09375
| 4
|
console.log("--- Questões da Lista de Estrutura de Decisão ---")
// 1 - Faça um Programa que peça dois números e imprima o maior deles.
function maiorNumero(numero1: number, numero2: number): number {
if (numero1 > numero2) {
return numero1
}
return numero2
}
console.log("1: O maior número é: " + maiorNumero(10, 15))
// 2- Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.
function valorPositivoNegativo(numero: number): string {
if( numero > 0) {
return 'Positivo'
} else if ( numero < 0 ) {
return 'Negativo'
} else {
return 'Zero é neutro'
}
}
console.log("2: O número é: " + valorPositivoNegativo(15))
// 3 - Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido.
function verificadorLetra(letra: string): string {
if (letra === 'F' || letra === 'f') {
return 'F - Feminino'
} else if (letra === 'M' || letra === 'm') {
return 'M - Masculino'
} else {
return 'Não identificado'
}
}
console.log("3: Sexo: " + verificadorLetra('m'))
// 4 - Faça um Programa que verifique se uma letra digitada é vogal ou consoante.
function verificadorVogal(vogal: string): string {
vogal.toUpperCase()
if (vogal === 'A' || vogal === 'E' || vogal === 'I' || vogal === 'O' || vogal === 'U' ) {
return 'vogal!'
}
return 'consoante!'
}
console.log("4: A letra é: " + verificadorVogal('m'))
// 5 - Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar:
// A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
// A mensagem "Reprovado", se a média for menor do que sete;
// A mensagem "Aprovado com Distinção", se a média for igual a dez.
function mediaAluno(nota1: number, nota2: number): string {
let media: number = (nota1 + nota2)/2
if (media === 10) {
return 'Aprovado com Distinção.'
} else if (media >= 7 && media < 10) {
return 'Aprovado.'
} else {
return 'Reprovado.'
}
}
console.log("5: " + mediaAluno(10, 10))
// 6 - Faça um Programa que leia três números e mostre o maior e o menor deles.
function maiorTres(num1: number, num2: number, num3: number): number {
if (num1 > num2 && num1 > num3) {
return num1
} else if (num2 > num1 && num2 > num3) {
return num2
} else {
return num3
}
}
// 7 - Faça um Programa que leia três números e mostre o maior e o menor deles.
function menorTres(num1: number, num2: number, num3: number): number {
if (num1 < num2 && num1 < num3) {
return num1
} else if (num2 < num1 && num2 < num3) {
return num2
} else {
return num3
}
}
console.log("6: Maior - " + maiorTres(15,16,17))
console.log("7: Menor - " + menorTres(15,18,17))
// 8 - Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato.
function melhorCompra(produto1: number, produto2: number, produto3: number): number {
if (produto1 < produto2 && produto1 < produto3) {
return produto1
} else if (produto2 < produto1 && produto2 < produto3) {
return produto2
} else {
return produto3
}
}
console.log("8: Produto com menor preço - R$ " + melhorCompra(55.20,60,65.99))
// 9 - Faça um Programa que leia três números e mostre-os em ordem decrescente.
function ordemDecrescente(num1: number, num2: number, num3: number): number[] {
if((num1 < num2) && (num1 < num3)) {
if(num2 < num3) {
return [num1, num2, num3]
} else {
return [num1, num3, num2]
}
} else if ((num2 < num1) && (num2 < num3)) {
if (num1 < num3) {
return [num1, num3, num2]
} else {
return [num2, num3, num1]
}
} else if ((num3 < num1) && (num3 < num2)) {
if (num1 < num2) {
return [num3, num1, num2]
} else {
return [num3, num2, num1]
}
} else {
return [0,0,0]
}
}
console.log("9: " + ordemDecrescente(15,11,10))
// 10 -Faça um Programa que pergunte em que turno você estuda. Peça para digitar:
// M-matutino ou V-Vespertino ou N- Noturno. Imprima a mensagem "Bom Dia!", "Boa Tarde!" ou "Boa Noite!" ou "Valor Inválido!",
// conforme o caso.
function turnoEstudo(turno: string): string {
turno = turno.toUpperCase();
if (turno === 'M') {
return "M-Matutino"
} else if (turno === 'V') {
return "V-Vespetino"
} else if (turno === 'N') {
return "N-Noturno"
} else {
return "Não identificado!"
}
}
console.log("10: " + turnoEstudo('v'))
// 11 - As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe contraram para desenvolver o programa que calculará os reajustes.
// Faça um programa que recebe o salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual:
// salários até R$ 280,00 (incluindo) : aumento de 20%
// salários entre R$ 280,00 e R$ 700,00 : aumento de 15%
// salários entre R$ 700,00 e R$ 1500,00 : aumento de 10%
// salários de R$ 1500,00 em diante : aumento de 5% Após o aumento ser realizado, informe na tela:
// o salário antes do reajuste;
// o percentual de aumento aplicado;
// o valor do aumento;
// o novo salário, após o aumento.
function salarioReajuste(salarioAtual: number): number[] {
let salarioReajuste: number;
let variavel: number;
if (salarioAtual < 280) {
salarioReajuste = salarioAtual * 1.20;
variavel = 20;
return [salarioReajuste, variavel];
} else if (salarioAtual >= 280 && salarioAtual < 700) {
salarioReajuste = salarioAtual * 1.15;
variavel = 15;
return [salarioReajuste, variavel];
} else if (salarioAtual >= 700 && salarioAtual < 1500) {
salarioReajuste = salarioAtual * 1.10;
variavel = 10;
return [salarioReajuste, variavel];
} else {
salarioReajuste = salarioAtual * 1.05;
variavel = 5;
return [salarioReajuste, variavel];
}
}
let salarioBase: number = 1500;
let s: number = salarioReajuste(salarioBase)[0]
let p: number = salarioReajuste(salarioBase)[1]
console.log("11: Reajuste Salário")
console.log("Salário antes do reajuste: R$ " + salarioBase)
console.log("Percentual de aumento aplicado " + p + "%")
console.log("Valor do aumento: R$ " + (salarioBase * (p/100)))
console.log("Salário novo: R$ " + s)
// 12 - Faça um programa para o cálculo de uma folha de pagamento, sabendo que os descontos são do Imposto de Renda, que depende do salário bruto
// (conforme tabela abaixo) e 3% para o Sindicato e que o FGTS corresponde a 11% do Salário Bruto, mas não é descontado
// (é a empresa que deposita). O Salário Líquido corresponde ao Salário Bruto menos os descontos.
// O programa deverá pedir ao usuário o valor da sua hora e a quantidade de horas trabalhadas no mês.
// Desconto do IR:
// Salário Bruto até 900 (inclusive) - isento
// Salário Bruto até 1500 (inclusive) - desconto de 5%
// Salário Bruto até 2500 (inclusive) - desconto de 10%
// Salário Bruto acima de 2500 - desconto de 20% Imprima na tela as informações, dispostas conforme o exemplo abaixo. No exemplo o valor da hora é 5 e a quantidade de hora é 220.
function salarioBrutoCalculoComHoras(horas: number, valorHora: number): number {
let salarioBruto: number = horas * valorHora;
return salarioBruto;
}
let salarioB: number = salarioBrutoCalculoComHoras(220, 31.82)
let descontoIr: number[] = [0.0, 0.05, 0.10, 0.20];
let valorDescontoINSS: number = 0.10;
let valorDescontoFGTS: number = 0.11;
function calculoDescontoIR(salarioB: number, ...descontoIr: number[]): number[] {
let v: number[] = descontoIr;
let desINSS: number;
if(salarioB < 900) {
desINSS = salarioB * Number(v[0]);
return [Number(v[3]*100), desINSS];
} else if (salarioB >= 900 && salarioB < 1500) {
desINSS = salarioB * Number(v[1]);
return [Number(v[3]*100), desINSS];
} else if (salarioB >= 1500 && salarioB < 2500) {
desINSS = salarioB * Number(v[2]);
return [Number(v[3]*100), desINSS];
} else if (salarioB >= 2500) {
desINSS = salarioB * Number(v[3]);
return [Number(v[3]*100), desINSS];
} else {
return [0, 0];
}
}
function calculoDescontoINSS(salarioB: number, valorDescontoINSS: number): number[] {
let descontoINSS: number;
descontoINSS = salarioB * valorDescontoINSS;
return [(valorDescontoINSS*100), descontoINSS];
}
function calculoDescontoFGTS(salarioB: number, valorDescontoFGTS: number): number {
let descontoFGTS: number;
descontoFGTS = salarioB * valorDescontoFGTS;
return descontoFGTS;
}
let totalDescontos: number = (calculoDescontoIR(salarioB, ...descontoIr)[1] + calculoDescontoINSS(salarioB, valorDescontoINSS)[1]);
let salarioLiquido: number = salarioB - totalDescontos;
console.log("12: Salário com Descontos")
console.log(" --- Salário Bruto: R$ " + salarioB)
console.log("( - ) Desconto IR (" + calculoDescontoIR(salarioB, ...descontoIr)[0] + "%) : R$ " + calculoDescontoIR(salarioB, ...descontoIr)[1])
console.log("( - ) Desconto INSS (" + calculoDescontoINSS(salarioB, valorDescontoINSS)[0]+ "%) : R$ " + calculoDescontoINSS(salarioB, valorDescontoINSS)[1])
console.log("( ) Desconto FGTS (" + valorDescontoFGTS*100 + "%) : R$ " + calculoDescontoFGTS(salarioB, valorDescontoFGTS));
console.log("( = ) Total de descontos: R$ " + totalDescontos);
console.log("( = ) Salário Líquido: R$ " + salarioLiquido);
// 13 - Faça um Programa que leia um número e exiba o dia correspondente da semana. (1-Domingo, 2- Segunda, etc.), se digitar outro valor deve aparecer valor inválido
function diasDaSemana(dia: number): string {
if ( dia === 1) {
return " 1 - Domingo.";
} else if ( dia === 2) {
return " 2 - Segunda-feira.";
} else if ( dia === 3) {
return " 3 - Terça-feira.";
} else if ( dia === 4) {
return " 4 - Quarta-feira.";
} else if ( dia === 5) {
return " 5 - Quinta-feira.";
} else if ( dia === 6) {
return " 6 - Sexta-feira.";
} else if ( dia === 7) {
return " 7 - Sábado.";
} else {
return " Valor inválido.";
}
}
console.log("13: Dia da semana: " + diasDaSemana(1));
// 14 - Faça um programa que lê as duas notas parciais obtidas por um aluno numa disciplina ao longo de um semestre, e calcule a sua média. A atribuição de conceitos obedece à tabela abaixo:
let notaParcial1: number = 10;
let notaParcial2: number = 9;
function conceitoAluno(notaParcial1: number, notaParcial2: number): string[] {
let media: number = (notaParcial1 + notaParcial2)/2;
if ( media >= 0 && media <= 10 ) {
if ( media > 9 && media <= 10 ) {
return ["9.0 e 10.0 ", " A", " APROVADO"];
} else if ( media > 7.5 && media <= 9 ) {
return ["7.5 e 9.0 ", " B", " APROVADO"];
} else if ( media > 6 && media <= 7.5 ) {
return ["6.0 e 7.5 ", " C", " APROVADO"];
} else if ( media > 4 && media <= 6 ) {
return ["4.0 e 6.0 ", " D", " REPROVADO"];
} else {
return ["4.0 e zero ", " E", " REPROVADO"];
}
} else {
return ["Nota inválida."];
}
}
console.log("14: Conceito Aluno: ");
console.log("Média de Aprovamento Conceito");
console.log("Entre " + conceitoAluno(notaParcial1, notaParcial2));
// 15 - Faça um Programa que peça os 3 lados de um triângulo. O programa deverá informar se os valores podem ser um triângulo.
// Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno.
// Dicas:
// + Três lados formam um triângulo quando a soma de quaisquer dois lados for maior que o terceiro;
// + Triângulo Equilátero: três lados iguais;
// + Triângulo Isósceles: quaisquer dois lados iguais;
// + Triângulo Escaleno: três lados diferentes;
let lado1: number = 10;
let lado2: number = 20;
let lado3: number = 40;
console.log("15: " );
function podeSerTriangulo(lado1: number, lado2: number, lado3: number): string {
if (((lado1+lado2) > lado3) || ((lado2+lado3) > lado3) || ((lado1+lado3) > lado3)) {
console.log("É um triângulo!");
if ((lado1 == lado2) && (lado1 == lado3) && (lado2 == lado3)) {
return "Triângulo Equilátero!";
} else if ((lado1 == lado2) || (lado1 == lado3) || (lado2 == lado3)) {
return "Triângulo Isósceles!";
} else if ((lado1 != lado2) && (lado1 != lado3) && (lado2 != lado3)) {
return "Triângulo Escaleno!";
} else {
return "Não identificado!";
}
} else {
return "Não poder ser um triângulo.";
}
}
console.log(podeSerTriangulo(lado1, lado2, lado3));
// 16 - Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e
// fazer as consistências, informando ao usuário nas seguintes situações:
// a - Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não deve fazer pedir os demais valores, sendo encerrado;
// b - Se o delta calculado for negativo, a equação não possui raizes reais. Informe ao usuário e encerre o programa;
// c - Se o delta calculado for igual a zero a equação possui apenas uma raiz real; informe-a ao usuário;
// d - Se o delta for positivo, a equação possui duas raiz reais; informe-as ao usuário;
let aEqua: number = 5;
let bEqua: number = 10;
let cEqua: number = 13;
function calculoRaizes(aEqua: number, bEqua: number, cEqua: number): string {
if (aEqua != 0) {
let delta: number = ((bEqua**2)-(4-aEqua*cEqua))
if (delta < 0) {
return "Delta negativo! Não possui raízes reais!";
} else if ((delta < 0) && (delta == 0)) {
let equma:number = (-bEqua)/2*aEqua;
return `A equação possui apenas uma raiz real! ${equma}`;
} else if (delta > 0) {
let eqdua1: number = (-bEqua+delta)/2*aEqua;
let eqdua2: number = (-bEqua-delta)/2*aEqua;
return `A equação possui duas raízes reias! ${eqdua1} e ${eqdua2}`;
} else {
return "Erro";
}
} else {
return "A equação não é do segundo grau!"
}
}
console.log("16: " + calculoRaizes(aEqua, bEqua, cEqua));
// 17 - Faça um Programa que peça um número correspondente a um determinado ano e em seguida informe se este ano é ou não bissexto
let ano: number = 1990;
function anoBisexto(ano: number): string {
if(((ano % 100) != 0) || ((ano % 4) == 0) || ((ano % 400) == 0)) {
return "O Ano é Bissexto!";
} else {
return "O Ano não é Bissexto!";
}
}
console.log("17: " + anoBisexto(ano));
// 18 - Faça um Programa que peça uma data no formato dd/mm/aaaa e determine se a mesma é uma data válida.
let dd: number = 9;
let mm: number = 12;
let aaaa: number = 1990;
function validarData(dd: number, mm: number, aaaa: number): string {
if ( ((dd > 0) && (dd <= 31)) && ((mm > 0) && (mm <= 12)) && ((aaaa > 0) && (aaaa <= 9999)) ) {
return "A data é válida!";
} else {
return "A data Não é válida!";
}
}
console.log("18: " + validarData(dd, mm, aaaa));
// 19 - Faça um Programa que leia um número inteiro menor que 1000 e imprima a quantidade de centenas, dezenas e unidades do mesmo.
// Observando os termos no plural a colocação do "e", da vírgula entre outros. Exemplo:
// a - 326 = 3 centenas, 2 dezenas e 6 unidades
// b - 12 = 1 dezena e 2 unidades Testar com: 326, 300, 100, 320, 310,305, 301, 101, 311, 111, 25, 20, 10, 21, 11, 1, 7 e 16
let nInt: number = 20;
function qunatCentenas(nInt: number): number[] | string {
let centenas: number = nInt / 100;
let dezenas: number = Math.floor(nInt / 100 ) / 10;
let unidades: number = Math.floor(Math.floor(nInt / 100) / 10);
if (nInt > 0 && nInt <= 1000) {
return [];
} else {
return "Insira um numero entre zero (0) ou menor que (1000)";
}
}
// 20 - Faça um Programa para leitura de três notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e presentar:
// a - A mensagem "Aprovado", se a média for maior ou igual a 7, com a respectiva média alcançada;
// b - A mensagem "Reprovado", se a média for menor do que 7, com a respectiva média alcançada;
// c - A mensagem "Aprovado com Distinção", se a média for igual a 10.
function mediaParcial(nota_par_01: number, nota_par_02: number, nota_par_03: number, aluno: string): string[] | string {
if ((nota_par_01 >= 0 && nota_par_01 <= 10) && (nota_par_02 >= 0 && nota_par_02 <= 10) && (nota_par_03 >= 0 && nota_par_03 <= 10)) {
let media: number = (nota_par_01 + nota_par_02 + nota_par_03)/3;
if (media >= 7 && media <=10) {
if (media == 10){
return ["Aluno: " + aluno," APROVADO COM DISTINÇÃO ", " Méida: " + media.toString()];
} else {
return ["Aluno: " + aluno," APROVADO ", " Méida: " + media.toString()];
}
} else {
return ["Aluno: " + aluno," REPROVADO ", " Méida: " + media.toString()];
}
} else {
return "Notas invalidas!";
}
}
console.log("20: " + mediaParcial(10, 8, 9, "Bruno"));
// 21 - Faça um Programa para um caixa eletrônico. O programa deverá perguntar ao usuário a valor do saque e depois informar quantas notas de cada valor serão fornecidas.
// As notas disponíveis serão as de 1, 5, 10, 50 e 100 reais. O valor mínimo é de 10 reais e o máximo de 600 reais.
// O programa não deve se preocupar com a quantidade de notas existentes na máquina.
// Exemplo 1: Para sacar a quantia de 256 reais, o programa fornece duas notas de 100, uma nota de 50, uma nota de 5 e uma nota de 1;
// Exemplo 2: Para sacar a quantia de 399 reais, o programa fornece três notas de 100, uma nota de 50, quatro notas de 10, uma nota de 5 e quatro notas de 1.
function caixaEletrinico(valorSaque: number): string {
let x: number = 3;
if (x == 3) {
return "aqui 1";
} else if (x == 2) {
return "aqui 2";
} else {
return "aqui fora";
}
}
console.log("21: " + caixaEletrinico(10));
// 22 - Faça um Programa que peça um número inteiro e determine se ele é par ou impar. Dica: utilize o operador módulo (resto da divisão).
function numImparPar(numero: number): string {
let n: number = Math.floor(numero)%2;
if (n == 1) {
return "Impar";
} else if (n == 0) {
return "Par";
} else {
return "Neutro";
}
}
console.log("22: " + numImparPar(9));
// 23 - Faça um Programa que peça um número e informe se o número é inteiro ou decimal. Dica: utilize uma função de arredondamento.
console.log("23: typeof(), só retorna se é um number, string, etc...");
// 24 - Faça um Programa que leia 2 números e em seguida pergunte ao usuário qual operação ele deseja realizar.
// O resultado da operação deve ser acompanhado de uma frase que diga se o número é:
// a - par ou ímpar;
// b - positivo ou negativo;
// c - inteiro ou decimal.
function numPositivoNegativo(numero: number): string {
let n: number = numero;
if (n > 0) {
return "Positivo";
} else if (n < 0) {
return "Negativo";
} else {
return "Neutro";
}
}
function operacaoEspecificado(n1: number, n2: number, ope: number): string[] {
if (ope == 1) {
let soma: number = n1 + n2;
let numIm: string = numImparPar(soma);
let numPn: string = numPositivoNegativo(soma);
return [`Operação - soma: ${n1} + ${n2} = ${soma}`, " a. " + numIm, " b. " + numPn];
} else if (ope == 2) {
let subtracao: number = n1 - n2;
let numIm: string = numImparPar(subtracao);
let numPn: string = numPositivoNegativo(subtracao);
return [`Operação - subtração: ${n1} - ${n2} = ${subtracao}`, " a. " + numIm, " b. " + numPn];
} else if (ope == 3) {
let multiplicacao: number = n1 * n2;
let numIm: string = numImparPar(multiplicacao);
let numPn: string = numPositivoNegativo(multiplicacao);
return [`Operação - multiplicação: ${n1} - ${n2} = ${multiplicacao}`, " a. " + numIm, " b. " + numPn];
} else if (ope == 4) {
let divisao: number = n1 / n2;
let numIm: string = numImparPar(divisao);
let numPn: string = numPositivoNegativo(divisao);
return [`Operação - divisão: ${n1} - ${n2} = ${divisao}`, " a. " + numIm, " b. " + numPn];
} else {
return ["operação errada."];
}
}
console.log("24: " + operacaoEspecificado(100, 90, 2));
// 25 - Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
// "Telefonou para a vítima?"
// "Esteve no local do crime?"
// "Mora perto da vítima?"
// "Devia para a vítima?"
// "Já trabalhou com a vítima?"
// O programa deve no final emitir uma classificação sobre a participação da pessoa no crime. Se a pessoa responder positivamente a 2 questões ela deve ser
// classificada como "Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente".
function classificacaoCrime(perg1: string, perg2: string, perg3: string, perg4: string, perg5: string): string {
let respostas: string[] = [perg1, perg2, perg3, perg4, perg5];
let reSim: number = 0;
for (let i = 0; i < respostas.length; i++) {
let r: string = respostas[i];
if (r === "sim") {
reSim = reSim + 1;
}
}
if (reSim === 1) {
return "Não é suspeito";
} else if (reSim === 2 ) {
return "Suspeito";
} else if (reSim >= 3 && reSim <= 4) {
return "Cúmpice";
} else if (reSim > 4) {
return "Assassino";
} else {
return "Algo deu errado.";
}
}
console.log("25: " + classificacaoCrime("sim", "não", "sim", "não", "sim"));
// 26 - Um posto está vendendo combustíveis com a seguinte tabela de descontos:
//
// Álcool:
// até 20 litros, desconto de 3% por litro
// acima de 20 litros, desconto de 5% por litro
// Gasolina:
// até 20 litros, desconto de 4% por litro
// acima de 20 litros, desconto de 6% por litro
//
// Escreva um algoritmo que leia o número de litros vendidos, o tipo de combustível (codificado da seguinte forma: A-álcool, G-gasolina),
// calcule e imprima o valor a ser pago pelo cliente sabendo-se que o preço do litro da gasolina é R$ 2,50 o preço do litro do álcool é R$ 1,90.
function calculadoraPosto(litros: number, tipoCombustivel: string): string {
let precoGasolina: number = 2.50;
let precoAlcool: number = 1.90;
if (tipoCombustivel === "A") {
let valor: number = precoAlcool * litros;
if ( litros <= 20) {
let desconto: number = valor * 0.03;
return `A - álcool R$: ${valor - desconto}`;
} else {
let desconto: number = valor * 0.05;
return `A - álcool R$: ${valor - desconto}`;
}
} else if (tipoCombustivel === "G") {
let valor: number = precoGasolina * litros;
if ( litros <= 20) {
let desconto: number = valor * 0.04;
return `A - gasolina R$: ${valor - desconto}`;
} else {
let desconto: number = valor * 0.06;
return `A - gasolina R$: ${valor - desconto}`;
}
} else {
return "Tipo de combustível errado! Informe novamente.";
}
}
console.log("26: " + calculadoraPosto(20, "A"));
// 27 - Uma fruteira está vendendo frutas com a seguinte tabela de preços:
//
// Até 5 Kg Acima de 5 Kg
// Morango R$ 2,50 por Kg R$ 2,20 por Kg
// Maçã R$ 1,80 por Kg R$ 1,50 por Kg
//Se o cliente comprar mais de 8 Kg em frutas ou o valor total da compra ultrapassar R$ 25,00, receberá ainda um desconto de 10% sobre este total.
// Escreva um algoritmo para ler a quantidade (em Kg) de morangos e a quantidade (em Kg) de maças adquiridas e escreva o valor a ser pago pelo cliente.
function calculadoraFruteira(morangoKilo: number, macaKilo: number): number {
function calculoMaca(macaKilo: number): number {
if (macaKilo >= 0 && macaKilo < 5) {
return macaKilo * 1.80;
} else if (macaKilo > 5) {
return macaKilo * 1.50;
} else {
return 0;
}
}
function calculoMorango(morangoKilo: number): number {
if (morangoKilo >= 0 && morangoKilo <5) {
return morangoKilo * 2.50
} else if (morangoKilo >= 5) {
return morangoKilo * 2.20
} else {
return 0;
}
}
if (((macaKilo + morangoKilo) > 8) || (calculoMaca(macaKilo) + calculoMorango(morangoKilo)) > 25) {
let valorDesconto: number = (calculoMaca(macaKilo) + calculoMorango(morangoKilo)) * 0.10;
let valorTotal: number = (calculoMaca(macaKilo) + calculoMorango(morangoKilo)) - valorDesconto;
return valorTotal;
} else {
let valorTotal: number = calculoMaca(macaKilo) + calculoMorango(morangoKilo);
return valorTotal;
}
}
console.log("27: valor a ser pago: R$ " + calculadoraFruteira(5, 3));
// 28 - O Hipermercado Tabajara está com uma promoção de carnes que é imperdível. Confira:
//
// Até 5 Kg Acima de 5 Kg
// File Duplo R$ 4,90 por Kg R$ 5,80 por Kg
// Alcatra R$ 5,90 por Kg R$ 6,80 por Kg
// Picanha R$ 6,90 por Kg R$ 7,80 por Kg
//
// Para atender a todos os clientes, cada cliente poderá levar apenas um dos tipos de carne da promoção, porém não há limites para a quantidade de carne por cliente.
// Se compra for feita no cartão Tabajara o cliente receberá ainda um desconto de 5% sobre o total da compra.
// Escreva um programa que peça o tipo e a quantidade de carne comprada pelo usuário e gere um cupom fiscal, contendo as informações da compra:
// tipo e quantidade de carne, preço total, tipo de pagamento, valor do desconto e valor a pagar.
function hiperMercado(tipoCarne: string, formaPagamento: string , quantCarne: number): number {
function fileDuplo(quantCarne: number): number {
if (quantCarne >= 0 && quantCarne < 5) {
return quantCarne * 4.90;
} else if (quantCarne >= 5) {
return quantCarne * 5.80;
} else {
return 0;
}
}
function alcantra(quantCarne: number): number {
if (quantCarne >= 0 && quantCarne < 5) {
return quantCarne * 5.90;
} else if (quantCarne >= 5) {
return quantCarne * 6.80;
} else {
return 0;
}
}
function picanha(quantCarne: number): number {
if (quantCarne >= 0 && quantCarne < 5) {
return quantCarne * 6.90;
} else if (quantCarne >= 5) {
return quantCarne * 7.80;
} else {
return 0;
}
}
return 0;
}
console.log("28: valor a ser pago: R$ " + hiperMercado("P", "S", 10));
|
958b1fc809239622694cf51bbfcf0453df9e302d
|
TypeScript
|
gudwnsdl88/corona_clone_server
|
/src/utils/webCrawler.ts
| 2.578125
| 3
|
import axios from 'axios';
import cheerio from 'cheerio';
import { statusType } from '../types/myType';
//보건부에서 감염정보 가져오기
//확진환자, 격리해제 ,사망자 ,검사진행
export const getStatusCrawler = async () => {
const statusData: statusType = {
confirmation: 0,
release: 0,
dead: 0,
inspection: 0,
date: ''
};
try {
const html = await axios.get(
'http://ncov.mohw.go.kr/bdBoardList_Real.do?brdId=1&brdGubun=11&ncvContSeq=&contSeq=&board_id=&gubun='
);
const $ = cheerio.load(html.data);
//날짜정보
const dateData = $('p.s_descript')
.first()
.text();
//감염정보
const $statusData = $('table.num')
.first()
.children('tbody')
.children('tr');
/*
0 확진환자
1 확진환자 격리해제
2 사망자
3 검사진행
*/
$statusData.each((index, item) => {
const text: string = $(item)
.find('td')
.text();
if (index === 0) {
statusData.confirmation = parseInt(text.replace(',', ''));
} else if (index === 1) {
statusData.release = parseInt(text.replace(',', ''));
} else if (index === 2) {
statusData.dead = parseInt(text.replace(',', ''));
} else {
statusData.inspection = parseInt(text.replace(',', ''));
}
});
statusData.date = dateData.split('(')[1].replace(')', '');
return statusData;
} catch (error) {
console.log(error.message);
return null;
}
};
|
e3fafb99a3789fdd5b1469cbfe92b528e162094c
|
TypeScript
|
FabienBrisset/genese-complexity
|
/src/languages-to-json-ast/java/cstToAstCases/integral-type.ts
| 2.578125
| 3
|
import { cstToAst } from '../cst-to-ast';
import { IntegralType } from '../models/integral-type.model';
import { IntegralTypeChildren } from '../models/integral-type-children.model';
// @ts-ignore
export function run(cstNode: IntegralType, children: IntegralTypeChildren): any {
const int = children.Int;
const byte = children.Byte;
const long = children.Long;
const char = children.Char;
const short = children.Short;
return [
...[].concat(int?.map(e => cstToAst(e, 'int')) ?? []),
...[].concat(byte?.map(e => cstToAst(e, 'byte')) ?? []),
...[].concat(long?.map(e => cstToAst(e, 'long')) ?? []),
...[].concat(char?.map(e => cstToAst(e, 'char')) ?? []),
...[].concat(short?.map(e => cstToAst(e, 'short')) ?? []),
]
}
|
b5a832c6fa4998f61f68d3a0df30779b73df4861
|
TypeScript
|
benjamin-t-brown/orbital-golfing
|
/src/server/lobby.ts
| 3.078125
| 3
|
interface Lobby {
id: string;
name: string;
playerIds: string[];
}
const lobbyStorage: Lobby[] = [];
const broadcastLobbies = () => {
sendIoMessageAll(getShared().G_S_LOBBIES_UPDATED, {
lobbies: lobbyStorage.map(lobby => {
return {
...lobby,
playerIds: undefined,
players: lobby.playerIds.map(playerId => {
const player = playerGetById(playerId);
return {
...player,
socket: undefined,
};
}),
};
}),
});
};
const lobbyCreate = (name: string, creator: Player): Lobby => {
name = name.trim();
if (name.length > 20 || name.length === 0) {
throw new Error(`Cannot create lobby. Name length invalid: ${name.length}`);
}
name = escapeString(name);
const lobby: Lobby = {
id: 'lobby_' + randomId(),
playerIds: [],
name,
};
console.debug(`Lobby created '${lobbyToString(lobby)}'`);
lobbyStorage.push(lobby);
lobbyJoin(lobby, creator);
return lobby;
};
const lobbyDestroy = (lobby: Lobby) => {
const ind = lobbyStorage.indexOf(lobby);
if (ind > -1) {
lobbyStorage.splice(ind, 1);
lobby.playerIds.forEach(playerId => {
const player = playerGetById(playerId);
if (player) {
player.lobbyId = '';
}
});
console.debug(`Lobby destroyed '${lobbyToString(lobby)}'`);
} else {
throw new Error(`Cannot destroy lobby '${lobby.id}'. It does not exist.`);
}
};
const lobbyStart = (lobby: Lobby) => {
// create game
// destroy lobby
};
const lobbyGetLeader = (lobby: Lobby): Player | undefined => {
return playerGetById(lobby.playerIds[0]);
};
const lobbyJoin = (lobby: Lobby, player: Player) => {
if (player.lobbyId) {
const plStr = playerToString(player);
throw new Error(`Cannot join lobby. ${plStr} is in another lobby.`);
}
if (lobby.playerIds.length >= 8) {
throw new Error(`Lobby full. ${lobby.playerIds}/8`);
}
lobby.playerIds.push(player.id);
player.lobbyId = lobby.id;
console.debug(
`Lobby join '${lobbyToString(lobby)}', ${playerToString(player)}`
);
broadcastLobbies();
};
const lobbyLeave = (lobby: Lobby, player: Player) => {
const ind = lobby.playerIds.indexOf(player.id);
if (ind > -1) {
lobby.playerIds.splice(ind, 1);
}
player.lobbyId = '';
console.debug(
`Lobby leave '${lobbyToString(lobby)}', ${playerToString(player)}`
);
if (lobby.playerIds.length === 0) {
lobbyDestroy(lobby);
} else {
console.debug('Not destroying lobby, some players remain', lobby.playerIds);
}
broadcastLobbies();
};
const lobbyGetById = (id: string) => {
return lobbyStorage.find(lobby => lobby.id === id);
};
const lobbyToString = (lobby: Lobby) => {
return `Lobby { ${lobby.name} (id=${
lobby.id
}) [playerIds=${lobby.playerIds.join(',')}]}`;
};
|
52f6efa15f4b99bc24a038aa3f8991cde3fe1ec9
|
TypeScript
|
plee42/RockPaperScissors
|
/src/app/game/game.component.spec.ts
| 2.5625
| 3
|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';
import { provideMockStore } from '@ngrx/store/testing';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { of } from 'rxjs';
import { GameComponent } from './game.component';
import { IRoundResult } from '../interfaces/IRoundResult';
import { AppState } from '../store/state/app.state';
import { UserService } from '../user/user.service';
import { Scissors } from '../models/Scissors';
describe('GameComponent', () => {
const expectedUser = 'User';
const initialResults: Array<IRoundResult> = [
{ roundNumber: null, playerChoice: null, computerChoice: null, playerScore: null, computerScore: null, winner: null }
];
const initialState: AppState = {
results: initialResults
};
class MockUserService {
getUser() { return of(expectedUser); }
setUser(name: string) { }
}
class MockRouter {
navigate(array: Array<string>) { }
}
const userService = new MockUserService();
const router = new MockRouter();
let component: GameComponent;
let fixture: ComponentFixture<GameComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ GameComponent ],
providers: [
{ provide: UserService, useValue: userService },
{ provide: Router, useValue: router },
provideMockStore({ initialState })
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(GameComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should show match score', () => {
// Arrange
const element: DebugElement = fixture.debugElement;
const scoreElement = element.query(By.css('.game__score'));
// Act
fixture.detectChanges();
const score: HTMLElement = scoreElement.nativeElement;
// Assert
expect(score.innerHTML).toContain(expectedUser);
expect(score.innerHTML).toContain('0 - 0');
expect(score.innerHTML).toContain('Computer');
});
it('should show round number', () => {
// Arrange
const element: DebugElement = fixture.debugElement;
const roundElement = element.query(By.css('.game__intro'));
// Act
fixture.detectChanges();
const round: HTMLElement = roundElement.nativeElement;
// Assert
expect(round.innerHTML).toContain(component.roundNumber.toString());
});
it('should set up user choices', () => {
// Assert
expect(component.moveList.length).toEqual(3);
});
it('round player winner is determined when turn is taken', () => {
// Arrange
const move = new Scissors();
component.roundPlayerWinner = null;
// Act
component.takeTurn(move);
// Assert
expect(component.roundPlayerWinner).toBeTruthy();
});
it('round move winner is determined when turn is taken', () => {
// Arrange
const move = new Scissors();
component.roundMoveWinner = null;
// Act
component.takeTurn(move);
// Assert
expect(component.roundMoveWinner).toBeTruthy();
});
it('round number is incremented when turn is taken', () => {
// Arrange
const move = new Scissors();
component.roundNumber = 2;
// Act
component.takeTurn(move);
// Assert
expect(component.roundNumber).toEqual(3);
});
it('user routed to results when round 10 is complete', () => {
// Arrange
const move = new Scissors();
component.roundNumber = 10;
const spy = spyOn(router, 'navigate');
// Act
component.takeTurn(move);
// Assert
expect(spy).toHaveBeenCalledWith(['/results']);
});
});
|
13fcc739b2a694723f3d78f265f74dc52686cd5b
|
TypeScript
|
saracelik/LiterarnoUdruzenje-1
|
/luservice-fe/src/app/shared/models/cart-item.ts
| 2.796875
| 3
|
import { Book } from "./book";
export class CartItem {
id;
price: number;
quantity: number;
book: Book;
constructor(id: any, price: number, quantity: number, book: Book) {
this.id = id;
this.price = price;
this.quantity = quantity;
this.book = book;
}
isTheSameBook(newCartItem: CartItem) {
return this.book.id == newCartItem.book.id;
}
}
|
8ffb988fa86c19004d840864e29140613a97bff1
|
TypeScript
|
Happy-Ferret/pixi-swf
|
/src/shumway/tools/profiler/flameChartBase.ts
| 2.53125
| 3
|
/**
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module Shumway.Tools.Profiler {
export const enum FlameChartDragTarget {
NONE,
WINDOW,
HANDLE_LEFT,
HANDLE_RIGHT,
HANDLE_BOTH
}
export interface FlameChartDragInfo {
windowStartInitial: number;
windowEndInitial: number;
target: FlameChartDragTarget;
}
export class FlameChartBase implements MouseControllerTarget {
_controller: Controller;
_mouseController: MouseController;
_canvas: HTMLCanvasElement;
_context: CanvasRenderingContext2D;
_width: number;
_height: number;
_windowStart: number;
_windowEnd: number;
_rangeStart: number;
_rangeEnd: number;
_initialized: boolean;
_dragInfo: FlameChartDragInfo;
static DRAGHANDLE_WIDTH = 4;
static MIN_WINDOW_LEN = 0.1;
preConstructor() {
}
constructor(controller: Controller, ...preArgs: Array<any>) {
this.preConstructor.apply(this, preArgs);
this._controller = controller;
this._initialized = false;
this._canvas = document.createElement("canvas");
this._context = this._canvas.getContext("2d");
this._mouseController = new MouseController(this, this._canvas);
let container = controller.container;
container.appendChild(this._canvas);
let rect = container.getBoundingClientRect();
this.setSize(rect.width);
}
get canvas(): HTMLCanvasElement {
return this._canvas;
}
public setSize(width: number, height: number = 20) {
this._width = width;
this._height = height;
this._resetCanvas();
this.draw();
}
public initialize(rangeStart: number, rangeEnd: number) {
this._initialized = true;
this.setRange(rangeStart, rangeEnd, false);
this.setWindow(rangeStart, rangeEnd, false);
this.draw();
}
public setWindow(start: number, end: number, draw: boolean = true) {
this._windowStart = start;
this._windowEnd = end;
!draw || this.draw();
}
public setRange(start: number, end: number, draw: boolean = true) {
this._rangeStart = start;
this._rangeEnd = end;
!draw || this.draw();
}
public destroy() {
this._mouseController.destroy();
this._mouseController = null;
this._controller.container.removeChild(this._canvas);
this._controller = null;
}
_resetCanvas() {
let ratio = window.devicePixelRatio;
let canvas = this._canvas;
canvas.width = this._width * ratio;
canvas.height = this._height * ratio;
canvas.style.width = this._width + "px";
canvas.style.height = this._height + "px";
}
draw() {
}
_almostEq(a: number, b: number, precision: number = 10): boolean {
let pow10 = Math.pow(10, precision);
return Math.abs(a - b) < (1 / pow10);
}
_windowEqRange(): boolean {
return (this._almostEq(this._windowStart, this._rangeStart) && this._almostEq(this._windowEnd, this._rangeEnd));
}
_decimalPlaces(value: number): number {
return ((+value).toFixed(10)).replace(/^-?\d*\.?|0+$/g, '').length;
}
_toPixelsRelative(time: number): number {
return 0;
}
_toPixels(time: number): number {
return 0;
}
_toTimeRelative(px: number): number {
return 0;
}
_toTime(px: number): number {
return 0;
}
onMouseWheel(x: number, y: number, delta: number) {
let time = this._toTime(x);
let windowStart = this._windowStart;
let windowEnd = this._windowEnd;
let windowLen = windowEnd - windowStart;
/*
* Find maximum allowed delta
* (windowEnd + (windowEnd - time) * delta) - (windowStart + (windowStart - time) * delta) = LEN
* (windowEnd - windowStart) + ((windowEnd - time) * delta) - ((windowStart - time) * delta) = LEN
* (windowEnd - windowStart) + ((windowEnd - time) - (windowStart - time)) * delta = LEN
* (windowEnd - windowStart) + (windowEnd - windowStart) * delta = LEN
* (windowEnd - windowStart) * delta = LEN - (windowEnd - windowStart)
* delta = (LEN - (windowEnd - windowStart)) / (windowEnd - windowStart)
*/
let maxDelta = Math.max((FlameChartBase.MIN_WINDOW_LEN - windowLen) / windowLen, delta);
let start = windowStart + (windowStart - time) * maxDelta;
let end = windowEnd + (windowEnd - time) * maxDelta;
this._controller.setWindow(start, end);
this.onHoverEnd();
}
onMouseDown(x: number, y: number): void {
}
onMouseMove(x: number, y: number): void {
}
onMouseOver(x: number, y: number): void {
}
onMouseOut(): void {
}
onDrag(startX: number, startY: number, currentX: number, currentY: number, deltaX: number, deltaY: number): void {
}
onDragEnd(startX: number, startY: number, currentX: number, currentY: number, deltaX: number, deltaY: number): void {
}
onClick(x: number, y: number): void {
}
onHoverStart(x: number, y: number): void {
}
onHoverEnd(): void {
}
}
}
|
d5a08660fcbaa5a58f6053ad6eff040e86c4b263
|
TypeScript
|
jet2jet/js-sequencer
|
/src/main/functions/index.ts
| 3.046875
| 3
|
export function getItemFromArray<T>(arr: T[], item: T): number {
return arr.indexOf(item);
}
export function removeItemFromArray<T>(arr: T[], item: T): boolean {
const n = arr.indexOf(item);
return n >= 0 ? (arr.splice(n, 1), true) : false;
}
export function gcd(m: number, n: number) {
if (m < n) {
const x = m;
m = n;
n = x;
}
while (n) {
const r = m % n;
m = n;
n = r;
}
return m;
}
export function isUndefined(value: any): value is undefined {
return typeof value === 'undefined';
}
export function isAudioAvailable() {
return typeof AudioContext !== 'undefined';
}
export function loadBinaryFromFile(fileElemId: string | HTMLInputElement) {
const f: HTMLInputElement | null =
typeof fileElemId === 'string'
? (document.getElementById(fileElemId) as HTMLInputElement | null)
: fileElemId;
if (!f || !f.files || !f.files.length) {
return Promise.reject(new Error('Invalid argument'));
}
return new Promise<ArrayBuffer>((resolve, reject) => {
const r = new FileReader();
r.onloadend = () => {
resolve(r.result! as ArrayBuffer);
};
r.onerror = (e) => {
reject(e);
};
r.readAsArrayBuffer(f.files![0]);
});
}
|
10be2967e64e78084a786255f034548f5bc4a762
|
TypeScript
|
kyiimn/actapublisher
|
/src/js/pageobject/textstyle/textattribute-absolute.ts
| 2.90625
| 3
|
import ActaFont from '../font/font';
import IActaTextAttribute from '../interface/textattribute';
import ActaTextAttribute from './textattribute';
export enum TextAlign {
JUSTIFY = 0, LEFT, RIGHT, CENTER
}
export default class ActaTextAttributeAbsolute extends IActaTextAttribute {
private _name?: string;
constructor(fontName: string) {
super();
this.fontName = fontName;
this.fontSize = 10;
this.xscale = 1;
this.letterSpacing = 0;
this.lineHeight = 1.2;
this.textAlign = TextAlign.JUSTIFY;
this.underline = false;
this.strikeline = false;
this.indent = 0;
this.colorId = 0;
}
merge(textAttr: IActaTextAttribute) {
super.merge(textAttr);
}
copy(textAttr: ActaTextAttributeAbsolute) {
super.copy(textAttr);
}
set name(name: string) { this._name = name; }
set font(font: ActaFont) { super.font = font; }
set fontName(fontName: string) { super.fontName = fontName; }
set fontSize(size: number) { super.fontSize = size; }
set xscale(scale: number) { super.xscale = scale; }
set letterSpacing(linespacing: number) { super.letterSpacing = linespacing; }
set lineHeight(lineheight: number) { super.lineHeight = lineheight; }
set textAlign(align: TextAlign) { super.textAlign = align; }
set underline(underline: boolean) { super.underline = underline; }
set strikeline(strikeline: boolean) { super.strikeline = strikeline; }
set indent(indent: number) { super.indent = indent; }
set colorId(color: number) { super.colorId = color; }
get name() { return this._name || ''; }
get font() { return super.font as ActaFont; }
get fontName() { return super.fontName; }
get fontSize() { return super.fontSize as number; }
get xscale() { return super.xscale as number; }
get letterSpacing() { return super.letterSpacing as number; }
get lineHeight() { return super.lineHeight as number; }
get textAlign() { return super.textAlign as TextAlign; }
get underline() { return super.underline as boolean; }
get strikeline() { return super.strikeline as boolean; }
get indent() { return super.indent as number; }
get colorId() { return super.colorId as number; }
};
|
f63f45b2d4a321ace3054d5b9a0a76b1c9eddfdb
|
TypeScript
|
patrickedqvist/soundwave
|
/utils/cookies.ts
| 2.828125
| 3
|
import { serialize, CookieSerializeOptions, parse } from 'cookie';
import { NextApiRequest, NextApiResponse } from 'next';
/**
* This sets `cookie` using the `res` object
*/
export function setCookie(
res: NextApiResponse,
tokenName: string,
value: unknown,
options: CookieSerializeOptions = {}
) {
const stringValue =
typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value);
if (options.maxAge) {
options.expires = new Date(Date.now() + options.maxAge);
options.maxAge = options.maxAge;
}
const cookie = serialize(tokenName, String(stringValue), options);
res.setHeader('Set-Cookie', cookie);
}
export function removeCookie(res: NextApiResponse, tokenName: string) {
const cookie = serialize(tokenName, '', {
maxAge: -1,
path: '/',
});
res.setHeader('Set-Cookie', cookie);
}
export function parseCookies(req: NextApiRequest) {
// For API Routes we don't need to parse the cookies.
if (req.cookies) return req.cookies;
// For pages we do need to parse the cookies.
const cookie = req.headers?.cookie;
return parse(cookie || '');
}
export function getTokenCookie(req: NextApiRequest, tokenName: string) {
const cookies = parseCookies(req);
return cookies[tokenName];
}
|
9737627c51b31c63af2f969bf9d53104220cd39b
|
TypeScript
|
denwilliams/mqtt-state
|
/src/throttle.test.ts
| 2.71875
| 3
|
import test from "ava";
import { createTestService } from "./_test-helper";
test.serial("throttle requests to the defined ms value", async (t) => {
const service = createTestService({
rules: [
{
key: "output",
source: "set(event.value);",
subscribe: "input",
throttle: 30,
},
],
});
await service.start();
let resolveLastInput: () => void;
let pLastInput = new Promise<void>((resolve) => {
resolveLastInput = resolve;
});
service.events.publish("input", 1);
t.is(service.activeState.get("output"), 1, "First event should be immediate");
setImmediate(async () => {
const MAX = 100;
for (let i = 1; i < MAX; i++) {
service.events.publish("input", i + 1);
if (i === MAX - 1) {
resolveLastInput();
}
await new Promise((resolve) => setTimeout(resolve, 5));
}
await service.stop();
});
await pLastInput;
await new Promise((resolve) => setTimeout(resolve, 30));
t.is(
service.activeState.get("output"),
100,
"Last event should always be emitted after throttle window"
);
const first = service.mqtt.sent[0];
const last = service.mqtt.sent[service.mqtt.sent.length - 1];
t.deepEqual(first, {
topic: "output",
message: 1,
options: undefined,
});
t.deepEqual(last, {
topic: "output",
message: 100,
options: undefined,
});
t.true(
service.mqtt.sent.length > 15,
"Should only have some throttled events in the middle"
);
t.true(
service.mqtt.sent.length < 70,
"Should not have all the middle events"
);
});
|
2a5640fc8669b6db1765330f70309cd411a45edc
|
TypeScript
|
keklol-123/myProject
|
/src/interfaces/clickEvent.ts
| 2.5625
| 3
|
interface OnClickEventTarget extends EventTarget {
value: string | null | undefined;
}
export default interface OnClickEvent extends React.MouseEvent<HTMLElement> {
target: OnClickEventTarget
}
|
f5c91e2c47f0c2feadeb94f47e09e948f2404448
|
TypeScript
|
scott-census/cedr2
|
/src/app/core/dispatch.service.ts
| 2.53125
| 3
|
import { Injectable } from '@angular/core';
import * as _ from 'lodash';
import { WhenService } from '../shared/when.service';
interface Subscription {
msg: string; // message id - should be changed to enum
when: any; // optional condition - must be valid when clause
func: any; // callee function to execute when activated
callee: any; // subscriber
id: string; // subscriber id
}
interface ConfigSub {
target: string; // id of publisher to listen for
func: string; // name of function to execute when activated
when?: any; // optional condition - must be valid when clause
event: string; // message id - should be changed to enum
}
@Injectable()
export class DispatchService {
private subscriptions: {key?: [Subscription]} = {};
constructor(private whenService: WhenService) { }
registerAll(subsToRegister: Array<ConfigSub>, scope: any, id: string): void {
_.forEach(subsToRegister, (subscr: ConfigSub) => {
if (typeof scope[subscr.func] === 'function') {
this.subscribe(subscr.target, subscr.event, scope[subscr.func], subscr.when, scope, id);
} else {
// issue exception?
console.log(id + ': Trying to subscribe to event ' + subscr.event + ' with non-function ' + subscr.func);
}
});
}
// Alert any subscribers for this message
publish(msg: string, publisherID: string, payload: any): void {
if (!publisherID) {
publisherID = 'system';
}
this.subscriptions[publisherID].forEach(function(subscr: Subscription) {
if (subscr.msg === msg && this.whenService.when(subscr.when)) {
subscr.func.call(subscr.callee, payload, msg);
}
});
}
// Register a listener for a specific message
private subscribe(target: string, msg: string, listener: any, whenClause: any, subscriber: any, id: string): void {
if (!this.subscriptions[target]) {
this.subscriptions[target] = [];
}
this.subscriptions[target].push({ 'msg': msg, 'when': whenClause, 'func': listener, 'callee': subscriber, 'id': id });
}
}
|
7f943d4695a551bdb5a714207f1fa282894f2ca4
|
TypeScript
|
vicente-valls/pingpongfy-firebase
|
/functions/src/errors/InvalidDtoError.ts
| 2.59375
| 3
|
import {ValidationErrorItem} from "./ValidationErrorItem";
export class InvalidDtoError extends Error {
public readonly errors: ValidationErrorItem[];
constructor(errors: ValidationErrorItem[], message: string) {
super(message);
Object.setPrototypeOf(this, InvalidDtoError.prototype);
this.errors = errors;
}
}
|
1404ac792f267593e074a9c0a973d1a74d91db02
|
TypeScript
|
thesayyn/ng-ally
|
/packages/schematics/application/schema.ts
| 2.5625
| 3
|
export interface Schema {
/**
* The root directory of the new application.
*/
projectRoot?: string;
/**
* The name of the application.
*/
name: string;
}
|
19381d6047b1c3b0342c0794239dba30f1086ab2
|
TypeScript
|
doroginalexanderqt/process-manager
|
/server/src/routers/services/db.ts
| 2.796875
| 3
|
import fs from 'fs/promises'
import faker from 'faker'
import { sortBy } from 'lodash'
import { Job, JobStatus, Process } from '../../../types'
import { getRandomInt } from './utils'
import moment from "moment"
type ReadDBShape = {
jobs: Job[]
processes: Process[]
}
const readDB = (): Promise<ReadDBShape> => fs.readFile(`${__dirname}/fake-db.json`, 'utf8').then(JSON.parse)
const writeDB = (newDB: { jobs: Job[]; processes: Process[] }): Promise<void> =>
fs.writeFile(`${__dirname}/fake-db.json`, JSON.stringify(newDB,null ,2))
export const getJobs = async () => (await readDB()).jobs
export const getProcesses = async (sortField?: string) => {
const { processes } = (await readDB())
return sortField ? sortBy(processes, sortField): processes
}
export const createProcess = async (): Promise<Process> => {
const newProcess: Process = {
id: faker.datatype.uuid(),
name: faker.commerce.productName(),
startTime: moment().subtract(getRandomInt(1, 5), 'day').valueOf(),
jobsCount: getRandomInt(1, 11) // [1; 10]
}
const newJobs: Job[] = Array.from(new Array(newProcess.jobsCount), () => ({
id: faker.datatype.uuid(),
name: faker.commerce.product(),
status: faker.random.arrayElement([JobStatus.failed, JobStatus.running, JobStatus.succeed]),
processId: newProcess.id
}))
const oldProcesses = await getProcesses()
const oldJobs = await getJobs()
await writeDB({ processes: oldProcesses.concat(newProcess), jobs: oldJobs.concat(newJobs) })
return newProcess
}
export const deleteProcess = async (idToRemove: string) => {
const oldProcesses = await getProcesses()
const oldJobs = await getJobs()
return await writeDB({
processes: oldProcesses.filter(({ id }) => id !== idToRemove),
jobs: oldJobs.filter(({ processId }) => processId !== idToRemove)
})
}
|
2503d723143a5fd188ba9907f40120bb6f388276
|
TypeScript
|
joonhocho/ts-jutil
|
/src/promise/allValues.test.ts
| 2.59375
| 3
|
import { allValues, promiseAll } from './allValues';
test('allValues', async () => {
expect(
await allValues({
a: undefined,
b: null,
c: 1,
d: Promise.resolve(4),
e: Promise.resolve(Promise.resolve({ f: 'g' })).then((x) =>
Promise.resolve(Promise.resolve(x))
),
})
).toEqual({
a: undefined,
b: null,
c: 1,
d: 4,
e: { f: 'g' },
});
promiseAll({
a: undefined,
b: null,
c: 1,
d: Promise.resolve(4),
e: Promise.resolve({ f: 'g' }),
f: Promise.reject(new Error('eee')),
}).then(
() => {
throw new Error('should not be here');
},
(e) => {
expect(e.message).toBe('eee');
}
);
});
|
f89f869573bba52bb86279e014e7f5aa30397e01
|
TypeScript
|
khirshah/react-component-library
|
/src/components/DatePicker/reducers/stateMachine.ts
| 2.84375
| 3
|
import {
Action,
ActionType,
State,
StateType,
} from '../types/stateMachineTypes';
const stateMachine = (
state: State,
action: Action,
): State => {
switch (action.type) {
case ActionType.UserClickedInputField:
return state;
case ActionType.UserClickedCalendarButton:
if (state.currentStatus === StateType.Idle) {
return {
...state,
currentStatus: StateType.DayView,
};
}
return {
...state,
currentStatus: StateType.Idle,
};
default:
return state;
}
};
export default stateMachine;
|
3c9d2fa21a918b252e2d156792f282b188f645af
|
TypeScript
|
JerlyJr/POO-Carro
|
/Principal.ts
| 3.15625
| 3
|
declare function require(msg : string) : any;
var readline = require('readline-sync');
import {Carro} from "./Carro";{
let car : Carro = new Carro();
while(true){
let statusCar : string = "\n" +
"mostrar - Informações sobre o carro \n" +
"in - adiciona um passageiro ao carro\n" +
"out - remove um passageiro do carro\n" +
"abastecer - abastece o carro\n" +
"andar - andar a distância determinada pelo usuário\n" +
"sair - para o programa";
console.log (statusCar);
let ações : string = readline.question("\n" +"Determine uma atividade do carro: ");
if (ações == "sair"){
console.log("Até a próxima");
break;
}
switch(ações){
case "mostrar" :
console.log("Passageiros: " + car.pass + " Gasolina: "+ car.gas + " Quilometragem: "+ car.km);
break;
case "in" :
car.entrar();
break;
case "out" :
car.sair();
break;
case "abastecer" :
let valor : number = Number(readline.question("Quantidade de gasolina: "));
car.abastecer(valor);
break;
case "andar" :
let andar : number = Number (readline.question("Distancia a ser percorrida: "));
car.andar(andar);
break;
default :
console.log("Comando Inválido")
}
}
}
|
5851615a7e8eb8fb19dbf63cbc7504595fbeee8f
|
TypeScript
|
delta94/ServiceHero
|
/servicehero-app/src/types/index.ts
| 2.515625
| 3
|
import { RootState } from './RootState';
export interface JwtPayload {
name: string;
sub: string;
type: string;
email: string;
iat: number;
exp: number;
}
export enum UserType {
Client = 'Client',
Specialist = 'Specialist',
Unknown = 'Unknown',
}
export enum ListingType {
CarRepair = 'CarRepair',
Carpentry = 'Carpentry',
Cleaning = 'Cleaning',
Demolition = 'Demolition',
HomeImprovement = 'HomeImprovement',
Landscaping = 'Landscaping',
Moving = 'Moving',
Other = 'Other',
}
export interface User {
_id: string;
name: string;
email: string;
type: UserType;
rating?: number;
}
export interface Listing {
_id: string;
type: ListingType;
description: string;
hourlyRate: number;
availability: string[];
specialist: User;
}
export interface ListingDto {
type: ListingType;
description: string;
hourlyRate: number;
availability: string[];
}
export interface FilterTypes {
hourlyRateFrom?: number | null;
hourlyRateTo?: number | null;
listingTypes?: ListingType[] | null;
rating?: number | null;
}
export enum ProjectStatus {
OfferPending = 'OfferPending',
InProgress = 'InProgress',
OfferRejected = 'OfferRejected',
CompletePending = 'CompletePending',
CompleteRejected = 'CompleteRejected',
Completed = 'Completed',
}
export interface Review {
comment: string;
rating: number;
}
export interface Project {
_id: string;
client: User;
specialist: User;
listing: Listing;
status: ProjectStatus;
review: Review;
}
export type { RootState };
|
e4fce4f989eb931d9c84e7ffd9bd2a6910d85c1d
|
TypeScript
|
rafaeljfec2/desafio-backend-framework
|
/src/infraestructure/repositories/orm/postgres/repository/Account/PostgresAccountRepository.ts
| 2.546875
| 3
|
import { IAccount } from '@entities/Account/IAccount';
import { IAccountRepository } from '@entities/Account/IAccountRepository';
import { ICreateAccountDTO } from '@entities/Account/ICreateAccountDTO';
import { getRepository, Repository } from 'typeorm';
import Account from '../../entities/Account/Account';
export default class PostgresAccountRepository implements IAccountRepository {
private ormRepository: Repository<Account>;
public async create({
name,
document,
email,
password,
type,
}: ICreateAccountDTO): Promise<Account> {
this.ormRepository = getRepository(Account);
const account = this.ormRepository.create({
name,
document,
email,
type,
password,
});
return account;
}
public async save(account: IAccount): Promise<IAccount> {
this.ormRepository = getRepository(Account);
await this.ormRepository.save(account);
return account;
}
public async findByDocument(document: string): Promise<IAccount | undefined> {
this.ormRepository = getRepository(Account);
const account = this.ormRepository.findOne({
where: {
document,
},
});
return account;
}
public async findByEmail(email: string): Promise<IAccount | undefined> {
this.ormRepository = getRepository(Account);
const account = this.ormRepository.findOne({
where: {
email,
},
});
return account;
}
public async findById(id: number): Promise<IAccount | undefined> {
this.ormRepository = getRepository(Account);
const account = this.ormRepository.findOne({
where: {
id,
},
});
return account;
}
}
|
0dc6dfaff9e243f4c3c1b9540d1c0469fdb87b75
|
TypeScript
|
IlyaSemenov/vue-observable-persist
|
/src/index.ts
| 3.015625
| 3
|
import { merge, pick } from "lodash"
import Vue from "vue"
interface Options {
storage?: Pick<Storage, "getItem" | "setItem">
key: string
fields?: string[]
serialize: (data: any) => any
deserialize: (data: any) => any
}
const defaults: Options = {
key: "store",
serialize: JSON.stringify,
deserialize: JSON.parse,
}
export default function persist<T>(store: T, opts?: Partial<Options>): T {
const options: Options = { ...defaults, ...opts }
// In some environments there is no localStorage at all.
// If we provided localStorage in defaults, it would crash.
const storage = options.storage || localStorage
const filter_data = (data: T) =>
options.fields ? pick(data, options.fields) : data
try {
merge(store, filter_data(options.deserialize(storage.getItem(options.key))))
} catch (err) {}
// Support Vue objects and plain observable objects
const store_data = (store as any).$data || store
const watcher = new Vue({
computed: {
data: () => store_data,
},
})
watcher.$watch(
"data",
data => storage.setItem(options.key, options.serialize(filter_data(data))),
{ deep: true },
)
return store
}
|
0532a9cc5f31098902d43e91a3cbfaaafe31c434
|
TypeScript
|
artalar/bacon.js
|
/test/startwith.ts
| 3.015625
| 3
|
import * as Bacon from "..";
import { expect } from "chai";
import { expectStreamEvents, expectPropertyEvents, series, semiunstable, unstable, fromArray } from "./util/SpecHelper";
describe("EventStream.startWith", function() {
describe("provides seed value, then the rest", () =>
expectStreamEvents(
function() {
const left = series(1, [1, 2, 3]);
return left.startWith(0);
},
[0, 1, 2, 3], semiunstable)
);
describe("works with synchronous source", () =>
expectStreamEvents(
function() {
const left = fromArray([1, 2, 3]);
return left.startWith(0);
},
[0, 1, 2, 3], semiunstable)
);
return it("toString", () => expect(Bacon.never().startWith(0).toString()).to.equal("Bacon.never().startWith(0)"));
});
describe("Property.startWith", function() {
describe("starts with given value if the Property doesn't have an initial value", () =>
expectPropertyEvents(
function() {
const left = series(1, [1, 2, 3]).toProperty();
return left.startWith(0);
},
[0, 1, 2, 3], semiunstable)
);
describe("works with synchronous source", () =>
expectPropertyEvents(
function() {
const left = fromArray([1, 2, 3]).toProperty();
return left.startWith(0);
},
[0, 1, 2, 3], unstable)
);
describe("starts with the initial value of the Property if any", () =>
expectPropertyEvents(
function() {
const left = series(1, [1, 2, 3]).toProperty(0);
return left.startWith(9);
},
[0, 1, 2, 3], semiunstable)
);
return it("toString", () => expect(Bacon.constant(2).startWith(1).toString()).to.equal("Bacon.constant(2).startWith(1)"));
});
|
0d1eed731a4bb0ec807bbef51fc4529393413e9e
|
TypeScript
|
sH4rk0/fornovo-presentation
|
/src/slides/slide49.ts
| 2.703125
| 3
|
export default class Slide49 extends Phaser.Scene {
private _text: Phaser.GameObjects.Text;
private _image: Phaser.GameObjects.Image;
private _ground: Phaser.GameObjects.Image;
private _isCollide: boolean;
constructor() {
super({
key: "Slide49"
});
//console.log(this.scene.key + ":constructor");
}
preload() {
console.log(this.scene.key + ":preload");
this.load.image("sprite", "/assets/images/sprite.png");
}
create(): void {
console.log(this.scene.key + ":create");
this._isCollide = false;
let graphics = this.make
.graphics({})
.fillStyle(0x00ff00)
.fillRect(0, 0, 1280, 100);
graphics.generateTexture("ground", 1280, 100);
graphics.destroy();
this._ground = this.physics.add
.image(0, 650, "ground")
.setDepth(10000)
.setOrigin(0)
.setAlpha(1)
.setImmovable(true);
//@ts-ignore
this._ground.body.allowGravity = false;
this._image = this.physics.add
.image(640, 400, "sprite")
.setScale(2)
.setGravityY(10);
this._text = this.add.text(640, 400, "y:" + this._image.y).setOrigin(0.5);
this.physics.add.collider(
this._image,
this._ground,
() => {
this._isCollide = true;
this._text
.setText("COLLISIONE!")
.setFontSize(40)
.setColor("#00ff00");
},
undefined,
this
);
}
update(): void {
if (!this._isCollide) {
if (this._image.y > 600) {
this._text
.setText("NULLA!!!!")
.setFontSize(40)
.setColor("#ff0000");
} else {
this._text.setText("y:" + this._image.y);
}
//console.log(this.scene.key + ":update");
}
}
}
|
f928e0b8696b7d5d776db4544e3249fcdfb22aa8
|
TypeScript
|
iharabukhouski/mango
|
/server/src/products/dal/data.ts
| 2.71875
| 3
|
import { getRepository } from 'typeorm';
import * as R from 'ramda';
import { Product } from './entity';
import { Review } from '../../reviews/dal/entity';
/**
* List Products
*/
export const listProducts =
async (): Promise<Product[]> => {
const repository = getRepository(Product);
return await repository
.find();
}
/**
* Create Product
*/
export const createProduct =
async (partialProduct: Pick<Product, `name`>): Promise<Product | undefined> => {
const repository = getRepository(Product);
return await repository
.save(
{
name: partialProduct.name,
},
);
}
/**
* Read Product
*/
type ProductComputedValues = {
avgScore?: number;
};
type ProductReadView =
& Product
& ProductComputedValues;
export const readProduct =
async (productId: Product['id']): Promise<ProductReadView | undefined> => {
const repository = getRepository(Product);
const rawAndEntities = await repository
.createQueryBuilder(`product`)
.addSelect(
(subQuery) => {
return subQuery
.select(`ROUND(AVG(review.score), 1)`)
.from(Review, `review`)
.where(`review.productId = :productId`, { productId });
},
`avgScore`,
)
.leftJoinAndSelect(`product.reviews`, `review`)
.where(`product.id = :productId`, { productId })
.orderBy(`review.createdAt`, `DESC`)
/**
* @see https://github.com/typeorm/typeorm/issues/296
* Unfortunately, TypeORM does not support yet somethink like `addSelectAndMap` or `ComputedColumn`
*/
.getRawAndEntities();
const entity = rawAndEntities.entities[0];
const raw = rawAndEntities.raw[0];
if (R.isNil(entity) || R.isNil(raw)) {
return undefined;
}
/**
* `raw.avgScore` is `null` if the product has 0 reviews
*/
const avgScore =
R.isNil(raw.avgScore)
? undefined
: parseFloat(raw.avgScore);
return {
...entity,
avgScore,
};
}
/**
* Update Product
*/
export const updateProduct =
(productId: Product['id']) =>
async (partialProduct: Pick<Product, `name`>): Promise<Product | undefined> => {
const repository = getRepository(Product);
const product = await repository.findOne(productId);
if (R.isNil(product)) {
return undefined;
}
return await repository.save(
{
...product,
name: partialProduct.name,
},
);
}
/**
* Delete Product
*/
export const deleteProduct =
async (productId: Product['id']): Promise<Product | undefined> => {
const repository = getRepository(Product);
const product = await repository.findOne(productId);
if (R.isNil(product)) {
return undefined;
}
return await repository.remove(product);
}
|
3d0dd5ae31aa6fb987cb554389d7c52a47bdec1b
|
TypeScript
|
sridharmallela/karma-typescript
|
/tests/integration-latest/src/ambient/ambient-module-tester.ts
| 2.515625
| 3
|
import * as module from "ambient";
export class AmbientModuleTester implements module.AmbientModule {
public doSomething(): string {
return "ambient";
}
public testAmbientModule() {
return this.doSomething();
}
}
|
c54caab8ede1822e5a382eb31c5ab83a85372156
|
TypeScript
|
MartijnHols/fullstack-typescript
|
/backend/src/modules/account/actions/_authenticateAccount.ts
| 2.984375
| 3
|
import Account from '../models/Account'
export class InvalidUsernameError extends Error {}
export class AccountUnavailableError extends Error {}
export class InvalidPasswordError extends Error {}
const authenticateAccount = async (
username: string,
password: string,
): Promise<Account> => {
const account = await Account.findOne({
where: {
email: username,
},
})
if (!account) {
// We differentiate invalid usernames to provide optimal user experience.
// The security benefit of hiding if an email is in use is extremely
// minimal, while it would require us to incapacitate email validation on
// registration, lost password, login and any other place we might want to
// include some sort of email search in the future, all of which are
// important places to help the user.
throw new InvalidUsernameError(
`No account could be found for the username: ${username}`,
)
}
if (!account.hasPassword) {
throw new AccountUnavailableError(
'This account has no password. Logging in to this account is not possible at this time.',
)
}
if (!(await account.validatePassword(password))) {
throw new InvalidPasswordError('This password is invalid')
}
return account
}
export default authenticateAccount
|
09bb8f576ca26ae39f5c57540b3ce4644f0d43be
|
TypeScript
|
dhianpratama/koa-router-rx6
|
/src/lib/koa-router-rx.ts
| 2.6875
| 3
|
import { Context } from "koa";
import * as Router from "koa-router";
import { Observable, of } from "rxjs";
type Epic<A, B> = (observable: Observable<A>) => Observable<B>;
enum HttpMethod {
GET, POST, PUT, PATCH, DELETE, OPTIONS,
}
class KoaRouterRx extends Router {
constructor (...args: any[]) {
super(...args);
}
public GET<B> (path: string, epic: Epic<object, B>) {
this._handleRequest(HttpMethod.GET, path, epic);
}
public POST<B> (path: string, epic: Epic<object, B>) {
this._handleRequest(HttpMethod.POST, path, epic);
}
public PUT<B> (path: string, epic: Epic<object, B>) {
this._handleRequest(HttpMethod.PUT, path, epic);
}
public PATCH<B> (path: string, epic: Epic<object, B>) {
this._handleRequest(HttpMethod.PATCH, path, epic);
}
public DELETE<B> (path: string, epic: Epic<object, B>) {
this._handleRequest(HttpMethod.DELETE, path, epic);
}
public OPTIONS<B> (path: string, epic: Epic<object, B>) {
this._handleRequest(HttpMethod.OPTIONS, path, epic);
}
private _handleContext<B> (epic: Epic<object, B>) {
return (ctx: Context) => {
epic(of(ctx))
.subscribe();
};
}
private _handleRequest<B> (method: HttpMethod, path: string, epic: Epic<object, B>) {
switch (method) {
case HttpMethod.GET:
this.get(path, this._handleContext(epic));
break;
case HttpMethod.POST:
this.post(path, this._handleContext(epic));
break;
case HttpMethod.PUT:
this.put(path, this._handleContext(epic));
break;
case HttpMethod.DELETE:
this.delete(path, this._handleContext(epic));
break;
case HttpMethod.PATCH:
this.patch(path, this._handleContext(epic));
break;
case HttpMethod.OPTIONS:
this.options(path, this._handleContext(epic));
break;
}
}
}
export { KoaRouterRx };
|
0ff74ec5c91ded7350344c015c062d72b7d432bc
|
TypeScript
|
GreatLaboratory/typescript-practice
|
/advanced/2-index_type.ts
| 3
| 3
|
{
type Person = {
name: string;
age: number;
gender: 'male' | 'female';
};
const p: Person = {
name: 'mg',
age: 24,
gender: 'male',
};
console.log(p.name);
console.log(p['name']);
type Name = Person['name'];
// const name: Name = 123; // error
const name: Name = 'mg';
type Gender = Person['gender'];
// const gender: Gender = 'qwer'; // error
const gender: Gender = 'male';
type Keys = keyof Person;
const keys1: Keys = 'age';
const keys2: Keys = 'gender';
const keys3: Keys = 'name';
// const keys4: Keys = 'qwer' // error
type Animal = {
type: string;
gender: Person['gender'];
};
}
|
2924f369f1d879853c50c3bc44f05e6ab3d3ceb7
|
TypeScript
|
varubi/nearley
|
/src/parser.ts
| 2.90625
| 3
|
import { Column } from "./column";
import { Grammar } from "./grammar";
import { StreamLexer } from "./streamlexer";
export class Parser {
static fail = {};
grammar;
lexer;
lexerState;
table;
current;
results;
constructor(private rules, private start?, private options?) {
if (rules instanceof Grammar) {
var grammar = rules;
var options = start;
} else {
var grammar = Grammar.fromCompiled(rules, start);
}
this.grammar = grammar;
// Read options
this.options = {
keepHistory: false,
lexer: grammar.lexer || new StreamLexer,
};
for (var key in (options || {})) {
this.options[key] = options[key];
}
// Setup lexer
this.lexer = this.options.lexer;
this.lexerState = undefined;
// Setup a table
var column = new Column(grammar, 0);
this.table = [column];
// I could be expecting anything.
column.wants[grammar.start] = [];
column.predict(grammar.start);
// TODO what if start rule is nullable?
column.process();
this.current = 0; // token index
}
feed(chunk) {
var lexer = this.lexer;
lexer.reset(chunk, this.lexerState);
var token;
while (token = lexer.next()) {
// We add new states to table[current+1]
var column = this.table[this.current];
// GC unused states
if (!this.options.keepHistory) {
delete this.table[this.current - 1];
}
var n = this.current + 1;
var nextColumn = new Column(this.grammar, n);
this.table.push(nextColumn);
// Advance all tokens that expect the symbol
var literal = token.text !== undefined ? token.text : token.value;
var value = lexer.constructor === StreamLexer ? token.value : token;
var scannable = column.scannable;
for (var w = scannable.length; w--;) {
var state = scannable[w];
var expect = state.rule.symbols[state.dot];
// Try to consume the token
// either regex or literal
if (expect.test ? expect.test(value) :
expect.type ? expect.type === token.type
: expect.literal === literal) {
// Add it
var next = state.nextState({ data: value, token: token, isToken: true, reference: n - 1 });
nextColumn.states.push(next);
}
}
// Next, for each of the rules, we either
// (a) complete it, and try to see if the reference row expected that
// rule
// (b) predict the next nonterminal it expects by adding that
// nonterminal's start state
// To prevent duplication, we also keep track of rules we have already
// added
nextColumn.process();
// If needed, throw an error:
if (nextColumn.states.length === 0) {
// No states at all! This is not good.
var err: TokenError = new Error(this.reportError(token));
err.offset = this.current;
err.token = token;
throw err;
}
// maybe save lexer state
if (this.options.keepHistory) {
column.lexerState = lexer.save()
}
this.current++;
}
if (column) {
this.lexerState = lexer.save()
}
// Incrementally keep track of results
this.results = this.finish();
// Allow chaining, for whatever it's worth
return this;
};
reportError(token) {
var lines = [];
const tokenDisplay = (token.type ? token.type + " token: " : "") + JSON.stringify(token.value !== undefined ? token.value : token);
lines.push(this.lexer.formatError(token, "Syntax error"));
lines.push('Unexpected ' + tokenDisplay + '. Instead, I was expecting to see one of the following:\n');
const lastColumnIndex = this.table.length - 2;
const lastColumn = this.table[lastColumnIndex];
const expectantStates = lastColumn.states
.filter(function (state) {
const nextSymbol = state.rule.symbols[state.dot];
return nextSymbol && typeof nextSymbol !== "string";
});
// Display a "state stack" for each expectant state
// - which shows you how this state came to be, step by step.
// If there is more than one derivation, we only display the first one.
const stateStacks = expectantStates
.map(function (state) {
const stacks = this.buildStateStacks(state, []);
return stacks[0];
}, this);
// Display each state that is expecting a terminal symbol next.
stateStacks.forEach(function (stateStack) {
const state = stateStack[0];
const nextSymbol = state.rule.symbols[state.dot];
const symbolDisplay = this.getSymbolDisplay(nextSymbol);
lines.push('A ' + symbolDisplay + ' based on:');
this.displayStateStack(stateStack, lines);
}, this);
lines.push("");
return lines.join("\n");
};
displayStateStack(stateStack, lines) {
var lastDisplay;
var sameDisplayCount = 0;
for (let j = 0; j < stateStack.length; j++) {
const state = stateStack[j];
const display = state.rule.toString(state.dot);
if (display === lastDisplay) {
sameDisplayCount++;
} else {
if (sameDisplayCount > 0) {
lines.push(' ⬆ ︎' + sameDisplayCount + ' more lines identical to this');
}
sameDisplayCount = 0;
lines.push(' ' + display);
}
lastDisplay = display;
}
};
getSymbolDisplay(symbol) {
const type = typeof symbol;
if (type === "string") {
return symbol;
} else if (type === "object" && symbol.literal) {
return JSON.stringify(symbol.literal);
} else if (type === "object" && symbol instanceof RegExp) {
return 'character matching ' + symbol;
} else if (type === "object" && symbol.type) {
return symbol.type + ' token';
} else {
throw new Error('Unknown symbol type: ' + symbol);
}
};
/*
Builds a number of "state stacks". You can think of a state stack as the call stack
of the recursive-descent parser which the Nearley parse algorithm simulates.
A state stack is represented as an array of state objects. Within a
state stack, the first item of the array will be the starting
state, with each successive item in the array going further back into history.
This function needs to be given a starting state and an empty array representing
the visited states, and it returns an array of state stacks.
*/
buildStateStacks(state, visited) {
if (visited.indexOf(state) !== -1) {
// Found cycle, return empty array (meaning no stacks)
// to eliminate this path from the results, because
// we don't know how to display it meaningfully
return [];
}
if (state.wantedBy.length === 0) {
return [[state]];
}
var that = this;
return state.wantedBy.reduce(function (stacks, prevState) {
return stacks.concat(that.buildStateStacks(
prevState,
[state].concat(visited))
.map(function (stack) {
return [state].concat(stack);
}));
}, []);
};
save() {
var column = this.table[this.current];
column.lexerState = this.lexerState;
return column;
};
restore(column) {
var index = column.index;
this.current = index;
this.table[index] = column;
this.table.splice(index + 1);
this.lexerState = column.lexerState;
// Incrementally keep track of results
this.results = this.finish();
};
// nb. deprecated: use save/restore instead!
rewind(index) {
if (!this.options.keepHistory) {
throw new Error('set option `keepHistory` to enable rewinding')
}
// nb. recall column (table) indicies fall between token indicies.
// col 0 -- token 0 -- col 1
this.restore(this.table[index]);
};
finish() {
// Return the possible parsings
var considerations = [];
var start = this.grammar.start;
var column = this.table[this.table.length - 1]
column.states.forEach(function (t) {
if (t.rule.name === start
&& t.dot === t.rule.symbols.length
&& t.reference === 0
&& t.data !== Parser.fail) {
considerations.push(t);
}
});
return considerations.map(function (c) { return c.data; });
};
}
interface TokenError extends Error {
offset?;
token?;
}
|
8288b89d7d56e9268fc6b751e8be2b92ff055a69
|
TypeScript
|
tiagocorreiaalmeida/design-patterns
|
/src/behaviour/observer/observer.test.ts
| 2.984375
| 3
|
import { Observer } from "./observer";
interface Changes {
value: string;
}
const makeObserver = () => {
const listener = {
update: jest.fn()
};
const changes: Changes = {
value: "system updated"
};
const observer = new Observer<Changes>();
return {
changes,
observer,
listener
};
};
describe("Observer", () => {
it("a listener should be called on notify", () => {
const { listener, changes, observer } = makeObserver();
observer.subscribe(listener);
observer.notify(changes);
expect(listener.update).toHaveBeenCalledWith(changes);
});
it("a listener should be able to unsubscribe from changes", () => {
const { listener, changes, observer } = makeObserver();
observer.subscribe(listener);
observer.notify(changes);
expect(listener.update).toBeCalledTimes(1);
observer.unsubscribe(listener);
expect(listener.update).toBeCalledTimes(1);
});
});
|