Datasets:

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
9a46eadb2e1c29823b734e6c8d185004f0a9b9c2
TypeScript
cacabo/starter
/src/routes/Users.ts
2.625
3
import { Request, Response, Router } from 'express' import { BAD_REQUEST, CREATED, OK, NOT_FOUND } from 'http-status-codes' import { ParamsDictionary } from 'express-serve-static-core' import { UserDao } from '@daos' import { genericParamMissingError, adminMW } from '@shared' import { IUser } from '@entities' import { IUserDao } from 'src/daos/User/UserDao' import { handleError, handleNotFound, handleBadRequest } from './handlers' // TODO have more than just admin MW (probably need more info in the JWT) // Init shared const router = Router() const userDao: IUserDao = new UserDao() /** * Get all users */ router.get('/all', adminMW, async (_, res: Response) => { try { const users = await userDao.getAll() return res.status(OK).json({ users }) } catch (err) { handleError(res, err) } }) /** * Get user with the specified id */ router.get('/:id', adminMW, async (req: Request, res: Response) => { try { const { id } = req.params as ParamsDictionary const user = await userDao.getOne(id) if (!user) { return res.status(NOT_FOUND).json({ error: 'User not found' }) } return res.status(OK).json(user) } catch (err) { handleError(res, err) } }) export interface IUpdateUserBody { user: Partial<IUser> } /** * Update the specified user's account */ router.put('/:id/update', adminMW, async (req: Request, res: Response) => { try { const { id } = req.params as ParamsDictionary // Check parameters const { user } = req.body as IUpdateUserBody if (!user) { return res.status(BAD_REQUEST).json({ error: genericParamMissingError, }) } const editableFields = { firstName: true, lastName: true } const keys: string[] = Object.keys(user) for (const key of keys) { if (!(key in editableFields) && key !== '_id') { return res .status(BAD_REQUEST) .json({ error: `Cannot update property ${key} on user` }) } } // TODO this might not be needed if (user._id && user._id !== id) { return res .status(BAD_REQUEST) .json({ error: 'Provided user IDs do not match' }) } // Update user await userDao.update(id, user) return res.status(OK).end() } catch (err) { handleError(res, err) } }) /** * Delete the user with the specified ID */ router.delete('/:id/delete', adminMW, async (req: Request, res: Response) => { try { const { id } = req.params as ParamsDictionary await userDao.delete(id) return res.status(OK).end() } catch (err) { handleError(res, err) } }) export interface IChangePasswordBody { id: any password: string newPassword: string } router.post( '/password/change', adminMW, async (req: Request, res: Response) => { try { const { id, password, newPassword } = req.body as IChangePasswordBody if (!id) return handleBadRequest(res, 'Missing ID') if (!password) return handleBadRequest(res, 'Missing password') if (!newPassword) return handleBadRequest(res, 'Missing newPassword') return await userDao.changePassword(id, password, newPassword) } catch (err) { handleError(res, err) } }, ) export interface IForgotPasswordBody { email: string } router.post( '/password/forgot', adminMW, async (req: Request, res: Response) => { try { const { email } = req.body if (!email) return handleBadRequest(res, 'Missing email') const user = await userDao.getOneByEmail(email) if (!user) return handleNotFound(res, 'User with email not found') return await userDao.requestForgotPassword(user._id) } catch (err) { handleError(res, err) } }, ) export interface IResetPasswordBody { token: string id: any newPassword: string } router.post('/password/reset', adminMW, async (req: Request, res: Response) => { try { const { token, id, newPassword } = req.body as IResetPasswordBody if (!token) return handleBadRequest(res, 'Missing token') if (!id) return handleBadRequest(res, 'Missing ID') if (!newPassword) return handleBadRequest(res, 'Missing newPassword') return await userDao.resetForgotPassword(id, token, newPassword) } catch (err) { handleError(res, err) } }) export default router
bb87521160976fca43f485da60b499f7805fb897
TypeScript
ecadlabs/taquito
/integration-tests/data/contractWithUnpair.ts
3.03125
3
export const miStr = `parameter int; # the participant's guess storage (pair int # the number of guesses made by participants address # the address to send the winning pot to if the participants fail ); code { # (pair parameter storage) : [] # make sure that the participant has contributed at least 1 tez PUSH mutez 1000000; AMOUNT; IFCMPGE {} { PUSH string "You did not provide enough tez."; FAILWITH; }; # check that the number of guesses has not been exceeded UNPAIR; SWAP; # storage : parameter : [] DUP; # storage : storage : parameter : [] CAR; # int : storage : parameter : [] DIP { PUSH int 15; }; IFCMPLT { # check if guess is correct SWAP; # parameter : storage : [] PUSH int 34; IFCMPEQ { # the participant guessed correctly, give them the tokens. SENDER; CONTRACT unit; IF_SOME {} { FAILWITH; }; BALANCE; UNIT; TRANSFER_TOKENS; NIL operation; SWAP; CONS; PAIR; } { # the participant guessed incorrectly, increment the number of guesses performed. UNPAIR; PUSH int 1; ADD; PAIR; NIL operation; PAIR; }; } { # attempts exceeded, give winnings to the specified address DIP { DROP; }; # storage : [] DUP; CDR; CONTRACT unit; IF_SOME {} { FAILWITH; }; BALANCE; UNIT; TRANSFER_TOKENS; NIL operation; SWAP; CONS; PAIR; }; }; `; export const miObject = [ { prim: 'parameter', args: [ { prim: 'int' } ] }, { prim: 'storage', args: [ { prim: 'pair', args: [ { prim: 'int' }, { prim: 'address' } ] } ] }, { prim: 'code', args: [ [ { prim: 'PUSH', args: [ { prim: 'mutez' }, { int: '1000000' } ] }, { prim: 'AMOUNT' }, [ { prim: 'COMPARE' }, { prim: 'GE' }, { prim: 'IF', args: [ [], [ { prim: 'PUSH', args: [ { prim: 'string' }, { string: 'You did not provide enough tez.' } ] }, { prim: 'FAILWITH' } ] ] } ], { prim: 'UNPAIR' }, { prim: 'SWAP' }, { prim: 'DUP' }, { prim: 'CAR' }, { prim: 'DIP', args: [ [ { prim: 'PUSH', args: [ { prim: 'int' }, { int: '15' } ] } ] ] }, [ { prim: 'COMPARE' }, { prim: 'LT' }, { prim: 'IF', args: [ [ { prim: 'SWAP' }, { prim: 'PUSH', args: [ { prim: 'int' }, { int: '34' } ] }, [ { prim: 'COMPARE' }, { prim: 'EQ' }, { prim: 'IF', args: [ [ { prim: 'SENDER' }, { prim: 'CONTRACT', args: [ { prim: 'unit' } ] }, [ { prim: 'IF_NONE', args: [ [ { prim: 'FAILWITH' } ], [] ] } ], { prim: 'BALANCE' }, { prim: 'UNIT' }, { prim: 'TRANSFER_TOKENS' }, { prim: 'NIL', args: [ { prim: 'operation' } ] }, { prim: 'SWAP' }, { prim: 'CONS' }, { prim: 'PAIR' } ], [ { prim: 'UNPAIR' }, { prim: 'PUSH', args: [ { prim: 'int' }, { int: '1' } ] }, { prim: 'ADD' }, { prim: 'PAIR' }, { prim: 'NIL', args: [ { prim: 'operation' } ] }, { prim: 'PAIR' } ] ] } ] ], [ { prim: 'DIP', args: [ [ { prim: 'DROP' } ] ] }, { prim: 'DUP' }, { prim: 'CDR' }, { prim: 'CONTRACT', args: [ { prim: 'unit' } ] }, [ { prim: 'IF_NONE', args: [ [ { prim: 'FAILWITH' } ], [] ] } ], { prim: 'BALANCE' }, { prim: 'UNIT' }, { prim: 'TRANSFER_TOKENS' }, { prim: 'NIL', args: [ { prim: 'operation' } ] }, { prim: 'SWAP' }, { prim: 'CONS' }, { prim: 'PAIR' } ] ] } ] ] ] } ];
f64592007ee8d5a4e72ebc4047c978e8716b38d1
TypeScript
blackbaud/skyux
/libs/components/popovers/src/lib/modules/popover/types/popover-message.ts
2.65625
3
import { SkyPopoverMessageType } from './popover-message-type'; /** * Specifies messages to be sent to the popover component. */ export interface SkyPopoverMessage { /** * The type of message to send. */ type?: SkyPopoverMessageType; }
3a48b17a40df5ddc398fca9d9aff9d20f5740859
TypeScript
eternalconcert/suitescript-types-tools-and-frameworks
/src/record/typedRecord/generated/taxgroup.ts
2.703125
3
// This file is auto generated, do not edit it. /** * Tax Group Fields Definition. * Record's Internal Id: taxgroup. * Supports Custom Fields: true */ export interface taxgroupFields { /** Enter the city where this tax should be applied. This value is used by NetSuite to automatically determine the correct tax when an order is entered or a customer places an order on your website. This field is available only if the SuiteTax feature is disabled in your account. */ city?: string; /** Enter the county where this tax should be applied. This value is used by NetSuite to automatically determine the correct tax when an order is entered or a customer places an order on your website. This field is available only if the SuiteTax feature is disabled in your account. */ county?: string; /** Enter a description for this record. */ description?: string; /** */ externalid?: string; /** Check this box to apply the tax code to the children of the subsidiary that you selected in the Subsidiaries field. In the Subsidiaries field, colons separate parent subsidiaries (on the left) from their children (on the right). This field is available only if the SuiteTax feature is disabled in your account. */ includechildren?: boolean; /** Check this box if this code is the default tax group selected on transactions. This tax code is selected if the customer's shipping address does not match another tax group. This field is available only if the SuiteTax feature is disabled in your account. */ isdefault?: boolean; /** This field is false by default. Check this box to inactivate this record. Inactive records do not show on transactions and records for selection in lists. On nexus and tax type records, this field is available only if the SuiteTax feature is enabled in your account. */ isinactive?: boolean; /** Enter a name for this record. This field is available only if the SuiteTax feature is disabled in your account. */ itemid: string; /** */ itemtype?: string; /** */ nexuscountry?: string; /** Check this box if you want this tax code to include GST in addition to the line item amount when calculating PST. If you do not check this box, PST is calculated for the line item amount only. */ piggyback?: boolean; /** Enter the appropriate tax rate as a percentage. Example: 8% This percentage will be calculated when you select this tax item on transactions. This field is available only if the SuiteTax feature is disabled in your account. */ rate?: number; /** Select the state, province, or county that you are making this record for. You can create a new state, province, or county at Setup > Company > Setup Tasks > States/Provinces/Counties. On tax code records, this field is available only if the SuiteTax feature is disabled in your account. */ state?: string; /** */ subsidiary?: string; /** Select the GST item you want to include in this tax code. */ taxitem1: string; /** Select the PST item you want to include in this tax code. */ taxitem2: string; /** Select the tax type for this tax code. You can create a new tax type at Setup > Accounting > Taxes > Tax Types > New. If the SuiteTax feature is enabled in your account, you cannot change the value in the Tax Type field after the tax code record has been saved. */ taxtype: string; /** The tax rate for the GST item is shown here. */ unitprice1?: string; /** The rate for the PST item is shown here. */ unitprice2?: string; /** Enter the zip codes where this tax should be applied. Separate each zip code with a comma. This value is used by NetSuite to automatically determine the correct tax when an order is entered or a customer places an order on your website. This field is available only if the SuiteTax feature is disabled in your account. */ zip?: string; } /** * Tax Group Sublists Definition. * Record's Internal Id: taxgroup. * Supports Custom Fields: true */ export interface taxgroupSublists { /** taxitem: Tax Codes */ taxitem: { /** basis - Basis */ basis: string; /** city - */ city: string; /** county - */ county: string; /** rate - Rate */ rate: number; /** state - */ state: string; /** taxitemnkey - */ taxitemnkey: string; /** taxname - Name */ taxname?: string; /** taxname2 - */ taxname2: string; /** taxtype - Type */ taxtype: string; } }
75e84efb8ce610ad2eef5b3f488adaeaa80edb62
TypeScript
ethers-io/ethers.js
/lib.esm/utils/properties.d.ts
2.6875
3
/** * Property helper functions. * * @_subsection api/utils:Properties [about-properties] */ /** * Resolves to a new object that is a copy of %%value%%, but with all * values resolved. */ export declare function resolveProperties<T>(value: { [P in keyof T]: T[P] | Promise<T[P]>; }): Promise<T>; /** * Assigns the %%values%% to %%target%% as read-only values. * * It %%types%% is specified, the values are checked. */ export declare function defineProperties<T>(target: T, values: { [K in keyof T]?: T[K]; }, types?: { [K in keyof T]?: string; }): void; //# sourceMappingURL=properties.d.ts.map
03815dd92ab325607f04c6cf9bb1a63212a9c169
TypeScript
DCUBEDcode/bog-api
/src/validators/user.ts
2.765625
3
import { body, query, param } from "express-validator"; class UserValidator { checkCreateUser() { return [ body("firstName") .notEmpty() .withMessage("The first name should not be empty"), body("lastName") .notEmpty() .withMessage("The last name should not be empty"), body("email") .notEmpty() .withMessage("The email should not be empty"), body("password") .notEmpty() .withMessage("The password should not be empty"), ] } checkReadUser() { return [ query('limit') .optional() .isInt({ min: 1, max: 10 }) .withMessage('The limit value should be a number and between 1-10'), query('offset') .optional() .isNumeric() .withMessage('Value should be a number') ] } checkUserParam() { return [ param('id') .notEmpty() .withMessage('The id should be not empty') .isUUID(4).withMessage('The value should be uuidv4') ] } } export default new UserValidator();
611298c8e095899ec5e9312f26832a372fd5394f
TypeScript
karenyov/curso-ionic-stencil
/src/pages/angular/binding/binding.ts
2.765625
3
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; /** * Generated class for the BindingPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-binding', templateUrl: 'binding.html', }) export class BindingPage { public valor: number = 1; public valor2: number = 2; public nome: string = 'Gabriel'; constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad = () => { /** * getActive retorna a view atual */ console.log(this.navCtrl.getActive()); console.log(this.navCtrl.getActive().index); } retornaValor = () => this.valor + this.valor2; /** * Ele retira todas as páginas da pilha e vai para a página root atual */ popToRoot = () => this.navCtrl.popToRoot(); /** * Ele desempilha seguidamente todas as views da pilha. */ popAll = () => this.navCtrl.popAll(); /** * Inserção de páginas no array */ insert = () => { //Insere 1 página this.navCtrl.insert(1, 'BindingPage', { name: 'Gabriel' }); //insere várias páginas this.navCtrl.insertPages(1, [ { page: 'BindingPage', params: { name: 'Gabriel' } }, { page: 'BindingPage', params: { name: 'Gabriel' } }, { page: 'BindingPage', params: { name: 'Gabriel' } } ]); }; /** * Removendo views */ remove = () => { /** * Remove a quantidade de páginas desejadas apartir de um index, * funciona como o splice do JavaScript */ this.navCtrl.remove(1, 1); } /** * Retorna true ou false se o usuário pode voltar ou não na pilha */ canGoBack = () => { console.log(this.navCtrl.canGoBack()); } }
bc00026abe95af8189b76ca324e18e7cdd029098
TypeScript
frankhu00/21Simulation
/app/src/model/CardCollection.ts
3.515625
4
import Card, { CardNumberMap, SuitType } from './Card' import Notifier from './Notifier' import { CountingSystem } from './CountingSystem' import { randomizeBetween } from './Utility' type RCObjectType = {[key: string]: CountingSystem | number} type setRCType = RCObjectType | boolean type deckConstructorType = { cards?: Card[] | number, setRC?: setRCType } type shoeConstructorType = { deck?: number, cards?: Card[] | number, setRC?: setRCType } const ShuffleType = { RNG: 'RNG Shuffle', Riffle: 'Riffle Shuffle', Mimic: 'Mimic Shuffle Flow' } interface CardStateLog { action: string state: Card[] changes?: any } export interface CardCollectionInterface { cards: Card[]; pastCardState: Array<CardStateLog>; get: () => Card[]; deal: () => Card|undefined; clone: () => CardCollectionInterface; count: () => number; saveCardState: (action: string, changes?: any) => void; shuffle: (repeat?: number) => CardCollectionInterface; setShuffleMethod: (shuffle: string, options?: number) => CardCollectionInterface; setShuffleIteration: (iteration: number) => CardCollectionInterface; getCardsRemaining: (cardList?: Card[]) => number; getCards: (cardList: Card[] | Card, matchSuit: boolean) => Card[] | boolean; addCard: (card: Card | Card[]) => CardCollectionInterface; removeCards: (card: Card | number, matchSuit: boolean) => Card[] | boolean; createCard: (representation: number, deck: number) => Card; generateDecks: (deck: number) => Card[]; generateCardList: (numCards: number, deck: number, setRC: setRCType ) => Card[]; } class CardCollection implements CardCollectionInterface { cards: Card[] = [] pastCardState: Array<CardStateLog> = [] //stores the previous card ordering. index 0 = most recent private shuffleIteration: number = 2 private doShuffle: () => CardCollectionInterface constructor(cards?: Card[]) { this.cards = cards ? cards : [] this.doShuffle = this.rngShuffle.bind(this, this.shuffleIteration) } get() { return this.cards } deal() { let dealtCard = this.cards.shift() if (!dealtCard) { Notifier.error('Ran out of cards to dealt') } return dealtCard } clone() { return new CardCollection(this.cards) } count() { return this.cards.length } saveCardState(action: string, changes?: any) { let stateLog: CardStateLog = { action, state: this.cards, changes } this.pastCardState.unshift(stateLog) } shuffle(repeat?: number) { this.saveCardState('Shuffle') if (repeat) { this.setShuffleIteration(repeat) } return this.doShuffle() } setShuffleMethod(shuffle: string, options?: number) { if (ShuffleType.RNG == shuffle) { Notifier.notify(`Shuffling method set to: ${shuffle} with intensity ${options ? options : '"default"'}`) this.doShuffle = this.rngShuffle.bind(this, this.shuffleIteration, options) } else if (ShuffleType.Riffle == shuffle) { Notifier.notify(`Shuffling method set to: ${shuffle}`) this.doShuffle = this.riffle.bind(this, this.shuffleIteration) } else if (ShuffleType.Mimic == shuffle) { Notifier.notify(`Shuffling method set to: ${shuffle}`) this.doShuffle = this.mimicShufflePattern.bind(this, this.shuffleIteration) } else { Notifier.warn(`Unknown shuffling method. Shuffling method set to: ${ShuffleType.RNG} with intensity "default"`) this.doShuffle = this.rngShuffle.bind(this, this.shuffleIteration, options) } return this } setShuffleIteration(iteration: number) { iteration = iteration > 0 ? iteration : 2 this.shuffleIteration = iteration return this } getCardsRemaining(cardList?: Card[]) { cardList = cardList ? cardList : this.cards return cardList.length } getCards(cardList: Card[] | Card, matchSuit: boolean = false) { cardList = (Array.isArray(cardList)) ? cardList : [cardList] let searchList = cardList as Card[] let comparator = matchSuit ? (card: Card, searchCard: Card) => searchCard.getKey() == card.getKey() && searchCard.getSuit() == card.getSuit() : (card: Card, searchCard: Card) => searchCard.getKey() == card.getKey() let foundCards = this.cards.filter( c => { let found = searchList.filter(s => { return comparator(c, s) }); return found.length > 0 }) if (foundCards.length > 0) { return foundCards } else { Notifier.notify('No card found') return false } } addCard(card: Card | Card[]) { this.saveCardState('Add Cards', card) this.cards.concat(card) return this } //Removes all matched cards removeCards(card: Card | number, matchSuit: boolean = false) { if (typeof card == 'number') { if (typeof this.cards[card] != 'undefined') { this.saveCardState('Remove Cards', [this.cards[card]]) let removed = this.cards.splice(card, 1) return removed } else { Notifier.error('Invalid index') return false } } else { let comparator = matchSuit ? (card: Card, searchCard: Card) => searchCard.getKey() == card.getKey() && searchCard.getSuit() == card.getSuit() : (card: Card, searchCard: Card) => searchCard.getKey() == card.getKey() let removedCards: Card[] = [] let newCardList = this.cards.filter( c => { if (comparator(c, card)) { //this is the card to remove, so return false removedCards.push(c) return false } else { return true } }) if (removedCards.length > 0) { this.saveCardState('Remove Cards', removedCards) this.cards = newCardList return removedCards } else { Notifier.notify('Cannot find specified cards to remove') return false } } } createCard(representation: number, deck: number = 1) { // deck means the # of decks // representation means the index value (1-indexed) when cards are ordered in // A (all suits), 2 (all suits), 3, 4, 5, ..., K (all suits) // i.e for 1 deck it would be // [A (spades), A (hearts), A (diamonds), A (clubs), 2(spades), 2 (hearts), 2 (diamonds), 2 (clubs), ...] // The corresponding values would be // [1 (represents A of spades), 2 (represents A of hearts), 3 (represents A of diamonds), 4 (represents A of clubs), ...] // // For two decks it would be // [1 (represents A of spades for deck 1), 2 (represents A of hearts for deck 1), 3 (represents A of diamonds for deck 1), 4 (represents A of clubs for deck 1), // 5 (represents A of spades for deck 2), 6 (represents A of hearts for deck 2), 7 (represents A of diamonds for deck 2), 8 (represents A of clubs for deck 2), ...] let cardIndex = representation % 4; let suit = SuitType.None; if (cardIndex == 0) { suit = SuitType.Spades } else if (cardIndex == 1) { suit = SuitType.Hearts } else if (cardIndex == 2) { suit = SuitType.Diamonds } else if (cardIndex == 3) { suit = SuitType.Clubs } let cardKey = CardNumberMap[Math.ceil(representation / (4*deck))] return new Card(cardKey, suit) } generateDecks(deck: number = 1) { deck = deck < 1 ? 1 : deck let cardList : Card[] = [] for (let i = 1; i <= 52*deck; i++) { cardList.push(this.createCard(i, deck)) } return cardList } generateCardList(numCards: number, deck: number = 1, setRC: setRCType = false ) { let cardList: Card[] = [] deck = deck >= 1 ? deck : 1 numCards = numCards < 1 ? 52 : numCards numCards = numCards > 52*deck ? 52*deck : numCards if (setRC === false) { //Determine which logic to use for performance if ( numCards/(52*deck) >= 0.6 ) { //Faster to remove the cards // console.log('Create cards by creating complete deck then removing random cards') let completeCardList: Card[] = this.generateDecks(deck) let totalCards = completeCardList.length //Start removing card until only numCards left let removedList = [] for (let i = 1; i <= totalCards - numCards; i++) { let randomIndex = randomizeBetween(0, 52*deck-1) while (removedList.indexOf(randomIndex) > -1) { randomIndex = randomizeBetween(0, 52*deck-1) } removedList.push(randomIndex) delete completeCardList[randomIndex] } cardList = completeCardList.filter(val => val) } else { //Faster to generate the cards // console.log('Create cards by creating random cards') let createdCards:number[] = [] for (let i = 1; i <= numCards; i++) { let represenationValue = randomizeBetween(1, 52*deck) while (createdCards.indexOf(represenationValue) > -1) { represenationValue = randomizeBetween(1, 52*deck) } createdCards.push(represenationValue) } cardList = createdCards.map( presentationVal => this.createCard(presentationVal, deck)) } } else { //NOT AVAILABLE ATM Notifier.warn('This functionality is WIP') cardList = this.generateDecks() //NOT AVAILABLE ATM } return cardList } private rngShuffle(repeat: number, intensity?: number) { // intensity means how many swaps to do (1 swap is 1 card switch position with another card) // default intensity is # of cards * 3 // This is purely shuffling by RNG, does not mimic human shuffling // This may be what machine shuffling does for 2 decks let shuffling : Card[] = this.cards.map( c => Object.assign({}, c)) intensity = intensity && intensity > 0 ? intensity : shuffling.length*3 for (let iter = 0; iter < repeat; iter++) { for (let i = 0; i < intensity; i++) { let randomized1 = randomizeBetween(0, shuffling.length-1) let randomized2 = randomizeBetween(0, shuffling.length-1) while (randomized2 === randomized1) { randomized2 = randomizeBetween(0, shuffling.length-1) } let swapped: Card = shuffling[randomized1] shuffling[randomized1] = shuffling[randomized2] shuffling[randomized2] = swapped; } } this.cards = shuffling return this } private riffle(repeat: number) { //This mimics the riffle (common) shuffling method with introduced roughness to simulate human riffle shuffle Notifier.warn(`Riffle Shuffle is WIP`) return this } private mimicShufflePattern(repeat: number = 2, decks: number = 6) { // NOTE: RANDOMNESS IS KEY HERE. DO NOT CODE SO IT HAS PRECISE SHUFFLING // Can try to mimic the shuffling flow for 6 or 8 decks // 1) Need to cut off last % (1-penetration), split that into ROUGHLY 3 parts // 2) Insert those 3 parts in ROUGHLY even spread into the remaining stack [name = whole stack ] // 3) Split the whole stack into ROUGHLY 2 halves [names = 1st half, 2nd half] // 4) Take ROUGHLY 33% from 1st half and 2 half, and call shuffle fn [names = shuffled1, shuffled2] // 5) Stack from bottom to top: shuffled1, shuffled2, shuffled3 // 6) Repeat step 3 - 5 for n times // 7) Done Notifier.warn(`Mimic Shuffle Flow is WIP`) return this } } class Deck extends CardCollection implements CardCollectionInterface { constructor({ cards, setRC = false } : deckConstructorType = {}) { super() if (cards) { this.cards = Array.isArray(cards) ? cards as Card[] : this.generateCardList(cards as number, 1, setRC) } else { //generate standard deck this.cards = this.generateDecks(1) } } clone() { return new Deck({cards: this.cards}) } } class Shoe extends CardCollection implements CardCollectionInterface { protected deck: number; constructor({ cards, deck = 2, setRC = false } : shoeConstructorType = {}) { super() this.deck = deck < 1 ? 2 : deck //default to 2 decks if invalid if (cards) { this.cards = Array.isArray(cards) ? cards as Card[] : this.generateCardList(cards as number, this.deck, setRC) } else { //generate standard shoe with specified decks this.cards = this.generateDecks(this.deck) } } clone() { return new Shoe({cards: this.cards, deck: this.deck}) } } export { Deck, Shoe, ShuffleType } export default CardCollection
0cf564bc143306a5ba373a04dac0637052923c93
TypeScript
z1maka/microservices
/auth/src/services/password.ts
2.875
3
import { scrypt, randomBytes } from "crypto"; import { promisify } from "util"; const scryptAsync = promisify(scrypt); export class PasswordService { static toHash = async (password: string): Promise<string> => { const salt = randomBytes(8).toString("hex"); const buf = (await scryptAsync(password, salt, 64)) as Buffer; return `${buf.toString("hex")}.${salt}`; }; static compare = async ( storedPassword: string, comparedPassword: string ): Promise<boolean> => { const [hashedPassword, salt] = storedPassword.split("."); const buf = (await scryptAsync(comparedPassword, salt, 64)) as Buffer; return buf.toString("hex") === hashedPassword; }; }
d6dc9efa6661f723d8cbd96e08353260727a49d3
TypeScript
santhosh-pro/sm-back
/src/template/row.service.ts
2.546875
3
import {Injectable} from "@nestjs/common"; import {Connection, Repository} from "typeorm"; import {Row} from "../entities/Row"; import {Cell} from "../entities/Cell"; import {InjectRepository} from "@nestjs/typeorm"; @Injectable() export class RowService { constructor( @InjectRepository(Row) private readonly rowRepository: Repository<Row>, @InjectRepository(Cell) private readonly cellRepository: Repository<Cell> ) {} async saveMany(row: Row[]) { let rows: Row[] = []; let cells: Cell[] = []; for (const r of row){ const nRow = new Row(); nRow.id = r.id; nRow.template = r.template; nRow.cells = JSON.parse(JSON.stringify(r.cells)); r.cells = []; rows.push(nRow); } let savedRows = await this.rowRepository.save(row); for (let i = 0; i < savedRows.length; i++) { let oldRow = rows[i]; let lightRow = new Row(); lightRow.id = savedRows[i].id; oldRow.cells.forEach(cell => { cell.row = lightRow; cells.push(cell); }) } await this.cellRepository.save(cells); } }
e0a45f679068931b7cc1d103b880b3e6158938a5
TypeScript
MEKKANIKKA/dfuse-eosio
/eosq/src/stores/block-store.ts
2.71875
3
import { observable, ObservableMap } from "mobx" import { BlockSummary } from "../models/block" const MAX_LIVE_BLOCKS = 500 const MAX_SNAPSHOT_BLOCKS = 5 export class BlockStore { liveBlocks = observable.map<string, BlockSummary>() /** * The list of block currently displayed in the dashboard. * First accumulated until reaching MAX_SNAPSHOT_BLOCKS then * refreshed only when requested. */ snapshotBlocks = observable.map<string, BlockSummary>() /** * The amount of new blocks accumulated since last snapshot * of blocks taken. */ @observable unseenBlockCount = 0 @observable searchResult: BlockSummary | null = null addIncomingBlock(block: BlockSummary) { // TODO: update the LIB in the store.. if (this.snapshotBlocks.size < MAX_SNAPSHOT_BLOCKS) { setBlockInMap(this.snapshotBlocks, block) } else { this.unseenBlockCount += 1 } if (this.liveBlocks.size >= MAX_LIVE_BLOCKS) { this.liveBlocks.delete(this.liveBlocks.keys().next().value) } setBlockInMap(this.liveBlocks, block) } updateSnapshot() { this.unseenBlockCount = 0 this.snapshotBlocks.clear() const updatedBlocks = Array.from(this.liveBlocks.values()).slice(-5) updatedBlocks.forEach((block) => setBlockInMap(this.snapshotBlocks, block)) } setSearchResult(block: BlockSummary) { this.searchResult = block } findById(blockId: string): BlockSummary | undefined { if (this.searchResult != null && blockMatchesIdentifier(this.searchResult, blockId)) { return this.searchResult } // TODO: Search by block hash (block_mroot) before using the key to return the value // previous block navigation uses the block_mroot, has such, to avoid unecessary // API calls, searching with block hash might return some results while with key // (being usually block_num) won't return this.liveBlocks.get(blockId) } } function setBlockInMap(map: ObservableMap<string, BlockSummary>, block: BlockSummary) { map.set(block.block_num.toString(), block) } function blockMatchesIdentifier(block: BlockSummary, blockId: string) { return block.block_num.toString() === blockId || block.id === blockId }
1eb37e939c3d997900d6eee6d926e9ce51bd11f7
TypeScript
Kotarski/Layout-Prototype-Boards
/typescript/fileIO/load/dasim/-buildComponents.ts
2.625
3
import Component from "../../../circuit/+component"; import mappings from "../../../circuit/mappings"; type savedManifist = { schematic: Component[], layout: Component[] }; export default function buildComponents(rawComponents: any[]): savedManifist { /*LOGSTART*/console.groupCollapsed("Component Load Data");/*LOGEND*/ let manifest: savedManifist = { schematic: [], layout: [] } for (let rawComponent of rawComponents) { const componentMap = mappings.getComponentMap(rawComponent.func); if (componentMap === undefined) { /*LOGSTART*/console.error("I don't know how to build %o yet!", rawComponent);/*LOGEND*/ continue; } const sectionName = componentMap.diagramType; let manifestSection = (sectionName === "schematic") ? manifest.schematic : manifest.layout; let newComponents = componentMap.load(rawComponent); if (Array.isArray(newComponents)) { manifestSection.push(...newComponents); } else { manifestSection.push(newComponents); } } /*LOGSTART*/console.groupEnd();/*LOGEND*/ return manifest; }
c13177770aaa7bb52267c687773447464bc3bdd1
TypeScript
hhy5277/nestjs-typeorm
/src/photos/photos.service.ts
2.5625
3
import { Injectable } from '@nestjs/common'; import { CreatePhotoMetadataDto } from './dto/create-photo-metadata.dto'; import { Photo } from './entities/photo.entity'; import { PhotoMetadata } from './entities/photo-meta.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { CreatePhotoAlbumsDto } from './dto/create-photo-albums.dto'; import { Album } from './entities/album.entity'; @Injectable() export class PhotosService { constructor( @InjectRepository(Photo) private readonly photosRepository: Repository<Photo>, @InjectRepository(PhotoMetadata) private readonly photoMetaRepository: Repository<PhotoMetadata>, @InjectRepository(Album) private readonly albumMetaRepository: Repository<Album>, ) { } async create(createPhotoMetadataDto: CreatePhotoMetadataDto) { // 实际中要用事务 // 或者 cascade: true ? (已经配置),只保存一次 const metadata = new PhotoMetadata(); metadata.height = createPhotoMetadataDto.height; metadata.width = createPhotoMetadataDto.width; metadata.compressed = createPhotoMetadataDto.compressed; metadata.comment = createPhotoMetadataDto.comment; metadata.orientation = createPhotoMetadataDto.orientation; const photo = new Photo(); photo.name = createPhotoMetadataDto.name; photo.description = createPhotoMetadataDto.description; photo.filename = createPhotoMetadataDto.filename; photo.views = createPhotoMetadataDto.views; photo.isPublished = createPhotoMetadataDto.isPublished; photo.metadata = metadata return this.photosRepository.save(photo); } findAll() { return this.photosRepository.find({ relations: ["metadata"] }) } findAllMetadata() { return this.photoMetaRepository.find({ relations: ["photo"] }) } async createPhotoAlbum(createPhotoAlbumsDto: CreatePhotoAlbumsDto) { const albums = [] for (const photoAlbum of createPhotoAlbumsDto.albums) { const album = new Album(); album.name = photoAlbum.name albums.push(album) await this.albumMetaRepository.save(album) } let photo = new Photo(); photo.name = createPhotoAlbumsDto.name; photo.description = createPhotoAlbumsDto.description; photo.filename = createPhotoAlbumsDto.filename; photo.views = createPhotoAlbumsDto.views; photo.isPublished = createPhotoAlbumsDto.isPublished; photo.albums = albums; return this.photosRepository.save(photo); } findAllphotoAlbum() { return this.photosRepository.find({ relations: ["albums"] }) } /* findOne(id: number) { return this.photosRepository.findOne(id); } async update(id: number, updatePhotoDto: UpdatePhotoDto) { // 这段代码只是演示,实际要使用事务 const photo = await this.findOne(id); photo.name = updatePhotoDto.name; photo.description = updatePhotoDto.description; photo.filename = updatePhotoDto.filename; photo.views = updatePhotoDto.views; photo.isPublished = updatePhotoDto.isPublished; return this.photosRepository.save(photo); } async remove(id: number) { // 这段代码只是演示,实际要使用事务 const user = await this.findOne(id); return this.photosRepository.remove(user); } */ }
39c3ed1700b13a7fd792066c0c5964ba0b1fa6dd
TypeScript
yiqu/udemy-ngrx
/src/app/auth/redux/auth.selectors.ts
2.796875
3
import { createSelector, createReducer, createFeatureSelector } from '@ngrx/store'; import { AuthState } from './auth.model'; import { AppState } from '../../ngrx-stores/global-store/app.reducer'; import { FireUser } from 'src/app/shared/models/user.model'; export const getAuthFeatureStateSelector = createFeatureSelector<AuthState>('auth'); //* Get the Auth User slice export const getAuthUserSelector = createSelector( getAuthFeatureStateSelector, (state: AuthState) => { return state?.user; } ); //* Get the Auth User's email property export const getAuthUserEmailSelector = createSelector( getAuthFeatureStateSelector, (state: AuthState) => { return state?.user?.email; } ); // get the email's uppercase export const getAuthUserEmailUppercaseSelector = createSelector( getAuthUserEmailSelector, (state: string) => { return state?.toUpperCase(); } ); // Also gets the Auth slice, without feature selector export const authSelector = createSelector( (state) => state['auth'], // <-- this is what the feature selector did above. Thus this can be extracted (auth: AuthState) => { return auth.user; } ) // Get only the email export const authEmailSelector = createSelector( authSelector, // <-- using a selector mapping function that is previous written (user: FireUser) => { return user?.email; } ) // Get the email adress's uppercase export const authEmailUppercaseSelector = createSelector( authEmailSelector, (email) => { if (email) { return email.toUpperCase(); } return "NONE"; } )
19c2b511a7db4337192788acdc6bd1695845cd8c
TypeScript
marcosnav/cuadro
/src/tests/services/imagefetcher.test.ts
2.546875
3
import axios from 'axios'; import { ImageFetcher } from './../../services/imagefetcher'; jest.mock('axios'); describe('ImageFetcher', () => { test('.get()', async () => { const reqMockData = { data: { id: 10, urls: { regular: 'https://image.url', }, user: { links: { html: 'https://author.url', }, name: 'John', }, }, }; const imageFetcher = new ImageFetcher({ unsplashAccessKey: 'TEST_ACCESS_KEY' }); axios.get.mockResolvedValue(reqMockData); const imageData = await imageFetcher.get(); expect(imageData.id).toBe(10); expect(imageData.author).toBe('John'); expect(imageData.authorUrl).toBe('https://author.url'); expect(imageData.url).toBe('https://image.url'); }); test('exception on .get()', async () => { const imageFetcher = new ImageFetcher({ unsplashAccessKey: 'TEST_ACCESS_KEY' }); axios.get.mockRejectedValue(new Error('test request error')); try { await imageFetcher.get(); } catch (err) { expect(err.message).toBe('test request error'); } }); });
d73f74605bc9493a3d67b8c0c23e2aac1e8ac68a
TypeScript
Nlbo/test
/src/app/platform/models/sidebar-nav.ts
2.765625
3
import { ISidebarNavigation } from '@interfaces/sidebar-nav'; export class SidebarNavigation { public name: string; public path: string; public languagePath: string; public languageControl: string; public opened: boolean = false; public exact: boolean = false; private _children: SidebarNavigation[] = []; constructor(data: ISidebarNavigation) { this.name = data.name; this.languagePath = data.languagePath; this.languageControl = data.languageControl; this.path = data.path; this.opened = data.opened; this.children = data.children || []; this.exact = data.exact; } public set children(data: SidebarNavigation[]) { if (data && data.length) { this._children = data.map(x => { x.path = `${this.path}/${x.path}`; return x; }); } } public get children(): SidebarNavigation[] { return this._children; } }
f5d51cccd7f5eff5e2dfacc0d21cddab17bb95cc
TypeScript
PedroHenriques/www.pedrojhenriques.com
/assets/ts/main.ts
2.8125
3
/*!!*********************************************************** * * * www.pedrojhenriques.com v2.2.0 * * * * Copyright 2017, PedroHenriques * * http://www.pedrojhenriques.com * * https://github.com/PedroHenriques * * * * Free to use under the MIT license. * * http://www.opensource.org/licenses/mit-license.php * * * ************************************************************/ // imports import {Engine} from "./classes/Engine"; // global variable storing the Engine instance to be used in the program let engine_obj_: Engine; // stores the duration of the css transitions in use (in milliseconds) export let css_transition_dur_: number | null = null; // stores a reference to the DOM element where all the textboxes will be appended const div_work_area_: HTMLElement | null = document.getElementById("work_area"); // runs once the document is done loading // sets basic parameters used to run the application // then starts the application (if building the content dynamically with JS) // OR simply sets the expand/collapse event listeners (if the content as built on the server) function init(built_on_server: boolean) : void { /* START OF THE CONFIGURATION AREA */ // list of file names to use // the files must be .txt and their contents will be written to a DOM element with // ID equal to the file's name const file_list: string[] = ["narrator_box", "style_box", "script_box", "about_box"]; // the index of "file_list" corresponding to the first file to run const start_index: number = 0; // stores the language to be used // NOTE: defaults to english let lang: string = "EN"; // stores the supported language tags const valid_langs: string[] = ["PT", "EN"]; /* END OF THE CONFIGURATION AREA */ // get a reference to the HTML DOM element const html_elem: HTMLElement = document.getElementsByTagName("html")[0]; // check if the HTML element has a "lang" property if ("lang" in html_elem) { // it has // get the language tag let tentative_lang: string = html_elem.lang.toUpperCase(); // check if the tentative language is one of the supported ones if (valid_langs.indexOf(tentative_lang) != -1) { // it is, so store it lang = tentative_lang; } } // check if the DOM has at least 1 style tag if (document.body.getElementsByTagName("style").length == 0) { // it hasn't // create a style tag and append it to the BODY element document.body.appendChild(document.createElement("style")); } // check if the DOM has a DIV with id "work_area", where all the textboxes will be appended if (document.getElementById("work_area") == null) { // it hasn't // create a div tag let div_elem: HTMLElement = document.createElement("div"); // add the id div_elem.id = "work_area"; // add the classes div_elem.className = "no_events"; // append it to the BODY element document.body.appendChild(div_elem); } // create an instance of the Engine class engine_obj_ = new Engine(lang, file_list, start_index, built_on_server); // check if the page content was be built on the server if (!built_on_server) { // it wasn't // start the program engine_obj_.run(); } } // finds the duration of the CSS transitions in use on the website // NOTE: must be called after any transitions are set in the style tag export function getTransitionDuration(): void { // by default set the duration to zero css_transition_dur_ = 0; // stores the style tag where all styles should be written to const dom_style_tag: HTMLElement = document.body.getElementsByTagName("style")[0]; // check if a reference to the DOM's style tag was acquired if (dom_style_tag == null) { // it wasn't, so bail out return; } // regexp to find and grab the duration value and unit const re_string = /\*\s*\{[^\{\}]+transition\s*:[^\{\}\d]+([\d\.]+)(s|ms)[^\{\}]+\}/i; // stores the match object from the regex below let re_match: RegExpMatchArray | null = null; // check if there is a style setting a transition duration if ((re_match = dom_style_tag.innerHTML.match(re_string)) != null) { // there is // calculate the transition duration value in milliseconds css_transition_dur_ = parseFloat(re_match[1]) * (re_match[2] == "s" ? 1000 : 1); } }
2c31cc84fa9e0b4b9278e4f279fc94a38606b098
TypeScript
hudas/react-study-playground
/src/tasks/services/TaskMappers.ts
2.578125
3
import {TaskDto, TaskStatusDto} from "./dto/TaskDto"; import {Task} from "../components/view/TaskView"; import moment from "moment"; import {TaskListDto} from "./dto/TaskListDto"; import {TaskRow} from "../components/list/TaskList"; import {TaskStatus} from "../store/task/TaskState"; export function taskDtoToFormState(dto: Partial<TaskDto>): Partial<Task> { return { ...dto, status: dto.status === "RESOLVED" ? TaskStatus.RESOLVED : TaskStatus.OPEN, createdAt: moment(dto.createdAt), comments: dto.comments && dto.comments.map(comment => ({ ...comment, createdAt: moment(comment.createdAt) })) } } export function taskListDtoToRow(listDto: Partial<TaskListDto>[]): Partial<TaskRow>[] { return listDto.map((dto: Partial<TaskListDto>) => ({ ...dto, createdAt: moment(dto.createdAt) })); } export function taskStatusToDto(status: string): TaskStatusDto { return { status }; }
6301b1a9f59960d19afc35a7df9d5a439a10b216
TypeScript
paperbits/paperbits-common
/src/ui/viewStack.ts
3.078125
3
import * as Html from "../html"; import { EventManager } from "../events"; import { View } from "./view"; export class ViewStack { private stack: View[]; constructor(private readonly eventManager: EventManager) { this.stack = []; this.eventManager.addEventListener("onPointerDown", this.onPointerDown.bind(this)); this.eventManager.addEventListener("onEscape", this.popView.bind(this)); } private onPointerDown(event: MouseEvent): void { const targetElement = <HTMLElement>event.target; this.runHitTest(targetElement); } public runHitTest(targetElement: HTMLElement): void { const views = [...this.stack]; // clone array for (const view of views.reverse()) { let hit: boolean; if (view.hitTest) { hit = view.hitTest(targetElement); } else { hit = !!Html.closest(targetElement, (node: HTMLElement) => node === view.element); } if (hit) { break; } this.stack.pop(); view.close(); } } /** * Pushes the view to the top of the stack. */ public pushView(view: View): void { this.stack.push(view); } /** * Removes the top view from the stack. */ public popView(): void { const view = this.stack.pop(); if (!view) { this.eventManager.dispatchEvent("onTopLevelEscape"); return; } view.close(); if (view.returnFocusTo) { view.returnFocusTo.focus(); } } /** * Removes specified view and all its children from the stack. * @param view - A view to be removed. */ public removeView(view: View): void { if (!this.stack.includes(view)) { return; } let topView: View; do { topView = this.stack.pop(); topView.close(); } while (!topView || topView !== view); if (!topView) { this.eventManager.dispatchEvent("onTopLevelEscape"); return; } if (topView.returnFocusTo) { view.returnFocusTo.focus(); } } /** * Returns all views in the stack. */ public getViews(): View[] { return [...this.stack]; // clone array } /** * Clears the view stack. */ public clear(): void { this.stack.forEach(view => view.close()); this.stack = []; } }
b005666f7c30979a16128c1fc321c3cff59adad8
TypeScript
guitarpoet/jsontool
/src/pagers/CombinedPager.ts
2.984375
3
/** * The Combined Pager * * @author Jack <jack@thinkingcloud.info> * @version 0.0.1 * @date Mon Apr 9 15:31:03 2018 */ import { Observable } from "rxjs/Observable"; import { Pager, flatMapper, PagerType } from "../models/Pager"; import "rxjs/add/observable/of"; import "rxjs/add/operator/map"; import "rxjs/add/operator/mergeMap"; @flatMapper export class CombinedPager implements Pager { public type: PagerType; private pagers: Array<Pager>; public constructor(pagers: Array<Pager>) { this.pagers = pagers; } public process(data:any):Observable<any> | any { let o = Observable.of(data); for(let pager of this.pagers) { if(pager.type == PagerType.Mapper) { // This is a map pager o = o.map(data => pager.process(data)); continue; } if(pager.type == PagerType.FlatMapper) { o = o.flatMap(data => pager.process(data)); continue; } } return o; } }
d8cfedadf58be8e1bbe43a0c72c0dc6d6c1a3eea
TypeScript
bastienlemaitre/angular-odata-es5
/src/angularODataUtils.ts
3.203125
3
export class ODataUtils { public static convertObjectToString(obj: any): string { const properties: string[] = []; for (const prop in obj) { if (obj.hasOwnProperty(prop) && obj[prop] !== undefined) { const value: any = ODataUtils.quoteValue(obj[prop]); properties.push(`${prop}=${value}`); } } return properties.join(', '); } public static quoteValue(value: number | string | boolean): string { // check if string if (typeof value !== 'string') { return `${value}`; } // check if GUID (UUID) type if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) { return value; } const escaped = value.replace(/'/g, '\'\''); return `'${escaped}'`; } }
20e2a2eed99a19a61a55321fb38099951444af94
TypeScript
kahirokunn/book-management
/src/submodules/validate.ts
3.21875
3
type funcType = (value: any) => void export function isValid(rule: funcType[], value: any) { rule.forEach((func) => { const result = func(value) if (typeof result === 'string') { throw Error(result) } }) }
600174059164658d9a042e18b59406a41e101d15
TypeScript
jroyer1986/connect4
/app/services/connect4API.ts
2.65625
3
import { Injectable } from '@angular/core'; import { Game } from '../shared/models/game'; import { User } from '../shared/models/user'; import { Board } from '../shared/models/board'; import { Space } from '../shared/models/space'; import { FakeGameData } from '../shared/models/fakeGameData'; @Injectable() export class Connect4API { constructor(){} public static getGame(gameId): Game { console.log('API getGame called'); //hit getGame API passing in the gameId. A json game should be returned. let jsonGame = FakeGameData.testGame; return jsonGame; } public static getGames(): Game[] { console.log('API getGames called'); return null; } public static resetGame(): Game { console.log('API resetGame called'); return null; } public static createPlayer(playerName: string){ console.log('API createPlayer called'); return null; } public static createGame(user: User){ console.log('API createGame called by ' + user.name); //get gameId returned from API to give back to the app and use to call getGame return FakeGameData.testGame.id; } public static joinGame(user: User, game: Game){ console.log('API joinGame called by ' + user.name + ' for game ' + game.id); return null; } public static play(spaceId: string, playerId: string, gameId: string){ console.log('API play called by player id # ' + playerId + ' for game ' + gameId); return null; } public static leave(gameId: string, playerId: string){ console.log('API leave called by player id # ' + playerId + ' for game ' + gameId); return null; } //i think these are needed in order to allow us to pass in playerIds and gameIds from click events }
1b7dcfcbbb1b7c8eb18c1cbed0b7e6ee62332bee
TypeScript
SpyglassMC/Spyglass
/packages/locales/test/index.spec.ts
3.1875
3
import { strict as assert } from 'assert' import { describe, it } from 'mocha' import { arrayToMessage } from '../lib/index.js' describe('arrayToMessage() Tests', () => { it('Should return message for an empty array', () => { const arr: string[] = [] const actual = arrayToMessage(arr) assert.strictEqual(actual, 'nothing') }) it('Should return message for a string', () => { const str = 'foo' const actual = arrayToMessage(str) assert.strictEqual(actual, '“foo”') }) it('Should return message for an one-element array', () => { const arr = ['foo'] const actual = arrayToMessage(arr) assert.strictEqual(actual, '“foo”') }) it('Should return message for a two-element array', () => { const arr = ['bar', 'foo'] const actual = arrayToMessage(arr) assert.strictEqual(actual, '“bar” or “foo”') }) it('Should return message for a multi-element array', () => { const arr = ['bar', 'baz', 'foo'] const actual = arrayToMessage(arr) assert.strictEqual(actual, '“bar”, “baz”, or “foo”') }) it('Should use another conjunction when specified', () => { const arr = ['bar', 'baz', 'foo'] const actual = arrayToMessage(arr, undefined, 'and') assert.strictEqual(actual, '“bar”, “baz”, and “foo”') }) it('Should not quote when specified', () => { const arr = ['bar', 'baz', 'foo'] const actual = arrayToMessage(arr, false) assert.strictEqual(actual, 'bar, baz, or foo') }) })
2c22a60654310b463fe47b2d47b1ae0e3e8a1109
TypeScript
EvgeniyBudaev/react-mirrorLook
/src/frontend/redux/middleware/generateId.ts
2.5625
3
import {v4 as uuid} from 'uuid' import {Middleware} from 'redux' import {RootStateType} from '../reducers' interface IKey { [key: string]: string } const generateId: Middleware<{}, RootStateType> = (store) => (next) => (action) => { if (!action.generateId) return next(action) const {generateId, ...rest} = action next({ ...rest, ...generateId.reduce((acc: IKey, key: string) => ({...acc, [key]: uuid()}), {}), }) } export default generateId
13df3fef50fa6388aed14cf4a2c66cc925280554
TypeScript
sschmeier/rna2drawer2
/src/draw/interact/annotate/positionsBetween.ts
3.015625
3
export function positionsBetween(inclusiveEnd1: number, inclusiveEnd2: number): number[] { let min = Math.min(inclusiveEnd1, inclusiveEnd2); let max = Math.max(inclusiveEnd1, inclusiveEnd2); let ps = [] as number[]; for (let p = min; p <= max; p++) { ps.push(p); } return ps; } export default positionsBetween;
8cfa2901a13b56a04f1b7bb3284b9dbbb60cf7e6
TypeScript
drew-gross/mpl
/interpreter.ts
2.765625
3
import debug from './util/debug'; import { Program } from './threeAddressCode/Program'; import { ExecutionResult } from './api'; import { Register } from './threeAddressCode/Register'; import { stringLiteralName } from './backend-utils'; export type Argument = { name: string; value: number | Pointer; }; export type State = { memory: { [key: string]: (number | Pointer)[] }; }; type Pointer = { block: string; offset: number; }; export const createInitialState = ({ stringLiterals, globals }: Program): State => { let state = { memory: {} }; for (let name in globals) { var global = globals[name]; state.memory[global.mangledName] = new Array(global.bytes); state.memory[global.mangledName].fill(0); } stringLiterals.forEach(stringLiteral => { let index = stringLiteralName(stringLiteral); state.memory[index] = []; for (var i = 0; i < stringLiteral.value.length; i++) { state.memory[index].push(stringLiteral.value.charCodeAt(i)); } state.memory[index].push(0); }); // TODO: make first_block less special-casey state.memory['first_block'] = [0]; return state; }; var isPointer = (val: number | Pointer): val is Pointer => { if (typeof val !== 'number') { return true; } return false; }; export const interpretFunction = ( { globals, functions, main, stringLiterals }: Program, args: Argument[], state: State // modified ): number | Pointer | undefined => { if (!main) { throw debug('interpret rquires a main'); } let registerValues: { [key: string]: number | Pointer } = {}; args.forEach(arg => { registerValues[arg.name] = arg.value; }); var ip = 0; var cycles = 0; let gotoLabel = (labelName: string) => { ip = main.instructions.findIndex( target => target.kind == 'label' && target.name == labelName ); if (ip === -1) { throw debug('no label'); } }; let findFunction = (funcName: string) => { // TODO: Get the types right for pointers to functions let f = functions.find(f => f.name == funcName || f.name == (funcName as any).block); if (!f) throw debug('failed to find function'); return f; }; let getRegister = (from: number | Register): number | Pointer => { if (typeof from === 'number') { return from; } let regVal = registerValues[from.name]; if (regVal !== undefined) { return regVal; } throw debug('unable to getRegister'); }; let getPointer = (from: Register): Pointer => { let val = getRegister(from); if (typeof val === 'number') throw debug('expected a pointer'); return val; }; let getValue = (from: number | Register): number => { let val = getRegister(from); if (typeof val !== 'number') throw debug('expected a value'); return val; }; let getName = (from: number | Register): string => { let val = getRegister(from); if (typeof val === 'number') throw debug('expected a name'); return val.block; }; let addToRegister = (name: string, amount: number) => { if (typeof registerValues[name] === 'number') { (registerValues as any)[name] += amount; } else { (registerValues as any)[name].offset += amount; } }; let getGlobal = (from: string) => { if (from in globals) { // TODO: Tidy up which things are pointers and which are values from = globals[from].mangledName; } return state.memory[from][0]; }; let getMemory = (block: string, offset: number) => { let val = state.memory[block][offset]; // TODO: Make this an error instead, once I have a debugger set up if (val === undefined) return 0; return val; }; var allocaCount = 0; var mmapCount = 0; while (true) { // One past the last instruction if (ip == main.instructions.length) { return undefined; } let i = main.instructions[ip]; switch (i.kind) { case 'empty': break; case 'label': break; case 'loadImmediate': registerValues[i.destination.name] = i.value; break; case 'move': registerValues[i.to.name] = getRegister(i.from); break; case 'loadSymbolAddress': registerValues[i.to.name] = { block: i.symbolName, offset: 0 }; break; case 'loadMemory': let pointer = getPointer(i.from); registerValues[i.to.name] = getMemory(pointer.block, pointer.offset + i.offset); break; case 'loadMemoryByte': { let pointer = getRegister(i.address); if (typeof pointer === 'number') { throw debug('expected a pointer'); } registerValues[i.to.name] = getMemory(pointer.block, pointer.offset); break; } case 'storeGlobal': state.memory[i.to][0] = getRegister(i.from); break; case 'storeMemory': { let pointer = getPointer(i.address); let value = getValue(i.from); state.memory[pointer.block][pointer.offset] = value; break; } case 'storeMemoryByte': { let pointer = getPointer(i.address); let value = getValue(i.contents); state.memory[pointer.block][pointer.offset] = value; break; } case 'storeZeroToMemory': { let pointer = getPointer(i.address); state.memory[pointer.block][pointer.offset + i.offset] = 0; break; } case 'loadGlobal': registerValues[i.to.name] = getGlobal(i.from); break; case 'callByRegister': { let func = findFunction(getName(i.function)); let args = i.arguments; let callResult = interpretFunction( { functions, globals, stringLiterals, main: func, }, func.arguments.map((arg, index) => ({ name: arg.name, value: getRegister(args[index]), })), state ); if (i.destination) { if (callResult === undefined) { throw debug('expected a result'); } registerValues[i.destination.name] = callResult; } break; } case 'callByName': { let func = findFunction(i.function); let args = i.arguments; let callResult = interpretFunction( { functions, globals, stringLiterals, main: func, }, func.arguments.map((arg, index) => ({ name: arg.name, value: getRegister(args[index]), })), state ); if (i.destination) { if (callResult === undefined) { throw debug('expected a result'); } registerValues[i.destination.name] = callResult; } break; } case 'goto': gotoLabel(i.label); break; case 'gotoIfZero': if (registerValues[i.register.name] === 0) { gotoLabel(i.label); } break; case 'gotoIfEqual': if (registerValues[i.lhs.name] == getRegister(i.rhs)) { gotoLabel(i.label); } break; case 'gotoIfNotEqual': if (registerValues[i.lhs.name] != getRegister(i.rhs)) { gotoLabel(i.label); } break; case 'gotoIfGreater': if (getRegister(i.lhs) > getRegister(i.rhs)) { gotoLabel(i.label); } break; case 'multiply': registerValues[i.destination.name] = getValue(i.lhs) * getValue(i.rhs); break; case 'increment': addToRegister(i.register.name, 1); break; case 'add': { let lhs = getRegister(i.lhs); let rhs = getRegister(i.rhs); if (isPointer(lhs) && isPointer(rhs)) { throw debug("Can't add 2 pointers"); } else if (isPointer(lhs) && !isPointer(rhs)) { registerValues[i.destination.name] = { ...lhs, offset: lhs.offset + rhs }; } else if (isPointer(rhs) && !isPointer(lhs)) { registerValues[i.destination.name] = { ...rhs, offset: rhs.offset + lhs }; } else if (!isPointer(rhs) && !isPointer(lhs)) { registerValues[i.destination.name] = lhs + rhs; } break; } case 'addImmediate': addToRegister(i.register.name, i.amount); break; case 'subtract': { let lhs = getRegister(i.lhs); let rhs = getValue(i.rhs); if (typeof lhs === 'number') { registerValues[i.destination.name] = lhs - rhs; } else { registerValues[i.destination.name] = { ...lhs, offset: lhs.offset - rhs }; } break; } case 'alloca': let blockName = `alloca_count_${allocaCount}`; allocaCount++; state.memory[blockName] = new Array(i.bytes); state.memory[blockName].fill(0); registerValues[i.register.name] = { block: blockName, offset: 0 }; break; case 'syscall': switch (i.name) { case 'print': let stringName = getName(i.arguments[0]); let string = stringLiterals[stringName]; if (typeof string !== 'string') throw debug('missing string'); console.log(string); break; case 'mmap': let blockName = `mmap_count_${mmapCount}`; mmapCount++; let amount = getValue(i.arguments[1]); state.memory[blockName] = new Array(amount); state.memory[blockName].fill(0); if (i.destination) { registerValues[i.destination.name] = { block: blockName, offset: 0 }; } break; case 'exit': default: debug(`${i.name} unhandled in syscall interpreter`); } break; case 'return': return getRegister(i.register); default: debug(`${i.kind} unhandled in interpret`); } ip++; cycles++; if (cycles > 10000) { debug('Too many cycles'); } } }; export const interpretProgram = ( program: Program, args: Argument[], state: State /* modified */ ): ExecutionResult => { let mainResult = interpretFunction(program, args, state); if (typeof mainResult !== 'number') throw debug('main should return a number'); return { exitCode: mainResult, stdout: '', executorName: 'interpreter', runInstructions: 'none yet', debugInstructions: 'none yet', }; };
37d758d92c4b63f9f708fd1d75bd96ca5ff8f8bc
TypeScript
mvniekerk/spoon-ui
/lib/validation/date.ts
2.546875
3
import moment from 'moment'; import { Validate } from './validate'; export const createDateValidator: (format: string) => Validate<string> = format => (i18nKey, val) => !!val && val.length >= format.length && moment(val.substr(0, format.length), format, true).format() !== 'Invalid date' ? [] : [ { value: val, name: i18nKey, display: i18nKey } ]; export const dateIsYyMmDd: Validate<string> = createDateValidator('YYMMDD'); export const dateIsDdMmYyyy: Validate<string> = createDateValidator('DD/MM/YYYY');
36b6761529203d61330e936f161260a9753be0ce
TypeScript
pinkbunny1/addressApp
/src/selectors/addressBook.ts
2.703125
3
import { sortBy as _sortBy } from 'lodash' import Types from 'Types' import { EntryData } from '../modules/Add' interface FilterState { text: string } const getVisibleEntries = (entries:EntryData[], { text }:FilterState) => { let filteredEntries = entries.filter(({ firstname, lastname }) => { const textMatch = firstname.toLowerCase().includes(text.toLowerCase()) || lastname.toLowerCase().includes(text.toLowerCase()) return textMatch }) return _sortBy(filteredEntries, ['lastname', 'firstname']) } export default getVisibleEntries
d5311ebedc92ede35f2c862f304a1a3100437641
TypeScript
antonylrds/tcc_back
/src/services/CreatePaperService.ts
2.640625
3
import { getRepository, In } from 'typeorm'; import AppError from '../errors/AppError'; import KeyWord from '../models/KeyWord'; import Paper from '../models/Paper'; import User from '../models/User'; interface PaperDTO { title: string; subtitle: string; author: string; professor: string; user_id: string; publicationDate: Date; keywords: string[]; filename: string; abstract: string; } class CreatePaperService { public async execute({ author, professor, title, subtitle, user_id, publicationDate, keywords, filename, abstract, }: PaperDTO): Promise<Paper> { const papersRepository = getRepository(Paper); const usersRepository = getRepository(User); const keywordsRepository = getRepository(KeyWord); const user = await usersRepository.findOne(user_id); if (!user) { throw new AppError('User not found'); } const existingKeywords = await keywordsRepository.find({ where: { word: In(keywords) }, }); const existingWords = existingKeywords.map(keyword => keyword.word); const nonExistingWords = keywords.filter( keyword => !existingWords.includes(keyword), ); const newKeywords = nonExistingWords.map(keyword => keywordsRepository.create({ word: keyword }), ); await keywordsRepository.save(newKeywords); const paper = papersRepository.create({ author, professor, title, subtitle, publicationDate, uploaded_by: user, keyWords: [...existingKeywords, ...newKeywords], path: filename, abstract, }); await papersRepository.save(paper); return paper; } } export default CreatePaperService;
59feaaa833b65c5d9241b8ed0127b44507cce7c0
TypeScript
nauy1216/mlz-pack
/ts/src/config.ts
2.546875
3
import path from 'path'; import merge from 'lodash.merge'; import { getPath } from './utils'; import { WebpackConfig } from './types'; export type PackConfig = { webpack:Partial<WebpackConfig>; }; class Config { private config = { webpack: {}, }; private jsonConfigName = 'mlz-pack.json'; private jsConfigName = 'mlz-pack.js'; public init(configs?:string|PackConfig) { let rootPath = process.cwd(); // 项目根目录 // 有传入mlz-pack配置的地址 if (configs && typeof configs === 'string') { const subConfigs = import(configs); Object.assign(this.config, subConfigs); return; } // 没有传入时 const jsonPath = getPath(this.jsonConfigName); const jsPath = getPath(this.jsConfigName); let subConfig = {}; if (jsonPath) { rootPath = path.dirname(jsonPath); subConfig = require(jsonPath); } else if (jsPath) { rootPath = path.dirname(jsonPath); subConfig = require(jsPath); } // 如果配置中存在根目录就使用,不存在就使用mlz-pack.json或者mlz-pack.js所在的目录为根目录 // 传入配置 merge(this.config, { webpack: { rootPath }}, subConfig); if (configs) { merge(this.config, configs); } } /** * @function getBuildConfig * @desc Find builder type in mlz-pack.json */ public get() { return this.config; } } export const config = new Config();
58b7e5928faf4bf0b3728d4d24624006b7a9428c
TypeScript
2fx0one/cocos-sushi-master
/assets/Script/Food.ts
2.546875
3
import FoodContainer from "./FoodContainer"; import FoodData from "./entity/FoodData"; import Utils from "./common/Utils"; const {ccclass, property} = cc._decorator; @ccclass export default class Food extends cc.Component { @property(cc.Label) label: cc.Label = null; @property(cc.ProgressBar) progressBar: cc.ProgressBar = null // @property(cc.Button) // button: cc.Button = null; private foodContainer: FoodContainer = null private amount: number = null public foodName: string = null public foodId: string = null public foodSmallPicPath: string = null public foodInContainerPicPath: string = null public foodCostPrice: number //食物购买价格 // LIFE-CYCLE CALLBACKS: // private coolDowning = false public init(foodContainer: FoodContainer, foodData: FoodData) { this.foodContainer = foodContainer this.foodId = foodData.foodId this.foodName = foodData.foodName this.foodSmallPicPath = foodData.foodSmallPicPath this.foodInContainerPicPath = foodData.foodInContainerPicPath this.amount = foodData.amount this.foodCostPrice = foodData.foodCostPrice this.updateLabelDisplay() Utils.loadResImage(this.foodInContainerPicPath, (err, spriteFrame: cc.SpriteFrame) => { this.getComponentInChildren(cc.Sprite).spriteFrame = spriteFrame }) return this } image updateLabelDisplay() { this.label.string = '' + this.amount } onclick(event, data) { // console.log(data) // console.log('this.amount', this.amount) // cc.loader.loadRes('audio/clickFoodInContainer', cc.AudioClip, function (err, clip) { // cc.audioEngine.play(clip, false, 1); // }); if (this.amount > 0) { cc.loader.loadRes('audio/clickFoodInContainer', cc.AudioClip, function (err, clip) { cc.audioEngine.play(clip, false, 1); }); this.foodContainer.clickFood(this) } else { cc.loader.loadRes('audio/noFood', cc.AudioClip, function (err, clip) { cc.audioEngine.play(clip, false, 1); }); } } addAmonut(amount: number) { this.amount += amount // console.log('add', this.amount) this.updateLabelDisplay() } subtractAmonut(amount: number) { this.amount -= amount this.updateLabelDisplay() // if(this.amount == 0) { // this.button.interactable = false // } // console.log('subtract', this.amount) } // 拿食物 tackFood(): Food { this.subtractAmonut(1) return this } // 退回食物 backFood(): Food { this.addAmonut(1) return this } //外卖通知倒计时 resetDeliveryProgressBar() { this.progressBar.node.active = true this.progressBar.progress = 1 } // 外卖食物送到 deliveryFood(amount: number) { this.addAmonut(amount) this.progressBar.node.active = false // this.node.color = cc.Color.GRAY return this } update(dt: number) { if (this.progressBar.node.active) { this.progressBar.progress -= dt * 0.1 } } }
0f9a0944cf931c9bfd86b6fd0f615f0fce3b0854
TypeScript
zanachka/noderdom-detached
/test/html/innerHTML.test.ts
2.578125
3
import DOMParser from '../../src/api/DOMParser'; describe('innerHTML', () => { it('parses basic text', () => { const dom = new DOMParser().parseFromString('<div class="address">Hello this is text.</div>', 'text/html'); const address = dom.querySelector('.address')!; expect(address.innerHTML).toBe('Hello this is text.'); expect(address.textContent).toBe('Hello this is text.'); }); });
4bf8b39f65480960d3260d684392491035dd33aa
TypeScript
pyradic/platform
/lib/components/script/Script.ts
2.515625
3
import Vue from 'vue'; import { component, prop } from '@/decorators'; const log = require('debug')('components:script') @component({}) export class Script extends Vue { static template = `<div class="py-script" style="display: none"><slot></slot></div>` @prop(String) src:string created(){ this.$nextTick(() => { let script = document.createElement('script'); document.body.append(script); if(this.src){ script.setAttribute('src', this.src); } else { let content = this.$el && this.$el.textContent ? this.$el.textContent : null this.$el.textContent = ''; script.textContent = content; } log('created script', script) }) log('created', this) } }
9bde7b28bf3efaba747cef1d12600beb6f955b25
TypeScript
spadek-w/relearn-web
/ts/src/index.ts
4.1875
4
let str: string = "hi"; // 布尔 let isDone: boolean = false; // 数字 let age: number =6; //数组 let list: number[] = [1,2,3] let list2: Array<number> = [1,2,3] //元祖 Tuple let x: [string,number] = ['hello',10] //枚举enum enum Color {red, Green, Blue} let c: Color = Color.Green; //Any let notSure: any = 4; //void /** 返回值 只能赋予undefined unll */ function warnUser(): void { console.log("this is my warning message") } // null undefined let u: undefined = undefined; let n: null = null //never function error(message: string): never { throw new Error(message); } //object declare function create(o: object | null): void; create({prop: 0}) //ok create(null) //ok // create(42) //Error // create("string") //Error // create(false) //Error // create(undefined) //Error //断言 let someValue: any = "this is a" let strLength: number = (<string>someValue).length //另一种as语法 let someValue2: any = 'this is a' let strLength2: number = (someValue2 as string).length
24733a277df45d318f91aa9a905b182f25b1813c
TypeScript
cyjo9603/cy-util
/src/is/isPromise.ts
2.8125
3
function isPromise(value: any): boolean { return ( Boolean(value) && ['object', 'function'].includes(typeof value) && typeof value.then === 'function' ); } export default isPromise;
5e7ecc33cfaaa5dc818e7c864d7e505d48b554c0
TypeScript
orionnye/CameraColorFilter
/src/math.ts
3.34375
3
export default class Vector { x: number; y: number; constructor(x : number = 0, y : number = 0) { this.x = x; this.y = y; } subtract(that: Vector) { return new Vector(this.x - that.x, this.y - that.y); } add(that: Vector) { return new Vector(this.x + that.x, this.y + that.y); } multiply(that: number | Vector) { if (typeof that === "number") { return new Vector(this.x * that, this.y * that); } return new Vector(this.x * that.x, this.y * that.y); } get normalize() { //simplifies the distances to a simple fraction let normal = new Vector(this.x / this.length, this.y / this.length); return normal; } get length() { let dist = Math.sqrt(this.x**2 + this.y**2); return dist; } } export class Line { a: Vector; b: Vector; constructor(a: Vector = new Vector(), b: Vector = new Vector) { this.a = a; this.b = b; } } export class Grid { size : Vector; pos : Vector; dim : Vector; constructor(pos : Vector = new Vector(0, 0), size : Vector = new Vector(1, 1), dimensions : Vector = new Vector(10, 10)) { this.pos = pos; this.size = size; this.dim = dimensions; } render(ctx : CanvasRenderingContext2D, color : string = "black") { let {size, pos, dim} = this ctx.strokeStyle = color ctx.fillStyle = color for (let y = 0; y < size.y; y++) { for (let x = 0; x < size.x; x++) { let cellSize = new Vector(dim.x / size.x, dim.y / size.y) let cellPos = new Vector(pos.x + x*cellSize.x, pos.y + y*cellSize.y) ctx.strokeRect(cellPos.x, cellPos.y, cellSize.x, cellSize.y) ctx.font = (cellSize.y / 2).toString() + "px times new roman" //x-axis labels ctx.fillText((cellPos.x - pos.x).toString(), cellPos.x, pos.y) //y-axis labels ctx.fillText((cellPos.y - pos.y).toString(), pos.x - cellSize.x / 2, cellPos.y) } } } }
4425e72b61d4bf5cc61af5b568d13c2e9729c714
TypeScript
sanderheieren/build-a-web-framework-in-typescript
/src/Models/Attributes.ts
3.40625
3
// import { UserProps } from './User'; export class Attributes<T> { constructor(private data: T) {} // limiting the different types K can be (name, age or id) bc in TS you can treat strings as types, because of how object keys are string // made it to an arrow function, because it will be correctly bound to the instance of attributes, i.e this = attriabutes get = <K extends keyof T>(key: K): T[K] => { return this.data[key]; }; set(update: T): void { // copy paste everything from 'update' onto 'this.data' (Object.assign) Object.assign(this.data, update); } getAll(): T { return this.data; } } // const attrs = new Attributes<UserProps>({ // id: 5, // age: 20, // name: 'sander', // }); // const name = attrs.get('name'); // const age = attrs.get('age'); // const id = attrs.get('id');
49f75cc6f79dd322580b926d6493ea113503a905
TypeScript
be-light/be-light
/src/utils/file.ts
2.515625
3
import * as multer from "multer"; import * as path from "path"; class BeLightFile { public option: multer.Instance; public storage: multer.StorageEngine; constructor() { /* Define Storage */ this.storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, "./public_dist/upload"); }, filename: (req, file, cb) => { cb(null, new Date().valueOf() + path.extname(file.originalname)); } }); /* Settings Multer Options */ this.option = multer({ dest: "./public_dist/upload", limits: { fileSize: 5 * 1024 * 1024 }, storage: this.storage }); } } export default new BeLightFile();
fbbcacb8714b761477ec13410b783f4125e95489
TypeScript
bny9164/learn_nestjs
/project/src/app.module.ts
2.53125
3
// * 애플리케이션의 루트 모듈 import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { MongooseModule } from '@nestjs/mongoose'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { CatsModule } from './cats/cats.module'; import { LoggerMiddleware } from './common/middlewares/logger.middleware'; import { AuthModule } from './auth/auth.module'; import { CommentsModule } from './comments/comments.module'; import * as mongoose from 'mongoose'; //app.module에서 의존성 주입 /** * providers Nest 인젝터에 의해 인스턴스화 되고 적어도 이 모듈에서 공유될 수 있는 프로바이더 * controllers 인스턴스화 되어야 하는 이 모듈에 정의된 컨트롤러 세트 * imports 이 모듈에 필요한 프로바이더를 내보내는 가져온 모듈 목록 * exports 이 모듈에서 제공하고 이 모듈을 임포트하는 다른 모듈에서 사용할 수 있어야 하는 프로바이더의 하위집합 * 모듈은 기본적으로 프로바이더를 캡슐화합니다. 즉, 현재 모듈에 직접 포함되거나 가져온(import) 모듈에서 내보내지(export) 않은 프로바이더를 삽입할 수 없습니다. * 따라서 모듈에서 내보낸 프로바이더를 모듈의 공용 인터페이스 또는 API로 간주할 수 있습니다. * 다른 module의 provider를 사용하고 싶을 때는 app.module의 provider에 직접 넣어주는 것이 아니라 * 해당 module에서 사용하는 provider를 export시켜서 사용한다. * app.module에서는 해당 module을 import 하는 것만으로도 해당 module의 provider를 사용할 수 있다. */ @Module({ //app.module에서 각각 모듈들을 import해서 사용함. imports: [ ConfigModule.forRoot(), //nestjs 환경변수 사용(내부적으로 dotenv package 사용함) MongooseModule.forRoot( process.env.MONGODB_URI /* , { //mongodb 연결 //mongoose 6버전부터 depreciate useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false, } */, ), CatsModule, AuthModule, CommentsModule, ], //db url을 사용 controllers: [AppController], providers: [AppService], //provider에 등록되지 않으면(의존성 주입이 되지 않으면) 사용할 수 없다. }) export class AppModule implements NestModule { private readonly isDev: boolean = process.env.MODE === 'dev' ? true : false; configure(consumer: MiddlewareConsumer) { //forRoutes('cats') cats controller에 bind //forRoutes('*') 전체 controller에 bind consumer.apply(LoggerMiddleware).forRoutes('*'); mongoose.set('debug', this.isDev); } }
92a3b68b9af6dea88d95d73426d1450bcba3699c
TypeScript
shashiWipro/finalFullStack1
/FrontEnd/src/app/pipes/survey-filter/survey-filter.pipe.ts
2.515625
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'surveyFilter' }) export class SurveyFilterPipe implements PipeTransform { transform(value: any[], status: string): any { const result = []; value.map((survey: any) => { if (survey.status === status) { result.push(survey); } }); return result; } }
3862337b7e7834fe5486b2fcc125a75995736ddf
TypeScript
nguyer/aws-sdk-js-v3
/clients/browser/client-app-mesh-browser/types/_VirtualRouterStatus.ts
2.796875
3
/** * <p>An object representing the status of a virtual router. </p> */ export interface _VirtualRouterStatus { /** * <p>The current status of the virtual router.</p> */ status: "ACTIVE" | "DELETED" | "INACTIVE" | string; } export type _UnmarshalledVirtualRouterStatus = _VirtualRouterStatus;
efa58ddc6284829770ff4402f311bec530e66ade
TypeScript
camirori/TP-Sala-de-Juegos-ANGULAR-
/src/app/clases/juego-agilidad.ts
3.0625
3
import { Juego } from '../clases/juego'; export class JuegoAgilidad extends Juego{ numeroIngresado = 0; operando1; operando2; operador: String; respuesta: Number; constructor(jugador?:string) { super("Agilidad aritmetica",jugador); this.generarOperacion(); //console.log(this); } generarOperacion(){ this.operando1 = Math.floor((Math.random() * 100) + 1); this.operando2 = Math.floor((Math.random() * 100) + 1); let op = Math.floor((Math.random() * 4) + 1); console.log(op); switch(op){ case 1: this.respuesta= Math.floor(this.operando1+this.operando2); this.operador='+'; break; case 2: this.respuesta= Math.floor(this.operando1-this.operando2); this.operador='-'; break; case 3: this.respuesta= Math.floor(this.operando1*this.operando2); this.operador='x'; break; case 4: this.respuesta= Math.floor(this.operando1/this.operando2); this.operador='/'; break; } console.log('respuesta '+this.respuesta); } public verificar():boolean{ if (this.numeroIngresado == this.respuesta) { this.Resultado = true; return true; } else { this.Resultado=false; return false; } } public calcularPuntaje(tiempo: any){ if(this.Resultado){ let puntajePerfectoMenosTiempo=1000-(tiempo*20); this.Puntaje=puntajePerfectoMenosTiempo<0? 10:puntajePerfectoMenosTiempo; } else this.Puntaje=0; } }
cf4869d4f69d6bc31f743c12db01fd94b52b6a3f
TypeScript
armenbb2004/typescript
/functions.ts
3.921875
4
function add(a:number, b:number): number { return a+b } function toUpperCase(str: string): string { return str.trim().toUpperCase() } interface MyPostion { x: number | undefined y: number | undefined } interface MyPostionWithDefault extends MyPostion { default: string } function position(): MyPostion function position(a: number): MyPostionWithDefault function position(a: number, b: number): MyPostion function position (a?: undefined, b?: undefined) { if (!a && !b) { return { x: undefined, y: undefined } } if(a && !b) { return { x:a, y:undefined, default: String(a) } } return { x:a, y:b } } console.log('Empty: ', position()) console.log('One param: ', position(42)) console.log('Two params: ', position(10, 15))
082a9d7a63e73de2e0c6730a2b8aca8106927c91
TypeScript
budihan/SpazeHaze
/dev/bullet.ts
3.34375
3
class Bullet { private ship:Ship; public div:HTMLElement; private x:number; private y:number; private width:number; private height:number; private upSpeed:number; constructor(x:number, y:number, fireDirection:number, s:Ship, speed:number){ this.ship = s; this.x = x+11; if(s instanceof Enemy){ this.y = y + 60; } else { this.y = y - 60; } this.width = 33; this.height = 48; this.upSpeed = speed * fireDirection; this.createDiv(); this.setPosition(); } public createDiv(){ if (this.ship instanceof Enemy){ this.div = document.createElement("bulletEnemy") } else{ this.div = document.createElement("bullet"); } document.body.appendChild(this.div); } public setPosition(){ this.div.style.transform = "translate("+this.x+"px, "+this.y+"px)"; } public move(){ this.y = this.y - this.upSpeed; this.div.style.transform = "translate("+this.x+"px, "+this.y+"px)"; } public removeBullet(){ this.div.remove(); } public getX():number{ return this.x; } public getY():number{ return this.y; } public getWidth():number{ return this.width; } public getHeight():number{ return this.height; } }
66f39f9d297c6ad2aeb8395c9c0682bf7bd3744b
TypeScript
pauloferraz/clean-architecture-node
/tests/data/usecases/account/db-load-accounts.spec.ts
2.75
3
import { DbLoadAccounts } from '@/data/usecases' import { LoadAccountsRepositorySpy } from '@/tests/data/mocks' import { throwError } from '@/tests/domain/mocks' import faker from 'faker' type SutTypes = { sut: DbLoadAccounts loadAccountsRepositorySpy: LoadAccountsRepositorySpy } const makeSut = (): SutTypes => { const loadAccountsRepositorySpy = new LoadAccountsRepositorySpy() const sut = new DbLoadAccounts(loadAccountsRepositorySpy) return { sut, loadAccountsRepositorySpy } } let role: string describe('DbLoadAccounts Usecase', () => { beforeEach(() => { role = faker.random.word() }) test('Should call LoadAccountsRepository with correct values', async () => { const { sut, loadAccountsRepositorySpy } = makeSut() await sut.loadAccounts(role) expect(loadAccountsRepositorySpy.role).toBe(role) }) test('Should return null if LoadAccountsRepository returns null', async () => { const { sut, loadAccountsRepositorySpy } = makeSut() loadAccountsRepositorySpy.result = null const account = await sut.loadAccounts(role) expect(account).toBeNull() }) test('Should return accounts on success', async () => { const { sut, loadAccountsRepositorySpy } = makeSut() const account = await sut.loadAccounts(role) expect(account).toEqual(loadAccountsRepositorySpy.result) }) test('Should throw if LoadAccountsRepository throws', async () => { const { sut, loadAccountsRepositorySpy } = makeSut() jest .spyOn(loadAccountsRepositorySpy, 'loadAccounts') .mockImplementationOnce(throwError) const promise = sut.loadAccounts(role) await expect(promise).rejects.toThrow() }) })
2813b2dd6af96298b60dc2a9895448b12234cdc1
TypeScript
sachiko0811/react-typescript-markdown
/src/indexeddb/memos.ts
3.015625
3
import Dexie from 'dexie' // define the data type for saving to IndexedDB export interface MemoRecord { datetime: string title: string text: string } // instance of Dexie, named DBname 'markdown-editor' const database = new Dexie('markdown-editor') // table database.version(1).stores({ memos: '&datetime' }) // data name(table and index) const memos: Dexie.Table<MemoRecord, string> = database.table('memos') export const putMemo = async (title: string, text: string) : Promise<void> => { // save to IndexedDB const datetime = new Date().toISOString() await memos.put({ datetime, title, text }) }
fdb976da7067e19f37375d024385bcc361e9de58
TypeScript
max-team/json-mirror-compiler
/src/common.ts
2.65625
3
/** * js、php 都会用到的逻辑 */ const parsers = { json: JSON.parse, json5: function (source) { return require('json5').parse(source); }, yaml: function (source) { return require('js-yaml').safeLoad(source); } }; export function compileTarget( source: string, CodeBuffer: any, options: { rootVar: string; extVar?: string; filePath: string; format: string; getNamespace?: (file: string) => string; target?: 'commonjs' | 'amd'; variable?: string; afterProcess?: object; publicPath?: string; } ): {code: string; errors?: object[];} { const { format, getNamespace } = options; const buffer = new CodeBuffer({ root: options.rootVar, ext: options.extVar, filePath: options.filePath, target: options.target, variable: options.variable, afterProcess: options.afterProcess, publicPath: options.publicPath }); let json: Mirror; try { json = (parsers[format](source) as Mirror); } catch (e) { console.error(`json parse error: ` + e.message); return { code: '', errors: [{ code: 1, message: 'json parse error: ' + e.message }] }; } if ('$title' in json) { delete json.$title; } if ('$template' in json) { delete json.$template; } if ('$preprocesser' in json) { const preprocesser = json.$preprocesser; buffer.addPreprocesser(preprocesser as string, getNamespace); delete json.$preprocesser; } buffer.walk(json); const code = buffer.toString(); return { code, errors: [] } }
e83ce31d7af85c458a2ca943db92483e8b50f2b4
TypeScript
thekhenzie/Typescript_2020
/Mangrobang/typescript/TS/app (2).ts
2.953125
3
import { Category } from './util'; import { Purge } from './util'; import Shelf from './Ifunctype'; import { ShelfItem, Book }from './interface'; let inventory: Array<Book> = [ { id: 10, title: 'The C Programming Language', author: 'K & R', available: true, category: Category.Software }, { id: 11, title: 'Code Complete', author: 'Steve McConnell', available: true, category: Category.Software }, { id: 12, title: '8-Bit Graphics with Cobol', author: 'A. B.', available: true, category: Category.Software }, { id: 13, title: 'Cool autoexec.bat Scripts!', author: 'C. D.', available: true, category: Category.Software } ]; let purgedBooks: Array<Book> = Purge<Book>(inventory); purgedBooks.forEach(book => console.log(book.title)); let purgedNums: Array<number> = Purge<number>([1, 2, 3, 4]); console.log(purgedNums); // let numberShelf: Shelf<number> = new Shelf<number>(); // [1,2,3,4].forEach(num => numberShelf.add(num)); let bookShelf: Shelf<Book> = new Shelf<Book>(); inventory.forEach(book => bookShelf.add(book)); let firstBook: Book = bookShelf.getFirst(); let softwareBook = bookShelf.find('Code Complete'); console.log(`${softwareBook.title} - ${softwareBook.author}`);
552aa602edcecb9bd0999e1ed51396a16c35782f
TypeScript
xennygrimmato/extractab
/app/javascript/test/music/unbound_chord_spec.ts
2.953125
3
import { UnboundNote, UnboundChord, BoundNote, BoundChord, ChordNames, Interval, Intervals } from "../../music"; describe("UnboundChord", () => { const c = UnboundNote.fromString("C"); const g = UnboundNote.fromString("G"); const a = UnboundNote.fromString("A"); const cMajor = UnboundChord.forName(c, ChordNames.Major); const cMinor = UnboundChord.forName(c, ChordNames.Minor); const cMajor7 = UnboundChord.forName(c, ChordNames.MajorSeventh); const gMajor = UnboundChord.forName(g, ChordNames.Major); it("should report its root and intervals", () => { expect(cMajor.root).toEqual(c); expect(gMajor.root).toEqual(g); expect(cMajor.intervals).toEqual([Intervals.MajorThird, Intervals.PerfectFifth]); }); it("spot checked chords should have the right notes", () => { expect("C E G").toEqual(cMajor.notesString()); expect("C D# G").toEqual(cMinor.notesString()); expect("C E G B").toEqual(cMajor7.notesString()); expect("C D# G A#").toEqual(UnboundChord.forName(c, ChordNames.MinorSeventh).notesString()); expect("C E G A#").toEqual(UnboundChord.forName(c, ChordNames.DominantSeventh).notesString()); expect("C E G B D").toEqual(UnboundChord.forName(c, ChordNames.MajorNinth).notesString()); expect("C D# G A# D").toEqual(UnboundChord.forName(c, ChordNames.MinorNinth).notesString()); expect("C E G A# D").toEqual(UnboundChord.forName(c, ChordNames.Ninth).notesString()); expect("C E G B F").toEqual(UnboundChord.forName(c, ChordNames.MajorEleventh).notesString()); expect("C D# G A# F").toEqual(UnboundChord.forName(c, ChordNames.MinorEleventh).notesString()); expect("C E G A# F").toEqual(UnboundChord.forName(c, ChordNames.Eleventh).notesString()); expect("C E G B A").toEqual(UnboundChord.forName(c, ChordNames.MajorThirteenth).notesString()); expect("C D# G A# A").toEqual(UnboundChord.forName(c, ChordNames.MinorThirteenth).notesString()); expect("C E G A# A").toEqual(UnboundChord.forName(c, ChordNames.Thirteenth).notesString()); }); it("different chord instance should be equal if they have hte same root and the same intervals", () => { expect(cMajor).toEqual(cMajor); expect(cMajor).toEqual(UnboundChord.forName(c, ChordNames.Major)); expect(cMajor).not.toEqual(gMajor); expect(cMajor).not.toEqual(cMajor7); }); it("should reflect a new, negative interval to the substitute root if created with a substitute root not already included in the chord", () => { const cOverA = UnboundChord.forName(c, ChordNames.Major, a); expect(cOverA.root).toEqual(c); expect(cOverA.intervals).toEqual([new Interval(-3), Intervals.MajorThird, Intervals.PerfectFifth]); const cSharpOverA = UnboundChord.forName(UnboundNote.fromString("C#"), ChordNames.Major, a); expect(cSharpOverA.root).toEqual(UnboundNote.fromString("C#")); expect(cSharpOverA.intervals).toEqual([new Interval(-4), Intervals.MajorThird, Intervals.PerfectFifth]); const nonsense = UnboundChord.forName(UnboundNote.fromString("Gb"), ChordNames.DominantSeventh, UnboundNote.fromString("D")); expect(nonsense.root).toEqual(UnboundNote.fromString("Gb")); expect(nonsense.intervals).toEqual([new Interval(-4), Intervals.MajorThird, Intervals.PerfectFifth, Intervals.MinorSeventh]); }); it("should reflect a replacement, negative interval to the substitute root if created with a substitute root already included in the chord", () => { const cOverG = UnboundChord.forName(c, ChordNames.Major, g); expect(c).toEqual(cOverG.root); expect(cOverG.intervals).toEqual([new Interval(-5), Intervals.MajorThird]); const aOverE = UnboundChord.forName(a, ChordNames.Major, UnboundNote.fromString("E")); expect(UnboundNote.fromString("A")).toEqual(aOverE.root); expect(aOverE.intervals).toEqual([new Interval(-5), Intervals.MajorThird]); }); it("should still be equal to other chords regardless of the order the intervals are given at construction time", () => { let left = new UnboundChord(c, [Intervals.MajorThird, Intervals.PerfectFifth]); let right = new UnboundChord(c, [Intervals.PerfectFifth, Intervals.MajorThird]); expect(left).toEqual(right); left = new UnboundChord(c, []); right = new UnboundChord(c, []); expect(left).toEqual(right); }); it("should be equivalent to other chords with the same intervals, regardless of constructor order", () => { expect(cMajor.equivalent(cMajor)).toEqual(true); expect(UnboundChord.forName(c, ChordNames.Major).equivalent(cMajor)).toEqual(true); let left = new UnboundChord(c, [Intervals.MajorThird, Intervals.PerfectFifth]); let right = new UnboundChord(c, [Intervals.PerfectFifth, Intervals.MajorThird]); expect(left.equivalent(right)).toEqual(true); expect(right.equivalent(left)).toEqual(true); left = new UnboundChord(c, []); right = new UnboundChord(c, []); expect(left.equivalent(right)).toEqual(true); expect(right.equivalent(left)).toEqual(true); }); it("should not be equivalent to other chords with different roots but the same intervals", () => { const left = new UnboundChord(c, [Intervals.MajorThird, Intervals.PerfectFifth]); const right = new UnboundChord(g, [Intervals.MajorThird, Intervals.PerfectFifth]); expect(left.equivalent(right)).toEqual(false); expect(right.equivalent(left)).toEqual(false); }); it("should not be equivalent to other chords with the same root but different intervals", () => { expect(cMajor.equivalent(cMinor)).toEqual(false); expect(cMinor.equivalent(cMajor)).toEqual(false); expect(cMajor.equivalent(cMajor7)).toEqual(false); expect(cMajor7.equivalent(cMajor)).toEqual(false); }); it("equivalent should return true for chords with different roots and intervals that compute to the same notes", () => { const left = new UnboundChord(c, [Intervals.MajorThird, Intervals.PerfectFifth]); const right = new UnboundChord(g, [Intervals.PerfectFourth, Intervals.MajorSixth]); expect(left.equivalent(right)).toEqual(true); expect(right.equivalent(left)).toEqual(true); }); it("equivalent should return true for chords with the same notes even if some are duplicated", () => { const left = new UnboundChord(c, [Intervals.MajorThird, Intervals.PerfectFifth]); const right = new UnboundChord(c, [Intervals.MajorThird, Intervals.PerfectFifth, Intervals.Octave.add(Intervals.MajorThird)]); expect(left.equivalent(right)).toEqual(true); expect(right.equivalent(left)).toEqual(true); }); it("equivalent should return true for chords that have the same notes with equivalent but not identical roots", () => { const left = new UnboundChord(UnboundNote.fromString("Gb"), [Intervals.MajorThird, Intervals.PerfectFifth]); const right = new UnboundChord(UnboundNote.fromString("F#"), [Intervals.MajorThird, Intervals.PerfectFifth]); expect(left.root).not.toEqual(right.root); expect(left.root.equivalent(right.root)).toEqual(true); expect(left.equivalent(right)).toEqual(true); expect(right.equivalent(left)).toEqual(true); }); it("should be bindable at an octave", () => { let expected = new BoundChord(BoundNote.fromString("C3"), [BoundNote.fromString("E3"), BoundNote.fromString("G3")]); expect(cMajor.bindAtRootOctave(3)).toEqual(expected); expected = new BoundChord(BoundNote.fromString("C4"), [BoundNote.fromString("D#4"), BoundNote.fromString("G4")]); expect(cMinor.bindAtRootOctave(4)).toEqual(expected); }); it("should carry through the display label with an octave addded when bound at an octave", () => { const cMajorWithLabel = UnboundChord.forName(c, ChordNames.Major, undefined, "Cmaj"); const expected = new BoundChord(BoundNote.fromString("C3"), [BoundNote.fromString("E3"), BoundNote.fromString("G3")], "Cmaj3"); let actual = cMajorWithLabel.bindAtRootOctave(3); expect(actual).toEqual(expected); expect(actual.displayLabel()).toEqual("Cmaj3"); actual = cMajorWithLabel.bindAtRootOctave(4); expect(actual.displayLabel()).toEqual("Cmaj4"); }); });
386e907d1326a403f8c842424deea617ce0bffa4
TypeScript
Rouux/matchmaking-bot
/src/core/functions/recursive-get-classes-dir.ts
2.703125
3
/* eslint-disable no-use-before-define */ import { recursiveReadDir } from "./recursive-read-dir"; export async function getInstancesFromFolder<T>( folderPath: string, ): Promise<T[]> { const files = recursiveReadDir(folderPath); if (files.length === 0) return []; return files .map(async filePath => { return _importClassesFromPath<T>(filePath); }) .reduce(async (promiseAccumulator, promiseCurrent) => { const accumulator = await promiseAccumulator; const current = await promiseCurrent; accumulator.push(...current); return promiseAccumulator; }); } async function _importClassesFromPath<T>(filePath: string): Promise<T[]> { return import(filePath) .then(file => { return _instantiateGivenClasses<T>(file); }) .catch(err => { return Promise.reject(new Error(err)); }); } function _instantiateGivenClasses<T>(classes: { [key: string]: new (...args: unknown[]) => T; }): T[] { return Object.keys(classes).map(cname => { return new classes[cname](); }); }
b07443ed0ed85f0fec50cd88f3733343e005d02c
TypeScript
wojtekjPJATK/my-notepad-ng
/src/app/validators/body.ts
2.578125
3
import { AbstractControl, ValidationErrors } from "@angular/forms"; export function ValidateBody(control: AbstractControl): ValidationErrors { if (control.value.length < 3) return { tooShort: true }; if (control.value.length > 50) return { tooLong: true }; if (/[^a-zA-Z0-9 \-\/]/.test(control.value)) return { invalidChar: true }; return null; }
b5b31183901351230e1aad29f0f5571e2b76b6b1
TypeScript
lalitghongade/revature_training
/Angular/sep6day1/variables.ts
2.703125
3
let x = 10; const y = 20; console.log(x); console.log(y); //can't redclare x //let x= 30; //can not ok! let sum;// can be declared without init console.log(sum); //const title;//should be initialised
e5bea1355a00570b87d321746790bb741a0bcb7c
TypeScript
IkarosKappler/plotboilerplate
/src/cjs/utils/algorithms/getContrastColor.d.ts
3
3
/** * @author Original from Martin Sojka. Ported to TypesScript by Ikaros Kappler * @date 2020-11-10 */ import { Color } from "../datastructures/Color"; /** * Contrast color algorithm by Martin Sojka's. * Found at * https://gamedev.stackexchange.com/questions/38536/given-a-rgb-color-x-how-to-find-the-most-contrasting-color-y/38542#38542 * * @requires Color */ export declare const getContrastColor: (color: Color) => Color;
63bcc1cb30e0c812b47d1d6ee98c909610cfae7d
TypeScript
LaunchMenu/LaunchMenu
/packages/applets/dictionary/src/scraper/wiktionary/Wiktionary.ts
2.671875
3
import {Wiki} from "../wiki/Wiki"; import {WiktionaryPage} from "./WitkionaryPage"; export class Wiktionary extends Wiki<WiktionaryPage> { /** * Creates a new wiktionary instance (You shouldn't create multiple instances however) */ public constructor() { super("https://en.wiktionary.org", title => new WiktionaryPage(this, title)); } }
a5810a5d41ae0869aca1c57ef402e2f77b8d81e3
TypeScript
paulotokimatu/github-label-tracker
/src/redux/reducers/alertReducer.ts
3.015625
3
import AlertType from 'core/models/AlertType'; import { HIDE_ALERT, SET_ALERT, } from '../actions/alertActions'; const initialState: { type: AlertType, text: string, isOn: boolean, } = { isOn: false, text: '', type: 'info', }; const alertReducer = (state = initialState, action: any) => { switch (action.type) { case SET_ALERT: { const {text, type} = action.payload; return { isOn: true, text, type, }; } case HIDE_ALERT: { return { isOn: false, text: '', type: 'info', }; } default: { return state; } } }; export default alertReducer;
185945ca4e9dbf0e9e30c1eaff91ef21c0a37838
TypeScript
usetech-llc/gallery_backend
/src/service/stores/store/JSONStore.ts
2.734375
3
import { Config, Store } from '../interface/Store'; import { getAccess, createDir, createFile, getDir, getFile } from '../utils'; class JSONStore implements Store { private pathFile = `${process.cwd()}/config.json`; //private contentFile: Promise<string>; public async add(config: Config): Promise<any> { const jsonConfig = JSON.parse(config.data || '[]'); const configHost = { 'host': config.hostname, 'protocol': config.protocol }; jsonConfig.push(configHost); const writeConfig = JSON.stringify(jsonConfig); await createFile(this.pathFile, writeConfig, 'utf-8'); return configHost; } public async get(): Promise<string | null> { const exists: boolean = await getAccess(this.pathFile); if (!exists) { const data = JSON.stringify([]); await createFile(this.pathFile, data, 'utf-8'); return data; } else { const data = await getFile(this.pathFile); return data; } } public async update(config: Config): Promise<void> { const writeConfig = JSON.stringify(config.data); await createFile(this.pathFile, writeConfig, 'utf-8'); } } export default JSONStore;
3b9a36b29b609534df56b862f1083b7da6de3185
TypeScript
ClementDEBOOS/CookiesClickerLike
/src/app/services/coockies.service.ts
2.5625
3
import {Injectable} from "@angular/core"; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import { Credentials } from '../user'; @Injectable() export class CoockiesService { // URL to web API private userUrl = 'api/credentials'; constructor( private http: HttpClient) { } getUsers(): Observable<Credentials[]> { console.log('BOO', this.http.get<Credentials[]>(this.userUrl)); return this.http.get<Credentials[]>(this.userUrl); } /** * Handle Http operation that failed. * Let the app continue. * @param operation - name of the operation that failed * @param result - optional value to return as the observable result */ private handleError<T> (operation = 'operation', result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // Let the app keep running by returning an empty result. return of(result as T); }; } }
2a249523374fecfb06a7f71a504ce0eb22f8534c
TypeScript
j3k0/ganomede-chat
/src/helpers/send-notification.ts
2.59375
3
import ServiceEnv from './service-env'; import * as superagent from 'superagent'; import log from '../log'; export const REQUIRED_KEYS = ['from', 'to', 'type']; export const OPTIONAL_KEYS = ['data', 'push', 'secret']; export const SERVERSIDE_KEYS = ['id', 'timestamp']; function required(options: Notification, key: keyof Notification): string { if (!options[key]) throw new Error("Required key missing: `" + key + "`"); return options[key]; } export type SendNotificationCallback = (err?: Error, body?: any) => void; export type SendNotificationFunction = (notification: Notification, callback?: SendNotificationCallback) => void; export interface Notification { secret?: string; from: string; to: string; type: string; data?: any, push?: { app: string; title: string[]; message: string[]; messageArgsTypes: string[]; } } export class NotificationPayload implements Notification { from: string; to: string; type: string; secret?: string; data?: any; push?: { app: string; title: string[]; message: string[]; messageArgsTypes: string[]; } constructor(options: Notification) { this.from = required(options, 'from'); this.to = required(options, 'to'); this.type = required(options, 'type'); this.secret = options.secret; this.data = options.data; this.push = options.push; } } export function sendNotification(baseURL: string, notification: Notification, callback?: SendNotificationCallback) { if (!notification.secret) { notification.secret = process.env.API_SECRET; } const url = `${baseURL}/notifications/v1/messages`; // log.info({ url, notification }, "sending notification"); return superagent .post(url) .send(notification) .end(function (err, res) { if (err) { log.warn({ err, url, notification }, 'sendNotification() failed'); } if (typeof callback === 'function') callback(err, res.body); }); }; export function createWithDefaults(noopIfNotFound: boolean = false): SendNotificationFunction { if (!ServiceEnv.exists('NOTIFICATIONS', 8080)) { if (!noopIfNotFound) { throw new Error("Notification.sendFn() failed to find NOTIFICATIONS service address in environment variables"); } return function () { const callback = arguments[arguments.length - 1]; if (typeof callback === "function") callback(null); }; } const baseURL = ServiceEnv.url('NOTIFICATIONS', 8080); return function (notification: Notification, callback?: SendNotificationCallback) { if (!baseURL) { if (callback) callback(new Error('Notification service misconfigured')); return; } sendNotification(baseURL, notification, callback); }; }; export default { create(baseURL): SendNotificationFunction { return (notification: Notification, callback?: SendNotificationCallback) => { if (!baseURL) { if (callback) callback(new Error('Notification service misconfigured')); return; } sendNotification(baseURL, notification, callback); } }, createWithDefaults }; // vim: ts=2:sw=2:et:
88d376215a31c823c4834319642ac38cd52445b8
TypeScript
FullStackSmartDev/CSharp-ASP.NET-Core-Angular-Medical-Management-System
/client/src/provider/sqlDataSource/sqlQueryStringProviders/sqlValuesProvider.ts
3.046875
3
import { TypeHelper } from "../../../helpers/typeHelper"; import { Injectable } from "@angular/core"; import { DateConverter } from "../../../helpers/dateConverter"; @Injectable() export class SqlValuesProvider { private _sqlValueProviders: Array<ISqlValueProvider> = []; constructor() { this.initSqlValueProviders(); } getSqlValue(value: any): SqlValue { let convertedValue = null; for (let i = 0; i < this._sqlValueProviders.length; i++) { const sqlValueProvider = this._sqlValueProviders[i]; const convertionResult = sqlValueProvider.tryGetSqlValue(value); if (convertionResult.success) { convertedValue = convertionResult.value; break; } } if (!convertedValue) { throw `Unable to find converter for type: "${value.constructor.name}"` } return convertedValue; } private initSqlValueProviders(): any { this._sqlValueProviders .push(new StringSqlValueProvider()); this._sqlValueProviders .push(new BooleanSqlValueProvider()); this._sqlValueProviders .push(new NullSqlValueProvider()); this._sqlValueProviders .push(new NumberSqlValueProvider()); this._sqlValueProviders .push(new DateSqlValueProvider()); } } class SqlValue { originalStringValue: string; sqlFormattedStringValue: string; constructor(originalStringValue: string, sqlFormattedStringValue: string) { this.originalStringValue = originalStringValue; this.sqlFormattedStringValue = sqlFormattedStringValue; } } class SqlConvertionResult { value: SqlValue; success: boolean; constructor(value: SqlValue = null, success: boolean = false) { this.value = value; this.success = success; } } interface ISqlValueProvider { tryGetSqlValue(value: any): SqlConvertionResult; } class BooleanSqlValueProvider implements ISqlValueProvider { tryGetSqlValue(value: any): SqlConvertionResult { const isBooleanValue = TypeHelper.isBoolean(value); if (!isBooleanValue) { return new SqlConvertionResult(); } value = (value ? 1 : 0).toString(); return new SqlConvertionResult(new SqlValue(value, value), true); } } class StringSqlValueProvider implements ISqlValueProvider { tryGetSqlValue(value: any): SqlConvertionResult { const isStringValue = TypeHelper.isString(value); if (!isStringValue) { return new SqlConvertionResult(); } const isSingleQuoteExist = value.indexOf("'") !== -1; if (isSingleQuoteExist) value = value.replace(/'/g, "''"); const sqlValue = new SqlValue(value, `'${value}'`); return new SqlConvertionResult(sqlValue, true); } } class NullSqlValueProvider implements ISqlValueProvider { tryGetSqlValue(value: any): SqlConvertionResult { if (value === null) { return new SqlConvertionResult(new SqlValue("null", "null"), true); } return new SqlConvertionResult(); } } class NumberSqlValueProvider implements ISqlValueProvider { tryGetSqlValue(value: any): SqlConvertionResult { const isNumber = TypeHelper.isNumber(value); if (isNumber) { return new SqlConvertionResult(new SqlValue(`${value}`, `${value}`), true); } return new SqlConvertionResult(); } } class DateSqlValueProvider implements ISqlValueProvider { tryGetSqlValue(value: any): SqlConvertionResult { const isNumber = TypeHelper.isDate(value); if (isNumber) { const sqlDate = DateConverter .jsLocalDateToSqlServerUtc(value); return new SqlConvertionResult(new SqlValue(`${sqlDate}`, `'${sqlDate}'`), true); } return new SqlConvertionResult(); } }
2fd58971476e0610db1e778bc6218ce865f2b138
TypeScript
avosalmon/angular-ngxs-hn
/src/app/news/store/news.state.ts
2.609375
3
import { HttpClient } from '@angular/common/http'; import { Action, Selector, State, StateContext } from '@ngxs/store'; import { catchError, tap } from 'rxjs/operators'; import { News } from '../models/news.model'; import * as newsActions from './news.actions'; export interface NewsStateModel { news: News[]; page: number; loading: boolean; } @State<NewsStateModel>({ name: 'newsState', defaults: { news: [], page: 1, loading: false } }) export class NewsState { constructor(private http: HttpClient) { } @Selector() static news(state: NewsStateModel) { return state.news; } @Selector() static page(state: NewsStateModel) { return state.page; } @Selector() static loading(state: NewsStateModel) { return state.loading; } @Action(newsActions.LoadNews) loadNews(ctx: StateContext<NewsStateModel>) { ctx.patchState({ loading: true }); const state = ctx.getState(); const url = `https://api.hackerwebapp.com/news?page=${state.page}`; return this.http.get<News[]>(url).pipe( tap(news => ctx.dispatch(new newsActions.LoadNewsSuccess(news))), catchError(error => ctx.dispatch(new newsActions.LoadNewsFail(error))) ); } @Action(newsActions.LoadNewsSuccess) loadNewsSuccess(ctx: StateContext<NewsStateModel>, action: newsActions.LoadNewsSuccess) { ctx.patchState({ news: action.payload, loading: false }); } @Action(newsActions.LoadNewsFail) loadNewsfail(ctx: StateContext<NewsStateModel>, action: newsActions.LoadNewsFail) { ctx.patchState({ loading: false }); window.alert(action.payload.message); } @Action(newsActions.ChangePage) changePage(ctx: StateContext<NewsStateModel>, action: newsActions.ChangePage) { ctx.patchState({ page: action.payload }); ctx.dispatch(new newsActions.LoadNews()); } }
ac1227252d71b38a09e120ba432b5eca37f262ed
TypeScript
calebmer/decode-universe
/studio/desktop/renderer/storage/Storage.ts
3
3
import * as path from 'path'; import * as fs from './FileSystemUtils'; import RecordingDirectoryStorage from './RecordingDirectoryStorage'; /** * Represents all of the persistent file system storage for the Decode Studio * Desktop client. This is the entry point of storage interfaces which support * both read and write operations. */ export default class Storage { /** * Opens up a storage instance for the provided directory. */ public static async open(directoryPath: string): Promise<Storage> { // Create the path for the recordings directory. const recordingsDirectory = path.join(directoryPath, 'recordings'); // Create the recordings directory if it does not already exist. if (!await fs.directoryExists(recordingsDirectory)) { await fs.createDirectory(recordingsDirectory); } // Open the recordings directory. const directory = await RecordingDirectoryStorage.open(recordingsDirectory); // Create a new storage instance using the private constructor. return new Storage({ directory, }); } /** * The directory of recordings which the user has made. */ public readonly directory: RecordingDirectoryStorage; private constructor({ directory }: { directory: RecordingDirectoryStorage }) { this.directory = directory; } }
e4e7d94f45751e36454a10b003be5fc6aa4c1f26
TypeScript
jhoijune/algorithm
/src/Baekjoon/14891.ts
3.328125
3
import { readFileSync } from 'fs'; const source = __dirname + '\\input.txt'; const input = readFileSync(source).toString().trim().split('\n'); const sawtooth = input.slice(0, 4).map((v) => v .trim() .split('') .map((v) => Number(v)) ); const instruction = input.slice(5, input.length).map((v) => v .trim() .split(' ') .map((v) => Number(v)) ); const solution = (sawtooth: number[][], instruction: number[][]) => { let curr = [0, 0, 0, 0]; const rotate = (num: number, direction: number) => { if (direction === 1) { curr[num - 1] = (8 + curr[num - 1] - 1) % 8; } else { curr[num - 1] = (curr[num - 1] + 1) % 8; } }; const direction3Value = (num: number) => { const index = (curr[num - 1] + 2) % 8; return sawtooth[num - 1][index]; }; const direction9Value = (num: number) => { const index = (8 + curr[num - 1] - 2) % 8; return sawtooth[num - 1][index]; }; for (const [num, direction] of instruction) { const queue = []; queue.push([num, direction]); let currNum = num; let currDir = direction; while (currNum > 1) { if (direction9Value(currNum) ^ direction3Value(currNum - 1)) { currNum -= 1; currDir = -currDir; queue.push([currNum, currDir]); } else { break; } } currNum = num; currDir = direction; while (currNum < 4) { if (direction3Value(currNum) ^ direction9Value(currNum + 1)) { currNum += 1; currDir = -currDir; queue.push([currNum, currDir]); } else { break; } } queue.forEach(([num, dir]) => rotate(num, dir)); } let sum = 0; for (let index = 0; index < 4; index++) { const idx = curr[index]; if (sawtooth[index][idx]) { sum += Math.pow(2, index); } } console.log(sum); }; solution(sawtooth, instruction);
314ef5d9619c4aaf646f74fd2cd98b2528892b59
TypeScript
tnrich/ve-range-utils-ts
/test/getShortestDistanceBetweenTwoPositions.test.ts
2.5625
3
import * as assert from "assert"; import { getShortestDistanceBetweenTwoPositions } from "../src"; describe('getShortestDistanceBetweenTwoPositions', function () { it('should return the correct length for positions that cross the origin', function (done) { var length = getShortestDistanceBetweenTwoPositions(9,0,10) assert.ok(length === 1) done() }); it('should return the correct length for ranges that do not cross the origin', function (done) { var length = getShortestDistanceBetweenTwoPositions(4,6,10) assert.ok(length === 2) done() }); });
1da2bd0622048e61f069c2585d68ab42499174f1
TypeScript
achristoph/rx-starter
/observable/Observable.ts
2.953125
3
import Rx = require('@reactivex/rxjs'); var fetch = require('node-fetch'); var streamA = Rx.Observable.of(1, 2, 3); var streamB = streamA.map(a => 10 * a); streamB.subscribe(b => console.log(b)); var requestStream = Rx.Observable.of('https://api.github.com/users'); // Option 1 // Two subscribe calls requestStream.subscribe(requestUrl => { var responseStream = Rx.Observable.fromPromise(fetch(requestUrl)); responseStream.subscribe((response: any) => { response.json().then((r) => console.log(r)); }); }); // Option 2 // One subscribe call only var responseStream = requestStream.flatMap(requestUrl => { return Rx.Observable.fromPromise(fetch(requestUrl)); }).subscribe((response: any) => { response.json().then((r) => console.log(r)); });
0ab4b39d306106658ed0c3ec6bf83730701d192d
TypeScript
sivagangadhar1420/AngularFolder-3-
/AngFolder/MyTypescript/DataTypes/Data1.ts
3.671875
4
// var nm:string = 'Gangadhar'; // var mbl:number = 9966860320; // var bl:boolean = true; // var msg:string = `Helloo ${nm} nd is this u r mobile number ${mbl}` // alert(msg); // let str:Array<string> = ["Ar", "Br"]; // let number:Array<number> = [12,3,4,5]; // // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // Enum // enum ff{Red, blue}; // let cl:ff= ff.Red; // alert(cl) // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // var a:number=10; // function finalFun(){ // var a:number=100; // alert(a) // } // finalFun(); // alert(a) // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // let ar:number=20; // function lfun(){ // let ar:number=21; // alert(ar) // } // lfun(); // alert(ar) // // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // let ar1:string="Hello"; // if(true){ // let ar1:string= "Welocome"; // } // alert(" let " + ar1); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // var ar1:string="Hello"; // if(true){ // var ar1:string= "Welocome"; // } // alert( "var" + ""+ar1); // XXXXXXXXXXXXXXXxXXXXXXXXXXXXXxXXXXXXXXXXXXXxXXXXXXXXXXXXXxXXXXXXXXXXXXXxXXXXXXXXXXXXXxXXXXXXXXXXXXXxXXXXXXXXXXXXXxXXXXXXXXXXXXXxXXXXXXXXXXXXXx var ar1:string[]= ["Nm", "nm1"]; var ar2:Array<string>= ["NM", "fm"]; var ar3:Array<number>= [1,2,3,4,5]; var ar4:Object = {fn:"Raju", ln:"Kumar", age:30}; var ar5:any= {fn:"Raju", ln:"Kumar", age:30}; var ar6:any= {fn:"Raju", ln:"Kumar", age:30}; // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // ForIN(Arrayy) // for(var ar in ar1){ // alert(ar) // } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // for(var ar in ar4){ // Keys And Values // alert(ar + " " + ar4[ar]) // Keys // alert(ar); // alert(Object.keys(ar)) // alert(Object.length) // } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // // ForOf // for(var vals of ar3){ // alert(vals) // } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // for(var vals of ar2){ // alert(vals) // } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // for(var vals of ar2){ // alert(vals) // } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // ArrayDestructuring // var [a1,a2,...b1]=[1,2,3,4,5,6]; // alert(a1) // alert(a2) // alert(b1) // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // ObjectDestructuring // let ob1={a:"foo",b:"doe"}; // let {a:h1, b:h2} = ob1; // alert(h1 + " " + h2); // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // let ob2={nm:"nm", fm:"fm", tm:"tm"}; // let {nm,...restd1} = ob2; // alert(nm+ " " + restd1.fm + " " + restd1.tm ); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // Spread // var sp1:Array<number>=[1,2,3,4,5]; // var sp2:number[]=[1,2,3,4,5,6,7,8,9]; // var sp3:any=[,14,21,...sp1, ...sp2,12,12,1,31]; // alert(sp3) // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // class students12 { // firstName:string; // lastName:string; // id:number; // constructor(fn:string, ln:string ,id:number){ // this.firstName = fn; // this.lastName = ln; // this.id=id; // } // public fullname():any{ // return `FllName is ${this.firstName} ${this.lastName} and Id is ${this.id} ` // } // } // var gr:students12=new students12("Raaju", "Kumar", 1); // alert(gr.fullname()); // // alert(gr.firstName + " " + gr.lastName + " " + gr.id) // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // class students123 { // firstName:string; // lastName:string; // id:number; // constructor(fn:string, ln:string ,id:number){ // this.firstName = fn; // this.lastName = ln; // this.id=id; // } // public get fullname():string{ // return `Getting FllName is ${this.firstName} ${this.lastName} and Id is ${this.id} ` // } // public set fullname(name:string){ // this.firstName = name.split( ' ')[0]; // this.lastName = name.split(' ')[1]; // } // public holidays(a):any{ // return `${this.firstName} needs ${a} nof days ` // } // } // class employee extends students123{ // dob:Date; // constructor(firstName, lastName,id, DOB:Date){ // super(firstName,lastName,id); // this.dob=DOB; // } // public dateofbirth(){ // return `Age of ${this.firstName} is ${this.dob}` // } // static salary(a):any{ // return `Salary of ${a}` // } // public prices(cp):any{ // return `${this.firstName} costs of ${cp} ` // } // } // // var gr:students123=new students123("Raaju", "Kumar", 1); // // alert(gr.fullname()); // // alert(gr.firstName + " " + gr.lastName + " " + gr.id) // var br:employee = new employee("Raju", "Kumar", 1, new Date('1/1/2020')); // // alert(br.fullname + " " + br.dob + br.firstName) ; // // alert(br.dateofbirth()); // // alert(br.firstName + " " + br.lastName + br.fullname + "Date Of B "+ // // + " " + br.prices(9) + + " " + br.dob + " SAlary" + employee.salary(400 + "k") + " " + br.holidays(5) ); // // br.firstName = "Abc xyz"; // // alert(br instanceof employee); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // Functions // function funn1(a:number, b:number, c?:number) { // if(!c){ // c=0; // return a+b+c; // } // } // alert(funn1(10,20)) // alert(funn1(10,20,30)) // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // function funn1(a:number, b:number, c:number=0) { // return a+b+c; // } // alert(funn1(10,20)) // alert(funn1(10,20,30)) // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // function name1(a:number=0, b:number=0, c:number=0) { // return a+b+c; // } // alert(name1(2,2,3)) // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // function funn1(...a:[]) { // var x:number=0; // for(var i=0; i<a.length; i++){ // x += a[i]; // } // return x; // } // alert(funn1(10,2030,50)) // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // function funn1(...a:[]) { // for(var x in a){ // x += a[x] // } // return x; // } // alert(funn1(10,20,30)) // alert(funn1(10,20,30,40,50,60)) // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // function funn1(x,y) { // if(typeof x == "number"){ // return x+y; // } // } // alert(funn1(10,20)) // alert(funn1("x",10)); // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // function funn1(x,y:string) { // if(typeof x == "number"){ // return x+y; // } // else{ // return x+ " " + y // } // } // alert(funn1(10,"y")) // alert(funn1("x","y")); // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // let sub:any=(x:number, y:number)=>{ // return x-y // } // alert(sub(20,10)) // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
fa65396f4965e9eb1b14768579873d0db1f698f1
TypeScript
huaweicloud/huaweicloud-sdk-nodejs-v3
/services/smn/v2/model/LogtankItem.ts
2.796875
3
export class LogtankItem { public id?: string; private 'log_group_id'?: string; private 'log_stream_id'?: string; private 'create_time'?: string; private 'update_time'?: string; public constructor(id?: string, logGroupId?: string, logStreamId?: string, createTime?: string, updateTime?: string) { this['id'] = id; this['log_group_id'] = logGroupId; this['log_stream_id'] = logStreamId; this['create_time'] = createTime; this['update_time'] = updateTime; } public withId(id: string): LogtankItem { this['id'] = id; return this; } public withLogGroupId(logGroupId: string): LogtankItem { this['log_group_id'] = logGroupId; return this; } public set logGroupId(logGroupId: string | undefined) { this['log_group_id'] = logGroupId; } public get logGroupId(): string | undefined { return this['log_group_id']; } public withLogStreamId(logStreamId: string): LogtankItem { this['log_stream_id'] = logStreamId; return this; } public set logStreamId(logStreamId: string | undefined) { this['log_stream_id'] = logStreamId; } public get logStreamId(): string | undefined { return this['log_stream_id']; } public withCreateTime(createTime: string): LogtankItem { this['create_time'] = createTime; return this; } public set createTime(createTime: string | undefined) { this['create_time'] = createTime; } public get createTime(): string | undefined { return this['create_time']; } public withUpdateTime(updateTime: string): LogtankItem { this['update_time'] = updateTime; return this; } public set updateTime(updateTime: string | undefined) { this['update_time'] = updateTime; } public get updateTime(): string | undefined { return this['update_time']; } }
ac4e689e08ee886ccb43abe928bf4dfccd04fe77
TypeScript
inureyes/PyconKR-2021-BTF
/src/functions/functions.ts
2.640625
3
/* eslint-disable no-undef */ import * as ai from "backend.ai-client/backend.ai-client-es6.js"; /* global clearInterval, console, setInterval */ async function connectToManager() { if ('baiclient' in globalThis && globalThis.baiclient.ready == true) { return Promise.resolve(true); } const api_key = "AKIAIOSFODNN7EXAMPLE"; const secret_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; const api_endpoint = "https://127.0.0.1:8091"; const clientConfig = new ai.backend.ClientConfig( api_key, secret_key, api_endpoint ); globalThis.baiclient = new ai.backend.Client( clientConfig, `Excel Adapter`, ); globalThis.baiclient.ready = false; globalThis.baiclient.get_manager_version().then((response) => { globalThis.baiclient.ready = true; return Promise.resolve(true); }).catch((e) =>{ return Promise.resolve(false); }); } function errorAsString(e) { let result = ''; for (let key in e) { if (e.hasOwnProperty(key)) { result = result + " " + key + "," + e[key] + "|"; } } return result; } /** * Adds two numbers. * @customfunction * @param first First number * @param second Second number * @returns The sum of the two numbers. */ export function add(first: number, second: number): number { return first + second + 5; } /** * Displays the current time once a second. * @customfunction * @param invocation Custom function handler */ export function clock(invocation: CustomFunctions.StreamingInvocation<string>): void { const timer = setInterval(() => { const time = currentTime(); invocation.setResult(time); }, 1000); invocation.onCanceled = () => { clearInterval(timer); }; } /** * Returns the current time. * @returns String with the current time formatted for the current locale. */ export function currentTime(): string { return new Date().toLocaleTimeString(); } /** * Increments a value once a second. * @customfunction * @param incrementBy Amount to increment * @param invocation Custom function handler */ export function increment(incrementBy: number, invocation: CustomFunctions.StreamingInvocation<number>): void { let result = 0; const timer = setInterval(() => { result += incrementBy; invocation.setResult(result); }, 1000); invocation.onCanceled = () => { clearInterval(timer); }; } /** * Test connection between Excel and Cluster * @customfunction TEST_CONNECTION * @param invocation Custom function handler */ export function testConnection(invocation: CustomFunctions.StreamingInvocation<string>): void { connectToManager().then((response) => { invocation.setResult("Succeed"); }).catch((e) =>{ let result = errorAsString(e); invocation.setResult(result); }); } /** * Run super-basic Python Hello World * @customfunction hello_python_world * @param invocation Custom function handler */ export function hello_python_world(invocation: CustomFunctions.StreamingInvocation<string>): void { connectToManager().then(() => { invocation.setResult("Creating..."); let resources = {"cpu": 1, "mem": "1g", "domain": "default", "group_name": "default", "scaling_group": "default", "cluster_mode": "single-node", "cluster_size": 1, "mounts": [], "env": {}, "resource_opts": {}, "maxWaitSeconds": 15}; return globalThis.baiclient.createIfNotExists("cr.backend.ai/stable/python:3.8-ubuntu18.04", "HelloWorld", resources); }).then(response => { invocation.setResult(`My session is created: ${response.sessionId}`); return globalThis.baiclient.execute(response.sessionId, 1, "query", "print('hello python world')", {}); }).then(response => { if (response.result.exitCode === 0) { invocation.setResult(response.result.console[0][1]); } }).catch(err => { switch (err.type) { case ai.backend.Client.ERR_SERVER: invocation.setResult(`Session creation failed: ${err.message}`); break; default: invocation.setResult(`request/response failed: ${err.message}`); } }); invocation.onCanceled = () => { }; } /** * Run TensorFlow environment * @customfunction RUN_TRAIN * @param invocation Custom function handler */ export function run_tf_environment(invocation: CustomFunctions.StreamingInvocation<string>): void { connectToManager().then(() => { invocation.setResult("Creating..."); let resources = {"cpu": 1, "mem": "6g", "domain": "default", "group_name": "default", "scaling_group": "default", "cluster_mode": "single-node", "cluster_size": 1, "mounts": [], "env": {}, "resource_opts": {}, "maxWaitSeconds": 15}; return globalThis.baiclient.createIfNotExists("cr.backend.ai/testing/python-tensorflow:2.5-py38-cuda11.3", "TF", resources); }).then(response => { invocation.setResult(`My session is created: ${response.sessionId}`); return globalThis.baiclient.execute(response.sessionId, 1, "query", "print('hello python world')", {}); }).then(response => { if (response.result.exitCode === 0) { invocation.setResult(response.result.console[0][1]); } }).catch(err => { switch (err.type) { case ai.backend.Client.ERR_SERVER: invocation.setResult(`Session creation failed: ${err.message}`); break; default: invocation.setResult(`request/response failed: ${err.message}`); } }); invocation.onCanceled = () => { }; } /** * Run TensorFlow environment test code * @customfunction TRAIN_TEST * @param {number[][]} values Multiple ranges of values. * @param invocation Custom function handler */ export function run_tf_test_code(values, invocation: CustomFunctions.StreamingInvocation<string>): void { try { let result = ""; for (var i = 0; i < values.length; i++) { for (var j = 0; j < values[i].length; j++) { result = result + "," + values[i][j].toString(); } } invocation.setResult(result); } catch(err) { } invocation.onCanceled = () => { }; } /** * Train IRIS flower dataset. * @customfunction IRIS_TRAIN * @param {number[][]} values IRIS data * @param invocation Custom function handler */ export function run_iris_training(values, invocation: CustomFunctions.StreamingInvocation<string>): void { try { let data = JSON.stringify(values); invocation.setResult(data); connectToManager().then(() => { invocation.setResult("Creating..."); let resources = {"cpu": 1, "mem": "6g", "mounts": ['code'], "env": {}, "resource_opts": {}, "maxWaitSeconds": 30}; return globalThis.baiclient.createIfNotExists("cr.backend.ai/testing/python-tensorflow:2.5-py38-cuda11.3", "TF_IRIS", resources); }).then(response => { invocation.setResult(`My session is created: ${response.sessionId}`); return globalThis.baiclient.execute("TF_IRIS", 1, "query", `import subprocess;print(subprocess.check_output("cd /home/work/code;python receive_iris_data.py ${data}", shell=True))`, {}); }).then(async response => { if (response.result.exitCode === 0) { invocation.setResult(`Training...`); let query = await globalThis.baiclient.execute("TF_IRIS", 1, "query", `import subprocess;print(subprocess.check_output("cd /home/work/code;python train_iris_model.py", shell=True))`, {}); while (query.result.status != 'finished') { query = await globalThis.baiclient.execute("TF_IRIS", 1, "query", ``, {}); } return query; } else { invocation.setResult(`Failed to send data.`); } }).then(response => { if (response.result.exitCode === 0) { invocation.setResult(`Training completed.`); } }).catch(err => { switch (err.type) { case ai.backend.Client.ERR_SERVER: invocation.setResult(`Session creation failed: ${err.message}`); break; default: invocation.setResult(`request/response failed: ${err.message}`); } }); } catch(err) { } invocation.onCanceled = () => { }; } /** * Inferencing IRIS flower class prediction model. * @customfunction IRIS * @param {number[][]} values IRIS data * @param invocation Custom function handler */ export function run_iris_inference(values, invocation: CustomFunctions.StreamingInvocation<string>): void { try { let data = JSON.stringify(values); invocation.setResult(data); connectToManager().then(() => { invocation.setResult("Creating..."); let resources = {"cpu": 1, "mem": "6g", "mounts": ['code'], "env": {}, "resource_opts": {}, "maxWaitSeconds": 30}; return globalThis.baiclient.createIfNotExists("cr.backend.ai/testing/python-tensorflow:2.5-py38-cuda11.3", "TF_IRIS", resources); }).then(async response => { invocation.setResult(`My session is created: ${response.sessionId}`); invocation.setResult(`Inferencing...`); let run_id = Math.floor(Math.random() * 50000).toString(); //globalThis.baiclient.requestTimeout = 15000; let query = await globalThis.baiclient.execute("TF_IRIS", run_id, "query", `import subprocess;print(subprocess.check_output("cd /home/work/code;python inference_iris_model.py '${data}'", shell=True).decode().strip())`, {}); while (query.result.status != 'finished') { query = await globalThis.baiclient.execute("TF_IRIS", run_id, "query", ``, {}); } return query; }).then(response => { if (response.result.exitCode === 0) { invocation.setResult(`Inference completed.`); ///let result = errorAsString(response.result); //if(response.result.console && response.result.console.stdout) { // invocation.setResult(response.result.stdout[0]); //} let results = response.result.console[0][1].split('\n'); if (results.length > 1) { invocation.setResult(response.result.console[0][1].replace('\n',',')); } else { invocation.setResult(results[0]); } //return results; } else { let result = errorAsString(response.result); invocation.setResult(result); } }).catch(err => { switch (err.type) { case ai.backend.Client.ERR_SERVER: invocation.setResult(`Session creation failed: ${err.message}`); break; default: invocation.setResult(`request/response failed: ${err.message}`); } }); } catch(err) { } invocation.onCanceled = () => { }; } /** * Train Yahoo stock market dataset. * @customfunction YAHOO_STOCK_TRAIN * @param {number[][]} values Yahoo stock market data * @param invocation Custom function handler */ export function run_stock_training(values, invocation: CustomFunctions.StreamingInvocation<string>): void { try { let data = JSON.stringify(values); invocation.setResult(data); connectToManager().then(() => { invocation.setResult("Creating..."); let resources = {"cpu": 4, "mem": "6g", "mounts": ['code'], "env": {}, "resource_opts": {}, "maxWaitSeconds": 30}; return globalThis.baiclient.createIfNotExists("cr.backend.ai/testing/python-tensorflow:2.5-py38-cuda11.3", "TF_STOCK", resources); }).then(response => { invocation.setResult(`My session is created: ${response.sessionId}`); return globalThis.baiclient.execute("TF_STOCK", 1, "query", `import subprocess;print(subprocess.check_output("cd /home/work/code;python receive_stock_data.py ${data}", shell=True))`, {}); }).then(async response => { if (response.result.exitCode === 0) { invocation.setResult(`Training...`); let query = await globalThis.baiclient.execute("TF_STOCK", 1, "query", `import subprocess;print(subprocess.check_output("cd /home/work/code;python train_stock_model.py", shell=True))`, {}); while (query.result.status != 'finished') { query = await globalThis.baiclient.execute("TF_STOCK", 1, "query", ``, {}); } return query; } else { invocation.setResult(`Failed to send data.`); } }).then(response => { if (response.result.exitCode === 0) { invocation.setResult(`Training completed.`); } }).catch(err => { switch (err.type) { case ai.backend.Client.ERR_SERVER: invocation.setResult(`Session creation failed: ${err.message}`); break; default: invocation.setResult(`request/response failed: ${err.message}`); } }); } catch(err) { } invocation.onCanceled = () => { }; } /** * Inferencing Yahoo stock market dataset. * @customfunction YAHOO_STOCK * @param {number[][]} values Yahoo stock market data * @param invocation Custom function handler */ export function run_stock_inference(values, invocation: CustomFunctions.StreamingInvocation<string>): void { try { let data = JSON.stringify(values); invocation.setResult(data); connectToManager().then(() => { invocation.setResult("Creating..."); let resources = {"cpu": 4, "mem": "6g", "mounts": ['code'], "env": {}, "resource_opts": {}, "maxWaitSeconds": 30}; return globalThis.baiclient.createIfNotExists("cr.backend.ai/testing/python-tensorflow:2.5-py38-cuda11.3", "TF_STOCK", resources); }).then(async response => { invocation.setResult(`My session is created: ${response.sessionId}`); invocation.setResult(`Inferencing...`); let run_id = Math.floor(Math.random() * 50000).toString(); //globalThis.baiclient.requestTimeout = 15000; let query = await globalThis.baiclient.execute("TF_STOCK", run_id, "query", `import subprocess;print(subprocess.check_output("cd /home/work/code;python inference_stock_model.py '${data}'", shell=True).decode().strip())`, {}); while (query.result.status != 'finished') { query = await globalThis.baiclient.execute("TF_STOCK", run_id, "query", ``, {}); } return query; }).then(response => { if (response.result.exitCode === 0) { invocation.setResult(`Inference completed.`); ///let result = errorAsString(response.result); //if(response.result.console && response.result.console.stdout) { // invocation.setResult(response.result.stdout[0]); //} let results = response.result.console[0][1].split('\n'); if (results.length > 1) { invocation.setResult(response.result.console[0][1].replace('\n',',')); } else { invocation.setResult(results[0]); } //return results; } else { let result = errorAsString(response.result); invocation.setResult(result); } }).catch(err => { switch (err.type) { case ai.backend.Client.ERR_SERVER: invocation.setResult(`Session creation failed: ${err.message}`); break; default: invocation.setResult(`request/response failed: ${err.message}`); } }); } catch(err) { } invocation.onCanceled = () => { }; } /** * Inferencing Yahoo stock market dataset. * @customfunction YAHOO_STOCK_PREDICT * @param {number[][]} values Yahoo stock market data * @return {any[][]} Predicted value */ export async function run_stock_inference_multi(values) { try { let data = JSON.stringify(values); await connectToManager(); let resources = {"cpu": 1, "mem": "6g", "mounts": ['code'], "env": {}, "resource_opts": {}, "maxWaitSeconds": 30}; await globalThis.baiclient.createIfNotExists("cr.backend.ai/testing/python-tensorflow:2.5-py38-cuda11.3", "TF_STOCK", resources); let run_id = Math.floor(Math.random() * 50000).toString(); //globalThis.baiclient.requestTimeout = 15000; let query = await globalThis.baiclient.execute("TF_STOCK", run_id, "query", `import subprocess;print(subprocess.check_output("cd /home/work/code;python inference_stock_model.py '${data}'", shell=True).decode().strip())`, {}); while (query.result.status != 'finished') { query = await globalThis.baiclient.execute("TF_STOCK", run_id, "query", ``, {}); } let response = query; if (response.result.exitCode === 0) { return JSON.parse(response.result.console[0][1]); } else { let result = errorAsString(response.result); return result; //invocation.setResult(result); } } catch (err) { switch (err.type) { case ai.backend.Client.ERR_SERVER: return [`Session creation failed: ${err.message}`]; default: return [`request/response failed: ${err.message}`]; } }; }
5aa990295e7079c71553e4d17d3edca19a640814
TypeScript
lakbir/SportsStore-Angular11
/src/app/services/caddy.service.ts
2.5625
3
import {Injectable} from '@angular/core'; import {Caddy} from '../models/caddy.model'; import {AuthService} from './auth.service'; import {TokenStorageService} from './token-storage.service'; import {ItemProduct} from '../models/item-product.model'; import {Product} from '../models/Product.model'; import {Client} from '../models/client.model'; @Injectable({ providedIn: 'root' }) export class CaddyService{ public currentCaddyName:string="Caddy1"; public listCaddies:Array<{num:number,name:string}>=[{num:1,name:'Caddy1'}]; public caddies:Map<string,Caddy>=new Map(); constructor(private authService:AuthService, private tokenStorageService: TokenStorageService ){ if(this.authService.isAuthenticated()) { this.loadCaddyFromLocalStorage(); } else{ this.caddies[this.currentCaddyName]=new Caddy(this.currentCaddyName); } } public addProductToCaddy(id:number,name:string,price:number,quantity:number):void{ let caddy=this.caddies[this.currentCaddyName]; let item = caddy.items[id]; if(item===undefined) { item=new ItemProduct(); item.id=id; item.name=name; item.price=price;item.quantity=quantity; caddy.items[id]=item; } else{ item.quantity+=quantity; } } public removeProduct(id:number):void{ let caddy=this.caddies[this.currentCaddyName]; delete caddy.items[id]; this.saveCaddy(); } public addProduct(product:Product){ this.addProductToCaddy(product.id,product.name,product.price,product.quantity) this.saveCaddy(); } public loadCaddyFromLocalStorage(){ let myCaddiesList=localStorage.getItem("ListCaddies_"+this.tokenStorageService.getUser().username); this.listCaddies=myCaddiesList==undefined?[{num:1,name:'Caddy1'}]:JSON.parse(myCaddiesList); this.listCaddies.forEach(c=>{ let cad=localStorage.getItem("myCaddy_"+this.tokenStorageService.getUser().username+"_"+c.name); this.caddies[c.name]=cad==undefined?new Caddy(c.name):JSON.parse(cad); }) } public getCaddy():Caddy{ let caddy=this.caddies[this.currentCaddyName]; if(caddy.client){ console.log(caddy.client); }else { caddy.client = {name:"",address:"",phoneNumber:"",email:"",username:""}; } return caddy; } saveCaddy() { let caddy=this.caddies[this.currentCaddyName]; localStorage.setItem("myCaddy_"+this.tokenStorageService.getUser().username+"_"+this.currentCaddyName,JSON.stringify(caddy)); } getSize(){ let caddy=this.caddies[this.currentCaddyName]; return Object.keys(caddy.items).length; } emptyCaddy(){ this.caddies=new Map(); this.listCaddies=[]; } getTotalCurrentCaddy() { let caddy=this.caddies[this.currentCaddyName]; let total=0; for(let key in caddy.items ){ total+=caddy.items[key].price*caddy.items[key].quantity; } return total; } addNewCaddy(c: { num: number; name: string }) { this.listCaddies.push(c); this.caddies[c.name]=new Caddy(c.name); localStorage.setItem("ListCaddies_"+this.tokenStorageService.getUser().username,JSON.stringify(this.listCaddies)); } setClient(client: Client) { this.getCaddy().client=client; this.saveCaddy(); } removeCaddyFromLocalStorage(){ if(localStorage.getItem("myCaddy_"+this.tokenStorageService.getUser().username+"_Caddy1")){ localStorage.removeItem("myCaddy_"+this.tokenStorageService.getUser().username+"_Caddy1"); } } }
2b109c250cfa100fb8a28db0fb593a92f35240a4
TypeScript
typpo/spacekit
/src/Camera.ts
2.671875
3
import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; import type { PerspectiveCamera } from 'three'; import { rescaleNumber, rescaleArray } from './Scale'; import type { Coordinate3d } from './Coordinates'; import type { SimulationContext } from './Simulation'; import type { SpaceObject } from './SpaceObject'; /** * A wrapper for Three.js camera and controls. * TODO(ian): Rename to "Viewer" */ export default class Camera { private context: SimulationContext; private camera: PerspectiveCamera; private cameraControls: OrbitControls; private followMesh?: THREE.Object3D; /** * @param {Object} context The simulation context */ constructor(context: SimulationContext) { // TODO(ian): Accept either context or container this.context = context; // Optional mesh that we are following. this.followMesh = undefined; const containerWidth = this.context.container.width; const containerHeight = this.context.container.height; const camera = new THREE.PerspectiveCamera( 50, containerWidth / containerHeight, rescaleNumber(0.00001), rescaleNumber(2000), ); this.camera = camera; // Controls // TODO(ian): Set maxDistance to prevent camera farplane cutoff. // See https://discourse.threejs.org/t/camera-zoom-to-fit-object/936/6 // TODO(ian): Access this better const renderer = this.context.simulation.getRenderer(); const controls = new OrbitControls(this.camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.05; controls.enablePan = true; controls.zoomSpeed = 1.5; controls.panSpeed = 2; controls.rotateSpeed = 2; controls.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN, }; controls.touches = { ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_ROTATE, }; this.cameraControls = controls; } /** * Move the camera to follow a SpaceObject as it moves. Currently only works * for non-particlesystems. * @param {SpaceObject} obj SpaceObject to follow. * @param {Array.<Number>} position Position of the camera with respect to * the object. */ followObject(obj: SpaceObject, position: Coordinate3d) { const followMesh = obj.get3jsObjects()[0]; this.cameraControls.enablePan = false; const rescaled = rescaleArray(position); this.camera.position.add( new THREE.Vector3(rescaled[0], rescaled[1], rescaled[2]), ); this.cameraControls.update(); this.followMesh = followMesh; } /** * Stop the camera from following the object. */ stopFollowingObject() { if (this.followMesh) { this.followMesh.remove(this.camera); this.followMesh = undefined; this.cameraControls.enablePan = true; } } /** * @returns {boolean} True if camera is following object. */ isFollowingObject(): boolean { return !!this.followMesh; } /** * @returns {THREE.PerspectiveCamera} The THREE.js camera object. */ get3jsCamera(): THREE.PerspectiveCamera { return this.camera; } /** * @returns {THREE.OrbitControls} The THREE.js CameraControls object. */ get3jsCameraControls(): OrbitControls { return this.cameraControls; } /** * Update the camera position and process control inputs. */ update() { if (this.isFollowingObject()) { const newpos = this.followMesh!.position.clone(); const offset = newpos.clone().sub(this.cameraControls.target); this.camera.position.add(offset); this.cameraControls.target.set(newpos.x, newpos.y, newpos.z); } // Handle control movements this.cameraControls.update(); // Update camera matrix this.camera.updateMatrixWorld(); } }
7db4d2fd00ee0851f4ce28c61dc0a919894a5410
TypeScript
N2AM/bawbty
/src/app/reducers/driver.reducer.ts
2.78125
3
import * as DriverActions from "../actions/driver.action"; import { Driver } from "../shared/models/driver.model"; // const initialState: Driver = { // driver_national_id: "", // date_of_birth: "", // Education_qualification: "", // children_below_16: 0, // Traffic_violations: [""], // Medical_conditions: [""], // driving_percentage: 0 // }; export function driverReducer( state: Driver[] = [], action: DriverActions.Actions ) { switch (action.type) { case DriverActions.Add_Driver: // console.log(state); return [...state, action.payload]; case DriverActions.Remove_Driver: return state.filter(state => state.driver_national_id !== action.payload); case DriverActions.Update_Driver: // console.log(state); let driver = state.findIndex( state => state.driver_national_id === action.payload.oldID ); // console.log(driver); state[driver] = action.payload.driver; // console.log(action.payload, state); return state; case DriverActions.RemoveAll_Drivers: return []; default: return state; } }
40bf8a39678f0083d37b34195da949465e2a050d
TypeScript
alepee/kata-solid-game-of-life
/tests/CoordinateNumber.test.ts
3.046875
3
import CoordinateNumberXAxis from '../src/CoordinateNumber/CoordinateNumberXAxis'; import CoordinateNumberYAxis from '../src/CoordinateNumber/CoordinateNumberYAxis'; describe('CoordinateNumber', () => { it('will return the correct distance beetween two CoordinateNumber', () => { const datasProvider = [ { a: 9, b: -1, res: 10 }, { a: -8, b: -1, res: 7 }, { a: 0, b: 0, res: 0 }, { a: 0, b: -1, res: 1 }, ]; datasProvider.forEach(datas => { const coordXA = new CoordinateNumberXAxis(datas.a); const coordXB = new CoordinateNumberXAxis(datas.b); const coordYA = new CoordinateNumberYAxis(datas.a); const coordYB = new CoordinateNumberYAxis(datas.b); const distanceX = coordXA.distance(coordXB); expect(distanceX).toBe(datas.res); const distanceY = coordXA.distance(coordXB); expect(distanceY).toBe(datas.res); }); }); });
d636a5c998baf85d6c7b4c5d706c30c9fcd7a9a5
TypeScript
Roger-Aguiar/imdb_movies
/src/genres/genres.service.ts
2.6875
3
import { Injectable } from '@nestjs/common'; import { NewGenreDto } from './dto/new-genre.dto'; import { GenreDto } from './dto/genre.dto'; @Injectable() export class GenresService { create(newGenreDto: NewGenreDto) { return 'This action adds a new genre'; } read() { return `This action returns all genres`; } readById(id: number) { return `This action returns a #${id} genre`; } update(id: number, genreDto: GenreDto) { return `This action updates a #${id} genre`; } delete(id: number) { return `This action removes a #${id} genre`; } }
155a4135020ca2b440c56ff6ccb457140f365c68
TypeScript
rharriso/sudoku-solution-gen-ts
/main.ts
3.28125
3
import { sample as _sample, times as _times, difference as _difference, shuffle as _shuffle, sortedUniqBy as _sortedUniqBy, sortedUniq as _sortedUniq } from 'lodash'; let total = 81; let size = 9; const third = 3; let validValues = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const board_count = 10;//jNumber(process.argv[2]); const all_neighbors = false;//prkocess.argv[3] == '--all-neighbors'; /** * */ interface coord { i: number; j: number; }; /** * */ class SudokuCell { value: Number = 0; position: coord; neighbors: Array<coord> = []; constructor (position: coord) { this.position = position; this.value = 0; // identify block top left const iBase = Math.floor(position.i / third) * third; const jBase = Math.floor(position.j / third) * third; const blockNeighbors = []; _times(size, (index: number) => { const i = Math.floor(index / third) + iBase; const j = (index % third) + jBase; if(i !== position.i || j !== position.j) { blockNeighbors.push({i, j}); } }); // identify row neighbors const rowNeighbors = _times(size, (i) => { return {i: i, j: position.j}; }); rowNeighbors.splice(position.i, 1); // identify col neighbors const colNeighbors = _times(size, (j) => { return {i: position.i, j: j}; }); colNeighbors.splice(position.j, 1); // all neighbors this.neighbors = _sortedUniqBy([ ...rowNeighbors, ...colNeighbors, ...blockNeighbors ], (c) => `${c.i}:${c.j}`); } } /** * */ class SudokuBoard { private cells: SudokuCell[]; constructor (){ this.cells = _times(total, (index) => { const position = this.resolveIndex(index); return new SudokuCell(position); }); } print() { const line = '--------------------------'; console.log(line) _times(size, (i) => { _times(size, (j) => { const cell = this.cells[this.resolvePosition({i, j})]; if ( j % third === 0) { process.stdout.write('| '); } process.stdout.write(`${cell.value} `); }); process.stdout.write('|\n'); if ( i % third === 2) { console.log(line); } }); } serialize () { return this.cells.map((c) => c.value).join(''); } clear () { for(const cell of this.cells) { cell.value = 0; } } fill () { if(!this.doFillCells(0)) { console.error('Unable to fill board'); } } doFillCells(index: number) { const cell = this.cells[index]; const neighborValues = _sortedUniq(cell.neighbors.map((n) => this.at(n).value )); const remainingOptions = _difference(validValues, neighborValues); for(const option of remainingOptions) { cell.value = option; // either this is the last cell, or the rest are good if (index === this.cells.length - 1 || this.doFillCells(index + 1)) { return true; } } cell.value = 0; return false; } resolveIndex(index: number) : coord { return { i: Math.floor(index / size), j: (index % size), } } resolvePosition(position: coord) : number { return position.i * size + position.j; } /** * */ at(c: coord): SudokuCell { return this.cells[this.resolvePosition(c)]; } atIndex(index: number): SudokuCell { return this.cells[index]; } set(c: coord, v: number) { this.cells[c.i][c.j].value = v; } } let board = new SudokuBoard(); let output = ''; let start = Date.now(); for(let i = 0; i < board_count; i++) { board.clear(); board.fill(); output += board.serialize() + '\n'; } const duration = Date.now() - start; console.log(`time: ${duration}`); console.log(`output size: ${output.length}`); console.log(`last board: ${board.serialize()}`); console.log(`boards per second: ${1000 * board_count / duration }`);
bfdd5a832adad5951612822d9a2d531aa6142f5b
TypeScript
rancher-sandbox/rancher-desktop
/pkg/rancher-desktop/backend/containerClient/__tests__/client.spec.ts
2.53125
3
import { MobyClient } from '@pkg/backend/containerClient/mobyClient'; import { NerdctlClient } from '@pkg/backend/containerClient/nerdctlClient'; import dockerRegistry from '@pkg/backend/containerClient/registry'; import { ContainerEngineClient } from '@pkg/backend/containerClient/types'; import MockBackend from '@pkg/backend/mock'; jest.mock('@pkg/backend/mock'); jest.mock('@pkg/backend/containerClient/registry'); describe.each(['nerdctl', 'moby'] as const)('%s', (clientName) => { let subject: ContainerEngineClient; beforeEach(() => { const executor = new MockBackend() as jest.Mocked<MockBackend>; switch (clientName) { case 'nerdctl': subject = new NerdctlClient(executor); break; case 'moby': subject = new MobyClient(executor, ''); break; default: throw new Error(`Unexpected client name ${ clientName }`); } }); describe('getTags', () => { const repository = 'registry.test/name'; let registryTags: string[]; let localTags: string[]; let localExtras: string[]; beforeEach(() => { registryTags = []; localTags = []; localExtras = []; jest.mocked(dockerRegistry).getTags.mockImplementation((name) => { expect(name).toEqual(repository); if (registryTags.length) { return Promise.resolve(registryTags); } return Promise.reject('Could not get tags from registry'); }); jest.spyOn(subject, 'runClient').mockImplementation((args, stdio) => { expect(args).toEqual(expect.arrayContaining(['image', 'list'])); expect(stdio).toEqual('pipe'); const results: string[] = []; if (localTags.length) { results.push(...localTags.map(t => `${ repository }:${ t }`)); } if (localExtras.length) { results.push(...localExtras); } if (results.length) { return Promise.resolve({ stdout: results.join('\n') }); } // We need the cast to any because `runClient()` is overloaded and // it's hard to convince TypeScript that the return value is fine. return Promise.reject('Could not get tags locally') as any; }); }); afterEach(() => { jest.restoreAllMocks(); jest.resetAllMocks(); }); it('should list tags from the registry', async() => { registryTags = ['apple', 'banana']; await expect(subject.getTags(repository)).resolves.toEqual(new Set(registryTags)); }); it('should list local tags', async() => { localTags = ['carrot', 'durian']; localExtras = ['irrelevant:grape', 'registry.invalid/other:honeydew']; await expect(subject.getTags(repository)).resolves.toEqual(new Set(localTags)); }); it('should merge tags', async() => { registryTags = ['jackfruit', 'kiwi']; localTags = ['kiwi', 'lemon']; await expect(subject.getTags(repository)).resolves.toEqual(new Set([...registryTags, ...localTags])); }); it('should ignore errors', async() => { await expect(subject.getTags(repository)).resolves.toEqual(new Set()); }); }); });
9eede2fa30e469d20506b809d6e9d506eec109db
TypeScript
My-Azure-Projects/azure-node-deploy
/src/deploy/get-local-file.ts
2.640625
3
import fs from 'fs'; import path from 'path'; import util from 'util'; import { AFileDesc, ADirDesc } from './go-through-dir'; export interface FsFileDesc<Client> extends AFileDesc { client: Client; } export interface FsDirDesc<Client> extends ADirDesc { client: Client; } const readDir = util.promisify(fs.readdir); const stat = util.promisify(fs.stat); export default async function getLocalFile<FileMeta, DirMeta>(payload: { fileName: string; dir: FsDirDesc<DirMeta>; getClient?: (pl: { dir: FsDirDesc<DirMeta>; file: FsDirDesc<null> | FsFileDesc<null>; fileName: string; }) => Promise<DirMeta | FileMeta>; }): Promise<FsDirDesc<DirMeta> | FsFileDesc<FileMeta>> { const filePath: string = path.join(payload.dir.path, payload.fileName); const fileStat: fs.Stats = await stat(filePath); const isDirectory: boolean = fileStat.isDirectory(); const file: FsDirDesc<null> | FsFileDesc<null> = { path: filePath, type: isDirectory ? 'dir' : 'file', files: isDirectory ? await readDir(filePath) : undefined, client: null, }; return { ...file, client: typeof payload.getClient === 'function' ? await payload.getClient({ file, dir: payload.dir, fileName: payload.fileName }) : null, } as FsDirDesc<DirMeta> | FsFileDesc<FileMeta>; }
c886ab534eda32986b41c847f29d864023ffd7e1
TypeScript
pewh/node-duckdb
/src/tests/result-stream.test.ts
2.8125
3
import { Readable } from "stream"; import { Connection, DuckDB } from "@addon"; import { IExecuteOptions, RowResultFormat } from "@addon-types"; const query = "SELECT * FROM read_csv_auto('src/tests/test-fixtures/web_page.csv')"; const executeOptions: IExecuteOptions = { rowResultFormat: RowResultFormat.Array }; function readStream<T>(rs: Readable): Promise<T[]> { return new Promise((resolve, reject) => { const elements: T[] = []; rs.on("data", (el: any) => elements.push(el)); rs.on("error", reject); rs.on("end", () => resolve(elements)); }); } describe("Result stream", () => { let db: DuckDB; let connection: Connection; beforeEach(() => { db = new DuckDB(); connection = new Connection(db); }); afterEach(() => { connection.close(); db.close(); }); it("reads a csv", async () => { const rs = await connection.execute(query, executeOptions); const elements = await readStream(rs); expect(elements.length).toBe(60); expect(elements[0]).toEqual([ 1, "AAAAAAAABAAAAAAA", "1997-09-03", null, 2450810, 2452620, "Y", 98539, "http://www.foo.com", "welcome", 2531, 8, 3, 4, ]); }); it("is able to read from two streams sequentially", async () => { const rs1 = await connection.execute(query, executeOptions); const elements1 = await readStream(rs1); expect(elements1.length).toBe(60); const rs2 = await connection.execute(query, executeOptions); const elements2 = await readStream(rs2); expect(elements2.length).toBe(60); }); it("correctly handles errors - closes resource", async () => { const rs1 = await connection.execute(query, executeOptions); await connection.execute(query, executeOptions); let hasClosedFired = false; rs1.on("close", () => (hasClosedFired = true)); await expect(readStream(rs1)).rejects.toMatchObject({ message: "Attempting to fetch from an unsuccessful or closed streaming query result: only one stream can be active on one connection at a time)", }); expect(hasClosedFired).toBe(true); }); it("is able to read from two streams on separate connections to one database while interleaving", async () => { const connection1 = new Connection(db); const connection2 = new Connection(db); const rs1 = await connection1.execute(query, executeOptions); const rs2 = await connection2.execute(query, executeOptions); const elements1 = await readStream(rs1); expect(elements1.length).toBe(60); const elements2 = await readStream(rs2); expect(elements2.length).toBe(60); }); // TODO: We probably want to stop queries when we close connection? it("is able to close - in prorgess queries run to the end", async () => { const query1 = "CREATE TABLE test (a INTEGER, b INTEGER);"; const query2 = "INSERT INTO test SELECT a, b FROM (VALUES (11, 22), (13, 22), (12, 21)) tbl1(a,b), repeat(0, 5000) tbl2(c)"; await connection.execute(query1, executeOptions); const p = connection.execute(query2, executeOptions); connection.close(); const elements = await readStream(await p); expect(elements).toEqual([[15000n]]); }); });
e42aac531c4a3dc5226a4ceb20c0bc01dca36c2b
TypeScript
Gr33nbl00d/alsatian
/packages/alsatian/test/unit-tests/decorators/ignore.spec.ts
2.609375
3
import "reflect-metadata"; import { Expect, METADATA_KEYS, Test, TestCase, SpyOn, TestFixture } from "../../../core/alsatian-core"; import { Ignore } from "../../../core/decorators/ignore-decorator"; import { Warner } from "../../../core/maintenance/warn"; @TestFixture("Ignore decorator tests") export class IgnoreDecoratorTests { @TestCase("key") @TestCase("another key") @TestCase("something-different") public ignoreTestKeyMetaDataAddedToCorrectKey(key: string) { const ignore = Ignore(""); const testFixture = {}; ignore(testFixture, key, undefined); Expect( Reflect.getMetadata(METADATA_KEYS.IGNORE, testFixture, key) ).toBe(true); } @TestCase("Ignored because of bla bla bla") @TestCase("another reason for it being ignored") @TestCase("bla bla bla") public ignoreTestCorrectReasonAdded(reason: string) { const key = "testKey"; const ignore = Ignore(reason); const testFixture = {}; ignore(testFixture, key, undefined); Expect( Reflect.getMetadata(METADATA_KEYS.IGNORE_REASON, testFixture, key) ).toBe(reason); } @Test() public ignoreTestFixtureMetaDataAdded(key: string) { const ignore = Ignore(""); class TestFixtureClass {} ignore(TestFixtureClass); Expect( Reflect.getMetadata(METADATA_KEYS.IGNORE, TestFixtureClass) ).toBe(true); } @TestCase("Ignored because of bla bla bla") @TestCase("another reason for it being ignored") @TestCase("bla bla bla") public ignoreTestFixtureCorrectReasonAdded(reason: string) { const ignoreTestDecorator = Ignore(reason); class TestFixtureClass {} ignoreTestDecorator(TestFixtureClass); Expect( Reflect.getMetadata(METADATA_KEYS.IGNORE_REASON, TestFixtureClass) ).toBe(reason); } }
89fc0ce45116f7247be4fae463b43183046cbcbb
TypeScript
AnaMariaTozi/sc
/src/utils/index.ts
2.65625
3
import { appConfig } from '@/config' const { MINIMUM_INITIAL_INVESTMENT, MINIMUM_YEARS_INVESTMENT, MAXIMUM_YEARS_INVESTMENT, MINIMUM_RISK_LEVEL, MAXIMUM_RISK_LEVEL } = appConfig const isValueInclusiveBetween = (value: number, min: number, max: number): boolean => value >= min && value <= max const isValidYear = (year: number): boolean => Number.isInteger(year) && isValueInclusiveBetween(year, MINIMUM_YEARS_INVESTMENT, MAXIMUM_YEARS_INVESTMENT) const isValidInvestment = (investmentValue: number): boolean => Number.isInteger(investmentValue) && investmentValue >= MINIMUM_INITIAL_INVESTMENT const isValidRiskLevel = (riskLevel: number): boolean => Number.isInteger(riskLevel) && isValueInclusiveBetween(riskLevel, MINIMUM_RISK_LEVEL, MAXIMUM_RISK_LEVEL) const formatCurrency = (value: number): string => Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(value) export { isValidYear, isValidInvestment, isValidRiskLevel, formatCurrency }
1f08a1b1d17881fbd1d198a4755a1af838ad7378
TypeScript
palasjir/disk-profiler
/src/utils/tree.ts
2.734375
3
import * as util from "lodash" import DirectoryTree from "../models/DirectoryTree" import DirectoryNode from "../models/DirectoryNode" import {NormalizedPath} from "../models/NormalizedPath" import {DirListItemModel, DirListItemType, FileInfo} from "../commons/types" import {normalizePath} from "./path" export function extractFileListFromNode( head: DirectoryNode, rootPath: NormalizedPath ): FileInfo[] { let list: FileInfo[] = [] const dirs = head.directories.values() for (const dir of dirs) { const normPath = normalizePath(dir.name) const absolutePath = rootPath.join(normPath) const found = extractFileListFromNode(dir, absolutePath) list = list.concat(found) } const files = head.files.values() for (const file of files) { list.push(file.info) } return list } export function extractFileListFromTree(tree: DirectoryTree): FileInfo[] { return extractFileListFromNode(tree.head, tree.rootPath) } export function getTopFiles(list: FileInfo[], limit: number): FileInfo[] { return util.take(util.sortBy(list, item => -item.size), limit) } export function extractDirectoryListItemsFromNode( node: DirectoryNode ): DirListItemModel[] { const items: DirListItemModel[] = [] for (const file of node.files.values()) { items.push({ type: DirListItemType.FILE, itemCount: undefined, name: file.name, size: file.info.size, }) } for (const dir of node.directories.values()) { items.push({ type: DirListItemType.FOLDER, itemCount: dir.files.size + dir.directories.size, name: dir.name, size: dir.sizeInBytes, }) } return util.sortBy(items, it => -it.size) // desc } export function extractDirectoryListItemsFromTree( tree: DirectoryTree, normalizedAbsolutePath: NormalizedPath ): DirListItemModel[] { const dir = tree.findDirectory(normalizedAbsolutePath) return !dir ? [] : extractDirectoryListItemsFromNode(dir) }
6624b35b202560617f4798dae2322f8c505128c8
TypeScript
AlexMeah/6a23a42d-82b1-4cce-935d-14663dc78e6f
/app/utils/calculateRating/index.ts
2.609375
3
import { ProductReview } from '.prisma/client'; export default function calculateRating(reviews: ProductReview[]) { return ( reviews.reduce((total: number, review) => total + review.rating, 0) / reviews.length ).toFixed(1); }
5be525de2d683f5917ece4598b07657116cec518
TypeScript
samuelsonnysalim/react-backoffice
/src/util/Error.ts
2.96875
3
export const throwRemoteResponseError = ( propertyPathName: string, propertyPathValue: string, foundResponseData: any, shouldBeAnArray = true, ): void => { throw new Error( `Response data must be an ${ shouldBeAnArray ? "array" : "object" } or use "${propertyPathName}" property to define property path. Found: "${typeof foundResponseData}", data property path: "${propertyPathValue}".`, ); };
f22e8afae5d22ddf314cb36f6814e14d2c019ce9
TypeScript
ynikolaev/PurpleBoard
/src/app/_services/user-data.service.spec.ts
2.53125
3
import { TestBed, inject } from '@angular/core/testing'; import { UserDataService } from './user-data.service'; import { User } from '../_models/user'; describe('UserDataService', () => { beforeEach(() => { //TestBed is a utility provided by @angular/core/testing to //configure and create an Angular testing module in which we want to //run our unit tests. TestBed.configureTestingModule({ providers: [UserDataService] }); }); it('should be created', inject([UserDataService], (service: UserDataService) => { expect(service).toBeTruthy(); })); describe('#getAllUsers()', () => { //inject the correct service from the TestBed injector in test function it('should return an empty array by default', inject([UserDataService], (service: UserDataService) => { expect(service.getAllUsers()).toEqual([]); })); it('should return all todos', inject([UserDataService], (service: UserDataService) => { let user1 = new User({ email: 'test@test.com', firstname: 'Yan', lastname: 'Nikolaev', password: 'password', firstTime: true, isAdmin: false }); let user2 = new User({ email: 'test2@test2.com', firstname: 'Bob', lastname: 'Bobbino', password: 'bob123', firstTime: true, isAdmin: false }); service.addUser(user1); service.addUser(user2); expect(service.getAllUsers()).toEqual([user1, user2]); })); }); describe('#save(user)', () => { it('should automatically assign an incrementing id', inject([UserDataService], (service: UserDataService) => { let user1 = new User({ email: 'test@test.com', firstname: 'Yan', lastname: 'Nikolaev', password: 'password', firstTime: true, isAdmin: false }); let user2 = new User({ email: 'test2@test2.com', firstname: 'Bob', lastname: 'Bobbino', password: 'bob123', firstTime: true, isAdmin: false }); service.addUser(user1); service.addUser(user2); expect(service.getUserById(1)).toEqual(user1); expect(service.getUserById(2)).toEqual(user2); })); }); describe('#deleteUserById(id)', () => { it('should remove user with the corresponding id', inject([UserDataService], (service: UserDataService) => { let user1 = new User({ email: 'test@test.com', firstname: 'Yan', lastname: 'Nikolaev', password: 'password', firstTime: true, isAdmin: false }); let user2 = new User({ email: 'test2@test2.com', firstname: 'Bob', lastname: 'Bobbino', password: 'bob123', firstTime: true, isAdmin: false }); service.addUser(user1); service.addUser(user2); expect(service.getAllUsers()).toEqual([user1, user2]); service.deleteUserById(1); expect(service.getAllUsers()).toEqual([user2]); service.deleteUserById(2); expect(service.getAllUsers()).toEqual([]); })); it('should not removing anything if user with corresponding id is not found', inject([UserDataService], (service: UserDataService) => { let user1 = new User({ email: 'test@test.com', firstname: 'Yan', lastname: 'Nikolaev', password: 'password', firstTime: true, isAdmin: false }); let user2 = new User({ email: 'test2@test2.com', firstname: 'Bob', lastname: 'Bobbino', password: 'bob123', firstTime: true, isAdmin: false }); service.addUser(user1); service.addUser(user2); expect(service.getAllUsers()).toEqual([user1, user2]); service.deleteUserById(3); expect(service.getAllUsers()).toEqual([user1, user2]); })); }); describe('#updateUserById(id, values)', () => { it('should return user with the corresponding id and updated data', inject([UserDataService], (service: UserDataService) => { let user1 = new User({ email: 'test@test.com', firstname: 'Yan', lastname: 'Nikolaev', password: 'password', firstTime: true, isAdmin: false }); service.addUser(user1); let updatedUser = service.updateUserById(1, { firstname: 'Ian' }); expect(updatedUser.firstname).toEqual('Ian'); })); it('should return null if user is not found', inject([UserDataService], (service: UserDataService) => { let user1 = new User({ email: 'test@test.com', firstname: 'Yan', lastname: 'Nikolaev', password: 'password', firstTime: true, isAdmin: false }); service.addUser(user1); let updatedUser = service.updateUserById(2, { firstname: 'Ian' }); expect(updatedUser).toEqual(null); })); }); });
0d50de17117250c09a2957427e52d32b5bde86a0
TypeScript
nguyer/aws-sdk-js-v3
/clients/node/client-cloudfront-node/types/_S3Origin.ts
2.78125
3
/** * <p>A complex type that contains information about the Amazon S3 bucket from which you want CloudFront to get your media files for distribution.</p> */ export interface _S3Origin { /** * <p>The DNS name of the Amazon S3 origin. </p> */ DomainName: string; /** * <p>The CloudFront origin access identity to associate with the distribution. Use an origin access identity to configure the distribution so that end users can only access objects in an Amazon S3 bucket through CloudFront.</p> <p>If you want end users to be able to access objects using either the CloudFront URL or the Amazon S3 URL, specify an empty <code>OriginAccessIdentity</code> element.</p> <p>To delete the origin access identity from an existing distribution, update the distribution configuration and include an empty <code>OriginAccessIdentity</code> element.</p> <p>To replace the origin access identity, update the distribution configuration and specify the new origin access identity.</p> <p>For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html">Using an Origin Access Identity to Restrict Access to Your Amazon S3 Content</a> in the <i> Amazon CloudFront Developer Guide</i>.</p> */ OriginAccessIdentity: string; } export type _UnmarshalledS3Origin = _S3Origin;
3a69b9212526cedf22dff23565231918833088e0
TypeScript
Pedroh1510/encurtador-url
/src/useCases/GetUrl/GetUrlUseCase.ts
2.640625
3
import { IUrlRepository } from '@/repositories/IUrlRepository' import { IGetUrlResponseDTO, IGetUrlRequestDTO } from './IGetUrlDTO' export class GetUrlUseCase { constructor ( private urlRepository: IUrlRepository ) {} async execute (data:IGetUrlRequestDTO):Promise<IGetUrlResponseDTO> { const originalUrl = await this.urlRepository.findUrl(data.smallUrl) if (!originalUrl) throw new Error('URL not found') const now = new Date().toUTCString() if (originalUrl.expire < now) throw new Error('URL expired') return { originalUrl: originalUrl.url } } }
26af2da8736504fbd11eebd8ca3cd83037dd6f01
TypeScript
AliceCengal/CanvasPractice
/raw.ts
3.109375
3
function createArray(length) { var arr = new Array(length || 0), i = length; if (arguments.length > 1) { var args = Array.prototype.slice.call(arguments, 1); while(i--) arr[length-1 - i] = createArray.apply(this, args); } return arr; } function sign(num: number): number { if (num > 0) { return 1; } else if (num < 0) { return -1; } else { return 0; } } function angle(x: number, y: number): number { var angle1 = Math.abs(Math.atan(y/x)); return sign(y) * ((sign(x) == 1) ? angle1 : (Math.PI-angle1)); } function mag(x: number, y: number): number { return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); } class Particle { constructor( public xx: number, public yy: number, public vx: number, public vy: number, public m: number) { } update() { this.xx += this.vx; this.yy += this.vy; } applyForce(fx: number, fy: number) { this.vx += (fx/this.m); this.vy += (fy/this.m); } } interface Field { interact(p: Particle): void; } class VelocityField { fieldPoints: number[] = []; cellHeight: number; cellWidth: number; constructor( public fieldWidth: number, public fieldHeight: number, public worldWidth: number, public worldHeight: number, public totalParticleCount: number) { this.cellWidth = worldWidth / fieldWidth; this.cellHeight = worldHeight / fieldHeight; for (var cellRow = 0; cellRow < fieldHeight; cellRow++) { for (var cellCol = 0; cellCol < fieldWidth; cellCol++) { } } } interact(p: Particle) { } } class BrakingField { maxV: number = 10; interact(p: Particle) { var vMag = mag(p.vx, p.vy); if (vMag > this.maxV) { var a = angle(p.vx, p.vy); p.applyForce((this.maxV - vMag)*0.75*Math.cos(a), (this.maxV - vMag)*0.75*Math.sin(a)); } } } class GravityField { constructor(public centerX: number, public centerY: number) { } interact(p: Particle) { var d = mag(p.xx - this.centerX, p.yy - this.centerY); var a = angle(p.xx - this.centerX, p.yy - this.centerY) + Math.PI; p.applyForce(d*Math.cos(a)/500, d*Math.sin(a)/500); } } class CurlingField { constructor(public centerX: number, public centerY: number) {} interact(p: Particle) { var d = mag(p.xx - this.centerX, p.yy - this.centerY)/500; var a = angle(p.vx, p.vy) - 0.5*Math.PI; p.applyForce(d*Math.cos(a), d*Math.sin(a)); } } class Simulation { balls: Particle[] = []; worldWidth: number; worldHeight: number; centerX: number; centerY: number; fields: Field[] = []; time: number = 0; fps: number = 0; frameDur: number = 0; constructor(width: number, height: number) { this.worldHeight = height; this.worldWidth = width; this.centerX = width/2; this.centerY = height/2; for (var i = 0; i < 1000; i++) { this.balls[i] = new Particle( (Math.random()*this.worldWidth), (Math.random()*this.worldHeight), (Math.random()*10) - 5, (Math.random()*10) - 5, (Math.random()*5) + 1) } this.fields = [ new BrakingField(), new GravityField(this.centerX, this.centerY), new CurlingField(this.centerX, this.centerY) ]; this.time = Date.now(); this.fps = 30; this.frameDur = 100; } cycle: number = 0; update() { var start = Date.now(); for (var p = 0; p < this.balls.length; p++) { this.balls[p].update(); for (var f = 0; f < this.fields.length; f++) { this.fields[f].interact(this.balls[p]); } } var now = Date.now(); this.frameDur = now - start; this.fps = Math.round(1000/(now - this.time)); this.time = now } }
f19c503162403269faf3f5fe7697681963e05921
TypeScript
iamlazy-dev/app
/packages/core/src/product-database/data/FakerRepository.ts
2.671875
3
import { commerce, datatype, random } from 'faker/locale/id_ID' import { DataError } from '../../shared/domain/DataError'; import { Either } from '../../shared/domain/Either'; import { Product } from '../domain/Model'; import { ProductRepository } from '../domain/Repository'; const seed: Product[] = Array.from(Array(25), () => Product.create({ id: datatype.uuid(), name: commerce.productName(), desc: commerce.productDescription(), price: datatype.number({ min: 1000, max: 100_000 }), img: [ random.image(), random.image(), random.image(), ], tags: [ commerce.department(), commerce.productAdjective(), commerce.productAdjective() ], specs: {}, _meta: {}, })) export class ProductFakerRepository implements ProductRepository { async get(id: string): Promise<Either<DataError, Product>> { const result = await this.find('id', id); return result.fold( (err) => Either.left(err), ([product]) => Either.right(product) ); } find(columnName: keyof Product, query: string | number): Promise<Either<DataError, Product[]>> { return new Promise((resolve, reject) => setTimeout(() => { try { const result = seed.filter((el) => JSON.stringify(el[columnName]) .toLowerCase() .includes(query.toString())) resolve(Either.right(result)); } catch (error) { reject(Either.left({ kind: 'UnexpectedError', error })) } }, 3000)) } async save(product: Product) { return new Promise<Either<DataError, Boolean>>((resolve, reject) => setTimeout(() => { try { const saved = seed.some(({id}, i) => { if (product.id === id) { seed[i] = product; return true; } }); resolve(saved ? Either.right(saved) : Either.left({ kind: 'UnexpectedError', error: new Error('Nothing changed!') })); } catch (error) { reject(Either.left({ kind: 'UnexpectedError', error })); } }, 1000)); } }
7d9d73cc370a83e0dca285400a3190149d54b17f
TypeScript
palmohit124/goodcode
/src/app/core/reducers/auth.reducer.ts
2.640625
3
import { AuthState, EmptyAuthState } from '../../models/user-tokens'; import { authActions } from '../actions'; export function reducer(state: AuthState = EmptyAuthState, action: authActions.Actions): AuthState { switch (action.type) { case authActions.AUTH_STATE_LOAD_SUCCEEDED: case authActions.SAVE_AUTH_STATE_SUCCEEDED: { const auth = <AuthState>action.payload; return { ...state, ...auth }; } case authActions.RESET_AUTH_ACTION_STATUS: { return { ...state, authAction: false }; } case authActions.LOADING_REFRESH_TOKEN: { return { ...state, loadingRefreshToken: true }; } default: { return state; } } }
3cdd933e556b87c6b0b3146fd5707ad1d00e2e4c
TypeScript
bcgov/embc-ess
/embc-app/ClientApp/src/app/core/services/cookie.service.ts
2.65625
3
import { Injectable, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Injectable({ providedIn: 'root' }) export class CookieService { constructor(@Inject(DOCUMENT) private document: Document) { } set(key: string, value: string, expires?: Date): void { let cookieValue = `${key}=${value}`; if (expires) { cookieValue += `;expires='${expires.toUTCString()}'`; } this.document.cookie = cookieValue; } setWithExpiryInYears(key: string, value: string, expires: number) { this.setWithExpiryInDays(key, value, expires * 365); } setWithExpiryInDays(key: string, value: string, expires: number) { this.setWithExpiryInHours(key, value, expires * 24); } setWithExpiryInHours(key: string, value: string, expires: number) { this.setWithExpiryInMinutes(key, value, expires * 60); } setWithExpiryInMinutes(key: string, value: string, expires: number) { this.setWithExpiryInSeconds(key, value, expires * 60); } setWithExpiryInSeconds(key: string, value: string, expires: number) { this.setWithExpiryInMilliseconds(key, value, expires * 1000); } setWithExpiryInMilliseconds(key: string, value: string, expires: number) { const expireDate = new Date(); const time = expireDate.getTime() + expires; expireDate.setTime(time); this.set(key, value, expireDate); } get(key: string): string { const decodedCookie: string = decodeURIComponent(this.document.cookie); const pairs: string[] = decodedCookie.split(/;\s*/); const prefix = `${key}=`; for (const pair of pairs) { if (pair.indexOf(prefix) === 0) { return pair.substring(prefix.length); } } return ''; } delete(key: string): void { this.set(key, '', new Date('Thu, 01 Jan 1970 00:00:01 GMT')); } clear(): void { const decodedCookie: string = decodeURIComponent(this.document.cookie); const pairs: string[] = decodedCookie.split(/;\s*/); for (const cookie of pairs) { const eqPos = cookie.indexOf('='); const cookieName = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; this.delete(cookieName); } } }
0a6e7eeafd5a22fa34ad57cf171f5415bfa6ee13
TypeScript
GaiaWorld/gaia_wallet
/src/app/view/guidePages/setLockScreenScret.ts
2.625
3
/** * set lock-screen psw */ import { popNew } from '../../../pi/ui/root'; import { Widget } from '../../../pi/widget/widget'; import { lockScreenHash,setLocalStorage } from '../../utils/tools'; interface Props { jump?:boolean; title1?:string; title2?:string; } export class SetLockScreenScret extends Widget { public ok: () => void; public props:Props; constructor() { super(); } public create() { super.create(); this.init(); } public setProps(props: Props, oldProps: Props): void { super.setProps(props, oldProps); if (props.title1) { this.state.passwordScreenTitle = props.title1; } } public init() { this.state = { passwordScreenTitle:`为了保护您的资产安全 请设置锁屏密码`, lockScreenPsw:'' }; } public completedInput(r:any) { const psw = r.psw; if (this.state.lockScreenPsw.length > 0) { if (this.state.lockScreenPsw === psw) { const close = popNew('pi-components-loading-loading', { text: '验证中...' }); setTimeout(() => { close.callback(close.widget); const hash256 = lockScreenHash(psw); setLocalStorage('lockScreenPsw',hash256); popNew('app-components-message-message', { itype: 'success', content: '设置成功', center: true }); this.ok && this.ok(); },1000); } else { popNew('app-components-message-message', { itype: 'error', content: '两次密码输入不一致,请重新输入', center: true }); this.init(); this.paint(); } } else { this.state.lockScreenPsw = psw; this.state.passwordScreenTitle = (this.props && this.props.title2) || '请重复'; this.paint(); } } public jumpClick() { this.ok && this.ok(); } }
e9b5b786324c1c7f336c2790a781ac4363e7dc6e
TypeScript
nerialexandre/backend-gobarber-ts
/src/app/services/authentication/UserAuthenticationService.ts
2.703125
3
import { compare } from 'bcryptjs'; import UserRepository from '../../repositories/UserRepository'; import User from '../../models/User'; import Jwt from '../../libs/jwt'; import config from '../../../config/config'; interface Request { email: string; password: string; } interface Response { user: User; token: string; } class UserAuthenticationService { public async execute({ email, password }: Request): Promise<Response> { const userRepository = new UserRepository(); const findUser = await userRepository.findByEmail(email); if (!findUser) { throw new Error('Email ou senha invalido'); } const checkPassword = await compare(password, findUser.password); if (!checkPassword) { throw new Error('Email ou senha invalido'); } const token = Jwt.generate( { id: findUser.id, name: findUser.name }, config.jwt.secret, config.jwt.expiresIn ); return { user: findUser, token }; } } export default new UserAuthenticationService();
5b3820645e33b1bb27dea6dcae030cfee0e049f1
TypeScript
TEAM-B-SOFT2020/LSDFrontEnd
/src/routes/api/api.ts
2.65625
3
// libraries import * as express from 'express'; // classes, interfaces & functions //import Contract from '../contract'; //import { IReservationSummary } from 'contract/src/dto/reservation'; //const contract = new Contract(); const router: express.Router = express.Router(); // middleware for json parsing router.use(express.json()); // middleware for console logging... can be deleted :) router.use((req, res, next) => { const { body } = req; console.log('Request body::', body); next(); }); // GET Method (Read) router.get('/', async (req, res) => { res.send({ method: 'GET', message: 'Hello TypeScript RPC' }); }); // POST Method (Create) router.post('/', (req, res) => { const { body } = req; res.send({ method: 'POST', ...body }); }); // PUT Method (Update) router.put('/', (req, res) => { const { body } = req; res.send({ method: 'PUT', ...body }); }); // DELETE Method (Remove) router.delete('/', (req, res) => { const { body } = req; res.send({ method: 'DELETE', ...body }); }); export default router;
4cbf6a45cff4a71bda341d7e867ac0dbca54c8e4
TypeScript
AlissonGiron/CloudniteClient
/src/game/Entities/Player.ts
2.875
3
import { Vector3 } from "babylonjs"; export enum Team { Blue, Red } export class Player { public Id: string; public Team: Team; public Body: BABYLON.AbstractMesh; public Pivot: BABYLON.AbstractMesh; public AttackMesh: BABYLON.AbstractMesh; public LastLife: number; public executeAttack: boolean; public InitialPosition: any; constructor(id) { this.Id = id; this.executeAttack = false; this.LastLife = 10; } Reset = () => { this.SetPosition(this.InitialPosition); } TakeDamage = () => { this.Move({ x: Math.random() * 100, z: Math.random() * 100 }, 100); setTimeout(() => { this.Move({ x: 0, z: 0 }, 0); }, 100); } Attack = (scene) => { if(this.Pivot != null) { return; } this.Pivot = BABYLON.MeshBuilder.CreateBox("myPivot", { size: 0.1 }, scene); this.Pivot.isVisible = false; this.AttackMesh = BABYLON.MeshBuilder.CreateBox("myBox", { depth: 2, width: 0.2, height: 0.5 }, scene); this.Pivot.parent = this.Body; this.AttackMesh.parent = this.Pivot; this.AttackMesh.position.x = this.Pivot.position.x + 2; this.AttackMesh.position.y = this.Pivot.position.y + 1.5; var myMaterial = new BABYLON.StandardMaterial("myMaterial", scene); myMaterial.diffuseColor = new BABYLON.Color3(1,1,1); myMaterial.specularColor = new BABYLON.Color3(1,1,1); myMaterial.emissiveColor = new BABYLON.Color3(1,1,1); myMaterial.ambientColor = new BABYLON.Color3(1,1,1); this.AttackMesh.material = myMaterial; setTimeout(() => { this.AttackMesh.dispose(); this.Pivot.dispose(); this.Pivot = null; this.AttackMesh = null; }, 300); } Move = (direction, impulse) => { let impulseDirection = new Vector3(direction.x, 0, direction.z); impulseDirection.normalize(); // @ts-ignore this.Body.physicsImpostor.setLinearVelocity(impulseDirection.scale(impulse)); } SetPosition = (position) => this.Body.position.set(position.x, position.y, position.z); }
1e203cb0bfa7064cd894088d112aaae1eb820e58
TypeScript
DJ956/UdonGuidApp
/UdonApp/src/app/model/request/Auth/UserRegistryRequest.model.ts
2.671875
3
/** * ユーザ登録リクエストモデル */ export interface UserRegistryRequestModel { /**登録ユーザ名 */ UserName: string; /**パスワード */ Password: string; }
d20df51e5d327ae9f9dae3958ef582971c6065a2
TypeScript
b-haytham/react-native-job-finder
/src/redux/user/user_slice.ts
2.765625
3
import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { CURRENT_USER } from "../data"; import { User } from "../data_types"; // Define a type for the slice state interface UserState { loading: boolean; current_user: User; error: string | null; } // Define the initial state using that type const initialState: UserState = { loading: false, current_user: CURRENT_USER, error: null, }; export const userSlice = createSlice({ name: "user", // `createSlice` will infer the state type from the `initialState` argument initialState, reducers: { updateImageProfile(state, action: PayloadAction<string>) { state.current_user.image = action.payload; }, updateFullName(state, action: PayloadAction<string>) { state.current_user.full_name = action.payload; }, updateMainInfo( state, action: PayloadAction<{ job_title: string; location: string; birth_day: string; }> ) { state.current_user.main_info = action.payload; }, uodateContactInfo( state, action: PayloadAction<{ email: string; phone: string; facebook?: string; tweeter?: string; }> ) { state.current_user.contact_info = action.payload; }, updateAbout(state, action: PayloadAction<string>) { state.current_user.about = action.payload; }, updateSkills(state, action: PayloadAction<string[]>) { state.current_user.skills = action.payload; }, updateWorkExperiences( state, action: PayloadAction< { position_title: string; where: string; image?: string; duration: string; }[] > ) { state.current_user.work_experiences = action.payload; }, updateEducation( state, action: PayloadAction<{ university_name: string; degree_name: string; duration: string; }> ) { state.current_user.education = action.payload; }, }, }); export const { uodateContactInfo, updateAbout, updateEducation, updateFullName, updateImageProfile, updateMainInfo, updateSkills, updateWorkExperiences } = userSlice.actions; export default userSlice.reducer;
a88804b1f40dee5a55206fee86366ec2c424a9ec
TypeScript
WaleedAshraf/metaphysics
/src/schema/v1/me/__tests__/followed_shows.test.ts
2.578125
3
/* eslint-disable promise/always-return */ import { runAuthenticatedQuery } from "schema/v1/test/utils" import gql from "lib/gql" import cityData from "schema/v1/city/cityDataSortedByDisplayPreference.json" import { LOCAL_DISCOVERY_RADIUS_KM } from "schema/v1/city/constants" const stubResolver = () => Promise.resolve({ body: [], headers: {} }) const generate_query = (params = `(first: 10)`) => gql` { me { followsAndSaves { shows${params} { edges { node { id } } } } } } ` describe("returns followed shows for a user", () => { let followedShowsLoader beforeEach(() => { followedShowsLoader = jest.fn(stubResolver) }) it("generates a predictable URL with no parameters", async () => { const query = generate_query() await runAuthenticatedQuery(query, { followedShowsLoader }) expect(followedShowsLoader).toHaveBeenCalledWith({ size: 10, offset: 0, total_count: true, }) }) describe("filter by status", () => { const assert_status_supported = async status => { const query = generate_query( `(first: 10, status: ${status.toUpperCase()})` ) await runAuthenticatedQuery(query, { followedShowsLoader }) expect(followedShowsLoader).toHaveBeenCalledWith({ size: 10, offset: 0, total_count: true, status: status, }) } const assert_invalid_status_fails = async status => { const query = generate_query( `(first: 10, status: ${status.toUpperCase()})` ) await expect( runAuthenticatedQuery(query, { followedShowsLoader }) ).rejects.toMatchInlineSnapshot( `[GraphQLError: Expected type EventStatus, found RANDOM_INVALID_STATUS.]` ) } it("handles all supported status definitions", async () => { await assert_status_supported("closed") await assert_status_supported("running") await assert_status_supported("upcoming") await assert_status_supported("closing_soon") await assert_status_supported("running_and_upcoming") }) it("throws an error if an unsupported status is supplied", async () => { await assert_invalid_status_fails("random_invalid_status") }) }) describe("filter by city", () => { it("generates a predictable URL with a city slug input", async () => { const nyc = cityData[0] expect(nyc.slug).toBe("new-york-ny-usa") const query = generate_query(`(first: 10, city: "${nyc.slug}")`) await runAuthenticatedQuery(query, { followedShowsLoader }) expect(followedShowsLoader).toHaveBeenCalledWith({ size: 10, offset: 0, total_count: true, near: `${nyc.coordinates.lat},${nyc.coordinates.lng}`, max_distance: LOCAL_DISCOVERY_RADIUS_KM, }) }) it("throws an error if presented with an invalid city slug", async () => { const query = generate_query(`(first: 10, city: "this-is-not-a-city")`) await expect( runAuthenticatedQuery(query, { followedShowsLoader }) ).rejects.toMatchInlineSnapshot( `[Error: City slug must be one of: new-york-ny-usa, los-angeles-ca-usa, london-united-kingdom, berlin-germany, paris-france, hong-kong-hong-kong]` ) }) it("relies on the state of cityData", () => { cityData .map(city => ({ name: city.name, slug: city.slug, lat: city.coordinates.lat, lng: city.coordinates.lng, })) .forEach(city => { expect(city).toMatchObject({ name: expect.any(String), slug: expect.any(String), lat: expect.any(Number), lng: expect.any(Number), }) }) }) }) })
f4caa175f2077802b6a9e5e63bac08394ad6a1a8
TypeScript
aaronksaunders/angular2-ngrx-test
/src/app/list/list.component.ts
2.71875
3
// // @see https://gist.github.com/btroncone/a6e4347326749f938510#taking-advantage-of-changedetectiononpush // for information on ChangeDetectionStrategy import {ListItem, AppState} from './../listStore'; import {Store} from '@ngrx/store'; import {Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core'; /** * * * @export * @class ListComponent * @implements {OnInit} */ @Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class ListComponent implements OnInit { /** * * @type {ListItem[]} * @memberOf ListComponent */ @Input() items: ListItem[]; /** * Creates an instance of ListComponent. * * @param {Store<AppState>} _store * * @memberOf ListComponent */ constructor(private _store: Store<AppState>) { } /** * * @memberOf ListComponent */ ngOnInit() { } /** * * @param {any} _item * * @memberOf ListComponent */ showItemDetail(_item) { debugger; this._store.dispatch({type: 'SELECT_ITEM', payload: _item}); } /** * * @param {any} _item * * @memberOf ListComponent */ deleteListItem(_item) { debugger; try { this._store.dispatch({type: 'REMOVE_LIST_ITEM', payload: _item}); this._store.dispatch({type: 'SELECT_ITEM'}); } catch (e) { console.log(e) } } } /** * * @export * @class ListItemComponent * @implements {OnInit} */ @Component({ selector: 'app-list-item', template: ` <p>{{ item.id}}</p> <p>{{ item.itemName}}</p> <p>{{ item.items && item.items.length }}</p> <div> <button (click)="onDeleteItem.emit(item)">DELETE</button> <button (click)="onShowDetailItem.emit(item)">SHOW</button> </div> `, styleUrls: ['./list.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class ListItemComponent implements OnInit { /** * @memberOf ListItemComponent */ @Input() item; /** * @memberOf ListItemComponent */ @Output() onDeleteItem = new EventEmitter() /** * @memberOf ListItemComponent */ @Output() onShowDetailItem = new EventEmitter() /** * Creates an instance of ListItemComponent. * * @memberOf ListItemComponent */ constructor() { } /** * * @memberOf ListItemComponent */ ngOnInit() { console.log("wrote item", this.item) } }
db4451653cf490463b75188145e7ae7d8b4d50d1
TypeScript
UD-CISC374/coding-2-try-phaser-mtmiller0417
/src/scripts/objects/asteroid.ts
2.921875
3
export default class Asteroid extends Phaser.GameObjects.Sprite { maxVelocity:number = 7; minVelocity:number = 3; x_vel:number = 0; y_vel:number = 0; scene: Phaser.Scene; sceneWidth: number; sceneHeight: number; constructor(scene: Phaser.Scene) { super(scene, 0, 0, 'asteroid-sprite-big'); scene.add.existing(this); this.scene = scene; this.sceneWidth = this.scene.cameras.main.width; this.sceneHeight = this.scene.cameras.main.height; } setTop():void{ // Set location this.x = Math.floor(Math.random() * (this.sceneWidth-this.width/2) + this.width/2); //this.y = -this.height/2; this.y = 0; // Set velocity this.x_vel = 0; this.y_vel = Math.floor(Math.random() * this.maxVelocity + this.minVelocity) } setBottom(){ // Set location this.x = Math.floor(Math.random() * (this.sceneWidth-this.width/2)); //this.y = this.sceneHeight + this.height/2; this.y = this.sceneHeight; // Set velocity this.x_vel = 0; this.y_vel = -Math.floor(Math.random() * this.maxVelocity + this.minVelocity) } setLeft(){ // Set location //this.x = -this.width/2; this.x = 0; this.y = Math.floor(Math.random() * (this.sceneHeight - this.height/2)); // Set velocity this.x_vel = Math.floor(Math.random() * this.maxVelocity + this.minVelocity); this.y_vel = 0; } setRight(){ // Set location //this.x = this.sceneWidth + this.width/2; this.x = this.sceneWidth; this.y = Math.floor(Math.random() * (this.sceneHeight - this.height/2) + this.height/2); // Set velocity this.x_vel = -Math.floor(Math.random() * this.maxVelocity + this.minVelocity); this.y_vel = 0; } setRandom(){ switch(Math.floor(Math.random() * 4)) { // Asteroid will come from the top case 0: { this.setTop(); break; } // Asteroid will come from the bottom case 1: { this.setBottom(); break; } // Asteroid will come from the left case 2: { this.setLeft(); break; } // Asteroid will come from the right case 3: { this.setRight(); break; } default: { //statements; break; } } } }
6a16d140267fc0bbf2866c2115375b7c9c9314ef
TypeScript
sf-entr-fin-soleng/test
/server/src/api/utils.ts
2.65625
3
import * as moment from 'moment' const generate = require('nanoid/generate') const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' function parseObject(row) { return Object.assign( { ...JSON.parse(row.data) }, { id: row['id'], parentId: row['parentid'], type: row['type'], totalCount: row['full_count'] } ) } function getBaseQuery(type, id?, parentId?): string { let query = 'SELECT Sfid as sfid, Heroku_Id__c as id, Heroku_Parent_Id__c as parentId, Type__c as type, Data__c as data, count(*) OVER() AS full_count' query += ' FROM sfgc.mock_container__c' query += ` WHERE Type__c='${type}'` if (parentId) query += ` AND Heroku_Parent_Id__c='${parentId}'` if (id) query += ` AND Heroku_Id__c = '${id}'` console.log(`[${moment().toString()}][DB_READ]: ${query}`) return query } function getWriteQuery(type, data, isInsert): string { const parseData = data => { return JSON.stringify( data, (key, value) => value !== undefined && value !== null ? value : undefined, 0 ) } let query = '' if (isInsert) { data.id = uuid() query = `INSERT INTO sfgc.mock_container__c (Heroku_Id__c, Type__c, Data__c, Heroku_Parent_Id__c)` query += ` VALUES ('${data.id}', '${type}', '${parseData(data)}'` query += `,'${data.parentId ? data.parentId : 'null'}')` } else { query = `UPDATE sfgc.mock_container__c SET Data__c = '${parseData( data )}'` // eslint-disable-next-line prettier/prettier query += `, Heroku_Parent_Id__c = '${ data.parentId ? data.parentId : 'null' }'` query += ` WHERE Heroku_Id__c = '${data.id}'` } console.log(`[${moment().toString()}][DB_WRITE]: ${query}`) return query } function uuid(size?): string { return generate(alphabet, size ? size : 18) } export { uuid, generate, alphabet, parseObject, getBaseQuery, getWriteQuery }
2a603177a1270532f689c16026844f82b3ac8c27
TypeScript
hieuctfe/Examination-Tool
/.svn/pristine/e5/e5160863a725b1a21add943d0ba8a8e1afc390d7.svn-base
2.5625
3
import {Deserializable} from '../interface/deserialize.interface'; export class Chapter implements Deserializable { id: number; name: string; order: number; courseCode: string; checked: boolean; deserialize(input: any): this { Object.assign(this, input); return this; } }